harperdb 4.3.21 → 4.3.22
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 +57 -57
- package/bin/lite.js +20 -20
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +19 -19
- package/launchServiceScripts/launchNatsReplyService.js +19 -19
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +19 -19
- package/npm-shrinkwrap.json +57 -62
- package/package.json +1 -1
- package/resources/IterableEventQueue.d.ts +6 -0
- package/resources/Resource.d.ts +6 -0
- package/resources/Table.d.ts +9 -0
- package/resources/databases.d.ts +9 -0
- package/server/jobs/jobProcess.js +19 -19
- package/server/threads/threadServer.js +19 -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.a22f6951.js → main.796f780e.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -19
- /package/studio/build-local/static/js/{main.a22f6951.js.LICENSE.txt → main.796f780e.js.LICENSE.txt} +0 -0
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
"use strict";var Dq=Object.create;var _c=Object.defineProperty;var Lq=Object.getOwnPropertyDescriptor;var Mq=Object.getOwnPropertyNames;var Pq=Object.getPrototypeOf,Uq=Object.prototype.hasOwnProperty;var a=(e,t)=>_c(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fe=(e,t)=>{for(var r in t)_c(e,r,{get:t[r],enumerable:!0})},fO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Mq(t))!Uq.call(e,s)&&s!==r&&_c(e,s,{get:()=>t[s],enumerable:!(n=Lq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Dq(Pq(e)):{},fO(t||!e||!e.__esModule?_c(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>fO(_c({},"__esModule",{value:!0}),e);var mO=g((oce,hO)=>{var vq=require("fast-glob"),{statSync:Lh,existsSync:Mh,readFileSync:Bq,writeFileSync:Hq}=require("fs"),{spawnSync:xq,spawn:Gq,execFileSync:ice}=require("child_process"),{isMainThread:qq}=require("worker_threads"),{join:Zs,relative:EO}=require("path"),{PACKAGE_ROOT:bn}=P(),{tmpdir:Fq,platform:kq}=require("os");require("source-map-support").install();var Vq=["resources","server","dataLayer","components"],dc="ts-build",Ph,$q=__filename.endsWith("tsBuild.js");if($q){if(qq){let r;try{Lh(Zs(bn,dc)),r=!0}catch{}if(r)for(let n of vq.sync(Vq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=Lh(Zs(bn,n)).mtimeMs-5e3,i=Lh(Zs(bn,dc,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."),Ph=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Ph=!0;if(Ph){let n=Zs(bn,"node_modules/.bin/tsc");kq()==="win32"&&(n+=".cmd");let s=xq(n,{cwd:bn});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Zs(Fq(),"harperdb-tsc.pid"),o;if(Mh(i))try{process.kill(+Bq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Gq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});Hq(i,c.pid.toString()),c.unref()}}}}let e=hO.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=EO(bn,n[0]),o;i.startsWith(dc)?o=Zs(bn,EO(dc,i)):o=Zs(bn,dc,i);let c=Zs(o,r),u=c+".js";if(Mh(u))return u;if(c.includes(".")&&Mh(c))return c}return t(r,n,s)}}});var P=g((uce,DO)=>{"use strict";var an=require("path"),Yq=require("fs"),{relative:ace,join:cce}=an,{existsSync:Kq}=Yq;function Wq(){let e=__dirname;for(;!Kq(an.join(e,"package.json"));){let t=an.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Wq,"getHDBPackageRoot");var ei=Wq(),pO="js",i_=pO,Qq="harperdb-config.yaml",zq="defaultConfig.yaml",Jq="hdb",SO=`harperdb.${i_}`,TO=`customFunctionsServer.${i_}`,jq=`restartHdb.${i_}`,vh="HarperDB",s_="Custom Functions",o_="Clustering Hub",a_="Clustering Leaf",Xq="Clustering Ingest Service",Zq="Clustering Reply Service",eF="foreground.pid",tF="hdb.pid",rF="data",nF={HDB:vh,CLUSTERING_HUB:o_,CLUSTERING_LEAF:a_,CLUSTERING_INGEST_SERVICE:Xq,CLUSTERING_REPLY_SERVICE:Zq,CUSTOM_FUNCTIONS:s_,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"},sF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},iF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},oF={harperdb:vh,"clustering hub":o_,"clustering leaf":a_,"custom functions":s_,custom_functions:s_,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},aF={CLUSTERING_HUB_PROC_DESCRIPTOR:o_,CLUSTERING_LEAF_PROC_DESCRIPTOR:a_},Uh={HDB:an.join(ei,"server/harperdb"),CUSTOM_FUNCTIONS:an.join(ei,"server/customFunctions"),CLUSTERING_HUB:an.join(ei,"server/nats"),CLUSTERING_LEAF:an.join(ei,"server/nats")},cF={HDB:an.join(Uh.HDB,SO),CUSTOM_FUNCTIONS:an.join(Uh.CUSTOM_FUNCTIONS,TO)},uF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:an.join(ei,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:an.join(ei,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:an.join(ei,"launchServiceScripts/launchUpdateNodes4-0-0.js")},lF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},gO="support@harperdb.io",_F="customer-success@harperdb.io",RO=1,dF=4141,AO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",fF="https://www.harperdb.io/product",EF=`For support, please submit a request at ${AO} or contact ${gO}`,OO=`For license support, please contact ${_F}`,hF="None of the specified records were found.",mF="hash attribute not found",pF=`Your current license only supports ${RO} role. ${OO}`,SF="Your current license only supports 3 connections to a node.",TF="127.0.0.1",gF=1,RF=/^\.$/,AF=/^\.\.$/,OF="U+002E",bF=/\//g,yF="U+002F",NF=/U\+002F/g,IF=/^U\+002E$/,wF=/^U\+002EU\+002E$/,CF="d",DF=999999,LF="*",MF="--max-old-space-size=",PF="system",UF="__hdb_hash",vF=".harperdb",BF=".hdb",HF="keys",xF="hdb_boot_properties.file",GF=".updateConfig.json",qF="SIGTSTP",FF=24,kF=6e4,VF=448,$F="blob",YF="trash",KF="database",WF="schema",QF="transactions",zF=".count",JF="id",jF="PROCESS_NAME",bO={SETTINGS_PATH_KEY:"settings_path"},yO=require("lodash"),XF={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"},ZF={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},ek={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},tk={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"},rk={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},Pr="hdb_internal:",nk={CREATE_SCHEMA:Pr+"create_schema",CREATE_TABLE:Pr+"create_table",CREATE_ATTRIBUTE:Pr+"create_attribute",ADD_USER:Pr+"add_user",ALTER_USER:Pr+"alter_user",DROP_USER:Pr+"drop_user",HDB_NODES:Pr+"hdb_nodes",HDB_USERS:Pr+"hdb_users",HDB_WORKERS:Pr+"hdb_workers",CATCHUP:Pr+"catchup",SCHEMA_CATCHUP:Pr+"schema_catchup",WORKER_ROOM:Pr+"cluster_workers"},sk={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"},ik="060493.ks",ok=".license",ak={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},ee={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},ck={CSV:".csv",JSON:".json"},uk={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},lk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},fc={};fc[ee.INSERT]=ee.INSERT;fc[ee.UPDATE]=ee.UPDATE;fc[ee.UPSERT]=ee.UPSERT;fc[ee.DELETE]=ee.DELETE;var He=Object.create(null);He[ee.DESCRIBE_ALL]=ee.DESCRIBE_ALL;He[ee.DESCRIBE_TABLE]=ee.DESCRIBE_TABLE;He[ee.DESCRIBE_SCHEMA]=ee.DESCRIBE_SCHEMA;He[ee.READ_LOG]=ee.READ_LOG;He[ee.ADD_NODE]=ee.ADD_NODE;He[ee.LIST_USERS]=ee.LIST_USERS;He[ee.LIST_ROLES]=ee.LIST_ROLES;He[ee.USER_INFO]=ee.USER_INFO;He[ee.SQL]=ee.SQL;He[ee.GET_JOB]=ee.GET_JOB;He[ee.SEARCH_JOBS_BY_START_DATE]=ee.SEARCH_JOBS_BY_START_DATE;He[ee.DELETE_FILES_BEFORE]=ee.DELETE_FILES_BEFORE;He[ee.EXPORT_LOCAL]=ee.EXPORT_LOCAL;He[ee.EXPORT_TO_S3]=ee.EXPORT_TO_S3;He[ee.CLUSTER_STATUS]=ee.CLUSTER_STATUS;He[ee.REMOVE_NODE]=ee.REMOVE_NODE;He[ee.RESTART]=ee.RESTART;He[ee.CUSTOM_FUNCTIONS_STATUS]=ee.CUSTOM_FUNCTIONS_STATUS;He[ee.GET_CUSTOM_FUNCTIONS]=ee.GET_CUSTOM_FUNCTIONS;He[ee.GET_CUSTOM_FUNCTION]=ee.GET_CUSTOM_FUNCTION;He[ee.SET_CUSTOM_FUNCTION]=ee.SET_CUSTOM_FUNCTION;He[ee.DROP_CUSTOM_FUNCTION]=ee.DROP_CUSTOM_FUNCTION;He[ee.ADD_CUSTOM_FUNCTION_PROJECT]=ee.ADD_CUSTOM_FUNCTION_PROJECT;He[ee.DROP_CUSTOM_FUNCTION_PROJECT]=ee.DROP_CUSTOM_FUNCTION_PROJECT;He[ee.PACKAGE_CUSTOM_FUNCTION_PROJECT]=ee.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[ee.DEPLOY_CUSTOM_FUNCTION_PROJECT]=ee.DEPLOY_CUSTOM_FUNCTION_PROJECT;var _k={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"},dk={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},NO={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"},fk=yO.invert(NO),Ek={CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root"},I={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS:"operationsApi_tls",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers",TLS:"tls",CLONED:"cloned"},IO={settings_path:bO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:I.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,customfunctions_tls:I.TLS,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,http_maxheadersize:I.HTTP_MAXHEADERSIZE,http_threadrange:I.HTTP_THREADRANGE,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:I.OPERATIONSAPI_TLS,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,storage_maxtransactionqueuetime:I.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls:I.TLS,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];IO[t.toLowerCase()]=t}var hk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},mk={csv_file_load:"csv_file_load",csv_data_load:ee.CSV_DATA_LOAD,csv_url_load:ee.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3",restart_service:"restart_service"},pk={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"},Sk={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Tk={VERSION_DEFAULT:"2.2.0"},gk={DEVELOPMENT:8192,DEFAULT:512},Rk={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"},Ak={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"},Ok={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},wO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},bk=Symbol("metadata"),yk="__clustering__",Nk=Object.values(wO),Ik=15984864e5,CO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},wk=yO.invert(CO),Ck={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"},Dk=111,Lk=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(Ts,"createLogRecord");function
|
|
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:lV.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(EV,"findPs")});var ft=g((pce,WO)=>{"use strict";var hV="__dbis__",mV="__txns__",pV="__environment_name__",SV="__dbi_defintion__",TV={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"},gV=["__createdtime__","__updatedtime__"],RV="\uFFFF",KO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},AV=Object.values(KO);WO.exports={AUDIT_STORE_NAME:mV,INTERNAL_DBIS_NAME:hV,DBI_DEFINITION_NAME:SV,SEARCH_TYPES:TV,TIMESTAMP_NAMES:gV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:pV,TRANSACTIONS_DBI_NAMES_ENUM:KO,TRANSACTIONS_DBIS:AV,OVERFLOW_MARKER:RV}});var Ur=g((Sce,rb)=>{"use strict";var QO=P(),zO=ft(),JO={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},jO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),XO={500:jO("There was an error processing your request."),400:"Invalid request"},OV=XO[JO.INTERNAL_SERVER_ERROR],bV={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.`},yV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},NV={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"},IV={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 ${zO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${zO.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"},wV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${QO.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 ${QO.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"},ZO={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"},CV={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."},DV={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`},LV={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"},MV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},PV={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`},eb={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.`},tb={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}`},UV={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."},vV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},BV={...ZO,...NV,...bV,...CV,...DV,...LV,...MV,...PV,...wV,...eb,...tb,...UV,...vV,...yV};rb.exports={CHECK_LOGS_WRAPPER:jO,HDB_ERROR_MSGS:BV,DEFAULT_ERROR_MSGS:XO,DEFAULT_ERROR_RESP:OV,HTTP_STATUS_CODES:JO,LMDB_ERRORS_ENUM:IV,AUTHENTICATION_ERROR_MSGS:ZO,VALIDATION_ERROR_MSGS:eb,ITC_ERRORS:tb}});var ne=g((gce,ib)=>{"use strict";var Vo=Ur(),HV=$(),xV=P(),d_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,nb),this.statusCode=n||Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Vo.DEFAULT_ERROR_MSGS[n]?Vo.DEFAULT_ERROR_MSGS[n]:Vo.DEFAULT_ERROR_MSGS[Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&HV[s](i)}},$h=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},Yh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function nb(e,t,r,n=xV.LOG_LEVELS.ERROR,s=null,i=!1){if(sb(e))return e;let o=new d_(e,t,r,n,s);return i&&delete o.stack,o}a(nb,"handleHDBError");function sb(e){return e.__proto__.constructor.name===d_.name}a(sb,"isHDBError");ib.exports={isHDBError:sb,handleHDBError:nb,ClientError:$h,ServerError:Yh,hdb_errors:Vo}});var je=g((Ace,db)=>{"use strict";var Oc=P(),GV=z(),ur=Z(),bc=require("path"),qV=require("minimist"),ob=require("fs-extra"),ab=require("lodash");ur.initSync();var{CONFIG_PARAMS:ti,DATABASES_PARAM_CONFIG:Tc,SYSTEM_SCHEMA_NAME:f_}=Oc,gc,Rc,Ac;function cb(){if(gc!==void 0)return gc;if(ur.getHdbBasePath()!==void 0)return gc=ur.get(ti.STORAGE_PATH)||bc.join(ur.getHdbBasePath(),Oc.DATABASES_DIR_NAME),gc}a(cb,"getBaseSchemaPath");function ub(){if(Rc!==void 0)return Rc;if(ur.getHdbBasePath()!==void 0)return Rc=_b(f_),Rc}a(ub,"getSystemSchemaPath");function lb(){if(Ac!==void 0)return Ac;if(ur.getHdbBasePath()!==void 0)return Ac=ur.get(Oc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||bc.join(ur.getHdbBasePath(),Oc.TRANSACTIONS_DIR_NAME),Ac}a(lb,"getTransactionAuditStoreBasePath");function FV(e,t){let r=ur.get(ti.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||bc.join(lb(),e.toString())}a(FV,"getTransactionAuditStorePath");function _b(e,t){e=e.toString(),t=t&&t.toString();let r=ur.get(Oc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||bc.join(cb(),e)}a(_b,"getSchemaPath");function kV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,qV(process.argv));let n=r[ti.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!GV.isObject(n))throw o;i=n}for(let o of i){let c=o[f_];if(!c)continue;let u=ur.get(ti.DATABASES);u=u??{};let _=c?.tables?.[t]?.[Tc.PATH];if(_)return ab.set(u,[f_,Tc.TABLES,t,Tc.PATH],_),ur.setProperty(ti.DATABASES,u),_;let l=c?.[Tc.PATH];if(l)return ab.set(u,[f_,Tc.PATH],l),ur.setProperty(ti.DATABASES,u),l}}let s=r[ti.STORAGE_PATH.toUpperCase()];if(s){if(!ob.pathExistsSync(s))throw new Error(s+" does not exist");let i=bc.join(s,e);return ob.mkdirsSync(i),ur.setProperty(ti.STORAGE_PATH,s),i}return ub()}a(kV,"initSystemSchemaPaths");function VV(){gc=void 0,Rc=void 0,Ac=void 0}a(VV,"resetPaths");db.exports={getBaseSchemaPath:cb,getSystemSchemaPath:ub,getTransactionAuditStorePath:FV,getTransactionAuditStoreBasePath:lb,getSchemaPath:_b,initSystemSchemaPaths:kV,resetPaths:VV}});var vr=g((Nce,pb)=>{"use strict";var $V=Ur().LMDB_ERRORS_ENUM,bce=require("lmdb"),YV=ft(),yce=require("buffer").Buffer,{OVERFLOW_MARKER:fb,MAX_SEARCH_KEY_LENGTH:E_}=YV,Eb=["number","string","symbol","boolean","bigint"];function KV(e){if(e=e?.primaryStore||e,!e)throw new Error($V.ENV_REQUIRED)}a(KV,"validateEnv");function WV(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(WV,"stringifyData");function QV(e){return e instanceof Date?e.valueOf():e}a(QV,"convertKeyValueToWrite");function zV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(Eb.includes(typeof e))return e.length>E_?[e.slice(0,E_)+fb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(Eb.includes(typeof i))i.length>E_?r.push(i.slice(0,E_)+fb):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(zV,"getIndexedValues");var h_=0,hb=0;function mb(){hb=Date.now()-performance.now()}a(mb,"adjustStartTime");mb();var JV=6e4;setInterval(mb,JV).unref();function jV(){let e=performance.now()+hb;return e>h_?(h_=e,e):(h_+=488e-6,h_)}a(jV,"getNextMonotonicTime");pb.exports={validateEnv:KV,stringifyData:WV,convertKeyValueToWrite:QV,getNextMonotonicTime:jV,getIndexedValues:zV}});var Sb,yn,Kh,yc=Re(()=>{Sb=require("events"),yn=class extends Sb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Kh;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)}},Kh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var xi={};Fe(xi,{server:()=>at});var Tb,at,lr=Re(()=>{Tb=require("../index"),at={};(0,Tb._assignPackageExport)("server",at)});var zh={};Fe(zh,{loadGQLSchema:()=>e$,start:()=>Qh,startOnMainThread:()=>ZV});function Qh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let Q=H(v.type);return Q.nullable=!1,Q}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let M={type:v.name?.value};return Object.defineProperty(M,"location",{value:v.loc.startToken}),M};a(H,"getProperty");let T=S.name.value,R=[],b={table:null,database:null,properties:R};E.set(T,b);for(let v of S.directives){if(v.name.value==="table"){for(let F of v.arguments)b[F.name.value]=F.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=T),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,f.push(b)}if(v.name.value==="sealed"&&(b.sealed=!0),v.name.value==="export"){b.export=!0;for(let F of v.arguments)F.name.value==="name"&&(b.export={name:F.value.value})}}let C=!1;for(let v of S.fields){let F=H(v.type);F.name=v.name.value,R.push(F);for(let M of v.directives)if(M.name.value==="primaryKey")C?console.warn("Can not define two attributes as a primary key"):(F.isPrimaryKey=!0,C=!0);else if(M.name.value==="indexed")F.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let J of M.arguments)Q[J.name.value]=J.value.value;F.relationship=Q}else if(M.name.value==="createdTime")F.assignCreatedTime=!0;else if(M.name.value==="updatedTime")F.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")F.expiresAt=!0;else if(M.name.value==="allow"){let Q=F.authorizedRoles=[];for(let J of M.arguments)J.name.value==="role"&&Q.push(J.value.value)}}b.type=T,T==="Query"&&(h=b)}function p(S){let T=E.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):XV.includes(S.type)||(0,gb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of E.values())for(let T of S.properties)p(T);for(let S of f)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Wh.dirname)(n),S.tableClass):i.set((0,Wh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Wh,gb,XV,ZV,e$,Rb=Re(()=>{Wh=require("path");Ae();gb=B(We()),XV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Qh,"start");ZV=Qh,e$=Qh({ensureTable:Et}).handleFile});async function m_(e){let t=(0,bb.pathToFileURL)(e).toString();return t$?(Nc||(Nc=r$(s$)),(await(await Nc).import(t)).namespace):import(t)}async function r$(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Nc=new Compartment({console,Math,Date,fetch:n$,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Ob.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:$t,tables:Br,databases:ct})}};let n=await(0,Ab.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Nc}function n$(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 s$(){return{Resource:$t,tables:Br}}var Ab,Ob,bb,t$,Nc,Jh=Re(()=>{Nn();Ae();Ab=require("fs/promises"),Ob=require("path"),bb=require("url"),t$=!1;a(m_,"secureImport");a(r$,"getCompartment");a(n$,"secureOnlyFetch");a(s$,"getGlobalVars")});var Xh={};Fe(Xh,{handleFile:()=>i$});async function i$(e,t,r,n){let s=new Map,i=await m_(r);c(i.default)&&n.set((0,jh.dirname)(t),i.default),o(i,(0,jh.dirname)(t));function o(u,_){for(let l in u){let d=u[l];c(d)?n.set(_+"/"+l,d):typeof d=="object"&&o(d,_+"/"+l)}}a(o,"recurseForResources");function c(u){return typeof u=="function"&&(u.get||u.put||u.post||u.delete)}return a(c,"isResource"),s}var jh,yb=Re(()=>{Jh();jh=require("path");a(i$,"handleFile")});var em={};Fe(em,{start:()=>o$});function o$({resources:e}){e.set("login",Zh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Zh,Nb=Re(()=>{Nn();a(o$,"start");Zh=class extends $t{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var Pb={};Fe(Pb,{parse:()=>rm,streamAsJSON:()=>Ic,stringify:()=>Gi});function Ic(e){return new tm({value:e})}function Ib(e){return console.error(e),JSON.stringify(e.toString())}function wb(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===Lb)return Mb(e);if(t.resolution)return t.resolution.then(()=>Gi(e));throw t}}function Mb(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+=Mb(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 rm(e){return u$.test(e)?a$.parse(e):JSON.parse(e)}var Cb,Db,a$,c$,Lb,tm,u$,nm=Re(()=>{Cb=require("stream"),Db=B(require("json-bigint-fixes")),a$=(0,Db.default)({useNativeBigInt:!0}),c$=1e4,Lb={};BigInt.prototype.toJSON=function(){throw Lb};a(Ic,"streamAsJSON");tm=class extends Cb.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),Ib)}catch(s){yield Ib(s)}else yield Gi(t)}else yield Gi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);wb(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>c$?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 wb(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(Ib,"handleError");a(wb,"when");a(Gi,"stringify");a(Mb,"jsStringify");u$=/[[,:]\s*-?\d{16,}/;a(rm,"parse")});var Kb=g((kce,Yb)=>{"use strict";var sm=require("recursive-iterator"),l$=require("alasql"),im=require("clone"),Ub=z(),{handleHDBError:vb,hdb_errors:_$}=ne(),{HDB_ERROR_MSGS:Bb,HTTP_STATUS_CODES:Hb}=_$,{getDatabases:d$}=(Ae(),ie(ke)),f$=["DISTINCT_ARRAY"],xb=Symbol("validateTables"),om=Symbol("validateTable"),Fce=Symbol("getAllColumns"),Gb=Symbol("validateAllColumns"),p_=Symbol("findColumn"),qb=Symbol("validateOrderBy"),wc=Symbol("validateSegment"),am=Symbol("validateColumn"),Fb=Symbol("setColumnsForTable"),kb=Symbol("checkColumnsForAsterisk"),Vb=Symbol("validateGroupBy"),$b=Symbol("hasColumns"),cm=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[xb](),this[kb](),this[Gb]()}[xb](){if(this[$b]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[om](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[om](t.table)})}}[$b](){let t=!1,r=new sm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[om](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=d$();if(!r[t.databaseid])throw vb(new Error,Bb.SCHEMA_NOT_FOUND(t.databaseid),Hb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw vb(new Error,Bb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Hb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=im(s);i.table=im(t),this.attributes.push(i)})}[p_](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)}[kb](){let t=new sm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Fb](r.tableid)}[Fb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new l$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Gb](){this[wc](this.statement.columns,!1),this[wc](this.statement.joins,!1),this[wc](this.statement.where,!1),this[Vb](this.statement.group,!1),this[wc](this.statement.order,!0)}[wc](t,r){if(!t)return;let n=new sm(t),s=[];for(let{node:i,path:o}of n)!Ub.isEmpty(i)&&!Ub.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[qb](i):s.push(this[am](i)));return s}[Vb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&f$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=im(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[p_](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[p_](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`}[qb](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[am](t)}[am](t){let r=this[p_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Yb.exports=cm});var Qb=g(($ce,Wb)=>{"use strict";var um=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Wb.exports=um});var Jb=g((Kce,zb)=>{"use strict";var lm=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};zb.exports=lm});var ey={};Fe(ey,{HAS_EXPIRATION:()=>pm,LAST_TIMESTAMP_PLACEHOLDER:()=>Lc,LOCAL_TIMESTAMP:()=>E$,METADATA:()=>Cc,NO_TIMESTAMP:()=>dm,PENDING_LOCAL_TIME:()=>Sm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>mm,RecordEncoder:()=>hm,TIMESTAMP_ASSIGN_LAST:()=>m$,TIMESTAMP_ASSIGN_NEW:()=>Xb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Zb,TIMESTAMP_PLACEHOLDER:()=>S_,TIMESTAMP_RECORD_PREVIOUS:()=>fm,getUpdateRecord:()=>Tm,handleLocalTimeForGets:()=>A_});function S$(){return Dc[0]=Dc[0]^64,h$.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?.[Cc];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?.[Cc]>=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[Cc];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 Tm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",E,f){if(E||u==null?$o=i?.localTime?fm|Zb:dm:$o=u?i?.localTime?fm|16384:Xb|16384:dm,l>0&&(c|=pm),g_=c,Em=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:$o>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(f&&(T_=e.encoder.encode(f)),E&&i?.localTime){let R=i?.localTime,b=r.get(R);if(b){let C=vt(b).previousLocalTime;return r.put(R,R_(o,t,n,C,T,d,T_),{ifVersion:p}),S}}r.put(Lc,R_(o,t,n,i?.localTime?1:0,T,d,T_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var jb,_m,S_,Lc,mm,E$,Cc,Dc,h$,dm,Xb,m$,Zb,fm,pm,Sm,p$,T_,$o,g_,Em,hm,qi,Mc=Re(()=>{jb=require("msgpackr");ri();_m=B($()),S_=new Uint8Array([1,1,1,1,4,64,0,0]),Lc=new Uint8Array([1,1,1,1,1,0,0,0]),mm=new Uint8Array([1,1,1,1,3,64,0,0]),E$=Symbol("local-timestamp"),Cc=Symbol("metadata"),Dc=new Uint8Array(8),h$=new DataView(Dc.buffer,0,8),dm=0,Xb=0,m$=1,Zb=3,fm=4,pm=16,Sm=1,$o=0,g_=-1,Em=0,hm=class extends jb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if($o||g_>=0){let i=0,o=$o;o&&(i+=8,$o=0);let c=g_,u=Em;c>=0&&(i+=2,g_=-1,u&&(i+=8,Em=0));let _=p$=r.call(this,n,s|2048|i);T_=_.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,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(Dc,0,c),c+=8;else for(let d=0;d<8;d++)Dc[d]=t[c++];u=S$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&pm&&(_=(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,[Cc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(S$,"getTimestamp");a(A_,"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?(_m.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):_m.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(Tm,"getUpdateRecord")});var Pc=g((jce,ry)=>{"use strict";var ty=Z(),T$=P(),{RecordEncoder:g$}=(Mc(),ie(ey)),Jce=require("fs");ty.initSync();var R$=ty.get(T$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,gm=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=R$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:g$})}};ry.exports=gm});var Uc=g((Zce,ny)=>{"use strict";var Hr=Z(),cn=P();Hr.initSync();var O_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Hr.get(cn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ny.exports=O_;O_.MAX_DBS=1e4});var Qe=g((tue,fy)=>{"use strict";var Am=require("lmdb"),In=require("fs-extra"),xr=require("path"),b_=vr(),oy=$(),_r=Ur().LMDB_ERRORS_ENUM,y_=Jb(),Om=Pc(),ay=Uc(),ni=ft(),sy=P(),{table:A$,resetDatabases:O$}=(Ae(),ie(ke)),iy=Z(),wn=ni.INTERNAL_DBIS_NAME,cy=ni.DBI_DEFINITION_NAME,b$="data.mdb",y$="lock.mdb",vc=".mdb",N$="-lock",Rm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=un(t,r),this.key_type=this.dbi[ni.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ni.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Am.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function N_(e,t){if(e===void 0)throw new Error(_r.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(_r.ENV_NAME_REQUIRED)}a(N_,"pathEnvNameValidation");async function bm(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(_r.INVALID_BASE_PATH):n}try{let n=xr.join(e,t+vc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(xr.join(e,t,b$),In.constants.R_OK|In.constants.F_OK),xr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(_r.INVALID_ENVIRONMENT)}else throw new Error(_r.INVALID_ENVIRONMENT);throw n}}a(bm,"validateEnvironmentPath");function I_(e,t){if(b_.validateEnv(e),t===void 0)throw new Error(_r.DBI_NAME_REQUIRED)}a(I_,"validateEnvDBIName");async function I$(e,t,r=!1,n=!1){N_(e,t);let s=xr.basename(e);t=t.toString();let i=iy.get(sy.CONFIG_PARAMS.DATABASES);i||iy.setProperty(sy.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await bm(e,t,n),uy(e,t,r)}catch(o){if(o.message===_r.INVALID_ENVIRONMENT){let c=xr.join(e,t);await In.mkdirp(n?c:e);let u=new ay(n?c:c+vc,!1),_=Am.open(u);_.dbis=Object.create(null);let l=new Om(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=ym(e,t,r);return _[ni.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(I$,"createEnvironment");async function w$(e,t,r,n=!0){N_(e,t),t=t.toString();let s=xr.join(e,t);return A$({table:t,database:xr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(w$,"copyEnvironment");async function uy(e,t,r=!1){N_(e,t),t=t.toString();let n=ym(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 bm(e,t),i=xr.join(e,t+vc),o=s!=i,c=new ay(s,o),u=Am.open(c);u.dbis=Object.create(null);let _=_y(u);for(let l=0;l<_.length;l++)un(u,_[l]);return u[ni.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(uy,"openEnvironment");async function C$(e,t,r=!1){N_(e,t),t=t.toString();let n=xr.join(e,t+vc),s=await bm(e,t);if(global.lmdb_map!==void 0){let i=ym(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await ly(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+N$:xr.join(xr.dirname(s),y$))}a(C$,"deleteEnvironment");async function ly(e){b_.validateEnv(e);let t=e[ni.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(ly,"closeEnvironment");function ym(e,t,r=!1){let s=`${xr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(ym,"getCachedEnvironmentName");function D$(e){b_.validateEnv(e);let t=Object.create(null),r=un(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new y_,s)}catch{oy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(D$,"listDBIDefinitions");function _y(e){b_.validateEnv(e);let t=[],r=un(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(_y,"listDBIs");function L$(e,t){let n=un(e,wn).getEntry(t),s=new y_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{oy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(L$,"getDBIDefinition");function dy(e,t,r,n=!r){if(I_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return un(e,t)}catch(s){if(s.message===_r.DBI_DOES_NOT_EXIST){let i=new Om(r,n===!0),o=e.openDB(t,i),c=new y_(r===!0,n);return o[cy]=c,un(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(dy,"createDBI");function un(e,t){if(I_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=L$(e,t):r=new y_,r===void 0)throw new Error(_r.DBI_DOES_NOT_EXIST);let n;try{let s=new Om(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(_r.DBI_DOES_NOT_EXIST):s}return n[cy]=r,e.dbis[t]=n,n}a(un,"openDBI");function M$(e,t){I_(e,t),t=t.toString();let r=un(e,t),n=r.getStats();return r[ni.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(M$,"statDBI");async function P$(e,t){try{let r=xr.join(e,t+vc);return(await In.stat(r)).size}catch{throw new Error(_r.INVALID_ENVIRONMENT)}}a(P$,"environmentDataSize");function U$(e,t){if(I_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_DROP_INTERNAL_DBIS_NAME);un(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],un(e,wn).removeSync(t)}a(U$,"dropDBI");function v$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{un(e,i)}catch(o){if(o.message===_r.DBI_DOES_NOT_EXIST)dy(e,i,i!==t,i===t),n=!0;else throw o}}n&&O$()}a(v$,"initializeDBIs");fy.exports={openDBI:un,openEnvironment:uy,createEnvironment:I$,listDBIs:_y,listDBIDefinitions:D$,createDBI:dy,dropDBI:U$,statDBI:M$,deleteEnvironment:C$,initializeDBIs:v$,TransactionCursor:Rm,environmentDataSize:P$,copyEnvironment:w$,closeEnvironment:ly}});var hy=g((nue,Ey)=>{"use strict";var Nm=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Ey.exports=Nm});var py=g((iue,my)=>{"use strict";var Im=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}};my.exports=Im});var Ty=g((aue,Sy)=>{"use strict";var wm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Sy.exports=wm});var Yo=g((due,Ay)=>{"use strict";var B$=Qe(),H$=hy(),x$=py(),G$=Ty(),Qn=vr(),Bc=Ur().LMDB_ERRORS_ENUM,q$=ft(),gs=P(),F$=z(),k$=require("uuid"),uue=require("lmdb"),{handleHDBError:V$,hdb_errors:$$}=ne(),{OVERFLOW_MARKER:lue,MAX_SEARCH_KEY_LENGTH:_ue}=q$,gy=Z();gy.initSync();var w_=gy.get(gs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Cm=gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Fi=gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function Y$(e,t,r,n,s=Qn.getNextMonotonicTime()){Pm(e,t,r,n),Dm(e,t,r);let i=new H$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ry(_,!0,s);let l=K$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Lm(o,c,n,i,s)}a(Y$,"insertRecords");function K$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][gs.FUNC_VAL],n[o]=c)}let u=Qn.getIndexedValues(c),_=e.dbis[o];if(u){w_&&_.prefetch(u.map(l=>({key:l,value:s})),C_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}w_&&e.dbis[t].prefetch([s],C_),e.dbis[t].put(s,n,n[Fi])})}a(K$,"insertRecord");function W$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(W$,"removeSkippedRecords");function Ry(e,t,r){let n=r>0;(n||!Number.isInteger(e[Fi]))&&(e[Fi]=r||(r=Qn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[Cm]))&&(e[Cm]=r||Qn.getNextMonotonicTime()):delete e[Cm]}a(Ry,"setTimestamps");function Dm(e,t,r){r.indexOf(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),B$.initializeDBIs(e,t,r)}a(Dm,"initializeTransaction");async function Q$(e,t,r,n,s=Qn.getNextMonotonicTime()){Pm(e,t,r,n),Dm(e,t,r);let i=new x$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],E;try{E=Mm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),u.push(d)}return Lm(c,u,n,i,s,o)}a(Q$,"updateRecords");async function z$(e,t,r,n,s=Qn.getNextMonotonicTime()){try{Pm(e,t,r,n)}catch(u){throw V$(u,u.message,$$.HTTP_STATUS_CODES.BAD_REQUEST)}Dm(e,t,r);let i=new G$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;F$.isEmpty(_[t])?(l=k$.v4(),_[t]=l):l=_[t];let d=Mm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Lm(o,c,n,i,s)}a(z$,"upsertRecords");async function Lm(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(),W$(r,i),n}a(Lm,"finalizeWrite");function Mm(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(Ry(r,!l,o),Number.isInteger(r[Fi])&&_[Fi]>r[Fi])return!1;l&&s.original_records.push(_);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let T=_[h];if(typeof p=="function"){let b=p([[_]]);Array.isArray(b)&&(p=b[0][gs.FUNC_VAL],r[h]=p)}if(p===T)continue;let R=Qn.getIndexedValues(T);if(R){w_&&S.prefetch(R.map(b=>({key:b,value:n})),C_);for(let b=0,C=R.length;b<C;b++)S.remove(R[b],n)}if(R=Qn.getIndexedValues(p),R){w_&&S.prefetch(R.map(b=>({key:b,value:n})),C_);for(let b=0,C=R.length;b<C;b++)S.put(R[b],n)}}let f=Object.assign({},_,r);c.put(n,f,f[Fi])},"do_put");return u?d=c.ifVersion(n,u.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:Mm(e,t,r,n,s,i,o))}a(Mm,"updateUpsertRecord");function J$(e,t,r){if(Qn.validateEnv(e),t===void 0)throw new Error(Bc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Bc.WRITE_ATTRIBUTES_REQUIRED):new Error(Bc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(J$,"validateBasic");function Pm(e,t,r,n){if(J$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Bc.RECORDS_REQUIRED):new Error(Bc.RECORDS_MUST_BE_ARRAY)}a(Pm,"validateWrite");function C_(){}a(C_,"noop");Ay.exports={insertRecords:Y$,updateRecords:Q$,upsertRecords:z$}});var ki=g((Eue,j$)=>{j$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var Jn=g((hue,yy)=>{"use strict";var by=z(),Oy=P(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zn=require("joi"),si={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},X$=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number(),zn.array()).required(),Z$=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number()),e1=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number()).required();function t1(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>si.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(t1,"checkValidTable");function r1(e,t){return by.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(r1,"validateSchemaExists");function n1(e,t){let r=t.state.ancestors[0].schema;return by.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(n1,"validateTableExists");function s1(e,t){return e.toLowerCase()===Oy.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Oy.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(s1,"validateSchemaName");yy.exports={common_validators:si,schema_regex:Ko,hdb_schema_table:X$,validateSchemaExists:r1,validateTableExists:n1,validateSchemaName:s1,checkValidTable:t1,hdb_database:Z$,hdb_table:e1}});var Xe=g((pue,Ny)=>{"use strict";var dr=require("validate.js");dr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||dr.validators.type.checks[t](e)?null:` must be a '${t}' value`};dr.validators.type.checks={Object:function(e){return dr.isObject(e)&&!dr.isArray(e)},Array:dr.isArray,Integer:dr.isInteger,Number:dr.isNumber,String:dr.isString,Date:dr.isDate,Boolean:function(e){return typeof e=="boolean"}};dr.validators.hasValidFileExt=function(e,t){return dr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};Ny.exports={validateObject:i1,validateObjectAsync:o1,validateBySchema:a1};function i1(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=dr(e,t,{format:"flat"});return r?new Error(r):null}a(i1,"validateObject");async function o1(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await dr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(o1,"validateObjectAsync");function a1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(a1,"validateBySchema")});var D_=g((Tue,Iy)=>{var{common_validators:jn}=Jn(),xc=Xe(),Hc="is required",gt={database:{presence:!1,format:jn.schema_format,length:jn.schema_length},schema:{presence:!1,format:jn.schema_format,length:jn.schema_length},table:{presence:!0,format:jn.schema_format,length:jn.schema_length},attribute:{presence:!0,format:jn.schema_format,length:jn.schema_length},hash_attribute:{presence:!0,format:jn.schema_format,length:jn.schema_length}};function Gc(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(Gc,"makeAttributesStrings");function c1(e){return e=Gc(e),gt.table.presence=!1,gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(c1,"schema_object");function u1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(u1,"table_object");function l1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,xc.validateObject(e,gt)}a(l1,"create_table_object");function _1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence={message:Hc},gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(_1,"attribute_object");function d1(e){return e=Gc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(d1,"describe_table");function f1(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(f1,"validateTableResidence");Iy.exports={schema_object:c1,create_table_object:l1,table_object:u1,attribute_object:_1,describe_table:d1,validateTableResidence:f1}});var Cy=g((Rue,wy)=>{"use strict";var E1=require("uuid"),Um=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||E1.v4(),this.schema_table=`${this.schema}.${this.table}`}};wy.exports=Um});var L_=g((Oue,Dy)=>{"use strict";var h1=Cy(),vm=class extends h1{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}};Dy.exports=vm});var My=g((yue,Ly)=>{"use strict";Ly.exports=p1;var m1="inserted";function p1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===m1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(p1,"returnObject")});var M_=g((Iue,Hy)=>{"use strict";var S1=P(),Bm=Qe(),T1=Yo(),{getSystemSchemaPath:g1,getSchemaPath:R1}=je(),A1=ki(),O1=D_(),b1=L_(),y1=My(),{handleHDBError:Py,hdb_errors:vy}=ne(),Uy=z(),{HTTP_STATUS_CODES:N1}=vy,Hm=A1.hdb_attribute,By=[];for(let e=0;e<Hm.attributes.length;e++)By.push(Hm.attributes[e].attribute);var I1="inserted";Hy.exports=w1;async function w1(e){let t=O1.attribute_object(e);if(t)throw Py(new Error,t.message,vy.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Uy.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Py(new Error,r,N1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Uy.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 b1(e.schema,e.table,e.attribute,e.id);try{let i=await Bm.openEnvironment(R1(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(g1(),S1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await T1.insertRecords(o,Hm.hash_attribute,By,[s]);return y1(I1,c,{records:[s]},u)}catch(i){throw i}}a(w1,"lmdbCreateAttribute")});var Gm=g((Cue,Gy)=>{var{hdb_table:C1,hdb_database:xy}=Jn(),D1=Xe(),xm=require("joi"),L1={undefined:"undefined",null:"null"},M1=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||L1[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"),P1=xm.object({database:xy,schema:xy,table:C1,records:xm.array().items(xm.object().custom(M1)).required()});Gy.exports=function(e){return D1.validateBySchema(e,P1)}});var qc=g((Mue,Fy)=>{"use strict";var Rs=z(),qy=$(),Lue=Gm(),{getDatabases:U1}=(Ae(),ie(ke)),{ClientError:Vi}=ne();Fy.exports=v1;function v1(e){if(Rs.isEmpty(e))throw new Vi("invalid update parameters defined.");if(Rs.isEmptyOrZeroLength(e.schema))throw new Vi("invalid schema specified.");if(Rs.isEmptyOrZeroLength(e.table))throw new Vi("invalid table specified.");if(!Array.isArray(e.records))throw new Vi("records must be an array");let t=U1()[e.schema]?.[e.table];if(Rs.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&&Rs.isEmptyOrZeroLength(o[r]))throw qy.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(!Rs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw qy.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`);!Rs.isEmpty(o[r])&&o[r]!==""&&n.has(Rs.autoCast(o[r]))&&(o.skip=!0),n.add(Rs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(v1,"insertUpdateValidate")});var Fc=g((Uue,ky)=>{"use strict";var B1=P().OPERATIONS_ENUM,qm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=B1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};ky.exports=qm});var kc=g((Hue,$y)=>{"use strict";var Bue=Fc(),P_=P(),Fm=z(),Vy=$(),H1=require("uuid"),{handleHDBError:U_,hdb_errors:x1}=ne(),{HDB_ERROR_MSGS:v_,HTTP_STATUS_CODES:B_}=x1;$y.exports=G1;function G1(e,t,r){for(let s=0;s<t.length;s++)q1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];F1(i,r,e.operation)}}a(G1,"processRows");function q1(e){if(Buffer.byteLength(String(e))>P_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw U_(new Error,v_.ATTR_NAME_LENGTH_ERR(e),B_.BAD_REQUEST,void 0,void 0,!0);if(Fm.isEmptyOrZeroLength(e)||Fm.isEmpty(e.trim()))throw U_(new Error,v_.ATTR_NAME_NULLISH_ERR,B_.BAD_REQUEST,void 0,void 0,!0)}a(q1,"validateAttribute");function F1(e,t,r){if(!e.hasOwnProperty(t)||Fm.isEmptyOrZeroLength(e[t])){if(r===P_.OPERATIONS_ENUM.INSERT||r===P_.OPERATIONS_ENUM.UPSERT){e[t]=H1.v4();return}throw Vy.error("Update transaction aborted due to record with no hash value:",e),U_(new Error,v_.RECORD_MISSING_HASH_ERR,B_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>P_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Vy.error(e),U_(new Error,v_.HASH_VAL_LENGTH_ERR,B_.BAD_REQUEST,void 0,void 0,!0)}a(F1,"validateHash")});var Ky=g((Gue,Yy)=>{"use strict";var km=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Yy.exports=km});var zy=g((Fue,Qy)=>{"use strict";var Vm=Qe(),k1=$(),Wy=Ur().LMDB_ERRORS_ENUM;Qy.exports=V1;async function V1(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 Vm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Wy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await Vm.closeEnvironment(global.lmdb_map[n]),await Vm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Wy.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){k1.error(t)}}a(V1,"cleanLMDBMap")});var As=g((Vue,Zy)=>{"use strict";var Vc=require("crypto"),$1=Z(),{CONFIG_PARAMS:Y1}=P(),jy="aes-256-cbc",K1=32,W1=16,$m=64,Xy=32,Q1=$m+Xy,Jy=new Map;Zy.exports={encrypt:z1,decrypt:J1,createNatsTableStreamName:j1};function z1(e){let t=Vc.randomBytes(K1),r=Vc.randomBytes(W1),n=Vc.createCipheriv(jy,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(z1,"encrypt");function J1(e){let t=e.substr(0,$m),r=e.substr($m,Xy),n=e.substr(Q1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Vc.createDecipheriv(jy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(J1,"decrypt");function j1(e,t){let r=$1.get(Y1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Jy.get(r);return n||(n=Vc.createHash("md5").update(r).digest("hex"),Jy.set(r,n)),n}a(j1,"createNatsTableStreamName")});var Os=g((Kue,tN)=>{"use strict";var Yue=Gr(),$c=$(),eN=D_(),X1=As(),H_=z(),{handleHDBError:x_,hdb_errors:Z1}=ne(),{HDB_ERROR_MSGS:G_,HTTP_STATUS_CODES:Ym}=Z1,eY=Z();eY.initSync();var{getDatabases:Km}=(Ae(),ie(ke)),tY=require("fs-extra");tN.exports={describeAll:rY,describeTable:q_,describeSchema:nY};async function rY(e){try{let t=H_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Km(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let E in d)try{let f;if(t||n)f=await q_({schema:l,table:E,exact_count:u});else if(r&&r[l].describe&&r[l].tables[E].describe){let h=r[l].tables[E].attribute_permissions;f=await q_({schema:l,table:E,exact_count:u},h)}f&&c.push(f)}catch(f){$c.error(f)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return $c.error("Got an error in describeAll"),$c.error(t),x_(new Error,G_.DESCRIBE_ALL_ERR)}}a(rY,"describeAll");async function q_(e,t){H_.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=eN.describe_table(e);if(i)throw i;let c=Km()[r];if(!c)throw x_(new Error,G_.SCHEMA_NOT_FOUND(e.schema),Ym.NOT_FOUND);let u=c[n];if(!u)throw x_(new Error,G_.TABLE_NOT_FOUND(e.schema,e.table),Ym.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(h=>({type:h.type,name:h.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(h=>{h.describe&&(f[h.attribute_name]=!0)}),u.attributes.forEach(h=>{f[h.name]&&_(h)})}else u.attributes?.forEach(f=>_(f));let d;try{d=(await tY.stat(u.primaryStore.env.path)).size}catch(f){$c.warn("unable to get database size",f)}let E={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,db_size:d};E.clustering_stream_name=X1.createNatsTableStreamName(E.schema,E.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});E.record_count=f.recordCount,E.estimated_record_range=f.estimatedRange;let h=u.auditStore;if(h)for(let p of h.getKeys({reverse:!0,limit:1}))E.last_updated_record=p[0];if(!E.last_updated_record&&u.indices.__updatedtime__)for(let p of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))E.last_updated_record=p}catch(f){$c.warn(`unable to stat table dbi due to ${f}`)}return E}a(q_,"descTable");async function nY(e){H_.transformReq(e);let t=eN.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=Km()[n];if(!i)throw x_(new Error,G_.SCHEMA_NOT_FOUND(e.schema),Ym.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),H_.isEmpty(u)||u.describe){let _=await q_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(nY,"describeSchema")});var bs=g((Jue,oN)=>{var sY=ki(),{callbackify:nN,promisify:iY}=require("util"),{getDatabases:sN}=(Ae(),ie(ke));oN.exports={setSchemaDataToGlobal:rN,getTableSchema:oY,getSystemSchema:aY,setSchemaDataToGlobalAsync:iY(rN)};var iN=Os(),Que=nN(iN.describeAll),zue=nN(iN.describeTable);function rN(e){global.hdb_schema=sN(),e&&e()}a(rN,"setSchemaDataToGlobal");function oY(e,t,r){let n=sN()[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(oY,"getTableSchema");function aY(){return sY}a(aY,"getSystemSchema")});var qr=g((Xue,lN)=>{"use strict";var k_=Gm(),Yt=z(),cY=require("util"),V_=Cn(),uY=bs(),aN=$(),{handleHDBError:$i,hdb_errors:lY}=ne(),{HTTP_STATUS_CODES:Yi}=lY,_Y=cY.promisify(uY.getTableSchema),dY="updated",cN="inserted",uN="upserted";lN.exports={insert:EY,update:hY,upsert:mY,validation:fY,flush:pY};async function fY(e){if(Yt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Yt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Yt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await _Y(e.schema,e.table),r=k_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Yt.isEmptyOrZeroLength(c[n]))throw aN.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!Yt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw aN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Yt.isEmpty(c[n])&&c[n]!==""&&s.has(Yt.autoCast(c[n]))&&(c.skip=!0),s.add(Yt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(fY,"validation");async function EY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=k_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await V_.createRecords(e);return F_(cN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(EY,"insertData");async function hY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=k_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await V_.updateRecords(e);return Yt.isEmpty(n.existing_rows)?F_(dY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):F_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(hY,"updateData");async function mY(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=k_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await V_.upsertRecords(e);return F_(uN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(mY,"upsertData");function F_(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===cN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===uN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(F_,"returnObject");function pY(e){return Yt.transformReq(e),V_.flush(e.schema,e.table)}a(pY,"flush")});var Qm=g((ele,fN)=>{var SY=Xe(),Wm=require("joi"),{hdb_table:TY,hdb_database:_N}=Jn(),dN={schema:_N,database:_N,table:TY},gY={date:Wm.date().iso().required()},RY={timestamp:Wm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};fN.exports=function(e,t){let r=t==="timestamp"?{...dN,...RY}:{...dN,...gY},n=Wm.object(r);return SY.validateBySchema(e,n)}});var mN=g((tle,hN)=>{var AY=Xe(),zm=require("joi"),{hdb_table:OY,hdb_database:EN}=Jn(),bY=zm.object({schema:EN,database:EN,table:OY,hash_values:zm.array().required(),ids:zm.array()});hN.exports=function(e){return AY.validateBySchema(e,bY)}});var SN=g((rle,pN)=>{"use strict";var Jm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},jm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Xm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};pN.exports={InsertObject:Jm,NoSQLSeachObject:jm,DeleteResponseObject:Xm}});var ai=g((sle,ON)=>{"use strict";var gN=Qm(),yY=mN(),Ki=z(),TN=require("moment"),RN=$(),{promisify:NY,callbackify:IY}=require("util"),Wi=P(),wY=bs(),Zm=NY(wY.getTableSchema),ep=Cn(),{DeleteResponseObject:CY}=SN(),{handleHDBError:ii,hdb_errors:DY}=ne(),{HDB_ERROR_MSGS:$_,HTTP_STATUS_CODES:oi}=DY,LY="records successfully deleted",MY=IY(AN);ON.exports={delete:MY,deleteRecord:AN,deleteFilesBefore:PY,deleteAuditLogsBefore:UY};async function PY(e){let t=gN(e,"date");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!TN(e.date,TN.ISO_8601).isValid())throw ii(new Error,$_.INVALID_DATE,oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,$_.INVALID_DATE,!0);let n=Ki.checkSchemaTableExist(e.schema,e.table);if(n)throw ii(new Error,n,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,n,!0);let s=await ep.deleteRecordsBefore(e);if(await Zm(e.schema,e.table),RN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(PY,"deleteFilesBefore");async function UY(e){let t=gN(e,"timestamp");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw ii(new Error,$_.INVALID_VALUE("Timestamp"),oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,$_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let n=await ep.deleteAuditLogsBefore(e);return await Zm(e.schema,e.table),RN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(UY,"deleteAuditLogsBefore");async function AN(e){e.ids&&(e.hash_values=e.ids);let t=yY(e);if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await Zm(e.schema,e.table);let n=await ep.deleteRecords(e);return Ki.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${LY}`),n}catch(n){if(n.message===Wi.SEARCH_NOT_FOUND_MESSAGE){let s=new CY;return s.message=Wi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(AN,"deleteRecord")});var Y_=g((ole,NN)=>{var vY=require("crypto"),bN=9;function BY(e){let t=xY(bN),r=yN(e+t);return t+r}a(BY,"createHash");function HY(e,t){let r=e?.substr(0,bN),n=r+yN(t+r);return e===n}a(HY,"validateHash");function xY(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(xY,"generateSalt");function yN(e){return vY.createHash("md5").update(e).digest("hex")}a(yN,"md5");NN.exports={hash:BY,validate:HY}});var wN=g((cle,IN)=>{var tp=Xe(),Zt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function GY(e){return Zt.password.presence=!0,Zt.username.presence=!0,Zt.role.presence=!0,Zt.active.presence=!0,tp.validateObject(e,Zt)}a(GY,"addUserValidation");function qY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,tp.validateObject(e,Zt)}a(qY,"alterUserValidation");function FY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,tp.validateObject(e,Zt)}a(FY,"dropUserValidation");IN.exports={addUserValidation:GY,alterUserValidation:qY,dropUserValidation:FY}});var Ve=g((_le,DN)=>{"use strict";var{platform:lle}=require("os"),kY="nats-server.zip",rp="nats-server",VY=process.platform==="win32"?`${rp}.exe`:rp,$Y=/^[^\s.,*>]+$/,CN="__request__",YY=a(e=>`${e}.${CN}`,"REQUEST_SUBJECT"),KY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},WY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},QY={HUB:"hub.pid",LEAF:"leaf.pid"},zY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},JY={SUCCESS:"success",ERROR:"error"},jY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},XY={TXN:"txn",MSGID:"msgid"},Wo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},ZY={[Wo.ERR]:1,[Wo.WRN]:2,[Wo.INF]:3,[Wo.DBG]:4,[Wo.TRC]:5},eK={debug:"-D",trace:"-DVV"};DN.exports={NATS_SERVER_ZIP:kY,NATS_SERVER_NAME:rp,NATS_BINARY_NAME:VY,PID_FILES:QY,NATS_CONFIG_FILES:WY,SERVER_SUFFIX:zY,NATS_TERM_CONSTRAINTS_RX:$Y,REQUEST_SUFFIX:CN,UPDATE_REMOTE_RESPONSE_STATUSES:JY,CLUSTER_STATUS_STATUSES:jY,REQUEST_SUBJECT:YY,SUBJECT_PREFIXES:XY,MSG_HEADERS:KY,LOG_LEVELS:Wo,LOG_LEVEL_FLAGS:eK,LOG_LEVEL_HIERARCHY:ZY}});var MN=g((fle,LN)=>{"use strict";var tK={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 Mq=Object.create;var dc=Object.defineProperty;var Pq=Object.getOwnPropertyDescriptor;var Uq=Object.getOwnPropertyNames;var vq=Object.getPrototypeOf,Bq=Object.prototype.hasOwnProperty;var a=(e,t)=>dc(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fe=(e,t)=>{for(var r in t)dc(e,r,{get:t[r],enumerable:!0})},EO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Uq(t))!Bq.call(e,s)&&s!==r&&dc(e,s,{get:()=>t[s],enumerable:!(n=Pq(t,s))||n.enumerable});return e};var x=(e,t,r)=>(r=e!=null?Mq(vq(e)):{},EO(t||!e||!e.__esModule?dc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>EO(dc({},"__esModule",{value:!0}),e);var pO=g((cce,mO)=>{var xq=require("fast-glob"),{statSync:Mh,existsSync:Ph,readFileSync:Hq,writeFileSync:Gq}=require("fs"),{spawnSync:qq,spawn:Fq,execFileSync:ace}=require("child_process"),{isMainThread:kq}=require("worker_threads"),{join:Zs,relative:hO}=require("path"),{PACKAGE_ROOT:yn}=P(),{tmpdir:Vq,platform:$q}=require("os");require("source-map-support").install();var Yq=["resources","server","dataLayer","components"],fc="ts-build",Uh,Kq=__filename.endsWith("tsBuild.js");if(Kq){if(kq){let r;try{Mh(Zs(yn,fc)),r=!0}catch{}if(r)for(let n of xq.sync(Yq.map(s=>s+"/**/*.ts"),{cwd:yn})){let s=0,i=0;try{s=Mh(Zs(yn,n)).mtimeMs-5e3,i=Mh(Zs(yn,fc,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."),Uh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Uh=!0;if(Uh){let n=Zs(yn,"node_modules/.bin/tsc");$q()==="win32"&&(n+=".cmd");let s=qq(n,{cwd:yn});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Zs(Vq(),"harperdb-tsc.pid"),o;if(Ph(i))try{process.kill(+Hq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Fq(n,["--watch"],{cwd:yn,detached:!0,stdio:"ignore"});Gq(i,c.pid.toString()),c.unref()}}}}let e=mO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(yn)&&!n[0].includes("node_modules")){let i=hO(yn,n[0]),o;i.startsWith(fc)?o=Zs(yn,hO(fc,i)):o=Zs(yn,fc,i);let c=Zs(o,r),u=c+".js";if(Ph(u))return u;if(c.includes(".")&&Ph(c))return c}return t(r,n,s)}}});var P=g((_ce,LO)=>{"use strict";var an=require("path"),Wq=require("fs"),{relative:uce,join:lce}=an,{existsSync:Qq}=Wq;function zq(){let e=__dirname;for(;!Qq(an.join(e,"package.json"));){let t=an.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(zq,"getHDBPackageRoot");var ei=zq(),SO="js",o_=SO,Jq="harperdb-config.yaml",jq="defaultConfig.yaml",Xq="hdb",TO=`harperdb.${o_}`,gO=`customFunctionsServer.${o_}`,Zq=`restartHdb.${o_}`,Bh="HarperDB",i_="Custom Functions",a_="Clustering Hub",c_="Clustering Leaf",eF="Clustering Ingest Service",tF="Clustering Reply Service",rF="foreground.pid",nF="hdb.pid",sF="data",iF={HDB:Bh,CLUSTERING_HUB:a_,CLUSTERING_LEAF:c_,CLUSTERING_INGEST_SERVICE:eF,CLUSTERING_REPLY_SERVICE:tF,CUSTOM_FUNCTIONS:i_,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"},oF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},aF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},cF={harperdb:Bh,"clustering hub":a_,"clustering leaf":c_,"custom functions":i_,custom_functions:i_,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},uF={CLUSTERING_HUB_PROC_DESCRIPTOR:a_,CLUSTERING_LEAF_PROC_DESCRIPTOR:c_},vh={HDB:an.join(ei,"server/harperdb"),CUSTOM_FUNCTIONS:an.join(ei,"server/customFunctions"),CLUSTERING_HUB:an.join(ei,"server/nats"),CLUSTERING_LEAF:an.join(ei,"server/nats")},lF={HDB:an.join(vh.HDB,TO),CUSTOM_FUNCTIONS:an.join(vh.CUSTOM_FUNCTIONS,gO)},_F={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:an.join(ei,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:an.join(ei,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:an.join(ei,"launchServiceScripts/launchUpdateNodes4-0-0.js")},dF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},RO="support@harperdb.io",fF="customer-success@harperdb.io",AO=1,EF=4141,OO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",hF="https://www.harperdb.io/product",mF=`For support, please submit a request at ${OO} or contact ${RO}`,bO=`For license support, please contact ${fF}`,pF="None of the specified records were found.",SF="hash attribute not found",TF=`Your current license only supports ${AO} role. ${bO}`,gF="Your current license only supports 3 connections to a node.",RF="127.0.0.1",AF=1,OF=/^\.$/,bF=/^\.\.$/,yF="U+002E",NF=/\//g,IF="U+002F",wF=/U\+002F/g,CF=/^U\+002E$/,DF=/^U\+002EU\+002E$/,LF="d",MF=999999,PF="*",UF="--max-old-space-size=",vF="system",BF="__hdb_hash",xF=".harperdb",HF=".hdb",GF="keys",qF="hdb_boot_properties.file",FF=".updateConfig.json",kF="SIGTSTP",VF=24,$F=6e4,YF=448,KF="blob",WF="trash",QF="database",zF="schema",JF="transactions",jF=".count",XF="id",ZF="PROCESS_NAME",yO={SETTINGS_PATH_KEY:"settings_path"},NO=require("lodash"),ek={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"},tk={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},rk={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},nk={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"},sk={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},Pr="hdb_internal:",ik={CREATE_SCHEMA:Pr+"create_schema",CREATE_TABLE:Pr+"create_table",CREATE_ATTRIBUTE:Pr+"create_attribute",ADD_USER:Pr+"add_user",ALTER_USER:Pr+"alter_user",DROP_USER:Pr+"drop_user",HDB_NODES:Pr+"hdb_nodes",HDB_USERS:Pr+"hdb_users",HDB_WORKERS:Pr+"hdb_workers",CATCHUP:Pr+"catchup",SCHEMA_CATCHUP:Pr+"schema_catchup",WORKER_ROOM:Pr+"cluster_workers"},ok={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"},ak="060493.ks",ck=".license",uk={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},te={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"},lk={CSV:".csv",JSON:".json"},_k={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},dk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Ec={};Ec[te.INSERT]=te.INSERT;Ec[te.UPDATE]=te.UPDATE;Ec[te.UPSERT]=te.UPSERT;Ec[te.DELETE]=te.DELETE;var Ge=Object.create(null);Ge[te.DESCRIBE_ALL]=te.DESCRIBE_ALL;Ge[te.DESCRIBE_TABLE]=te.DESCRIBE_TABLE;Ge[te.DESCRIBE_SCHEMA]=te.DESCRIBE_SCHEMA;Ge[te.READ_LOG]=te.READ_LOG;Ge[te.ADD_NODE]=te.ADD_NODE;Ge[te.LIST_USERS]=te.LIST_USERS;Ge[te.LIST_ROLES]=te.LIST_ROLES;Ge[te.USER_INFO]=te.USER_INFO;Ge[te.SQL]=te.SQL;Ge[te.GET_JOB]=te.GET_JOB;Ge[te.SEARCH_JOBS_BY_START_DATE]=te.SEARCH_JOBS_BY_START_DATE;Ge[te.DELETE_FILES_BEFORE]=te.DELETE_FILES_BEFORE;Ge[te.EXPORT_LOCAL]=te.EXPORT_LOCAL;Ge[te.EXPORT_TO_S3]=te.EXPORT_TO_S3;Ge[te.CLUSTER_STATUS]=te.CLUSTER_STATUS;Ge[te.REMOVE_NODE]=te.REMOVE_NODE;Ge[te.RESTART]=te.RESTART;Ge[te.CUSTOM_FUNCTIONS_STATUS]=te.CUSTOM_FUNCTIONS_STATUS;Ge[te.GET_CUSTOM_FUNCTIONS]=te.GET_CUSTOM_FUNCTIONS;Ge[te.GET_CUSTOM_FUNCTION]=te.GET_CUSTOM_FUNCTION;Ge[te.SET_CUSTOM_FUNCTION]=te.SET_CUSTOM_FUNCTION;Ge[te.DROP_CUSTOM_FUNCTION]=te.DROP_CUSTOM_FUNCTION;Ge[te.ADD_CUSTOM_FUNCTION_PROJECT]=te.ADD_CUSTOM_FUNCTION_PROJECT;Ge[te.DROP_CUSTOM_FUNCTION_PROJECT]=te.DROP_CUSTOM_FUNCTION_PROJECT;Ge[te.PACKAGE_CUSTOM_FUNCTION_PROJECT]=te.PACKAGE_CUSTOM_FUNCTION_PROJECT;Ge[te.DEPLOY_CUSTOM_FUNCTION_PROJECT]=te.DEPLOY_CUSTOM_FUNCTION_PROJECT;var fk={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"},Ek={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},IO={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"},hk=NO.invert(IO),mk={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",HTTP_THREADRANGE:"http_threadRange",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS:"operationsApi_tls",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers",TLS:"tls",CLONED:"cloned"},wO={settings_path:yO.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,customfunctions_tls:w.TLS,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,http_maxheadersize:w.HTTP_MAXHEADERSIZE,http_threadrange:w.HTTP_THREADRANGE,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:w.OPERATIONSAPI_TLS,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,storage_maxtransactionqueuetime:w.STORAGE_MAXTRANSACTIONQUEUETIME,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:w.TLS,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];wO[t.toLowerCase()]=t}var pk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Sk={csv_file_load:"csv_file_load",csv_data_load:te.CSV_DATA_LOAD,csv_url_load:te.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3",restart_service:"restart_service"},Tk={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"},gk={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Rk={VERSION_DEFAULT:"2.2.0"},Ak={DEVELOPMENT:8192,DEFAULT:512},Ok={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"},bk={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"},yk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},CO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Nk=Symbol("metadata"),Ik="__clustering__",wk=Object.values(CO),Ck=15984864e5,DO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Dk=NO.invert(DO),Lk={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"},Mk=111,Pk=`\r
|
|
2
|
+
`,Uk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},vk=["*","%"],Bk="unauthorized_access",xk="func_val",Hk={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Gk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},qk={SHUTDOWN:"shutdown",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request",METRICS:"metrics",GET_METRICS:"get_metrics",RESTART:"restart",START_JOB:"start_job",NATS_CONSUMER_UPDATE:"nats_consumer_update"},Fk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},kk={HTTP:"http"},Vk={STOPPED:"stopped",ONLINE:"online"},$k="3.x.x",Yk={SUCCESS:"success",FAILURE:"failure"},Kk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};LO.exports={LOCAL_HARPERDB_OPERATIONS:Ge,HDB_SUPPORT_ADDRESS:RO,HDB_SUPPORT_URL:OO,HDB_PRICING_URL:hF,SUPPORT_HELP_MSG:mF,LICENSE_HELP_MSG:bO,HDB_PROC_NAME:TO,HDB_PROC_DESCRIPTOR:Bh,CLUSTERING_LEAF_PROC_DESCRIPTOR:c_,CLUSTERING_HUB_PROC_DESCRIPTOR:a_,SYSTEM_SCHEMA_NAME:vF,HASH_FOLDER_NAME:BF,HDB_HOME_DIR_NAME:xF,UPDATE_FILE_NAME:FF,LICENSE_KEY_DIR_NAME:GF,BOOT_PROPS_FILE_NAME:qF,JOB_TYPE_ENUM:Sk,JOB_STATUS_ENUM:uk,SYSTEM_TABLE_NAMES:nk,SYSTEM_TABLE_HASH_ATTRIBUTES:sk,OPERATIONS_ENUM:te,VALID_S3_FILE_TYPES:lk,S3_BUCKET_AUTH_KEYS:_k,VALID_SQL_OPS_ENUM:dk,GEO_CONVERSION_ENUM:Ek,HDB_SETTINGS_NAMES:IO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:hk,SERVICE_ACTIONS_ENUM:fk,CLUSTER_MESSAGE_TYPE_ENUM:Tk,CLUSTER_CONNECTION_DIRECTION_ENUM:gk,CLUSTER_EVENTS_DEFS_ENUM:Ok,PERIOD_REGEX:OF,DOUBLE_PERIOD_REGEX:bF,UNICODE_PERIOD:yF,FORWARD_SLASH_REGEX:NF,UNICODE_FORWARD_SLASH:IF,ESCAPED_FORWARD_SLASH_REGEX:wF,ESCAPED_PERIOD_REGEX:CF,ESCAPED_DOUBLE_PERIOD_REGEX:DF,REG_KEY_FILE_NAME:ak,RESTART_TIMEOUT_MS:$F,HDB_FILE_PERMISSIONS:YF,DATABASES_DIR_NAME:QF,LEGACY_DATABASES_DIR_NAME:zF,TRANSACTIONS_DIR_NAME:JF,LIMIT_COUNT_NAME:jF,ID_ATTRIBUTE_STRING:XF,INSERT_MODULE_ENUM:tk,UPGRADE_JSON_FIELD_NAMES_ENUM:rk,RESTART_CODE:kF,RESTART_CODE_NUM:VF,CLUSTER_OPERATIONS:Ec,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:ok,HDB_INTERNAL_SC_CHANNEL_PREFIX:Pr,INTERNAL_SC_CHANNELS:ik,CLUSTERING_MESSAGE_TYPES:Lk,HDB_FILE_SUFFIX:HF,BLOB_FOLDER_NAME:KF,HDB_TRASH_DIR:WF,ORIGINATOR_SET_VALUE:Mk,LICENSE_VALUES:Rk,RAM_ALLOCATION_ENUM:Ak,TIME_STAMP_NAMES_ENUM:CO,TIME_STAMP_NAMES:wk,PERMS_UPDATE_RELEASE_TIMESTAMP:Ck,SEARCH_NOT_FOUND_MESSAGE:pF,SEARCH_ATTRIBUTE_NOT_FOUND:SF,LICENSE_ROLE_DENIED_RESPONSE:TF,LICENSE_MAX_CONNS_REACHED:gF,BASIC_LICENSE_MAX_NON_CU_ROLES:AO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:EF,VALUE_SEARCH_COMPARATORS:DO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Dk,LICENSE_FILE_NAME:ck,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:bk,NEW_LINE:Pk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:AF,MOMENT_DAYS_TAG:LF,API_TURNOVER_SEC:MF,LOOPBACK:RF,CODE_EXTENSION:o_,WILDCARD_SEARCH_VALUE:PF,NODE_ERROR_CODES:yk,JAVASCRIPT_EXTENSION:SO,PERMS_CRUD_ENUM:Uk,UNAUTHORIZED_PERMISSION_NAME:Bk,SEARCH_WILDCARDS:vk,FUNC_VAL:xk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Hk,JWT_ENUM:Gk,CLUSTERING_FLAG:Ik,ITC_EVENT_TYPES:qk,CUSTOM_FUNCTION_PROC_NAME:gO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:i_,SERVICES:Fk,THREAD_TYPES:kk,MEM_SETTING_KEY:UF,HDB_RESTART_SCRIPT:Zq,PROCESS_DESCRIPTORS:iF,SERVICE_SERVERS:lF,SERVICE_SERVERS_CWD:vh,PROCESS_DESCRIPTORS_VALIDATE:cF,LAUNCH_SERVICE_SCRIPTS:_F,LOG_LEVELS:aF,PROCESS_NAME_ENV_PROP:ZF,LOG_NAMES:oF,PM2_PROCESS_STATUSES:Vk,CONFIG_PARAM_MAP:wO,CONFIG_PARAMS:w,HDB_CONFIG_FILE:Jq,HDB_DEFAULT_CONFIG_FILE:jq,ROLE_TYPES_ENUM:dF,BOOT_PROP_PARAMS:yO,INSTALL_PROMPTS:ek,HDB_ROOT_DIR_NAME:Xq,CLUSTERING_PROCESSES:uF,FOREGROUND_PID_FILE:rF,PACKAGE_ROOT:ei,PRE_4_0_0_VERSION:$k,DATABASES_PARAM_CONFIG:pk,METADATA_PROPERTY:Nk,AUTH_AUDIT_STATUS:Yk,AUTH_AUDIT_TYPES:Kk,HDB_PID_FILE:nF,DEFAULT_DATABASE_NAME:sF,LEGACY_CONFIG_PARAMS:mk};pO()});var xh=g((fce,UO)=>{"use strict";var MO=require("minimist");UO.exports=Wk;function Wk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=PO(process.env),n=PO(MO(process.argv))):(r=process.env,n=MO(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(Wk,"assignCMDENVVariables");function PO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(PO,"objKeysToLowerCase")});var $=g((hce,$h)=>{"use strict";var xi=require("fs-extra"),{workerData:Qk,threadId:zk}=require("worker_threads"),Ss=require("path"),xO=require("yaml"),HO=require("properties-reader"),Tt=P(),vO=xh(),Jk=require("os"),{PACKAGE_ROOT:Gh}=P(),{_assignPackageExport:jk}=require("../index"),mc={};for(let e in console)mc[e]||(mc[e]=console[e]);var cr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},GO={STDOUT:"stdOut",STDERR:"stdErr"},Xk=Ss.join(Gh,"logs"),Zk=Ss.join(Gh,"config/yaml/",Tt.HDB_DEFAULT_CONFIG_FILE),eV=1e4,ps,Wn,ar,u_,l_,pc,ko,hc;hc===void 0&&qO();$h.exports={notify:VO,fatal:$O,error:Sc,warn:Vh,info:__,debug:kh,trace:Fh,setLogLevel:aV,log_level:ar,loggerWithTag:tV,suppressLogging:rV,initLogSettings:qO,setupConsoleLogging:FO,logCustomLevel:iV,closeLogFile:qh,getLogFilePath:()=>pc,OUTPUTS:GO,AuthAuditLog:lV};jk("logger",$h.exports);function qO(e=!1){try{if(hc===void 0||e){qh();let t=oV(),r=vO(["ROOTPATH"]);try{hc=HO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!xi.pathExistsSync(Ss.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE)))throw n}({level:ar,config_log_path:l_,to_file:ps,to_stream:Wn}=cV(r.ROOTPATH?Ss.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE):hc.get("settings_path"))),u_=Tt.LOG_NAMES.HDB,pc=Ss.join(l_,u_)}}catch(t){if(hc=void 0,t.code===Tt.NODE_ERROR_CODES.ENOENT||t.code===Tt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=vO(Object.keys(Tt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Tt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Tt.CONFIG_PARAMS.LOGGING_LEVEL){ar=u;continue}if(c===Tt.CONFIG_PARAMS.LOGGING_STDSTREAMS){Wn=u;continue}c===Tt.CONFIG_PARAMS.LOGGING_FILE&&(ps=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=uV();ps=ps===void 0?s:ps,ps=BO(ps),Wn=Wn===void 0?i:Wn,Wn=BO(Wn),ar=ar===void 0?n:ar,l_=Xk,u_=Tt.LOG_NAMES.INSTALL,pc=Ss.join(l_,u_);return}throw Sc("Error initializing log settings"),Sc(t),t}process.env.DEV_MODE&&(Wn=!0),FO()}a(qO,"initLogSettings");var Hh=!0;function FO(){Fo("error",Sc),Fo("warn",Vh),Fo("log",__),Fo("info",__),Fo("debug",kh),Fo("trace",Fh)}a(FO,"setupConsoleLogging");function Fo(e,t){console[e]=function(...r){if(Hh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return mc[e](...r)}}a(Fo,"logConsole");function tV(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(VO),fatal:r($O),error:r(Sc),warn:r(Vh),info:r(__),debug:r(kh),trace:r(Fh)};function r(n){return function(...s){return n(t,...s)}}}a(tV,"loggerWithTag");function rV(e){try{Hh=!1,e()}finally{Hh=!0}}a(rV,"suppressLogging");var nV=Qk?.name?.replace(/ /g,"-")||"main";function Ts(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||nV+"/"+zk);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
3
|
+
`}a(Ts,"createLogRecord");function Tc(e){ps&&kO(e),Wn&&process.stdout.write(e)}a(Tc,"logStdOut");function d_(e){ps&&kO(e),Wn&&process.stderr.write(e)}a(d_,"logStdErr");function kO(e){sV(),ko?xi.appendFileSync(ko,e):mc.log(e)}a(kO,"logToFile");function qh(){try{xi.closeSync(ko)}catch{}ko=null}a(qh,"closeLogFile");function sV(){if(!ko){try{if(!pc)debugger;ko=xi.openSync(pc,"a")}catch(e){mc.error(e)}setTimeout(()=>{qh()},eV).unref()}}a(sV,"openLogFile");function __(...e){cr[ar]<=cr.info&&Tc(Ts("info",e))}a(__,"info");function Fh(...e){cr[ar]<=cr.trace&&Tc(Ts("trace",e))}a(Fh,"trace");function Sc(...e){cr[ar]<=cr.error&&d_(Ts("error",e))}a(Sc,"error");function kh(...e){cr[ar]<=cr.debug&&Tc(Ts("debug",e))}a(kh,"debug");function VO(...e){cr[ar]<=cr.notify&&Tc(Ts("notify",e))}a(VO,"notify");function $O(...e){cr[ar]<=cr.fatal&&d_(Ts("fatal",e))}a($O,"fatal");function Vh(...e){cr[ar]<=cr.warn&&d_(Ts("warn",e))}a(Vh,"warn");function iV(e,t,...r){t===GO.STDERR?d_(Ts(e,r)):Tc(Ts(e,r))}a(iV,"logCustomLevel");function oV(){let e;try{e=Jk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Ss.join(e,Tt.HDB_HOME_DIR_NAME,Tt.BOOT_PROPS_FILE_NAME);return xi.existsSync(t)||(t=Ss.join(Gh,"utility/hdb_boot_properties.file")),t}a(oV,"getPropsFilePath");function aV(e){ar=e}a(aV,"setLogLevel");function BO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(BO,"autoCastBoolean");function cV(e){try{if(e.includes("config/settings.js")){let o=HO(e);return{level:o.get(Tt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Ss.dirname(o.get(Tt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=xO.parseDocument(xi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===Tt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(cV,"getLogConfig");function uV(){try{let e=xO.parseDocument(xi.readFileSync(Zk,"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(uV,"getDefaultConfig");function lV(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(lV,"AuthAuditLog")});var KO=g((pce,YO)=>{"use strict";var _V=require("util"),dV=require("path"),fV=require("child_process"),EV=_V.promisify(fV.execFile),hV=1e3*1e3*10;YO.exports={findPs:mV};async function mV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await EV("ps",["wwxo",`pid,${r}`],{maxBuffer:hV});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:dV.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(mV,"findPs")});var ft=g((Tce,QO)=>{"use strict";var pV="__dbis__",SV="__txns__",TV="__environment_name__",gV="__dbi_defintion__",RV={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__"],OV="\uFFFF",WO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},bV=Object.values(WO);QO.exports={AUDIT_STORE_NAME:SV,INTERNAL_DBIS_NAME:pV,DBI_DEFINITION_NAME:gV,SEARCH_TYPES:RV,TIMESTAMP_NAMES:AV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:TV,TRANSACTIONS_DBI_NAMES_ENUM:WO,TRANSACTIONS_DBIS:bV,OVERFLOW_MARKER:OV}});var Ur=g((gce,nb)=>{"use strict";var zO=P(),JO=ft(),jO={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},XO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),ZO={500:XO("There was an error processing your request."),400:"Invalid request"},yV=ZO[jO.INTERNAL_SERVER_ERROR],NV={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.`},IV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},wV={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"},CV={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 ${JO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${JO.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"},DV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${zO.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 ${zO.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"},eb={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"},LV={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."},MV={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`},PV={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"},UV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},vV={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`},tb={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.`},rb={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}`},BV={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."},xV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},HV={...eb,...wV,...NV,...LV,...MV,...PV,...UV,...vV,...DV,...tb,...rb,...BV,...xV,...IV};nb.exports={CHECK_LOGS_WRAPPER:XO,HDB_ERROR_MSGS:HV,DEFAULT_ERROR_MSGS:ZO,DEFAULT_ERROR_RESP:yV,HTTP_STATUS_CODES:jO,LMDB_ERRORS_ENUM:CV,AUTHENTICATION_ERROR_MSGS:eb,VALIDATION_ERROR_MSGS:tb,ITC_ERRORS:rb}});var se=g((Ace,ob)=>{"use strict";var Vo=Ur(),GV=$(),qV=P(),f_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,sb),this.statusCode=n||Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Vo.DEFAULT_ERROR_MSGS[n]?Vo.DEFAULT_ERROR_MSGS[n]:Vo.DEFAULT_ERROR_MSGS[Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&GV[s](i)}},Yh=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 sb(e,t,r,n=qV.LOG_LEVELS.ERROR,s=null,i=!1){if(ib(e))return e;let o=new f_(e,t,r,n,s);return i&&delete o.stack,o}a(sb,"handleHDBError");function ib(e){return e.__proto__.constructor.name===f_.name}a(ib,"isHDBError");ob.exports={isHDBError:ib,handleHDBError:sb,ClientError:Yh,ServerError:Kh,hdb_errors:Vo}});var je=g((bce,fb)=>{"use strict";var bc=P(),FV=z(),ur=ee(),yc=require("path"),kV=require("minimist"),ab=require("fs-extra"),cb=require("lodash");ur.initSync();var{CONFIG_PARAMS:ti,DATABASES_PARAM_CONFIG:gc,SYSTEM_SCHEMA_NAME:E_}=bc,Rc,Ac,Oc;function ub(){if(Rc!==void 0)return Rc;if(ur.getHdbBasePath()!==void 0)return Rc=ur.get(ti.STORAGE_PATH)||yc.join(ur.getHdbBasePath(),bc.DATABASES_DIR_NAME),Rc}a(ub,"getBaseSchemaPath");function lb(){if(Ac!==void 0)return Ac;if(ur.getHdbBasePath()!==void 0)return Ac=db(E_),Ac}a(lb,"getSystemSchemaPath");function _b(){if(Oc!==void 0)return Oc;if(ur.getHdbBasePath()!==void 0)return Oc=ur.get(bc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||yc.join(ur.getHdbBasePath(),bc.TRANSACTIONS_DIR_NAME),Oc}a(_b,"getTransactionAuditStoreBasePath");function VV(e,t){let r=ur.get(ti.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||yc.join(_b(),e.toString())}a(VV,"getTransactionAuditStorePath");function db(e,t){e=e.toString(),t=t&&t.toString();let r=ur.get(bc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||yc.join(ub(),e)}a(db,"getSchemaPath");function $V(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,kV(process.argv));let n=r[ti.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!FV.isObject(n))throw o;i=n}for(let o of i){let c=o[E_];if(!c)continue;let u=ur.get(ti.DATABASES);u=u??{};let _=c?.tables?.[t]?.[gc.PATH];if(_)return cb.set(u,[E_,gc.TABLES,t,gc.PATH],_),ur.setProperty(ti.DATABASES,u),_;let l=c?.[gc.PATH];if(l)return cb.set(u,[E_,gc.PATH],l),ur.setProperty(ti.DATABASES,u),l}}let s=r[ti.STORAGE_PATH.toUpperCase()];if(s){if(!ab.pathExistsSync(s))throw new Error(s+" does not exist");let i=yc.join(s,e);return ab.mkdirsSync(i),ur.setProperty(ti.STORAGE_PATH,s),i}return lb()}a($V,"initSystemSchemaPaths");function YV(){Rc=void 0,Ac=void 0,Oc=void 0}a(YV,"resetPaths");fb.exports={getBaseSchemaPath:ub,getSystemSchemaPath:lb,getTransactionAuditStorePath:VV,getTransactionAuditStoreBasePath:_b,getSchemaPath:db,initSystemSchemaPaths:$V,resetPaths:YV}});var vr=g((wce,Sb)=>{"use strict";var KV=Ur().LMDB_ERRORS_ENUM,Nce=require("lmdb"),WV=ft(),Ice=require("buffer").Buffer,{OVERFLOW_MARKER:Eb,MAX_SEARCH_KEY_LENGTH:h_}=WV,hb=["number","string","symbol","boolean","bigint"];function QV(e){if(e=e?.primaryStore||e,!e)throw new Error(KV.ENV_REQUIRED)}a(QV,"validateEnv");function zV(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(zV,"stringifyData");function JV(e){return e instanceof Date?e.valueOf():e}a(JV,"convertKeyValueToWrite");function jV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(hb.includes(typeof e))return e.length>h_?[e.slice(0,h_)+Eb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(hb.includes(typeof i))i.length>h_?r.push(i.slice(0,h_)+Eb):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(jV,"getIndexedValues");var m_=0,mb=0;function pb(){mb=Date.now()-performance.now()}a(pb,"adjustStartTime");pb();var XV=6e4;setInterval(pb,XV).unref();function ZV(){let e=performance.now()+mb;return e>m_?(m_=e,e):(m_+=488e-6,m_)}a(ZV,"getNextMonotonicTime");Sb.exports={validateEnv:QV,stringifyData:zV,convertKeyValueToWrite:JV,getNextMonotonicTime:ZV,getIndexedValues:jV}});var Tb,Nn,Wh,Nc=Re(()=>{Tb=require("events"),Nn=class extends Tb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new Wh;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(){let t=this.queue?.shift();return t||this.emit("drained"),t}waitForDrain(){return new Promise(t=>{!this.queue||this.queue.length===0?t(!0):(this.once("drained",()=>t(!0)),this.currentDrainResolver=t,this.drainCloseListener||(this.drainCloseListener=!0,this.on("close",()=>{this.currentDrainResolver?.(!1)})))})}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)}},Wh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Hi={};Fe(Hi,{server:()=>at});var gb,at,lr=Re(()=>{gb=require("../index"),at={};(0,gb._assignPackageExport)("server",at)});var Jh={};Fe(Jh,{loadGQLSchema:()=>r$,start:()=>zh,startOnMainThread:()=>t$});function zh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(U){if(U.kind==="NonNullType"){let Q=H(U.type);return Q.nullable=!1,Q}if(U.kind==="ListType")return{type:"array",elements:H(U.type)};let M={type:U.name?.value};return Object.defineProperty(M,"location",{value:U.loc.startToken}),M};a(H,"getProperty");let T=S.name.value,R=[],N={table:null,database:null,properties:R};E.set(T,N);for(let U of S.directives){if(U.name.value==="table"){for(let k of U.arguments)N[k.name.value]=k.value.value;N.schema&&(N.database=N.schema),N.table||(N.table=T),N.audit&&(N.audit=N.audit!=="false"),N.attributes=N.properties,f.push(N)}if(U.name.value==="sealed"&&(N.sealed=!0),U.name.value==="export"){N.export=!0;for(let k of U.arguments)k.name.value==="name"&&(N.export={name:k.value.value})}}let I=!1;for(let U of S.fields){let k=H(U.type);k.name=U.name.value,R.push(k);for(let M of U.directives)if(M.name.value==="primaryKey")I?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,I=!0);else if(M.name.value==="indexed")k.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let J of M.arguments)Q[J.name.value]=J.value.value;k.relationship=Q}else if(M.name.value==="createdTime")k.assignCreatedTime=!0;else if(M.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")k.expiresAt=!0;else if(M.name.value==="allow"){let Q=k.authorizedRoles=[];for(let J of M.arguments)J.name.value==="role"&&Q.push(J.value.value)}}N.type=T,T==="Query"&&(h=N)}function p(S){let T=E.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):e$.includes(S.type)||(0,Rb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of E.values())for(let T of S.properties)p(T);for(let S of f)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Qh.dirname)(n),S.tableClass):i.set((0,Qh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Qh,Rb,e$,t$,r$,Ab=Re(()=>{Qh=require("path");Ae();Rb=x(We()),e$=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(zh,"start");t$=zh,r$=zh({ensureTable:Et}).handleFile});async function p_(e){let t=(0,yb.pathToFileURL)(e).toString();return n$?(Ic||(Ic=s$(o$)),(await(await Ic).import(t)).namespace):import(t)}async function s$(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Ic=new Compartment({console,Math,Date,fetch:i$,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,bb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:$t,tables:Br,databases:ct})}};let n=await(0,Ob.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Ic}function i$(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 o$(){return{Resource:$t,tables:Br}}var Ob,bb,yb,n$,Ic,jh=Re(()=>{cn();Ae();Ob=require("fs/promises"),bb=require("path"),yb=require("url"),n$=!1;a(p_,"secureImport");a(s$,"getCompartment");a(i$,"secureOnlyFetch");a(o$,"getGlobalVars")});var Zh={};Fe(Zh,{handleFile:()=>a$});async function a$(e,t,r,n){let s=new Map,i=await p_(r);c(i.default)&&n.set((0,Xh.dirname)(t),i.default),o(i,(0,Xh.dirname)(t));function o(u,_){for(let l in u){let d=u[l];c(d)?n.set(_+"/"+l,d):typeof d=="object"&&o(d,_+"/"+l)}}a(o,"recurseForResources");function c(u){return typeof u=="function"&&(u.get||u.put||u.post||u.delete)}return a(c,"isResource"),s}var Xh,Nb=Re(()=>{jh();Xh=require("path");a(a$,"handleFile")});var tm={};Fe(tm,{start:()=>c$});function c$({resources:e}){e.set("login",em),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var em,Ib=Re(()=>{cn();a(c$,"start");em=class extends $t{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var Ub={};Fe(Ub,{parse:()=>nm,streamAsJSON:()=>wc,stringify:()=>Gi});function wc(e){return new rm({value:e})}function wb(e){return console.error(e),JSON.stringify(e.toString())}function Cb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Gi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Mb)return Pb(e);if(t.resolution)return t.resolution.then(()=>Gi(e));throw t}}function Pb(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+=Pb(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 nm(e){return _$.test(e)?u$.parse(e):JSON.parse(e)}var Db,Lb,u$,l$,Mb,rm,_$,sm=Re(()=>{Db=require("stream"),Lb=x(require("json-bigint-fixes")),u$=(0,Lb.default)({useNativeBigInt:!0}),l$=1e4,Mb={};BigInt.prototype.toJSON=function(){throw Mb};a(wc,"streamAsJSON");rm=class extends Db.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),wb)}catch(s){yield wb(s)}else yield Gi(t)}else yield Gi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Cb(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>l$?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return Cb(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(wb,"handleError");a(Cb,"when");a(Gi,"stringify");a(Pb,"jsStringify");_$=/[[,:]\s*-?\d{16,}/;a(nm,"parse")});var Wb=g(($ce,Kb)=>{"use strict";var im=require("recursive-iterator"),d$=require("alasql"),om=require("clone"),vb=z(),{handleHDBError:Bb,hdb_errors:f$}=se(),{HDB_ERROR_MSGS:xb,HTTP_STATUS_CODES:Hb}=f$,{getDatabases:E$}=(Ae(),ie(ke)),h$=["DISTINCT_ARRAY"],Gb=Symbol("validateTables"),am=Symbol("validateTable"),Vce=Symbol("getAllColumns"),qb=Symbol("validateAllColumns"),S_=Symbol("findColumn"),Fb=Symbol("validateOrderBy"),Cc=Symbol("validateSegment"),cm=Symbol("validateColumn"),kb=Symbol("setColumnsForTable"),Vb=Symbol("checkColumnsForAsterisk"),$b=Symbol("validateGroupBy"),Yb=Symbol("hasColumns"),um=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Gb](),this[Vb](),this[qb]()}[Gb](){if(this[Yb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[am](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[am](t.table)})}}[Yb](){let t=!1,r=new im(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[am](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=E$();if(!r[t.databaseid])throw Bb(new Error,xb.SCHEMA_NOT_FOUND(t.databaseid),Hb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Bb(new Error,xb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Hb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=om(s);i.table=om(t),this.attributes.push(i)})}[S_](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)}[Vb](){let t=new im(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[kb](r.tableid)}[kb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new d$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[qb](){this[Cc](this.statement.columns,!1),this[Cc](this.statement.joins,!1),this[Cc](this.statement.where,!1),this[$b](this.statement.group,!1),this[Cc](this.statement.order,!0)}[Cc](t,r){if(!t)return;let n=new im(t),s=[];for(let{node:i,path:o}of n)!vb.isEmpty(i)&&!vb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Fb](i):s.push(this[cm](i)));return s}[$b](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&h$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=om(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[S_](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[S_](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`}[Fb](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[cm](t)}[cm](t){let r=this[S_](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=um});var zb=g((Kce,Qb)=>{"use strict";var lm=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")}};Qb.exports=lm});var jb=g((Qce,Jb)=>{"use strict";var _m=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Jb.exports=_m});var ty={};Fe(ty,{HAS_EXPIRATION:()=>Sm,LAST_TIMESTAMP_PLACEHOLDER:()=>Mc,LOCAL_TIMESTAMP:()=>m$,METADATA:()=>Dc,NO_TIMESTAMP:()=>fm,PENDING_LOCAL_TIME:()=>Tm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>pm,RecordEncoder:()=>mm,TIMESTAMP_ASSIGN_LAST:()=>S$,TIMESTAMP_ASSIGN_NEW:()=>Zb,TIMESTAMP_ASSIGN_PREVIOUS:()=>ey,TIMESTAMP_PLACEHOLDER:()=>T_,TIMESTAMP_RECORD_PREVIOUS:()=>Em,getUpdateRecord:()=>gm,handleLocalTimeForGets:()=>O_});function g$(){return Lc[0]=Lc[0]^64,p$.getFloat64(0)}function O_(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?.[Dc];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?.[Dc]>=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[Dc];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 gm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",E,f){if(E||u==null?$o=i?.localTime?Em|ey:fm:$o=u?i?.localTime?Em|16384:Zb|16384:fm,l>0&&(c|=Sm),R_=c,hm=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:$o>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(f&&(g_=e.encoder.encode(f)),E&&i?.localTime){let R=i?.localTime,N=r.get(R);if(N){let I=vt(N).previousLocalTime;return r.put(R,A_(o,t,n,I,T,d,g_),{ifVersion:p}),S}}r.put(Mc,A_(o,t,n,i?.localTime?1:0,T,d,g_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Xb,dm,T_,Mc,pm,m$,Dc,Lc,p$,fm,Zb,S$,ey,Em,Sm,Tm,T$,g_,$o,R_,hm,mm,qi,Pc=Re(()=>{Xb=require("msgpackr");ri();dm=x($()),T_=new Uint8Array([1,1,1,1,4,64,0,0]),Mc=new Uint8Array([1,1,1,1,1,0,0,0]),pm=new Uint8Array([1,1,1,1,3,64,0,0]),m$=Symbol("local-timestamp"),Dc=Symbol("metadata"),Lc=new Uint8Array(8),p$=new DataView(Lc.buffer,0,8),fm=0,Zb=0,S$=1,ey=3,Em=4,Sm=16,Tm=1,$o=0,R_=-1,hm=0,mm=class extends Xb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if($o||R_>=0){let i=0,o=$o;o&&(i+=8,$o=0);let c=R_,u=hm;c>=0&&(i+=2,R_=-1,u&&(i+=8,hm=0));let _=T$=r.call(this,n,s|2048|i);g_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(T_[4]=o,T_[5]=o>>8,_.set(T_,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(Lc,0,c),c+=8;else for(let d=0;d<8;d++)Lc[d]=t[c++];u=g$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Sm&&(_=(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,[Dc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(g$,"getTimestamp");a(O_,"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?(dm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):dm.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(gm,"getUpdateRecord")});var Uc=g((Zce,ny)=>{"use strict";var ry=ee(),R$=P(),{RecordEncoder:A$}=(Pc(),ie(ty)),Xce=require("fs");ry.initSync();var O$=ry.get(R$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Rm=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=O$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:A$})}};ny.exports=Rm});var vc=g((tue,sy)=>{"use strict";var xr=ee(),un=P();xr.initSync();var b_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=2048,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=xr.get(un.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||xr.get(un.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||xr.get(un.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",xr.get(un.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=xr.get(un.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),xr.get(un.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=xr.get(un.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),xr.get(un.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=xr.get(un.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),xr.get(un.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=xr.get(un.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=xr.get(un.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};sy.exports=b_;b_.MAX_DBS=1e4});var Qe=g((nue,Ey)=>{"use strict";var Om=require("lmdb"),In=require("fs-extra"),Hr=require("path"),y_=vr(),ay=$(),_r=Ur().LMDB_ERRORS_ENUM,N_=jb(),bm=Uc(),cy=vc(),ni=ft(),iy=P(),{table:b$,resetDatabases:y$}=(Ae(),ie(ke)),oy=ee(),wn=ni.INTERNAL_DBIS_NAME,uy=ni.DBI_DEFINITION_NAME,N$="data.mdb",I$="lock.mdb",Bc=".mdb",w$="-lock",Am=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=ln(t,r),this.key_type=this.dbi[ni.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ni.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Om.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function I_(e,t){if(e===void 0)throw new Error(_r.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(_r.ENV_NAME_REQUIRED)}a(I_,"pathEnvNameValidation");async function ym(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(_r.INVALID_BASE_PATH):n}try{let n=Hr.join(e,t+Bc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(Hr.join(e,t,N$),In.constants.R_OK|In.constants.F_OK),Hr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(_r.INVALID_ENVIRONMENT)}else throw new Error(_r.INVALID_ENVIRONMENT);throw n}}a(ym,"validateEnvironmentPath");function w_(e,t){if(y_.validateEnv(e),t===void 0)throw new Error(_r.DBI_NAME_REQUIRED)}a(w_,"validateEnvDBIName");async function C$(e,t,r=!1,n=!1){I_(e,t);let s=Hr.basename(e);t=t.toString();let i=oy.get(iy.CONFIG_PARAMS.DATABASES);i||oy.setProperty(iy.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await ym(e,t,n),ly(e,t,r)}catch(o){if(o.message===_r.INVALID_ENVIRONMENT){let c=Hr.join(e,t);await In.mkdirp(n?c:e);let u=new cy(n?c:c+Bc,!1),_=Om.open(u);_.dbis=Object.create(null);let l=new bm(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Nm(e,t,r);return _[ni.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(C$,"createEnvironment");async function D$(e,t,r,n=!0){I_(e,t),t=t.toString();let s=Hr.join(e,t);return b$({table:t,database:Hr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(D$,"copyEnvironment");async function ly(e,t,r=!1){I_(e,t),t=t.toString();let n=Nm(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 ym(e,t),i=Hr.join(e,t+Bc),o=s!=i,c=new cy(s,o),u=Om.open(c);u.dbis=Object.create(null);let _=dy(u);for(let l=0;l<_.length;l++)ln(u,_[l]);return u[ni.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(ly,"openEnvironment");async function L$(e,t,r=!1){I_(e,t),t=t.toString();let n=Hr.join(e,t+Bc),s=await ym(e,t);if(global.lmdb_map!==void 0){let i=Nm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await _y(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+w$:Hr.join(Hr.dirname(s),I$))}a(L$,"deleteEnvironment");async function _y(e){y_.validateEnv(e);let t=e[ni.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(_y,"closeEnvironment");function Nm(e,t,r=!1){let s=`${Hr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(Nm,"getCachedEnvironmentName");function M$(e){y_.validateEnv(e);let t=Object.create(null),r=ln(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new N_,s)}catch{ay.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(M$,"listDBIDefinitions");function dy(e){y_.validateEnv(e);let t=[],r=ln(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(dy,"listDBIs");function P$(e,t){let n=ln(e,wn).getEntry(t),s=new N_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{ay.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(P$,"getDBIDefinition");function fy(e,t,r,n=!r){if(w_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return ln(e,t)}catch(s){if(s.message===_r.DBI_DOES_NOT_EXIST){let i=new bm(r,n===!0),o=e.openDB(t,i),c=new N_(r===!0,n);return o[uy]=c,ln(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(fy,"createDBI");function ln(e,t){if(w_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=P$(e,t):r=new N_,r===void 0)throw new Error(_r.DBI_DOES_NOT_EXIST);let n;try{let s=new bm(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(_r.DBI_DOES_NOT_EXIST):s}return n[uy]=r,e.dbis[t]=n,n}a(ln,"openDBI");function U$(e,t){w_(e,t),t=t.toString();let r=ln(e,t),n=r.getStats();return r[ni.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(U$,"statDBI");async function v$(e,t){try{let r=Hr.join(e,t+Bc);return(await In.stat(r)).size}catch{throw new Error(_r.INVALID_ENVIRONMENT)}}a(v$,"environmentDataSize");function B$(e,t){if(w_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_DROP_INTERNAL_DBIS_NAME);ln(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],ln(e,wn).removeSync(t)}a(B$,"dropDBI");function x$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{ln(e,i)}catch(o){if(o.message===_r.DBI_DOES_NOT_EXIST)fy(e,i,i!==t,i===t),n=!0;else throw o}}n&&y$()}a(x$,"initializeDBIs");Ey.exports={openDBI:ln,openEnvironment:ly,createEnvironment:C$,listDBIs:dy,listDBIDefinitions:M$,createDBI:fy,dropDBI:B$,statDBI:U$,deleteEnvironment:L$,initializeDBIs:x$,TransactionCursor:Am,environmentDataSize:v$,copyEnvironment:D$,closeEnvironment:_y}});var my=g((iue,hy)=>{"use strict";var Im=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};hy.exports=Im});var Sy=g((aue,py)=>{"use strict";var wm=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}};py.exports=wm});var gy=g((uue,Ty)=>{"use strict";var Cm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Ty.exports=Cm});var Yo=g((Eue,Oy)=>{"use strict";var H$=Qe(),G$=my(),q$=Sy(),F$=gy(),Qn=vr(),xc=Ur().LMDB_ERRORS_ENUM,k$=ft(),gs=P(),V$=z(),$$=require("uuid"),_ue=require("lmdb"),{handleHDBError:Y$,hdb_errors:K$}=se(),{OVERFLOW_MARKER:due,MAX_SEARCH_KEY_LENGTH:fue}=k$,Ry=ee();Ry.initSync();var C_=Ry.get(gs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Dm=gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Fi=gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function W$(e,t,r,n,s=Qn.getNextMonotonicTime()){Um(e,t,r,n),Lm(e,t,r);let i=new G$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ay(_,!0,s);let l=Q$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Mm(o,c,n,i,s)}a(W$,"insertRecords");function Q$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][gs.FUNC_VAL],n[o]=c)}let u=Qn.getIndexedValues(c),_=e.dbis[o];if(u){C_&&_.prefetch(u.map(l=>({key:l,value:s})),D_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}C_&&e.dbis[t].prefetch([s],D_),e.dbis[t].put(s,n,n[Fi])})}a(Q$,"insertRecord");function z$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(z$,"removeSkippedRecords");function Ay(e,t,r){let n=r>0;(n||!Number.isInteger(e[Fi]))&&(e[Fi]=r||(r=Qn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[Dm]))&&(e[Dm]=r||Qn.getNextMonotonicTime()):delete e[Dm]}a(Ay,"setTimestamps");function Lm(e,t,r){r.indexOf(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),H$.initializeDBIs(e,t,r)}a(Lm,"initializeTransaction");async function J$(e,t,r,n,s=Qn.getNextMonotonicTime()){Um(e,t,r,n),Lm(e,t,r);let i=new q$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],E;try{E=Pm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),u.push(d)}return Mm(c,u,n,i,s,o)}a(J$,"updateRecords");async function j$(e,t,r,n,s=Qn.getNextMonotonicTime()){try{Um(e,t,r,n)}catch(u){throw Y$(u,u.message,K$.HTTP_STATUS_CODES.BAD_REQUEST)}Lm(e,t,r);let i=new F$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;V$.isEmpty(_[t])?(l=$$.v4(),_[t]=l):l=_[t];let d=Pm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Mm(o,c,n,i,s)}a(j$,"upsertRecords");async function Mm(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(),z$(r,i),n}a(Mm,"finalizeWrite");function Pm(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(Ay(r,!l,o),Number.isInteger(r[Fi])&&_[Fi]>r[Fi])return!1;l&&s.original_records.push(_);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let T=_[h];if(typeof p=="function"){let N=p([[_]]);Array.isArray(N)&&(p=N[0][gs.FUNC_VAL],r[h]=p)}if(p===T)continue;let R=Qn.getIndexedValues(T);if(R){C_&&S.prefetch(R.map(N=>({key:N,value:n})),D_);for(let N=0,I=R.length;N<I;N++)S.remove(R[N],n)}if(R=Qn.getIndexedValues(p),R){C_&&S.prefetch(R.map(N=>({key:N,value:n})),D_);for(let N=0,I=R.length;N<I;N++)S.put(R[N],n)}}let f=Object.assign({},_,r);c.put(n,f,f[Fi])},"do_put");return u?d=c.ifVersion(n,u.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:Pm(e,t,r,n,s,i,o))}a(Pm,"updateUpsertRecord");function X$(e,t,r){if(Qn.validateEnv(e),t===void 0)throw new Error(xc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(xc.WRITE_ATTRIBUTES_REQUIRED):new Error(xc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(X$,"validateBasic");function Um(e,t,r,n){if(X$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(xc.RECORDS_REQUIRED):new Error(xc.RECORDS_MUST_BE_ARRAY)}a(Um,"validateWrite");function D_(){}a(D_,"noop");Oy.exports={insertRecords:W$,updateRecords:J$,upsertRecords:j$}});var ki=g((mue,Z$)=>{Z$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var Jn=g((pue,Ny)=>{"use strict";var yy=z(),by=P(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zn=require("joi"),si={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},e1=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number(),zn.array()).required(),t1=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number()),r1=zn.alternatives(zn.string().min(1).max(si.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+si.schema_format.message}),zn.number()).required();function n1(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>si.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(n1,"checkValidTable");function s1(e,t){return yy.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(s1,"validateSchemaExists");function i1(e,t){let r=t.state.ancestors[0].schema;return yy.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(i1,"validateTableExists");function o1(e,t){return e.toLowerCase()===by.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${by.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(o1,"validateSchemaName");Ny.exports={common_validators:si,schema_regex:Ko,hdb_schema_table:e1,validateSchemaExists:s1,validateTableExists:i1,validateSchemaName:o1,checkValidTable:n1,hdb_database:t1,hdb_table:r1}});var Xe=g((Tue,Iy)=>{"use strict";var dr=require("validate.js");dr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||dr.validators.type.checks[t](e)?null:` must be a '${t}' value`};dr.validators.type.checks={Object:function(e){return dr.isObject(e)&&!dr.isArray(e)},Array:dr.isArray,Integer:dr.isInteger,Number:dr.isNumber,String:dr.isString,Date:dr.isDate,Boolean:function(e){return typeof e=="boolean"}};dr.validators.hasValidFileExt=function(e,t){return dr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};Iy.exports={validateObject:a1,validateObjectAsync:c1,validateBySchema:u1};function a1(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=dr(e,t,{format:"flat"});return r?new Error(r):null}a(a1,"validateObject");async function c1(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await dr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(c1,"validateObjectAsync");function u1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(u1,"validateBySchema")});var L_=g((Rue,wy)=>{var{common_validators:jn}=Jn(),Gc=Xe(),Hc="is required",gt={database:{presence:!1,format:jn.schema_format,length:jn.schema_length},schema:{presence:!1,format:jn.schema_format,length:jn.schema_length},table:{presence:!0,format:jn.schema_format,length:jn.schema_length},attribute:{presence:!0,format:jn.schema_format,length:jn.schema_length},hash_attribute:{presence:!0,format:jn.schema_format,length:jn.schema_length}};function qc(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(qc,"makeAttributesStrings");function l1(e){return e=qc(e),gt.table.presence=!1,gt.attribute.presence=!1,gt.hash_attribute.presence=!1,Gc.validateObject(e,gt)}a(l1,"schema_object");function _1(e){return e=qc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,Gc.validateObject(e,gt)}a(_1,"table_object");function d1(e){return e=qc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,Gc.validateObject(e,gt)}a(d1,"create_table_object");function f1(e){return e=qc(e),gt.table.presence={message:Hc},gt.attribute.presence={message:Hc},gt.hash_attribute.presence=!1,Gc.validateObject(e,gt)}a(f1,"attribute_object");function E1(e){return e=qc(e),gt.table.presence={message:Hc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,Gc.validateObject(e,gt)}a(E1,"describe_table");function h1(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(h1,"validateTableResidence");wy.exports={schema_object:l1,create_table_object:d1,table_object:_1,attribute_object:f1,describe_table:E1,validateTableResidence:h1}});var Dy=g((Oue,Cy)=>{"use strict";var m1=require("uuid"),vm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||m1.v4(),this.schema_table=`${this.schema}.${this.table}`}};Cy.exports=vm});var M_=g((yue,Ly)=>{"use strict";var p1=Dy(),Bm=class extends p1{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}};Ly.exports=Bm});var Py=g((Iue,My)=>{"use strict";My.exports=T1;var S1="inserted";function T1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===S1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(T1,"returnObject")});var P_=g((Cue,Hy)=>{"use strict";var g1=P(),xm=Qe(),R1=Yo(),{getSystemSchemaPath:A1,getSchemaPath:O1}=je(),b1=ki(),y1=L_(),N1=M_(),I1=Py(),{handleHDBError:Uy,hdb_errors:By}=se(),vy=z(),{HTTP_STATUS_CODES:w1}=By,Hm=b1.hdb_attribute,xy=[];for(let e=0;e<Hm.attributes.length;e++)xy.push(Hm.attributes[e].attribute);var C1="inserted";Hy.exports=D1;async function D1(e){let t=y1.attribute_object(e);if(t)throw Uy(new Error,t.message,By.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&vy.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Uy(new Error,r,w1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=vy.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 N1(e.schema,e.table,e.attribute,e.id);try{let i=await xm.openEnvironment(O1(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}`);xm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await xm.openEnvironment(A1(),g1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await R1.insertRecords(o,Hm.hash_attribute,xy,[s]);return I1(C1,c,{records:[s]},u)}catch(i){throw i}}a(D1,"lmdbCreateAttribute")});var qm=g((Lue,qy)=>{var{hdb_table:L1,hdb_database:Gy}=Jn(),M1=Xe(),Gm=require("joi"),P1={undefined:"undefined",null:"null"},U1=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||P1[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"),v1=Gm.object({database:Gy,schema:Gy,table:L1,records:Gm.array().items(Gm.object().custom(U1)).required()});qy.exports=function(e){return M1.validateBySchema(e,v1)}});var Fc=g((Uue,ky)=>{"use strict";var Rs=z(),Fy=$(),Pue=qm(),{getDatabases:B1}=(Ae(),ie(ke)),{ClientError:Vi}=se();ky.exports=x1;function x1(e){if(Rs.isEmpty(e))throw new Vi("invalid update parameters defined.");if(Rs.isEmptyOrZeroLength(e.schema))throw new Vi("invalid schema specified.");if(Rs.isEmptyOrZeroLength(e.table))throw new Vi("invalid table specified.");if(!Array.isArray(e.records))throw new Vi("records must be an array");let t=B1()[e.schema]?.[e.table];if(Rs.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&&Rs.isEmptyOrZeroLength(o[r]))throw Fy.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(!Rs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw Fy.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`);!Rs.isEmpty(o[r])&&o[r]!==""&&n.has(Rs.autoCast(o[r]))&&(o.skip=!0),n.add(Rs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(x1,"insertUpdateValidate")});var kc=g((Bue,Vy)=>{"use strict";var H1=P().OPERATIONS_ENUM,Fm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=H1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Vy.exports=Fm});var Vc=g((Gue,Yy)=>{"use strict";var Hue=kc(),U_=P(),km=z(),$y=$(),G1=require("uuid"),{handleHDBError:v_,hdb_errors:q1}=se(),{HDB_ERROR_MSGS:B_,HTTP_STATUS_CODES:x_}=q1;Yy.exports=F1;function F1(e,t,r){for(let s=0;s<t.length;s++)k1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];V1(i,r,e.operation)}}a(F1,"processRows");function k1(e){if(Buffer.byteLength(String(e))>U_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw v_(new Error,B_.ATTR_NAME_LENGTH_ERR(e),x_.BAD_REQUEST,void 0,void 0,!0);if(km.isEmptyOrZeroLength(e)||km.isEmpty(e.trim()))throw v_(new Error,B_.ATTR_NAME_NULLISH_ERR,x_.BAD_REQUEST,void 0,void 0,!0)}a(k1,"validateAttribute");function V1(e,t,r){if(!e.hasOwnProperty(t)||km.isEmptyOrZeroLength(e[t])){if(r===U_.OPERATIONS_ENUM.INSERT||r===U_.OPERATIONS_ENUM.UPSERT){e[t]=G1.v4();return}throw $y.error("Update transaction aborted due to record with no hash value:",e),v_(new Error,B_.RECORD_MISSING_HASH_ERR,x_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>U_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw $y.error(e),v_(new Error,B_.HASH_VAL_LENGTH_ERR,x_.BAD_REQUEST,void 0,void 0,!0)}a(V1,"validateHash")});var Wy=g((Fue,Ky)=>{"use strict";var Vm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Ky.exports=Vm});var Jy=g((Vue,zy)=>{"use strict";var $m=Qe(),$1=$(),Qy=Ur().LMDB_ERRORS_ENUM;zy.exports=Y1;async function Y1(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 $m.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Qy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await $m.closeEnvironment(global.lmdb_map[n]),await $m.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Qy.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){$1.error(t)}}a(Y1,"cleanLMDBMap")});var As=g((Yue,eN)=>{"use strict";var $c=require("crypto"),K1=ee(),{CONFIG_PARAMS:W1}=P(),Xy="aes-256-cbc",Q1=32,z1=16,Ym=64,Zy=32,J1=Ym+Zy,jy=new Map;eN.exports={encrypt:j1,decrypt:X1,createNatsTableStreamName:Z1};function j1(e){let t=$c.randomBytes(Q1),r=$c.randomBytes(z1),n=$c.createCipheriv(Xy,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(j1,"encrypt");function X1(e){let t=e.substr(0,Ym),r=e.substr(Ym,Zy),n=e.substr(J1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=$c.createDecipheriv(Xy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(X1,"decrypt");function Z1(e,t){let r=K1.get(W1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=jy.get(r);return n||(n=$c.createHash("md5").update(r).digest("hex"),jy.set(r,n)),n}a(Z1,"createNatsTableStreamName")});var Os=g((Que,rN)=>{"use strict";var Wue=Gr(),Yc=$(),tN=L_(),eY=As(),H_=z(),{handleHDBError:G_,hdb_errors:tY}=se(),{HDB_ERROR_MSGS:q_,HTTP_STATUS_CODES:Km}=tY,rY=ee();rY.initSync();var{getDatabases:Wm}=(Ae(),ie(ke)),nY=require("fs-extra");rN.exports={describeAll:sY,describeTable:F_,describeSchema:iY};async function sY(e){try{let t=H_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Wm(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let E in d)try{let f;if(t||n)f=await F_({schema:l,table:E,exact_count:u});else if(r&&r[l].describe&&r[l].tables[E].describe){let h=r[l].tables[E].attribute_permissions;f=await F_({schema:l,table:E,exact_count:u},h)}f&&c.push(f)}catch(f){Yc.error(f)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return Yc.error("Got an error in describeAll"),Yc.error(t),G_(new Error,q_.DESCRIBE_ALL_ERR)}}a(sY,"describeAll");async function F_(e,t){H_.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=tN.describe_table(e);if(i)throw i;let c=Wm()[r];if(!c)throw G_(new Error,q_.SCHEMA_NOT_FOUND(e.schema),Km.NOT_FOUND);let u=c[n];if(!u)throw G_(new Error,q_.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(h=>({type:h.type,name:h.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(h=>{h.describe&&(f[h.attribute_name]=!0)}),u.attributes.forEach(h=>{f[h.name]&&_(h)})}else u.attributes?.forEach(f=>_(f));let d;try{d=(await nY.stat(u.primaryStore.env.path)).size}catch(f){Yc.warn("unable to get database size",f)}let E={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,db_size:d};E.clustering_stream_name=eY.createNatsTableStreamName(E.schema,E.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});E.record_count=f.recordCount,E.estimated_record_range=f.estimatedRange;let h=u.auditStore;if(h)for(let p of h.getKeys({reverse:!0,limit:1}))E.last_updated_record=p[0];if(!E.last_updated_record&&u.indices.__updatedtime__)for(let p of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))E.last_updated_record=p}catch(f){Yc.warn(`unable to stat table dbi due to ${f}`)}return E}a(F_,"descTable");async function iY(e){H_.transformReq(e);let t=tN.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=Wm()[n];if(!i)throw G_(new Error,q_.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]),H_.isEmpty(u)||u.describe){let _=await F_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(iY,"describeSchema")});var bs=g((Xue,aN)=>{var oY=ki(),{callbackify:sN,promisify:aY}=require("util"),{getDatabases:iN}=(Ae(),ie(ke));aN.exports={setSchemaDataToGlobal:nN,getTableSchema:cY,getSystemSchema:uY,setSchemaDataToGlobalAsync:aY(nN)};var oN=Os(),Jue=sN(oN.describeAll),jue=sN(oN.describeTable);function nN(e){global.hdb_schema=iN(),e&&e()}a(nN,"setSchemaDataToGlobal");function cY(e,t,r){let n=iN()[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(cY,"getTableSchema");function uY(){return oY}a(uY,"getSystemSchema")});var qr=g((ele,_N)=>{"use strict";var V_=qm(),Yt=z(),lY=require("util"),$_=Cn(),_Y=bs(),cN=$(),{handleHDBError:$i,hdb_errors:dY}=se(),{HTTP_STATUS_CODES:Yi}=dY,fY=lY.promisify(_Y.getTableSchema),EY="updated",uN="inserted",lN="upserted";_N.exports={insert:mY,update:pY,upsert:SY,validation:hY,flush:TY};async function hY(e){if(Yt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Yt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Yt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await fY(e.schema,e.table),r=V_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Yt.isEmptyOrZeroLength(c[n]))throw cN.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!Yt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw cN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Yt.isEmpty(c[n])&&c[n]!==""&&s.has(Yt.autoCast(c[n]))&&(c.skip=!0),s.add(Yt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(hY,"validation");async function mY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=V_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await $_.createRecords(e);return k_(uN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(mY,"insertData");async function pY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=V_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await $_.updateRecords(e);return Yt.isEmpty(n.existing_rows)?k_(EY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):k_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(pY,"updateData");async function SY(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=V_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await $_.upsertRecords(e);return k_(lN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(SY,"upsertData");function k_(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===uN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===lN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(k_,"returnObject");function TY(e){return Yt.transformReq(e),$_.flush(e.schema,e.table)}a(TY,"flush")});var zm=g((rle,EN)=>{var gY=Xe(),Qm=require("joi"),{hdb_table:RY,hdb_database:dN}=Jn(),fN={schema:dN,database:dN,table:RY},AY={date:Qm.date().iso().required()},OY={timestamp:Qm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};EN.exports=function(e,t){let r=t==="timestamp"?{...fN,...OY}:{...fN,...AY},n=Qm.object(r);return gY.validateBySchema(e,n)}});var pN=g((nle,mN)=>{var bY=Xe(),Jm=require("joi"),{hdb_table:yY,hdb_database:hN}=Jn(),NY=Jm.object({schema:hN,database:hN,table:yY,hash_values:Jm.array().required(),ids:Jm.array()});mN.exports=function(e){return bY.validateBySchema(e,NY)}});var TN=g((sle,SN)=>{"use strict";var jm=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}},Xm=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=[]}};SN.exports={InsertObject:jm,NoSQLSeachObject:Xm,DeleteResponseObject:Zm}});var ai=g((ole,bN)=>{"use strict";var RN=zm(),IY=pN(),Ki=z(),gN=require("moment"),AN=$(),{promisify:wY,callbackify:CY}=require("util"),Wi=P(),DY=bs(),ep=wY(DY.getTableSchema),tp=Cn(),{DeleteResponseObject:LY}=TN(),{handleHDBError:ii,hdb_errors:MY}=se(),{HDB_ERROR_MSGS:Y_,HTTP_STATUS_CODES:oi}=MY,PY="records successfully deleted",UY=CY(ON);bN.exports={delete:UY,deleteRecord:ON,deleteFilesBefore:vY,deleteAuditLogsBefore:BY};async function vY(e){let t=RN(e,"date");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!gN(e.date,gN.ISO_8601).isValid())throw ii(new Error,Y_.INVALID_DATE,oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,Y_.INVALID_DATE,!0);let n=Ki.checkSchemaTableExist(e.schema,e.table);if(n)throw ii(new Error,n,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,n,!0);let s=await tp.deleteRecordsBefore(e);if(await ep(e.schema,e.table),AN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(vY,"deleteFilesBefore");async function BY(e){let t=RN(e,"timestamp");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw ii(new Error,Y_.INVALID_VALUE("Timestamp"),oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,Y_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let n=await tp.deleteAuditLogsBefore(e);return await ep(e.schema,e.table),AN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(BY,"deleteAuditLogsBefore");async function ON(e){e.ids&&(e.hash_values=e.ids);let t=IY(e);if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await ep(e.schema,e.table);let n=await tp.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 LY;return s.message=Wi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(ON,"deleteRecord")});var K_=g((cle,IN)=>{var xY=require("crypto"),yN=9;function HY(e){let t=qY(yN),r=NN(e+t);return t+r}a(HY,"createHash");function GY(e,t){let r=e?.substr(0,yN),n=r+NN(t+r);return e===n}a(GY,"validateHash");function qY(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(qY,"generateSalt");function NN(e){return xY.createHash("md5").update(e).digest("hex")}a(NN,"md5");IN.exports={hash:HY,validate:GY}});var CN=g((lle,wN)=>{var rp=Xe(),Zt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function FY(e){return Zt.password.presence=!0,Zt.username.presence=!0,Zt.role.presence=!0,Zt.active.presence=!0,rp.validateObject(e,Zt)}a(FY,"addUserValidation");function kY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,rp.validateObject(e,Zt)}a(kY,"alterUserValidation");function VY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,rp.validateObject(e,Zt)}a(VY,"dropUserValidation");wN.exports={addUserValidation:FY,alterUserValidation:kY,dropUserValidation:VY}});var Ve=g((fle,LN)=>{"use strict";var{platform:dle}=require("os"),$Y="nats-server.zip",np="nats-server",YY=process.platform==="win32"?`${np}.exe`:np,KY=/^[^\s.,*>]+$/,DN="__request__",WY=a(e=>`${e}.${DN}`,"REQUEST_SUBJECT"),QY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},zY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},JY={HUB:"hub.pid",LEAF:"leaf.pid"},jY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},XY={SUCCESS:"success",ERROR:"error"},ZY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},eK={TXN:"txn",MSGID:"msgid"},Wo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},tK={[Wo.ERR]:1,[Wo.WRN]:2,[Wo.INF]:3,[Wo.DBG]:4,[Wo.TRC]:5},rK={debug:"-D",trace:"-DVV"};LN.exports={NATS_SERVER_ZIP:$Y,NATS_SERVER_NAME:np,NATS_BINARY_NAME:YY,PID_FILES:JY,NATS_CONFIG_FILES:zY,SERVER_SUFFIX:jY,NATS_TERM_CONSTRAINTS_RX:KY,REQUEST_SUFFIX:DN,UPDATE_REMOTE_RESPONSE_STATUSES:XY,CLUSTER_STATUS_STATUSES:ZY,REQUEST_SUBJECT:WY,SUBJECT_PREFIXES:eK,MSG_HEADERS:QY,LOG_LEVELS:Wo,LOG_LEVEL_FLAGS:rK,LOG_LEVEL_HIERARCHY:tK}});var PN=g((hle,MN)=>{"use strict";var nK={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
|
-
`)},rK="certificate.pem",nK="privateKey.pem",sK="ca.pem";LN.exports={CERTIFICATE_VALUES:tK,CERTIFICATE_PEM_NAME:rK,PRIVATEKEY_PEM_NAME:nK,CA_PEM_NAME:sK}});var np=g((hle,xN)=>{"use strict";var BN=require("fs-extra"),oe=require("joi"),iK=require("os"),{boolean:be,string:er,number:rt,array:K_}=oe.types(),{totalmem:PN}=require("os"),Qi=require("path"),oK=$(),W_=z(),Ele=MN(),UN=P(),aK=Xe(),vN="log",cK="components",uK="Invalid logging.rotation.maxSize unit. Available units are G, M or K",lK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",_K="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",dK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",fK="rootPath config parameter is undefined",EK="clustering.enabled config parameter is undefined",zi=rt.min(0).required(),Q_=K_.items({host:er.required(),port:zi}).empty(null),Xn,HN=!1;xN.exports={configValidator:hK,routesValidator:RK,route_constraints:Q_};function hK(e,t=!1){if(HN=t,Xn=e.rootPath,W_.isEmpty(Xn))throw fK;let r=be.required(),n=rt.min(0).max(1e3).empty(null).default(gK),s=er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Yc),i=er.optional().empty(null),o=er.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(Yc),u=oe.custom(pK).empty(null).default(Yc),_=e.clustering?.enabled;if(W_.isEmpty(_))throw EK;let l=oe.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:zi,routes:Q_}).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:Q_}).required(),streams:oe.object({maxAge:rt.min(120).allow(null).optional(),maxBytes:rt.min(1).allow(null).optional(),maxMsgs:rt.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:er.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:rt.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:rt}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).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:er.custom(TK).optional().empty(null),maxSize:er.custom(SK).optional().empty(null),path:er.optional().empty(null).default(Yc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:K_.optional(),headersTimeout:rt.min(1).optional(),keepAliveTimeout:rt.min(1).optional(),port:rt.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Yc),securePort:rt.optional().empty(null),timeout:rt.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:zi,securePort:zi,mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:rt.optional(),cors:be.optional(),corsAccessList:K_.optional(),headersTimeout:rt.min(1).optional(),port:rt.min(0).optional().empty(null),securePort:rt.min(0).optional().empty(null),maxHeaderSize:rt.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})]),threadRange:oe.alternatives([K_.optional(),er.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:rt.min(1).optional(),host:er.optional(),waitForDebugger:be.optional()})),maxHeapMemory:rt.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:er.optional(),threshold:rt.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:u,prefetchWrites:be.optional(),maxFreeSpaceToLoad:rt.optional(),maxFreeSpaceToRetain:rt.optional()}).required(),ignoreScripts:be.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(hK,"configValidator");function mK(e){return HN||BN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(mK,"doesPathExist");function pK(e,t){oe.assert(e,er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=mK(e);if(r)return t.message(r)}a(pK,"validatePath");function SK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(uK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(_K):e}a(SK,"validateRotationMaxSize");function TK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(lK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(dK):e}a(TK,"validateRotationInterval");function gK(e,t){let r=t.state.path.join("."),n=iK.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||PN();return i=Math.round(Math.min(i,PN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),oK.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(gK,"setDefaultThreads");function Yc(e,t){let r=t.state.path.join(".");if(!W_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(W_.isEmpty(Xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Qi.join(Xn,cK);case"logging.root":return Qi.join(Xn,vN);case"clustering.leafServer.streams.path":return Qi.join(Xn,"clustering","leaf");case"storage.path":let n=Qi.join(Xn,UN.LEGACY_DATABASES_DIR_NAME);return BN.existsSync(n)?n:Qi.join(Xn,UN.DATABASES_DIR_NAME);case"logging.rotation.path":return Qi.join(Xn,vN);case"operationsApi.network.domainSocket":return r==null?null:Qi.join(Xn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Yc,"setDefaultRoot");function RK(e){let t=oe.object({routes:Q_});return aK.validateBySchema({routes:e},t)}a(RK,"routesValidator")});var Er=g((Sle,WN)=>{"use strict";var kr=P(),Bt=z(),It=$(),{configValidator:AK,routesValidator:GN}=np(),fr=require("fs-extra"),OK=require("yaml"),Dn=require("path"),bK=require("is-number"),FN=require("properties-reader"),yK=require("lodash"),{handleHDBError:NK}=ne(),{HTTP_STATUS_CODES:IK,HDB_ERROR_MSGS:z_}=Ur(),ple=require("minimist"),{server:wK}=(lr(),ie(xi)),{DATABASES_PARAM_CONFIG:Kc,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Ln}=kr,CK="Unable to get config value because config is uninitialized",DK="Config successfully initialized",LK="Error backing up config file",MK="Empty parameter sent to getConfigValue",kN=Dn.join(kr.PACKAGE_ROOT,"config","yaml",kr.HDB_DEFAULT_CONFIG_FILE),PK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",qN={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"},J_,wt,j_;WN.exports={createConfigFile:UK,getDefaultConfig:vK,getConfigValue:$N,initConfig:ip,flattenConfig:Qo,updateConfigValue:YN,updateConfigObject:HK,getConfiguration:qK,setConfiguration:FK,readConfigFile:ap,getClusteringRoutes:kK,initOldConfig:KN,getConfigFromFile:VK,getConfigFilePath:Ji,addConfig:$K,deleteConfigFromFile:YK,getConfigObj:KK};function UK(e,t=!1){let r=ci(kN);J_=Qo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=sp(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){It.error(d)}}}n&&VN(r,n),op(r,t);let s=r.toJSON();wt=Qo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,kr.HDB_CONFIG_FILE);fr.createFileSync(o),fr.writeFileSync(o,String(r)),It.trace(`Config file written to ${o}`)}a(UK,"createConfigFile");function VN(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Bt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Kc.TABLES))for(let i in n[s][Kc.TABLES])for(let o in n[s][Kc.TABLES][i]){let c=n[s][Kc.TABLES][i][o],u=[Fr.DATABASES,s,Kc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Fr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){It.error("Error parsing schemas CLI/env config arguments",n)}}a(VN,"setSchemasConfig");function vK(e){if(J_===void 0){let r=ci(kN);J_=Qo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return J_[t.toLowerCase()]}a(vK,"getDefaultConfig");function $N(e){if(e==null){It.error(MK);return}if(wt===void 0){It.trace(CK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return wt[t.toLowerCase()]}a($N,"getConfigValue");function Ji(e=Bt.getPropsFilePath()){let t=Bt.getEnvCliRootPath();return t?Dn.join(t,kr.HDB_CONFIG_FILE):FN(e).get(kr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ji,"getConfigFilePath");function ip(e=!1){if(wt===void 0||e){let t;if(!Bt.noBootFile()){t=Bt.getPropsFilePath();try{fr.accessSync(t,fr.constants.F_OK|fr.constants.R_OK)}catch(i){throw It.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ji(t),n;if(r.includes("config/settings.js"))try{KN(r);return}catch(i){if(i.code!==kr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ci(r)}catch(i){if(i.code===kr.NODE_ERROR_CODES.ENOENT){It.trace(`HarperDB config file not found at ${r}.
|
|
7
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw It.error(i),new Error(`Error reading HarperDB config file at ${r}`)}BK(n,r),op(n);let s=n.toJSON();if(wK.config=s,wt=Qo(s),wt.logging_rotation_rotate)for(let i in qN)wt[i]&&It.error(`Config ${qN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);It.trace(DK)}}a(ip,"initConfig");function BK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(It.trace("Updating config file with missing config params"),fr.writeFileSync(t,String(e)))}a(BK,"checkForUpdatedConfig");function op(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=AK(r,t);if(n.error)throw z_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(op,"validateConfig");function HK(e,t){wt===void 0&&(wt={});let r=Ln[e.toLowerCase()];if(r===void 0){It.trace(`Unable to update config object because config param '${e}' does not exist`);return}wt[r.toLowerCase()]=t}a(HK,"updateConfigObject");function YN(e,t,r=void 0,n=!1,s=!1,i=!1){wt===void 0&&ip();let o=$N(Ln.hdb_root),c=Dn.join(o,kr.HDB_CONFIG_FILE),u=ci(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Ln[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=sp(E,t);u.setIn([...f],h)}else for(let E in r){let f=Ln[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===wt[Fr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===wt[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=kr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=sp(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){It.error(T)}}}_&&VN(u,_),op(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,kr.HDB_CONFIG_FILE);n===!0&&xK(c,l),fr.writeFileSync(d,String(u)),s&&(wt=Qo(u.toJSON())),It.trace(`Config parameter: ${e} updated with value: ${t}`)}a(YN,"updateConfigValue");function xK(e,t){try{let r=Dn.join(t,"backup",`${kr.HDB_CONFIG_FILE}.bak`);fr.copySync(e,r),It.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){It.error(LK),It.error(r)}}a(xK,"backupConfigFile");var GK=["databases"];function Qo(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),j_=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!GK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Fr[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Qo,"flattenConfig");function sp(e,t){if(e===Fr.CLUSTERING_NODENAME||e===Fr.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(bK(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Bt.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return Bt.autoCast(t)}a(sp,"castConfigValue");function qK(){let e=Bt.getPropsFilePath(),t=Ji(e);return ci(t).toJSON()}a(qK,"getConfiguration");async function FK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return YN(void 0,void 0,s,!0),PK}catch(i){throw typeof i=="string"||i instanceof String?NK(i,i,IK.BAD_REQUEST,void 0,void 0,!0):i}}a(FK,"setConfiguration");function ap(){let e=Bt.getPropsFilePath();try{fr.accessSync(e,fr.constants.F_OK|fr.constants.R_OK)}catch(n){if(!Bt.noBootFile())throw It.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ji(e);return ci(t).toJSON()}a(ap,"readConfigFile");function ci(e){return OK.parseDocument(fr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ci,"parseYamlDoc");function kK(){let e=ap(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Bt.isEmptyOrZeroLength(t)?[]:t;let r=GN(t);if(r)throw z_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Bt.isEmptyOrZeroLength(n)?[]:n;let s=GN(n);if(s)throw z_.CONFIG_VALIDATION(s.message);if(!Bt.isEmptyOrZeroLength(n)&&!Bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Bt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw z_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(kK,"getClusteringRoutes");function KN(e){let t=FN(e);wt={};for(let r in Ln){let n=t.get(r.toUpperCase());if(Bt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Fr.LOGGING_ROOT?wt[s]=Dn.dirname(n):wt[s]=n}return wt}a(KN,"initOldConfig");function VK(e){let t=ap();return yK.get(t,e.replaceAll("_","."))}a(VK,"getConfigFromFile");async function $K(e,t){let r=ci(Ji());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await fr.writeFile(Ji(),String(r))}a($K,"addConfig");function YK(e){let t=Ji(Bt.getPropsFilePath()),r=ci(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,kr.HDB_CONFIG_FILE);fr.writeFileSync(s,String(r))}a(YK,"deleteConfigFromFile");function KK(){return j_||(ip(),j_)}a(KK,"getConfigObj")});var zN=g((gle,QN)=>{"use strict";var X_=P(),Z_=class{static{a(this,"BaseLicense")}constructor(t=0,r=X_.RAM_ALLOCATION_ENUM.DEFAULT,n=X_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},cp=class extends Z_{static{a(this,"ExtendedLicense")}constructor(t=0,r=X_.RAM_ALLOCATION_ENUM.DEFAULT,n=X_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};QN.exports={BaseLicense:Z_,ExtendedLicense:cp}});var ji=g((Ale,tI)=>{"use strict";var Jo=require("fs-extra"),jN=Y_(),XN=require("crypto"),WK=require("moment"),QK=require("uuid").v4,tr=$(),lp=require("path"),zK=z(),ui=P(),{totalmem:JN}=require("os"),JK=zN().ExtendedLicense,zo="invalid license key format",jK="061183",XK="mofi25",ZK="aes-256-cbc",eW=16,tW=32,ZN=Z();ZN.initSync();var up;tI.exports={validateLicense:eI,generateFingerPrint:nW,licenseSearch:fp,getLicense:oW,checkMemoryLimit:aW};function _p(){return lp.join(ZN.getHdbBasePath(),ui.LICENSE_KEY_DIR_NAME,ui.LICENSE_FILE_NAME)}a(_p,"getLicenseDirPath");function rW(){let e=_p();return lp.join(e,ui.LICENSE_FILE_NAME)}a(rW,"getLicenseFilePath");function dp(){let e=_p();return lp.join(e,ui.REG_KEY_FILE_NAME)}a(dp,"getFingerPrintFilePath");async function nW(){let e=dp();try{return await Jo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await sW();throw tr.error(`Error writing fingerprint file to ${e}`),tr.error(t),new Error("There was an error generating the fingerprint")}}a(nW,"generateFingerPrint");async function sW(){let e=QK(),t=jN.hash(e),r=dp();try{await Jo.mkdirp(_p()),await Jo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw tr.error(`Error writing fingerprint file to ${r}`),tr.error(n),new Error("There was an error generating the fingerprint")}return t}a(sW,"writeFingerprint");function eI(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ui.RAM_ALLOCATION_ENUM.DEFAULT,version:ui.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return tr.error("empty license key passed to validate."),r;let n=dp(),s=!1;try{s=Jo.statSync(n)}catch(i){tr.error(i)}if(s){let i;try{i=Jo.readFileSync(n,"utf8")}catch{tr.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(XK),c=o[1];c=Buffer.concat([Buffer.from(c)],eW);let u=Buffer.concat([Buffer.from(i)],tW),_=XN.createDecipheriv(ZK,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let f=iW(o[0],i);if(f)l=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(zo),tr.error(zo),new Error(zo)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(zo),tr.error(zo),new Error(zo)}else r.exp_date=l;r.exp_date<WK().valueOf()&&(r.valid_date=!1),jN.validate(o[1],`${jK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||tr.error("Invalid licence"),r}a(eI,"validateLicense");function iW(e,t){try{let r=XN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{tr.warn("Check old license failed")}}a(iW,"checkOldLicense");function fp(){let e=new JK,t=[];try{t=Jo.readFileSync(rW(),"utf-8").split(ui.NEW_LINE)}catch(r){r.code==="ENOENT"?tr.info("no license file found"):tr.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(zK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=eI(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){tr.error("There was an error parsing the license string."),tr.error(s),e.ram_allocation=ui.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return up=e,e}a(fp,"licenseSearch");async function oW(){return up||await fp(),up}a(oW,"getLicense");function aW(){let e=fp().ram_allocation,t=process.constrainedMemory?.()||JN();if(t=Math.round(Math.min(t,JN())/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(aW,"checkMemoryLimit")});var ln=g((Ile,pI)=>{"use strict";var iI="username is required",oI="nothing to update, must supply active, role or password to update",aI="password cannot be an empty string",cI="If role is specified, it cannot be empty.",uI="active must be true or false";pI.exports={addUser:mW,alterUser:pW,dropUser:TW,getSuperUser:OW,userInfo:gW,listUsers:td,listUsersExternal:RW,setUsersToGlobal:Xo,findAndValidateUser:hI,getClusterUser:bW,USERNAME_REQUIRED:iI,ALTERUSER_NOTHING_TO_UPDATE:oI,EMPTY_PASSWORD:aI,EMPTY_ROLE:cI,ACTIVE_BOOLEAN:uI};var lI=qr(),cW=ai(),mp=Y_(),_I=wN(),dI=Gr(),pp=ys(),Vr=z(),fI=require("validate.js"),Oe=$(),{promisify:uW}=require("util"),Sp=As(),rI=P(),nI=Ve(),lW=Er(),ble=Z(),yle=ji(),_W=ki(),{table:Nle}=(Ae(),ie(ke)),{handleHDBError:Zn,hdb_errors:dW}=ne(),{HTTP_STATUS_CODES:es,AUTHENTICATION_ERROR_MSGS:Ep,HDB_ERROR_MSGS:jo}=dW,{UserEventMsg:Tp}=Mn(),hp=require("lodash"),{server:gp}=(lr(),ie(xi)),fW=$();gp.getUser=(e,t)=>hI(e,t,t!=null);var EI={username:!0,active:!0,role:!0,password:!0},sI=new Map,ed=dI.searchByValue,EW=dI.searchByHash,hW=uW(cW.delete);async function mW(e){let t=fI.cleanAttributes(e,EI),r=_I.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 ed(n),s=s&&Array.from(s)}catch(u){throw Oe.error("There was an error searching for a role in add user"),Oe.error(u),u}if(!s||s.length<1)throw Zn(new Error,jo.ROLE_NAME_NOT_FOUND(t.role),es.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Zn(new Error,jo.DUP_ROLES_FOUND(t.role),es.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=Sp.encrypt(t.password)),t.password=mp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await lI.insert(i)}catch(u){throw Oe.error("There was an error searching for a user."),Oe.error(u),u}Oe.debug(o);try{await Xo()}catch(u){throw Oe.error("Got an error setting users to global"),Oe.error(u),u}if(o.skipped_hashes.length===1)throw Zn(new Error,jo.USER_ALREADY_EXISTS(t.username),es.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],pp.signalUserChange(new Tp(process.pid)),`${c.username} successfully added`}a(mW,"addUser");async function pW(e){let t=fI.cleanAttributes(e,EI);if(Vr.isEmptyOrZeroLength(t.username))throw new Error(iI);if(Vr.isEmptyOrZeroLength(t.password)&&Vr.isEmptyOrZeroLength(t.role)&&Vr.isEmptyOrZeroLength(t.active))throw new Error(oI);if(!Vr.isEmpty(t.password)&&Vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(aI);if(!Vr.isEmpty(t.active)&&!Vr.isBoolean(t.active))throw new Error(uI);let r=SW(t.username);if(!Vr.isEmpty(t.password)&&!Vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Sp.encrypt(t.password)),t.password=mp.hash(t.password)),t.role==="")throw new Error(cI);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 ed(i)||[])}catch(c){throw Oe.error("Got an error searching for a role."),Oe.error(c),c}if(!o||o.length===0){let c=jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Oe.error(c),Zn(new Error,c,es.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=jo.ALTER_USER_DUP_ROLES(t.role);throw Oe.error(c),Zn(new Error,c,es.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await lI.update(n)}catch(i){throw Oe.error("Error during update."),Oe.error(i),i}try{await Xo()}catch(i){throw Oe.error("Got an error setting users to global"),Oe.error(i),i}return pp.signalUserChange(new Tp(process.pid)),s}a(pW,"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 TW(e){try{let t=_I.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Vr.isEmpty(global.hdb_users.get(e.username)))throw Zn(new Error,jo.USER_NOT_EXIST(e.username),es.NOT_FOUND,void 0,void 0,!0);let n;try{n=await hW(r)}catch(s){throw Oe.error("Got an error deleting a user."),Oe.error(s),s}Oe.debug(n);try{await Xo()}catch(s){throw Oe.error("Got an error setting users to global."),Oe.error(s),s}return pp.signalUserChange(new Tp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(TW,"dropUser");async function gW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=hp.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 Oe.error("Got an error searching for a role."),Oe.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Oe.error(r),r}return t}a(gW,"userInfo");async function RW(){let e;try{e=await td()}catch(t){throw Oe.error("Got an error listing users."),Oe.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(RW,"listUsersExternal");async function td(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await ed(e)}catch(o){throw Oe.error("Got an error searching for roles."),Oe.error(o),o}let r={};for(let o of t)r[o.id]=hp.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 ed(n)}catch(o){throw Oe.error("Got an error searching for users."),Oe.error(o),o}let i=new Map;for(let o of s)o=hp.cloneDeep(o),o.role=r[o.role],AW(o.role),i.set(o.username,o);return i}catch(e){throw Oe.error("got an error listing users"),Oe.error(e),Vr.errorizeMessage(e)}return null}a(td,"listUsers");function AW(e){try{if(!e){Oe.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(_W)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Oe.error("Got an error trying to set system permissions."),Oe.error(t)}}a(AW,"appendSystemTablesToRole");async function Xo(){try{let e=await td();global.hdb_users=e}catch(e){throw Oe.error(e),e}}a(Xo,"setUsersToGlobal");async function hI(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,Ep.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Zn(new Error,Ep.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(sI.get(t)===n.password)return s;if(mp.validate(n.password,t))sI.set(t,n.password);else throw Zn(new Error,Ep.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}return s}a(hI,"findAndValidateUser");async function OW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(OW,"getSuperUser");async function bW(){let e=await td(),t=lW.getConfigFromFile(rI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Vr.isEmpty(r)&&r?.role?.role===rI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Sp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+nI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+nI.SERVER_SUFFIX.ADMIN,r}a(bW,"getClusterUser");var mI=[];gp.invalidateUser=function(e){for(let t of mI)try{t(e)}catch(r){fW.error("Error invalidating user",r)}};gp.onInvalidatedUser=function(e){mI.push(e)}});var Qc=g((Lle,RI)=>{"use strict";var Xi=$(),$r=P(),yW=zy(),Cle=bs(),Dle=Os(),NW=ln(),{validateEvent:SI}=Mn(),Wc=Cn(),IW=require("process"),{resetDatabases:wW}=(Ae(),ie(ke)),CW={[$r.ITC_EVENT_TYPES.SCHEMA]:DW,[$r.ITC_EVENT_TYPES.USER]:gI};async function DW(e){let t=SI(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await yW(e.message),await LW(e.message)}a(DW,"schemaHandler");async function LW(e){try{Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=wW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(LW,"syncSchemaMetadata");var TI=[];async function gI(e){try{try{Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Wc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.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 ${$r.HDB_ITC_CLIENT_PREFIX}${IW.pid} received user event:`,e),await NW.setUsersToGlobal();for(let r of TI)r()}catch(t){Xi.error(t)}}a(gI,"userHandler");gI.addListener=function(e){TI.push(e)};RI.exports=CW});var Mn=g((Hle,OI)=>{"use strict";var Ple=$(),Rp=z(),MW=P(),{ITC_ERRORS:zc}=Ur(),{parentPort:Ule,threadId:PW,isMainThread:UW,workerData:vle}=require("worker_threads"),{onMessageFromWorkers:vW,broadcast:Ble,broadcastWithAcknowledgement:BW}=We();OI.exports={sendItcEvent:HW,validateEvent:AI,SchemaEventMsg:xW,UserEventMsg:GW};var rd;vW(async(e,t)=>{rd=rd||Qc(),AI(e),rd[e.type]&&await rd[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function HW(e){return!UW&&e.message&&(e.message.originator=PW),BW(e)}a(HW,"sendItcEvent");function AI(e){if(typeof e!="object")return zc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Rp.isEmpty(e.type))return zc.MISSING_TYPE;if(!e.hasOwnProperty("message")||Rp.isEmpty(e.message))return zc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Rp.isEmpty(e.message.originator))return zc.MISSING_ORIGIN;if(MW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return zc.INVALID_EVENT(e.type)}a(AI,"validateEvent");function xW(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(xW,"SchemaEventMsg");function GW(e){this.originator=e}a(GW,"UserEventMsg")});var ys=g((qle,II)=>{"use strict";var bI=P(),Gle=z(),nd=$(),yI=Ky(),Zo,{sendItcEvent:NI}=Mn();function qW(e){try{nd.trace("signalSchemaChange called with message:",e),Zo=Zo||Qc();let t=new yI(bI.ITC_EVENT_TYPES.SCHEMA,e);return Zo.schema(t),NI(t)}catch(t){nd.error(t)}}a(qW,"signalSchemaChange");function FW(e){try{nd.trace("signalUserChange called with message:",e),Zo=Zo||Qc();let t=new yI(bI.ITC_EVENT_TYPES.USER,e);return Zo.user(t),NI(t)}catch(t){nd.error(t)}}a(FW,"signalUserChange");II.exports={signalSchemaChange:qW,signalUserChange:FW}});var sd=g((kle,CI)=>{"use strict";var wI=z(),kW=P(),VW=$(),$W=M_(),YW=L_(),KW=ys(),{SchemaEventMsg:WW}=Mn(),QW="already exists in";CI.exports=zW;async function zW(e,t,r){if(wI.isEmptyOrZeroLength(r))return r;let n=[];wI.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 JW(e,t.schema,t.name,i)})),s}a(zW,"lmdbCheckForNewAttributes");async function JW(e,t,r,n){let s=new YW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await jW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(QW))VW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(JW,"createNewAttribute");async function jW(e){let t;return t=await $W(e),KW.signalSchemaChange(new WW(process.pid,kW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(jW,"createAttribute")});var ea=g(($le,DI)=>{"use strict";var Ap=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}};DI.exports=Ap});var MI=g((Kle,LI)=>{"use strict";var XW=ea(),ZW=P().OPERATIONS_ENUM,Op=class extends XW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(ZW.INSERT,r,n,s,i),this.records=t}};LI.exports=Op});var UI=g((Qle,PI)=>{"use strict";var eQ=ea(),tQ=P().OPERATIONS_ENUM,bp=class extends eQ{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(tQ.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};PI.exports=bp});var BI=g((Jle,vI)=>{"use strict";var rQ=ea(),nQ=P().OPERATIONS_ENUM,yp=class extends rQ{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(nQ.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};vI.exports=yp});var xI=g((Xle,HI)=>{"use strict";var sQ=ea(),iQ=P().OPERATIONS_ENUM,Np=class extends sQ{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(iQ.DELETE,n,s,t,i),this.original_records=r}};HI.exports=Np});var Jc=g((t_e,kI)=>{"use strict";var e_e=require("path"),GI=Qe(),oQ=MI(),aQ=UI(),cQ=BI(),uQ=xI(),ta=ft(),qI=z(),{CONFIG_PARAMS:lQ}=P(),FI=Z();FI.initSync();var id=P().OPERATIONS_ENUM,{getTransactionAuditStorePath:_Q}=je();kI.exports=dQ;async function dQ(e,t){if(FI.get(lQ.LOGGING_AUDITLOG)===!1)return;let r=_Q(e.schema,e.table),n=await GI.openEnvironment(r,e.table,!0),s=fQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){GI.initializeDBIs(n,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),qI.isEmpty(s.user_name)||n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(dQ,"writeTransaction");function fQ(e,t){let r=qI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===id.INSERT)return new oQ(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.UPDATE)return new aQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.UPSERT)return new cQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.DELETE)return new uQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(fQ,"createTransactionObject")});var Ip=g((s_e,VI)=>{"use strict";var EQ=qc(),n_e=Fc(),jc=P(),hQ=kc(),mQ=Yo().insertRecords,pQ=Qe(),SQ=$(),TQ=sd(),{getSchemaPath:gQ}=je(),RQ=Jc();VI.exports=AQ;async function AQ(e){try{let{schema_table:t,attributes:r}=EQ(e);hQ(e,r,t.hash_attribute),e.schema!==jc.SYSTEM_SCHEMA_NAME&&(r.includes(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await TQ(e.hdb_auth_header,t,r),s=gQ(e.schema,e.table),i=await pQ.openEnvironment(s,e.table),o=await mQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await RQ(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(AQ,"lmdbCreateRecords")});var KI=g((o_e,YI)=>{"use strict";var $I=P(),OQ=Ip(),bQ=Fc(),yQ=require("fs-extra"),{getSchemaPath:NQ}=je();YI.exports=IQ;async function IQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new bQ($I.SYSTEM_SCHEMA_NAME,$I.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await OQ(r),await yQ.mkdirp(NQ(e.schema))}a(IQ,"lmdbCreateSchema")});var QI=g((c_e,WI)=>{"use strict";var wp=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}};WI.exports=wp});var XI=g((f_e,jI)=>{"use strict";var zI=Qe(),Cp=vr(),Dp=Ur().LMDB_ERRORS_ENUM,wQ=ft(),JI=$(),l_e=z(),CQ=require("lmdb"),DQ=QI(),LQ=P(),{OVERFLOW_MARKER:__e,MAX_SEARCH_KEY_LENGTH:d_e}=wQ,MQ=LQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function PQ(e,t,r,n){if(Cp.validateEnv(e),t===void 0)throw new Error(Dp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Dp.IDS_REQUIRED):new Error(Dp.IDS_MUST_BE_ITERABLE);try{let s=zI.listDBIs(e);zI.initializeDBIs(e,t,s);let i=new DQ,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[MQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,CQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let R=e.dbis[T],b=h[T];if(b!=null)try{let C=Cp.getIndexedValues(b);if(C)for(let H=0,v=C.length;H<v;H++)R.remove(C[H],o)}catch{JI.warn(`cannot delete from attribute: ${T}, ${b}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){JI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let E=0,f=l.length;E<f;E++)l[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),_.push(E));let d=0;for(let E=0;E<_.length;E++){let f=_[E];i.original_records.splice(f-d,1),d++}return i.txn_time=Cp.getNextMonotonicTime(),i}catch(s){throw s}}a(PQ,"deleteRecords");jI.exports={deleteRecords:PQ}});var Xc=g((h_e,ew)=>{"use strict";var ra=z(),UQ=XI(),vQ=Qe(),{getSchemaPath:BQ}=je(),HQ=Jc(),xQ=$();ew.exports=GQ;async function GQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ra.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ra.isEmptyOrZeroLength(e.hash_values)&&!ra.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ra.isEmpty(u)||e.hash_values.push(u)}}if(ra.isEmptyOrZeroLength(e.hash_values))return ZI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ra.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=BQ(e.schema,e.table),i=await vQ.openEnvironment(s,e.table),o=await UQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await HQ(e,o)}catch(c){xQ.error(`unable to write transaction due to ${c.message}`)}return ZI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(GQ,"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 Mp=g((S_e,tw)=>{"use strict";var qQ=P(),p_e=vr();function Lp(e,t){let r=Object.create(null);if(t.length===1&&qQ.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(Lp,"parseRow");function FQ(e,t,r,n){let s=Lp(r,e);n.push(s)}a(FQ,"searchAll");function kQ(e,t,r,n){let s=Lp(r,e);n[t]=s}a(kQ,"searchAllToMap");function VQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(VQ,"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 $Q(e,t,r,n,s,i){t.toString().endsWith(e)&&Zi(t,r,n,s,i)}a($Q,"endsWith");function YQ(e,t,r,n,s,i){t.toString().includes(e)&&Zi(t,r,n,s,i)}a(YQ,"contains");function KQ(e,t,r,n,s,i){t>e&&Zi(t,r,n,s,i)}a(KQ,"greaterThanCompare");function WQ(e,t,r,n,s,i){t>=e&&Zi(t,r,n,s,i)}a(WQ,"greaterThanEqualCompare");function QQ(e,t,r,n,s,i){t<e&&Zi(t,r,n,s,i)}a(QQ,"lessThanCompare");function zQ(e,t,r,n,s,i){t<=e&&Zi(t,r,n,s,i)}a(zQ,"lessThanEqualCompare");tw.exports={parseRow:Lp,searchAll:FQ,searchAllToMap:kQ,iterateDBI:VQ,endsWith:$Q,contains:YQ,greaterThanCompare:KQ,greaterThanEqualCompare:WQ,lessThanCompare:QQ,lessThanEqualCompare:zQ,pushResults:Zi}});var na=g((O_e,cw)=>{"use strict";var li=Qe(),g_e=$(),Yr=vr(),od=ft(),ht=Ur().LMDB_ERRORS_ENUM,R_e=z(),JQ=P(),ad=Mp(),{parseRow:jQ}=ad,A_e=require("lmdb"),{OVERFLOW_MARKER:rw,MAX_SEARCH_KEY_LENGTH:XQ}=od;function nw(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(nw,"iterateFullIndex");function Zc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return eo(e,t,r,(l,d,E,f)=>{let R={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return f===r?(R.values=!1,d.getRange(R).map(b=>({value:b}))):d.getRange(R)})}a(Zc,"iterateRangeBetween");function eo(e,t,r,n){let s=e.database||e,i=li.openDBI(s,r);i[od.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&li.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 sw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(rw)){if(!s)if(r)s=li.openDBI(e,r);else{let u=li.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=li.openDBI(e,u[_]),!s[od.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(sw,"getOverflowCheck");function ZQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return eo(e,t,t,(o,c,u)=>(cd(r),r=eu(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>jQ(_.value,r))))}a(ZQ,"searchAll");function ez(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);cd(r),r=eu(e.database||e,r);let o=new Map;for(let{key:c,value:u}of nw(e,t,t,n,s,i))o.set(c,ad.parseRow(u,r));return o}a(ez,"searchAllToMap");function tz(e,t,r=!1,n=void 0,s=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=nw(e,void 0,t,r,n,s),c=o.transaction,u=sw(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(tz,"iterateDBI");function rz(e,t){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return li.statDBI(e,t).entryCount}a(rz,"countAll");function nz(e,t,r,n,s=!1,i=void 0,o=void 0){return _i(e,r,n),eo(e,t,r,(c,u,_,l)=>(n=Yr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(nz,"equals");function sz(e,t,r){return _i(e,t,r),li.openDBI(e,t).getValuesCount(r)}a(sz,"count");function iz(e,t,r,n,s=!1,i=void 0,o=void 0){return _i(e,r,n),eo(e,null,r,(c,u)=>{n=Yr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let E of u.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(n))return E;if(_===!0)return l.DONE}}),l.filter(E=>E)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(iz,"startsWith");function oz(e,t,r,n,s=!1,i=void 0,o=void 0){return iw(e,t,r,n,s,i,o,!0)}a(oz,"endsWith");function iw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return _i(e,r,n),eo(e,null,r,(u,_,l,d)=>{let E=sw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(rw)?_.getValues(f,{transaction:u}).map(p=>{let S=E(f,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[od.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:u}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(iw,"contains");function az(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Zc(e,t,r,n,u,s,i,o,!0,!1)}a(az,"greaterThan");function cz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Zc(e,t,r,n,u,s,i,o,!1,!1)}a(cz,"greaterThanEqual");function uz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Zc(e,t,r,u,n,s,i,o,!1,!0)}a(uz,"lessThan");function lz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Zc(e,t,r,u,n,s,i,o,!1,!1)}a(lz,"lessThanEqual");function _z(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Yr.validateEnv(e),r===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ht.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ht.END_VALUE_REQUIRED);if(n=Yr.convertKeyValueToWrite(n),s=Yr.convertKeyValueToWrite(s),n>s)throw new Error(ht.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Zc(e,t,r,n,s,i,o,c)}a(_z,"between");function dz(e,t,r,n){Yr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(cd(r),r=eu(s,r),n===void 0)throw new Error(ht.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=ad.parseRow(c,r)),o}a(dz,"searchByHash");function fz(e,t,r){Yr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(fz,"checkHashExists");function Ez(e,t,r,n,s=[]){return aw(e,t,r,n,s),ow(e,t,r,n,s).map(i=>i[1])}a(Ez,"batchSearchByHash");function hz(e,t,r,n,s=[]){aw(e,t,r,n,s);let i=new Map;for(let[o,c]of ow(e,t,r,n,s))i.set(o,c);return i}a(hz,"batchSearchByHashToMap");function ow(e,t,r,n,s=[]){return eo(e,t,t,(i,o,c)=>{r=eu(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,ad.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(ow,"batchHashSearch");function aw(e,t,r,n,s){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(cd(r),n==null)throw new Error(ht.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ht.IDS_MUST_BE_ITERABLE)}a(aw,"initializeBatchSearchByHash");function cd(e){if(!Array.isArray(e))throw e===void 0?new Error(ht.FETCH_ATTRIBUTES_REQUIRED):new Error(ht.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(cd,"validateFetchAttributes");function _i(e,t,r){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.SEARCH_VALUE_REQUIRED);if(r?.length>XQ)throw new Error(ht.SEARCH_VALUE_TOO_LARGE)}a(_i,"validateComparisonFunctions");function eu(e,t){return t.length===1&&JQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=li.listDBIs(e)),t}a(eu,"setGetWholeRowAttributes");cw.exports={searchAll:ZQ,searchAllToMap:ez,count:sz,countAll:rz,equals:nz,startsWith:iz,endsWith:oz,contains:iw,searchByHash:dz,setGetWholeRowAttributes:eu,batchSearchByHash:Ez,batchSearchByHashToMap:hz,checkHashExists:fz,iterateDBI:tz,greaterThan:az,greaterThanEqual:cz,lessThan:uz,lessThanEqual:lz,between:_z}});var sa=g((y_e,fw)=>{var uw=require("lodash"),lw=Xe(),fe=require("joi"),mz=z(),{hdb_schema_table:tu,checkValidTable:_w,hdb_table:dw,hdb_database:ud}=Jn(),{handleHDBError:pz,hdb_errors:Sz}=ne(),{getDatabases:Tz}=(Ae(),ie(ke)),{HTTP_STATUS_CODES:gz}=Sz,Rz=fe.object({database:ud,schema:ud,table:dw,search_attribute:tu,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(tu,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),Az=fe.object({database:ud,schema:ud,table:dw,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(tu,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(tu,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(tu,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()});fw.exports=function(e,t){let r=null;switch(t){case"value":r=lw.validateBySchema(e,Rz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(_w("database",e.schema)),i(_w("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=lw.validateBySchema(e,Az);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=mz.checkGlobalSchemaTable(e.schema,e.table);if(s)return pz(new Error,s,gz.NOT_FOUND);let o=Tz()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,E=l.conditions.length;d<E;d++){let f=l.conditions[d];f.conditions?u(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=uw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!uw.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 Pp=g((I_e,Ew)=>{"use strict";var Oz=Qe(),bz=sa(),{getSchemaPath:yz}=je();Ew.exports=Nz;function Nz(e){let t=bz(e,"hashes");if(t)throw t;let r=yz(e.schema,e.table);return Oz.openEnvironment(r,e.table)}a(Nz,"initialize")});var Up=g((C_e,hw)=>{"use strict";var Iz=na(),wz=Pp();hw.exports=Cz;async function Cz(e){let t=await wz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Iz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Cz,"lmdbGetDataByHash")});var ia=g((L_e,mw)=>{"use strict";var vp=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};mw.exports=vp});var Sw=g((U_e,pw)=>{"use strict";var P_e=ia(),Dz=na(),Lz=Pp();pw.exports=Mz;async function Mz(e){let t=await Lz(e),r=global.hdb_schema[e.schema][e.table];return Dz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(Mz,"lmdbSearchByHash")});var ts=g((B_e,Tw)=>{"use strict";var Bp=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}};Tw.exports=Bp});var ld=g((x_e,yw)=>{"use strict";var rr=na(),Pz=Qe(),Uz=z(),Ee=ft(),to=P(),vz=ki(),gw=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:Bz}=je(),Ns=to.SEARCH_WILDCARDS;async function Hz(e,t,r){let n;e.schema===to.SYSTEM_SCHEMA_NAME?n=vz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=bw(e,n.hash_attribute,r,t);return Aw(e,s,n.hash_attribute,r)}a(Hz,"prepSearch");async function Aw(e,t,r,n){let s=Bz(e.schema,e.table),i=await Pz.openEnvironment(s,e.table),o=Ow(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(xz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Rw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[l]:E.key}),"toObject");return n?Rw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?rr.batchSearchByHashToMap(c,r,e.get_attributes,_):rr.batchSearchByHash(c,r,e.get_attributes,_)}a(Aw,"executeSearch");function Ow(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=rr.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=rr.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=rr.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=rr.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return rr.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return rr.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return rr.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return rr.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=rr.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=rr.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=rr.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=rr.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=rr.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Ow,"searchByType");function Rw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Rw,"createMapFromIterable");function xz(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(xz,"checkToFetchMore");function bw(e,t,r,n){if(Uz.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Ns.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Ns[0])<0&&s.indexOf(Ns[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(Ns.indexOf(i)>=0&&Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(Ns.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(Ns[0])||s.includes(Ns[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(gw.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(gw.UNKNOWN_SEARCH_TYPE)}}a(bw,"createSearchTypeFromSearchObject");yw.exports={executeSearch:Aw,createSearchTypeFromSearchObject:bw,prepSearch:Hz,searchByType:Ow}});var Iw=g((F_e,Nw)=>{"use strict";var q_e=ts(),Gz=sa(),qz=z(),Fz=P(),kz=ld();Nw.exports=Vz;function Vz(e,t){if(!qz.isEmpty(t)&&Fz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Gz(e,"value");if(n)throw n;return kz.prepSearch(e,t,!0)}a(Vz,"lmdbGetDataByValue")});var ru=g(($_e,ww)=>{"use strict";var V_e=ts(),$z=sa(),Yz=z(),Kz=P(),Wz=ld();ww.exports=Qz;async function Qz(e,t){if(!Yz.isEmpty(t)&&Kz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=$z(e,"value");if(n)throw n;return Wz.prepSearch(e,t,!1)}a(Qz,"lmdbSearchByValue")});var Dw=g((W_e,Cw)=>{"use strict";var K_e=ft(),Hp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},xp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Gp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Cw.exports={SearchByConditionsObject:Hp,SearchCondition:xp,SortAttribute:Gp}});var vw=g((j_e,Uw)=>{"use strict";var z_e=Dw().SearchByConditionsObject,zz=ts(),Jz=sa(),qp=na(),_d=ft(),{Resource:J_e}=(Nn(),ie(Fp)),Pw=ld(),jz=Mp(),Xz=require("lodash"),{getSchemaPath:Zz}=je(),Lw=Qe(),{handleHDBError:eJ,hdb_errors:tJ}=ne(),{HTTP_STATUS_CODES:rJ}=tJ,nJ=1e8;Uw.exports=sJ;async function sJ(e){let t=Jz(e,"conditions");if(t)throw eJ(t,t.message,rJ.BAD_REQUEST,void 0,void 0,!0);e.operator=e.operator?e.operator.toLowerCase():void 0,e.offset=Number.isInteger(e.offset)?e.offset:0;let r=Zz(e.schema,e.table),n=await Lw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Lw.openDBI(n,_.search_attribute);let i=Xz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===_d.SEARCH_TYPES.EQUALS?_.estimated_count=qp.count(n,_.search_attribute,_.search_value):l===_d.SEARCH_TYPES.CONTAINS||l===_d.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=nJ}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Mw(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(Pw.filterByType),d=l.length,E=qp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!l[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>jz.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await Mw(o,e,E,s.hash_attribute);c=c.concat(f)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=qp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(sJ,"lmdbSearchByConditions");async function Mw(e,t,r,n){let s=new zz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===_d.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Pw.searchByType(e,s,i,n).map(o=>o.value)}a(Mw,"executeConditionSearch")});var oa=g((Z_e,Bw)=>{"use strict";var iJ=P().OPERATIONS_ENUM,kp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=iJ.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Bw.exports=kp});var Vp=g((tde,$w)=>{"use strict";var qw=ts(),Fw=oa(),kw=ru(),Vw=Xc(),hr=P(),Hw=z(),xw=Qe(),{getTransactionAuditStorePath:oJ,getSchemaPath:aJ}=je(),Gw=$();$w.exports=cJ;async function cJ(e){try{if(Hw.isEmpty(global.hdb_schema[e.schema])||Hw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await uJ(e),await lJ(e);let t=aJ(e.schema,e.table);try{await xw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Gw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=oJ(e.schema,e.table);await xw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Gw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(cJ,"lmdbDropTable");async function uJ(e){let t=new qw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await kw(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 Fw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Vw(s)}a(uJ,"deleteAttributesFromSystem");async function lJ(e){let t=new qw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await kw(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 Fw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Vw(s)}catch(i){throw i}}a(lJ,"dropTableFromSystem")});var Kw=g((nde,Yw)=>{"use strict";var _J=require("fs-extra"),dJ=ts(),fJ=ia(),EJ=oa(),hJ=Vp(),mJ=Xc(),pJ=Up(),SJ=ru(),Is=P(),{getSchemaPath:TJ}=je(),{handleHDBError:gJ,hdb_errors:RJ}=ne(),{HDB_ERROR_MSGS:AJ,HTTP_STATUS_CODES:OJ}=RJ;Yw.exports=bJ;async function bJ(e){let t;try{t=await yJ(e.schema);let r=new dJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await SJ(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await hJ(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new EJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await mJ(s);let i=TJ(t);await _J.remove(i)}catch(r){throw r}}a(bJ,"lmdbDropSchema");async function yJ(e){let t=new fJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await pJ(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw gJ(new Error,AJ.SCHEMA_NOT_FOUND(e),OJ.NOT_FOUND,void 0,void 0,!0);return n}a(yJ,"validateDropSchema")});var dd=g((ide,Ww)=>{"use strict";var $p=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Ww.exports=$p});var zw=g((cde,Qw)=>{"use strict";var NJ=require("fs-extra"),fd=Qe(),{getTransactionAuditStorePath:IJ}=je(),Yp=ft(),ade=dd();Qw.exports=wJ;async function wJ(e){let t;try{let r=IJ(e.schema,e.table);await NJ.mkdirp(r),t=await fd.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{fd.createDBI(t,Yp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),fd.createDBI(t,Yp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),fd.createDBI(t,Yp.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(wJ,"createTransactionsAuditEnvironment")});var Zw=g((lde,Xw)=>{"use strict";var Kp=P(),Jw=Qe(),CJ=Yo(),{getSystemSchemaPath:DJ,getSchemaPath:LJ}=je(),MJ=ki(),PJ=M_(),Wp=L_(),UJ=$(),vJ=zw(),zp=MJ.hdb_table,jw=[];for(let e=0;e<zp.attributes.length;e++)jw.push(zp.attributes[e].attribute);Xw.exports=BJ;async function BJ(e,t){let r=LJ(t.schema,t.table),n=new Wp(t.schema,t.table,Kp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Wp(t.schema,t.table,Kp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Wp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Jw.createEnvironment(r,t.table),e!==void 0){let o=await Jw.openEnvironment(DJ(),Kp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await CJ.insertRecords(o,zp.hash_attribute,jw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Qp(n),await Qp(s),await Qp(i)}await vJ(t)}catch(o){throw o}}a(BJ,"lmdbCreateTable");async function Qp(e){try{await PJ(e)}catch(t){UJ.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Qp,"createAttribute")});var tC=g((dde,eC)=>{"use strict";var HJ=qc(),xJ=kc(),GJ=sd(),nu=P(),qJ=Yo().updateRecords,FJ=Qe(),{getSchemaPath:kJ}=je(),VJ=Jc(),$J=$();eC.exports=YJ;async function YJ(e){try{let{schema_table:t,attributes:r}=HJ(e);xJ(e,r,t.hash_attribute),e.schema!==nu.SYSTEM_SCHEMA_NAME&&(r.includes(nu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(nu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(nu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(nu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await GJ(e.hdb_auth_header,t,r),s=kJ(e.schema,e.table),i=await FJ.openEnvironment(s,e.table),o=await qJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await VJ(e,o)}catch(c){$J.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(YJ,"lmdbUpdateRecords")});var nC=g((Ede,rC)=>{"use strict";var KJ=P().OPERATIONS_ENUM,Jp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=KJ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};rC.exports=Jp});var iC=g((pde,sC)=>{"use strict";var mde=nC(),WJ=qc(),QJ=kc(),zJ=sd(),su=P(),JJ=Yo().upsertRecords,jJ=Qe(),{getSchemaPath:XJ}=je(),ZJ=Jc(),e2=$(),{handleHDBError:t2,hdb_errors:r2}=ne();sC.exports=n2;async function n2(e){let t;try{t=WJ(e)}catch(u){throw t2(u,u.message,r2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;QJ(e,n,r.hash_attribute),e.schema!==su.SYSTEM_SCHEMA_NAME&&(n.includes(su.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(su.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(su.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(su.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await zJ(e.hdb_auth_header,r,n),i=XJ(e.schema,e.table),o=await jJ.openEnvironment(i,e.table),c=await JJ(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await ZJ(e,c)}catch(u){e2.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(n2,"lmdbUpsertRecords")});var aC=g((Tde,oC)=>{"use strict";var jp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};oC.exports=jp});var uC=g((Rde,cC)=>{"use strict";var Xp=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}};cC.exports=Xp});var dC=g((bde,_C)=>{"use strict";var Zp=Qe(),{getTransactionAuditStorePath:s2}=je(),Ode=aC(),iu=ft(),i2=z(),lC=uC(),o2=require("util").promisify,a2=o2(setTimeout),c2=1e4,u2=100;_C.exports=l2;async function l2(e){let t=s2(e.schema,e.table),r=await Zp.openEnvironment(t,e.table,!0),n=Zp.listDBIs(r);Zp.initializeDBIs(r,iu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new lC;do s=await _2(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 a2(u2);while(s.transactions_deleted>0);return i}a(l2,"deleteAuditLogsBefore");async function _2(e,t){let r=new lC;try{let n=e.dbis[iu.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[iu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];i2.isEmpty(c)||(s=e.dbis[iu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[iu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>c2)break}return await s,r}catch(n){throw n}}a(_2,"deleteTransactions")});var EC=g((Nde,fC)=>{"use strict";var eS=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};fC.exports=eS});var mC=g((Cde,hC)=>{"use strict";var d2=ts(),f2=oa(),wde=EC(),rs=P(),E2=z(),tS=Qe(),h2=ki(),m2=ru(),p2=Xc(),{getSchemaPath:S2}=je();hC.exports=T2;async function T2(e,t=!0){let r;e.schema===rs.SYSTEM_SCHEMA_NAME?r=h2[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await R2(e),s=S2(e.schema,e.table),i=await tS.openEnvironment(s,e.table);return t===!0&&await g2(e,i,r.hash_attribute),tS.dropDBI(i,e.attribute),n}a(T2,"lmdbDropAttribute");async function g2(e,t,r){let n=tS.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(g2,"removeAttributeFromAllObjects");async function R2(e){let t=new d2(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 m2(t)).filter(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(E2.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 f2(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return p2(i)}a(R2,"dropAttributeFromSystem")});var AC=g((Mde,RC)=>{"use strict";var rS=Qe(),aa=ft(),Lde=vr(),nS=P(),pC=z(),{getTransactionAuditStorePath:A2}=je(),O2=na(),Ed=ea(),b2=$();RC.exports=y2;async function y2(e){let t=A2(e.schema,e.table),r=await rS.openEnvironment(t,e.table,!0),n=rS.listDBIs(r);rS.initializeDBIs(r,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case nS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return SC(r,e.search_values);case nS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,I2(r,e.search_values,s);case nS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return N2(r,e.search_values);default:return SC(r)}}a(y2,"readAuditLog");function SC(e,t=[0,Date.now()]){pC.isEmpty(t[0])&&(t[0]=0),pC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new Ed,s))}a(SC,"searchTransactionsByTimestamp");function N2(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,gC(e,i))}return Object.fromEntries(r)}a(N2,"searchTransactionsByUsername");function I2(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=O2.equals(e,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,aa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=gC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);TC(u,"records",r,l,o),TC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(I2,"searchTransactionsByHashValues");function TC(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 Ed(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new Ed(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(TC,"loopRecords");function gC(e,t){let r=[];try{let n=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new Ed,i);r.push(o)}}catch(i){b2.warn(i)}return r}catch(n){throw n}}a(gC,"batchSearchTransactions")});var bC=g((Bde,OC)=>{"use strict";var{getSchemaPath:Ude}=je(),vde=Qe(),{database:w2}=(Ae(),ie(ke));OC.exports={writeTransaction:C2};async function C2(e,t,r){return w2({database:e,table:t}).transaction(r)}a(C2,"writeTransaction")});var wC=g((xde,IC)=>{"use strict";var{getSchemaPath:yC}=je(),NC=Qe();IC.exports={flush:D2,resetReadTxn:L2};async function D2(e,t){return(await NC.openEnvironment(yC(e,t),t.toString())).flushed}a(D2,"flush");async function L2(e,t){try{(await NC.openEnvironment(yC(e,t),t.toString())).resetReadTxn()}catch{}}a(L2,"resetReadTxn")});var MC=g((qde,LC)=>{"use strict";var{Readable:M2}=require("stream"),{getDatabases:P2}=(Ae(),ie(ke)),{readSync:U2,openSync:v2,createReadStream:CC}=require("fs"),{open:B2}=require("lmdb"),DC=Pc(),H2=Uc(),{AUDIT_STORE_OPTIONS:x2}=(ri(),ie(PC)),{INTERNAL_DBIS_NAME:G2,AUDIT_STORE_NAME:q2}=ft();LC.exports=k2;var sS=32768,F2=100;async function k2(e){let t=e.database||e.schema||"data",r=P2()[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=B2({noSync:!0,maxDbs:H2.MAX_DBS}),E,f=d.openDB(G2,new DC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(R,b){b.encoding="binary",b.encoder=void 0;let C=d.openDB(R,b),H=l.openDB(R,b);for(let{key:v,version:F,value:M}of H.getRange({start:null,transaction:h,versions:H.useVersions}))E=C.put(v,M,F),p++%F2===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:b}of l.getRange({transaction:h,start:!1}))if(s.some(C=>R.startsWith?.(C+"/"))){f.put(R,b);let[,C]=R.split("/"),H=!C,v=new DC(!H,H);await S(R,v)}e.include_audit&&await S(q2,Object.assign({},x2)),await E;let T=CC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=v2(o.path);return o.transaction(()=>{let _=Buffer.alloc(sS);U2(c,_,0,sS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=CC(null,{fd:c,start:sS}),E=new M2.from(async function*(){yield _;for await(let f of d)l.openTimer&&(l.openTimer=0),yield f;l.done()}());return E.headers=u(),E});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(k2,"getBackup")});var BC=g((kde,vC)=>{"use strict";var V2=$(),{handleHDBError:$2}=ne(),Y2=Qb(),K2=M_(),W2=Ip(),Q2=KI(),z2=Xc(),J2=Up(),j2=Sw(),X2=Iw(),Z2=ru(),e4=vw(),t4=Kw(),r4=Zw(),n4=tC(),s4=iC(),i4=dC(),o4=Vp(),a4=mC(),c4=AC(),u4=bC(),UC=wC(),l4=MC(),iS=class extends Y2{static{a(this,"LMDBBridge")}async searchByConditions(t){return e4(t)}async getDataByHash(t){return await J2(t)}async searchByHash(t){return await j2(t)}async getDataByValue(t,r){return await X2(t,r)}async searchByValue(t){return await Z2(t)}async createSchema(t){return await Q2(t)}async dropSchema(t){return await t4(t)}async createTable(t,r){return await r4(t,r)}async dropTable(t){return await o4(t)}async createAttribute(t){return await K2(t)}async createRecords(t){return await W2(t)}async updateRecords(t){return await n4(t)}async upsertRecords(t){try{return await s4(t)}catch(r){throw $2(r,null,null,V2.ERR,r)}}async deleteRecords(t){return await z2(t)}async dropAttribute(t){return await a4(t)}async deleteAuditLogsBefore(t){return await i4(t)}async readAuditLog(t){return await c4(t)}writeTransaction(t,r,n){return u4.writeTransaction(t,r,n)}flush(t,r){return UC.flush(t,r)}resetReadTxn(t,r){return UC.resetReadTxn(t,r)}getBackup(t){return l4(t)}};vC.exports=iS});function E4(){f4=setInterval(function(){for(let e of oS)if(e.stale){let t=e[ye]?.url;qC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},d4).unref()}var aS,GC,qC,FC,kC,VC,HC,oS,_4,ou,xC,ro,hd,d4,f4,cS=Re(()=>{aS=B(vr()),GC=B(ne()),qC=B($());Nn();FC=B(Z()),kC=B(P()),VC=B(z()),HC=100,oS=new Set,_4=(0,VC.convertToMS)(FC.get(kC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,ro=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),oS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(oS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(ou&&!this.overloadChecked&&performance.now()-xC>_4)throw new GC.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,aS.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let f=d;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=d;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let p=d;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let T=S[f===0?"before":"beforeIntermediate"];if(T){let R=T();h?h.push?h.push(R):h=[h,R]:h=R}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),u=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let E=d.store.ifVersion(d.key,d.entry?.version??null,u);s=s||E}else u();else for(let E of this.writes)c(E)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<HC>>n?u():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return ou||(ou=s,xC=performance.now(),ou.then(()=>{ou=null})),s.then(d=>d?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(_&&(_.retryRisk=(_.retryRisk||0)+HC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},hd=class extends ro{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,aS.getNextMonotonicTime)())}getReadTxn(){}},d4=3e4;a(E4,"startMonitoringTxns");E4()});function Ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new 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 $C,no=Re(()=>{$C=require("../index");Nn();cS();a(Ze,"transaction");(0,$C._assignPackageExport)("transaction",Ze);Ze.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ze.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 ZC={};Fe(ZC,{ResourceBridge:()=>_S});function dS({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 KC(e,t){let r=ns(e),n=dS(e,r);if(!r)throw new Pn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&pd(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||m4,r=mr()[t];if(!r)throw(0,Pn.handleHDBError)(new Error,h4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function WC(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 zC,md,Pn,JC,jC,Un,uS,lS,XC,h4,m4,p4,S4,YC,_S,eD=Re(()=>{"use strict";zC=B(BC()),md=B(sa()),Pn=B(ne());Ae();JC=B(qc()),jC=B(kc()),Un=B(P()),uS=B(ys()),lS=B(Mn()),XC=B(z());no();Sd();({HDB_ERROR_MSGS:h4}=Pn.hdb_errors),m4="data",p4=1e4,S4=10,_S=class extends zC.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,md.default)(t,"conditions");if(r)throw(0,Pn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=ns(t);if(!n)throw new Pn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:dS(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Pn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}Et({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await ns(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=ns(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){ns(t).dropTable()}createSchema(t){return ca({database:t.schema,table:null}),uS.signalSchemaChange(new lS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await fS(t.schema),uS.signalSchemaChange(new lS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,YC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,JC.default)(t);(0,jC.default)(t,n,r.primaryKey);let s,i=mr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(E=>E.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=pd(d));for(let E in l)if(Object.prototype.hasOwnProperty.call(l,E)){let f=l[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,l[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(l),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(l,E)||(l[E]=d[E]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=mr()[t.schema][t.table],n={user:t.hdb_user};return Ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return WC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=mr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Pn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,XC.async_set_timeout)(S4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%p4===0&&await _();return u.length>0&&await _(),s?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,md.default)(t,"hashes");if(r)throw r;return KC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of KC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,md.default)(t,"value");if(n)throw n;let s=ns(t);if(!s)throw new Pn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Un.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:dS(t,s)})}async getDataByValue(t,r){let n=new Map,s=ns(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){ns({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return ns(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=ns(t),n={};switch(t.search_type){case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of 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(dS,"getSelect");a(KC,"getRecords");a(ns,"getTable");a(WC,"createDeleteResponse");a(QC,"groupRecordsInHistory")});var Cn=g((nfe,tD)=>{"use strict";var{ResourceBridge:T4}=(eD(),ie(ZC)),g4=Z();g4.initSync();var Td;function R4(){return Td||(Td=new T4,Td)}a(R4,"getBridge");tD.exports=R4()});var iD=g((ife,sD)=>{"use strict";var rD=require("lodash"),au=require("mathjs"),A4=require("jsonata"),nD=z();sD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?rD.uniqWith(e,rD.isEqual):e,searchJSON:O4,mad:cu.bind(null,au.mad),mean:cu.bind(null,au.mean),mode:cu.bind(null,au.mode),prod:cu.bind(null,au.prod),median:cu.bind(null,au.median)};function cu(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(cu,"aggregateFunction");function O4(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(nD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),nD.isEmpty(this.__ala__.res[r])){let n=A4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(O4,"searchJSON")});var aD=g((afe,oD)=>{"use strict";var Rt=require("moment"),ES="YYYY-MM-DDTHH:mm:ss.SSSZZ";Rt.suppressDeprecationWarnings=!0;oD.exports={current_date:()=>Rt().utc().format("YYYY-MM-DD"),current_time:()=>Rt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Rt(e).utc().format("YYYY");case"month":return Rt(e).utc().format("MM");case"day":return Rt(e).utc().format("DD");case"hour":return Rt(e).utc().format("HH");case"minute":return Rt(e).utc().format("mm");case"second":return Rt(e).utc().format("ss");case"millisecond":return Rt(e).utc().format("SSS");default:break}},date:e=>Rt(e).utc().format(ES),date_format:(e,t)=>Rt(e).utc().format(t),date_add:(e,t,r)=>Rt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Rt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=Rt(e).utc(),s=Rt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>Rt().utc().valueOf(),get_server_time:()=>Rt().format(ES),offset_utc:(e,t)=>Rt(e).utc().utcOffset(t).format(ES)}});var _D=g((cfe,lD)=>{"use strict";var b4=require("@turf/area"),y4=require("@turf/length"),N4=require("@turf/circle"),I4=require("@turf/difference"),w4=require("@turf/distance"),C4=require("@turf/boolean-contains"),D4=require("@turf/boolean-equal"),L4=require("@turf/boolean-disjoint"),M4=require("@turf/helpers"),cD=P(),Se=z(),ws=$();lD.exports={geoArea:P4,geoLength:U4,geoCircle:v4,geoDifference:B4,geoDistance:uD,geoNear:H4,geoContains:x4,geoEqual:G4,geoCrosses:q4,geoConvert:F4};function P4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return b4.default(e)}catch(t){return ws.trace(t,e),NaN}}a(P4,"geoArea");function U4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return y4.default(e,{units:t||"kilometers"})}catch(r){return ws.trace(r,e),NaN}}a(U4,"geoLength");function v4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return N4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(v4,"geoCircle");function B4(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 I4(e,t)}catch(r){return ws.trace(r,e,t),NaN}}a(B4,"geoDifference");function uD(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 w4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(uD,"geoDistance");function H4(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 uD(e,t,n)<=r}catch(s){return ws.trace(s,e,t),!1}}a(H4,"geoNear");function x4(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 C4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(x4,"geoContains");function G4(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 D4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(G4,"geoEqual");function q4(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!L4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(q4,"geoCrosses");function F4(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(cD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(cD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),M4[t](e,r)}a(F4,"geoConvert")});var gd=g((lfe,dD)=>{var so=iD(),Kr=aD(),ss=_D();dD.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=Kr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Kr.current_time,e.fn.extract=e.fn.EXTRACT=Kr.extract,e.fn.date=e.fn.DATE=Kr.date,e.fn.date_format=e.fn.DATE_FORMAT=Kr.date_format,e.fn.date_add=e.fn.DATE_ADD=Kr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Kr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Kr.date_diff,e.fn.now=e.fn.NOW=Kr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Kr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Kr.get_server_time,e.fn.getdate=e.fn.GETDATE=Kr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Kr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ss.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ss.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ss.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ss.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ss.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ss.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ss.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ss.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ss.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ss.geoNear}});var mD=g((_fe,hD)=>{"use strict";var uu=require("lodash"),pr=require("alasql");pr.options.cache=!1;var k4=gd(),fD=require("clone"),Rd=require("recursive-iterator"),_e=$(),De=z(),ua=Cn(),V4=P(),{hdb_errors:$4}=ne(),{getDatabases:ED}=(Ae(),ie(ke)),Y4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";k4(pr);var hS=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.isEmpty(t))throw _e.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.isEmptyOrZeroLength(n))return _e.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw _e.error("Error thrown from checkEmptySQL in SQLSearch class method search."),_e.error(n),new Error(vn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw _e.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),_e.error(n),new Error(vn)}if(Object.keys(this.data).length===0)return _e.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw _e.error("Error thrown from processJoins in SQLSearch class method search."),_e.error(n),new Error(vn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw _e.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),_e.error(n),new Error(vn)}try{return t=await this._finalSQL(),t}catch(n){throw _e.error("Error thrown from finalSQL in SQLSearch class method search."),_e.error(n),new Error(vn)}}_getColumns(){let t=new Rd(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(fD(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=uu.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=ED()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){_e.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Rd(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new pr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new pr.yy.LogicValue({value:i}):n instanceof pr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new pr.yy.NumValue({value:i}))});if(t){_e.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Rd(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!De.isEmpty(V4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(De.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&uu.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pr.promise(r)}catch(r){throw _e.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),_e.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(fD(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(De.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(Y4)>-1&&this.tables.forEach(s=>{let i={columnid:ED()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=uu.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ua.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let E=await ua.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,E=l.length;d<E;d++){let f=l[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ua.getDataByValue(c,f.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ua.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(vn)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof pr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new pr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new pr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new pr.yy.FuncValue:new pr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,p=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${p}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${p}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await pr.promise(h,t),t=null}catch(f){throw _e.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),_e.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let p=E[f];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),p=uu.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let R=p[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[R]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new Rd(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=uu.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw _e.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),_e.error(i),new Error(vn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ua.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let E=o[l],f=u.get(E);for(let h=0;h<_;h++){let p=s.columns[h],S=f[p]===void 0?null:f[p];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getData."),_e.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();_e.trace(`Final SQL: ${s}`),n=await pr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),_e.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw _e.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),_e.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return _e.error($4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),_e.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ua.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw _e.error("There was an error when processing this SQL operation. Check your logs"),_e.error(o),new Error(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};hD.exports=hS});var Gr=g((ffe,pD)=>{"use strict";var K4=Kb();pD.exports={searchByConditions:Q4,searchByHash:z4,searchByValue:J4,search:j4};var mS=Cn(),{transformReq:pS}=z(),W4=mD();async function Q4(e){return pS(e),mS.searchByConditions(e)}a(Q4,"searchByConditions");async function z4(e){pS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of mS.searchByHash(e))r&&t.push(r);return t}a(z4,"searchByHash");async function J4(e){pS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of mS.searchByValue(e))t.push(r);return t}a(J4,"searchByValue");function j4(e,t){try{let r=new K4(e);r.validate(),new W4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(j4,"search")});var Ad=g((hfe,SD)=>{"use strict";var X4=Cn();SD.exports={writeTransaction:Z4};function Z4(e,t,r){return X4.writeTransaction(e,t,r)}a(Z4,"writeTransaction")});var AD=g((Sfe,RD)=>{"use strict";var ej=Gr(),tj=bs(),TD=$(),rj=qr(),pfe=Ad(),nj=require("clone"),TS=require("alasql"),sj=gd(),gD=require("util"),ij=gD.promisify(tj.getTableSchema),oj=gD.promisify(ej.search),aj=P(),SS=z();sj(TS);RD.exports={update:uj};var cj="There was a problem performing this update. Please check the logs and try again.";async function uj({statement:e,hdb_user:t}){let r=await ij(e.table.databaseid,e.table.tableid),n=lj(e.columns);SS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=nj(s),c=SS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=TS.parse(u).statements[0],l=await oj(_),d=_j(n,l);return dj(o,d,t)}a(uj,"update");function lj(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=TS.compile(`SELECT ${r.expression.toString()} AS [${aj.FUNC_VAL}] FROM ?`)}),t}catch(t){throw TD.error(t),new Error(cj)}}a(lj,"createUpdateRecord");function _j(e,t){return SS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(_j,"buildUpdateRecords");async function dj(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await rj.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){TD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(dj,"updateRecords")});var bD=g((Afe,OD)=>{var fj=require("alasql"),Ej=Gr(),hj=$(),mj=Cn(),RS=require("util"),gS=z(),pj=P(),Sj=bs(),gfe=Ad(),Rfe=qr(),Tj="record",gj="successfully deleted",Rj=RS.callbackify(yj),Aj=RS.promisify(Ej.search),Oj=RS.promisify(Sj.getTableSchema);OD.exports={convertDelete:Rj};function bj(e){return`${e.deleted_hashes.length} ${Tj}${e.deleted_hashes.length===1?"":"s"} ${gj}`}a(bj,"generateReturnMessage");async function yj({statement:e,hdb_user:t}){let r=await Oj(e.table.databaseid,e.table.tableid);gS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=gS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=fj.parse(o).statements[0],u={operation:pj.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await Aj(c);let _=await mj.deleteRecords(u);return gS.isEmptyOrZeroLength(_.message)&&(_.message=bj(_)),delete _.txn_time,_}catch(_){throw hj.error(_),_.hdb_code?_.message:_}}a(yj,"convertDelete")});var CD=g((bfe,wD)=>{"use strict";var Nj=Os(),{hdb_errors:yD}=ne(),{getDatabases:ND}=(Ae(),ie(ke));wD.exports={checkSchemaExists:ID,checkSchemaTableExists:Ij,schema_describe:Nj};async function ID(e){if(!ND()[e])return yD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(ID,"checkSchemaExists");async function Ij(e,t){let r=await ID(e);if(r)return r;if(!ND()[e][t])return yD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Ij,"checkSchemaTableExists")});var lu=g((Nfe,wj)=>{wj.exports={name:"harperdb",version:"4.3.21",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","enterprise","Fastify","NATS","HarperDB","Harper","clustering","replication","REST","WebSockets","decentralized","server-sent events","document store"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.635.0","@aws-sdk/lib-storage":"3.635.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.14",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.4.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.17.1",yaml:"2.4.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.22.11","newman-reporter-teamcity":"0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var hu={};Fe(hu,{addAnalyticsListener:()=>Eu,recordAction:()=>Sr,recordActionBinary:()=>Wr,setAnalyticsEnabled:()=>Cj});function Cj(e){xD=e}function Sr(e,t,r,n,s){if(!xD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=yd.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},yd.set(i,o)}Od||Dj()}function Wr(e,t,r,n,s){Sr(!!e,t,r,n,s)}function Eu(e){FD.push(e)}function Dj(){Od=performance.now(),setTimeout(async()=>{let e=performance.now()-Od;Od=0;let t=[],r={time:Date.now(),period:e,threadId:io.threadId,metrics:t};for(let[s,i]of yd){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 kD){let E=Math.floor(c*d),f=o[E-1];if(E>u){let h=E-u;if(f===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:f,count:h}:f),l=f;u=E}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await VD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:io.threadId,byThread:!0,...n});for(let s of FD)s(t);yd=new Map,io.parentPort?io.parentPort.postMessage({type:qD,report:r}):KD({report:r})},GD).unref()}async function Lj(e,t=6e4){let r=bS(),n=$D(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,_u.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,_u.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:R}=S;for(let b of T||[]){let{path:C,method:H,type:v,metric:F,count:M,total:Q,distribution:J,threads:j,...ae}=b;M||(M=1);let ce=F+(C?"-"+C:"");H!==void 0&&(ce+="-"+H),v!==void 0&&(ce+="-"+v);let ge=c.get(ce);if(ge){if(ge.threads){let Ne=ge.threads[R];if(Ne)ge=Ne;else{ge.threads[R]=Object.assign({},ae);continue}}ge.count||(ge.count=1);let Ge=ge.count;for(let Ne in ae){let ve=ae[Ne];typeof ve=="number"&&(ge[Ne]=(ge[Ne]*Ge+ve*M)/(Ge+M))}ge.count+=M,Q>=0&&(ge.total+=Q,ge.ratio=ge.total/ge.count)}else ge=Object.assign({period:t},b),delete ge.distribution,c.set(ce,ge),ge.byThread&&(ge.threads=[],ge.threads[R]=Object.assign({},ae),_.push(ge));if(J){J=J.map(Ne=>typeof Ne=="number"?{value:Ne,count:1}:Ne);let Ge=u.get(ce);Ge?Ge.push(...J):u.set(ce,J)}}await VD()}for(let p of _){let{path:S,method:T,type:R,metric:b,count:C,total:H,distribution:v,threads:F,...M}=p;F=F.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let J=0;for(let j of F){let ae=j[Q];typeof ae=="number"&&(J+=ae)}p[Q]=J}p.count=F.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Ne,ve)=>Ne.value>ve.value?1:-1);let R=T.count-1,b=[],C=0,H=0,v;for(let Ne of kD){let ve=R*Ne;for(;C<ve;)v=S[H++],C+=v.count,H===1&&C--;let e_=S[H>1?H-2:0];v||(v=S[0]),b.push(v.value-(v.value-e_.value)*(C-ve)/v.count)}let[F,M,Q,J,j,ae,ce,ge,Ge]=b;Object.assign(T,{p1:F,p10:M,p25:Q,median:J,p75:j,p90:ae,p95:ce,p99:ge,p999:Ge})}let d;for(let[p,S]of c)S.id=(0,bd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(d||h*10>f){let p=(0,bd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-DD,active:h-LD,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}DD=f,LD=h}async function MD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function bS(){return PD||(PD=Et({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function $D(){return UD||(UD=Et({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function Uj(){YD=!0;let e=(0,fu.get)(OS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await Lj(GD,e),await MD(bS(),Mj),await MD($D(),Pj)},Math.min(e/2,2147483647)).unref()}function KD(e,t){let r=e.report;r.threadId=t?.threadId||io.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(vD+=n.mean*n.count);r.totalBytesProcessed=vD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(BD.get(t))}),BD.set(t,t.performance.eventLoopUtilization())),r.id=(0,bd.getNextMonotonicTime)(),bS().primaryStore.put(r.id,r),YD||Uj(),vj&&(WD=Hj(r))}async function Hj(e){if(await WD,!di){let r=(0,du.dirname)((0,_u.getLogFilePath)());try{di=await(0,AS.open)((0,du.join)(r,"analytics.log"),"r+")}catch{di=await(0,AS.open)((0,du.join)(r,"analytics.log"),"w+")}}let t=(await di.stat()).size;if(t>Bj){let r=Buffer.alloc(t);await di.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await di.write(r,{position:0}),await di.truncate(r.length),t=r.length}await di.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var io,HD,
|
|
6
|
+
`)},sK="certificate.pem",iK="privateKey.pem",oK="ca.pem";MN.exports={CERTIFICATE_VALUES:nK,CERTIFICATE_PEM_NAME:sK,PRIVATEKEY_PEM_NAME:iK,CA_PEM_NAME:oK}});var sp=g((ple,GN)=>{"use strict";var xN=require("fs-extra"),oe=require("joi"),aK=require("os"),{boolean:be,string:er,number:rt,array:W_}=oe.types(),{totalmem:UN}=require("os"),Qi=require("path"),cK=$(),Q_=z(),mle=PN(),vN=P(),uK=Xe(),BN="log",lK="components",_K="Invalid logging.rotation.maxSize unit. Available units are G, M or K",dK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",fK="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",EK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",hK="rootPath config parameter is undefined",mK="clustering.enabled config parameter is undefined",zi=rt.min(0).required(),z_=W_.items({host:er.required(),port:zi}).empty(null),Xn,HN=!1;GN.exports={configValidator:pK,routesValidator:OK,route_constraints:z_};function pK(e,t=!1){if(HN=t,Xn=e.rootPath,Q_.isEmpty(Xn))throw hK;let r=be.required(),n=rt.min(0).max(1e3).empty(null).default(AK),s=er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Kc),i=er.optional().empty(null),o=er.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(Kc),u=oe.custom(TK).empty(null).default(Kc),_=e.clustering?.enabled;if(Q_.isEmpty(_))throw mK;let l=oe.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:zi,routes:z_}).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:z_}).required(),streams:oe.object({maxAge:rt.min(120).allow(null).optional(),maxBytes:rt.min(1).allow(null).optional(),maxMsgs:rt.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:er.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:rt.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:rt}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).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:er.custom(RK).optional().empty(null),maxSize:er.custom(gK).optional().empty(null),path:er.optional().empty(null).default(Kc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:W_.optional(),headersTimeout:rt.min(1).optional(),keepAliveTimeout:rt.min(1).optional(),port:rt.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Kc),securePort:rt.optional().empty(null),timeout:rt.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:zi,securePort:zi,mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:rt.optional(),cors:be.optional(),corsAccessList:W_.optional(),headersTimeout:rt.min(1).optional(),port:rt.min(0).optional().empty(null),securePort:rt.min(0).optional().empty(null),maxHeaderSize:rt.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})]),threadRange:oe.alternatives([W_.optional(),er.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:rt.min(1).optional(),host:er.optional(),waitForDebugger:be.optional()})),maxHeapMemory:rt.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:er.optional(),threshold:rt.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:u,prefetchWrites:be.optional(),maxFreeSpaceToLoad:rt.optional(),maxFreeSpaceToRetain:rt.optional()}).required(),ignoreScripts:be.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(pK,"configValidator");function SK(e){return HN||xN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(SK,"doesPathExist");function TK(e,t){oe.assert(e,er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=SK(e);if(r)return t.message(r)}a(TK,"validatePath");function gK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(_K);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(fK):e}a(gK,"validateRotationMaxSize");function RK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(dK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(EK):e}a(RK,"validateRotationInterval");function AK(e,t){let r=t.state.path.join("."),n=aK.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||UN();return i=Math.round(Math.min(i,UN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),cK.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(AK,"setDefaultThreads");function Kc(e,t){let r=t.state.path.join(".");if(!Q_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(Q_.isEmpty(Xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Qi.join(Xn,lK);case"logging.root":return Qi.join(Xn,BN);case"clustering.leafServer.streams.path":return Qi.join(Xn,"clustering","leaf");case"storage.path":let n=Qi.join(Xn,vN.LEGACY_DATABASES_DIR_NAME);return xN.existsSync(n)?n:Qi.join(Xn,vN.DATABASES_DIR_NAME);case"logging.rotation.path":return Qi.join(Xn,BN);case"operationsApi.network.domainSocket":return r==null?null:Qi.join(Xn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Kc,"setDefaultRoot");function OK(e){let t=oe.object({routes:z_});return uK.validateBySchema({routes:e},t)}a(OK,"routesValidator")});var Er=g((gle,QN)=>{"use strict";var kr=P(),Bt=z(),It=$(),{configValidator:bK,routesValidator:qN}=sp(),fr=require("fs-extra"),yK=require("yaml"),Dn=require("path"),NK=require("is-number"),kN=require("properties-reader"),IK=require("lodash"),{handleHDBError:wK}=se(),{HTTP_STATUS_CODES:CK,HDB_ERROR_MSGS:J_}=Ur(),Tle=require("minimist"),{server:DK}=(lr(),ie(Hi)),{DATABASES_PARAM_CONFIG:Wc,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Ln}=kr,LK="Unable to get config value because config is uninitialized",MK="Config successfully initialized",PK="Error backing up config file",UK="Empty parameter sent to getConfigValue",VN=Dn.join(kr.PACKAGE_ROOT,"config","yaml",kr.HDB_DEFAULT_CONFIG_FILE),vK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",FN={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"},j_,wt,X_;QN.exports={createConfigFile:BK,getDefaultConfig:xK,getConfigValue:YN,initConfig:op,flattenConfig:Qo,updateConfigValue:KN,updateConfigObject:GK,getConfiguration:kK,setConfiguration:VK,readConfigFile:cp,getClusteringRoutes:$K,initOldConfig:WN,getConfigFromFile:YK,getConfigFilePath:Ji,addConfig:KK,deleteConfigFromFile:WK,getConfigObj:QK};function BK(e,t=!1){let r=ci(VN);j_=Qo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=ip(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){It.error(d)}}}n&&$N(r,n),ap(r,t);let s=r.toJSON();wt=Qo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,kr.HDB_CONFIG_FILE);fr.createFileSync(o),fr.writeFileSync(o,String(r)),It.trace(`Config file written to ${o}`)}a(BK,"createConfigFile");function $N(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Bt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Wc.TABLES))for(let i in n[s][Wc.TABLES])for(let o in n[s][Wc.TABLES][i]){let c=n[s][Wc.TABLES][i][o],u=[Fr.DATABASES,s,Wc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Fr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){It.error("Error parsing schemas CLI/env config arguments",n)}}a($N,"setSchemasConfig");function xK(e){if(j_===void 0){let r=ci(VN);j_=Qo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return j_[t.toLowerCase()]}a(xK,"getDefaultConfig");function YN(e){if(e==null){It.error(UK);return}if(wt===void 0){It.trace(LK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return wt[t.toLowerCase()]}a(YN,"getConfigValue");function Ji(e=Bt.getPropsFilePath()){let t=Bt.getEnvCliRootPath();return t?Dn.join(t,kr.HDB_CONFIG_FILE):kN(e).get(kr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ji,"getConfigFilePath");function op(e=!1){if(wt===void 0||e){let t;if(!Bt.noBootFile()){t=Bt.getPropsFilePath();try{fr.accessSync(t,fr.constants.F_OK|fr.constants.R_OK)}catch(i){throw It.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ji(t),n;if(r.includes("config/settings.js"))try{WN(r);return}catch(i){if(i.code!==kr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ci(r)}catch(i){if(i.code===kr.NODE_ERROR_CODES.ENOENT){It.trace(`HarperDB config file not found at ${r}.
|
|
7
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw It.error(i),new Error(`Error reading HarperDB config file at ${r}`)}HK(n,r),ap(n);let s=n.toJSON();if(DK.config=s,wt=Qo(s),wt.logging_rotation_rotate)for(let i in FN)wt[i]&&It.error(`Config ${FN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);It.trace(MK)}}a(op,"initConfig");function HK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(It.trace("Updating config file with missing config params"),fr.writeFileSync(t,String(e)))}a(HK,"checkForUpdatedConfig");function ap(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=bK(r,t);if(n.error)throw J_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(ap,"validateConfig");function GK(e,t){wt===void 0&&(wt={});let r=Ln[e.toLowerCase()];if(r===void 0){It.trace(`Unable to update config object because config param '${e}' does not exist`);return}wt[r.toLowerCase()]=t}a(GK,"updateConfigObject");function KN(e,t,r=void 0,n=!1,s=!1,i=!1){wt===void 0&&op();let o=YN(Ln.hdb_root),c=Dn.join(o,kr.HDB_CONFIG_FILE),u=ci(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Ln[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=ip(E,t);u.setIn([...f],h)}else for(let E in r){let f=Ln[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===wt[Fr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===wt[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=kr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=ip(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){It.error(T)}}}_&&$N(u,_),ap(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,kr.HDB_CONFIG_FILE);n===!0&&qK(c,l),fr.writeFileSync(d,String(u)),s&&(wt=Qo(u.toJSON())),It.trace(`Config parameter: ${e} updated with value: ${t}`)}a(KN,"updateConfigValue");function qK(e,t){try{let r=Dn.join(t,"backup",`${kr.HDB_CONFIG_FILE}.bak`);fr.copySync(e,r),It.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){It.error(PK),It.error(r)}}a(qK,"backupConfigFile");var FK=["databases"];function Qo(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),X_=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])&&!FK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Fr[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Qo,"flattenConfig");function ip(e,t){if(e===Fr.CLUSTERING_NODENAME||e===Fr.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(NK(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Bt.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return Bt.autoCast(t)}a(ip,"castConfigValue");function kK(){let e=Bt.getPropsFilePath(),t=Ji(e);return ci(t).toJSON()}a(kK,"getConfiguration");async function VK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return KN(void 0,void 0,s,!0),vK}catch(i){throw typeof i=="string"||i instanceof String?wK(i,i,CK.BAD_REQUEST,void 0,void 0,!0):i}}a(VK,"setConfiguration");function cp(){let e=Bt.getPropsFilePath();try{fr.accessSync(e,fr.constants.F_OK|fr.constants.R_OK)}catch(n){if(!Bt.noBootFile())throw It.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ji(e);return ci(t).toJSON()}a(cp,"readConfigFile");function ci(e){return yK.parseDocument(fr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ci,"parseYamlDoc");function $K(){let e=cp(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Bt.isEmptyOrZeroLength(t)?[]:t;let r=qN(t);if(r)throw J_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Bt.isEmptyOrZeroLength(n)?[]:n;let s=qN(n);if(s)throw J_.CONFIG_VALIDATION(s.message);if(!Bt.isEmptyOrZeroLength(n)&&!Bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Bt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw J_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a($K,"getClusteringRoutes");function WN(e){let t=kN(e);wt={};for(let r in Ln){let n=t.get(r.toUpperCase());if(Bt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Fr.LOGGING_ROOT?wt[s]=Dn.dirname(n):wt[s]=n}return wt}a(WN,"initOldConfig");function YK(e){let t=cp();return IK.get(t,e.replaceAll("_","."))}a(YK,"getConfigFromFile");async function KK(e,t){let r=ci(Ji());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await fr.writeFile(Ji(),String(r))}a(KK,"addConfig");function WK(e){let t=Ji(Bt.getPropsFilePath()),r=ci(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,kr.HDB_CONFIG_FILE);fr.writeFileSync(s,String(r))}a(WK,"deleteConfigFromFile");function QK(){return X_||(op(),X_)}a(QK,"getConfigObj")});var JN=g((Ale,zN)=>{"use strict";var Z_=P(),ed=class{static{a(this,"BaseLicense")}constructor(t=0,r=Z_.RAM_ALLOCATION_ENUM.DEFAULT,n=Z_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},up=class extends ed{static{a(this,"ExtendedLicense")}constructor(t=0,r=Z_.RAM_ALLOCATION_ENUM.DEFAULT,n=Z_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};zN.exports={BaseLicense:ed,ExtendedLicense:up}});var ji=g((ble,rI)=>{"use strict";var Jo=require("fs-extra"),XN=K_(),ZN=require("crypto"),zK=require("moment"),JK=require("uuid").v4,tr=$(),_p=require("path"),jK=z(),ui=P(),{totalmem:jN}=require("os"),XK=JN().ExtendedLicense,zo="invalid license key format",ZK="061183",eW="mofi25",tW="aes-256-cbc",rW=16,nW=32,eI=ee();eI.initSync();var lp;rI.exports={validateLicense:tI,generateFingerPrint:iW,licenseSearch:Ep,getLicense:cW,checkMemoryLimit:uW};function dp(){return _p.join(eI.getHdbBasePath(),ui.LICENSE_KEY_DIR_NAME,ui.LICENSE_FILE_NAME)}a(dp,"getLicenseDirPath");function sW(){let e=dp();return _p.join(e,ui.LICENSE_FILE_NAME)}a(sW,"getLicenseFilePath");function fp(){let e=dp();return _p.join(e,ui.REG_KEY_FILE_NAME)}a(fp,"getFingerPrintFilePath");async function iW(){let e=fp();try{return await Jo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await oW();throw tr.error(`Error writing fingerprint file to ${e}`),tr.error(t),new Error("There was an error generating the fingerprint")}}a(iW,"generateFingerPrint");async function oW(){let e=JK(),t=XN.hash(e),r=fp();try{await Jo.mkdirp(dp()),await Jo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw tr.error(`Error writing fingerprint file to ${r}`),tr.error(n),new Error("There was an error generating the fingerprint")}return t}a(oW,"writeFingerprint");function tI(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ui.RAM_ALLOCATION_ENUM.DEFAULT,version:ui.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return tr.error("empty license key passed to validate."),r;let n=fp(),s=!1;try{s=Jo.statSync(n)}catch(i){tr.error(i)}if(s){let i;try{i=Jo.readFileSync(n,"utf8")}catch{tr.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(eW),c=o[1];c=Buffer.concat([Buffer.from(c)],rW);let u=Buffer.concat([Buffer.from(i)],nW),_=ZN.createDecipheriv(tW,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let f=aW(o[0],i);if(f)l=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(zo),tr.error(zo),new Error(zo)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(zo),tr.error(zo),new Error(zo)}else r.exp_date=l;r.exp_date<zK().valueOf()&&(r.valid_date=!1),XN.validate(o[1],`${ZK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||tr.error("Invalid licence"),r}a(tI,"validateLicense");function aW(e,t){try{let r=ZN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{tr.warn("Check old license failed")}}a(aW,"checkOldLicense");function Ep(){let e=new XK,t=[];try{t=Jo.readFileSync(sW(),"utf-8").split(ui.NEW_LINE)}catch(r){r.code==="ENOENT"?tr.info("no license file found"):tr.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(jK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=tI(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){tr.error("There was an error parsing the license string."),tr.error(s),e.ram_allocation=ui.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return lp=e,e}a(Ep,"licenseSearch");async function cW(){return lp||await Ep(),lp}a(cW,"getLicense");function uW(){let e=Ep().ram_allocation,t=process.constrainedMemory?.()||jN();if(t=Math.round(Math.min(t,jN())/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(uW,"checkMemoryLimit")});var _n=g((Cle,SI)=>{"use strict";var oI="username is required",aI="nothing to update, must supply active, role or password to update",cI="password cannot be an empty string",uI="If role is specified, it cannot be empty.",lI="active must be true or false";SI.exports={addUser:SW,alterUser:TW,dropUser:RW,getSuperUser:yW,userInfo:AW,listUsers:rd,listUsersExternal:OW,setUsersToGlobal:Xo,findAndValidateUser:mI,getClusterUser:NW,USERNAME_REQUIRED:oI,ALTERUSER_NOTHING_TO_UPDATE:aI,EMPTY_PASSWORD:cI,EMPTY_ROLE:uI,ACTIVE_BOOLEAN:lI};var _I=qr(),lW=ai(),pp=K_(),dI=CN(),fI=Gr(),Sp=ys(),Vr=z(),EI=require("validate.js"),Oe=$(),{promisify:_W}=require("util"),Tp=As(),nI=P(),sI=Ve(),dW=Er(),Nle=ee(),Ile=ji(),fW=ki(),{table:wle}=(Ae(),ie(ke)),{handleHDBError:Zn,hdb_errors:EW}=se(),{HTTP_STATUS_CODES:es,AUTHENTICATION_ERROR_MSGS:hp,HDB_ERROR_MSGS:jo}=EW,{UserEventMsg:gp}=Mn(),mp=require("lodash"),{server:Rp}=(lr(),ie(Hi)),hW=$();Rp.getUser=(e,t)=>mI(e,t,t!=null);var hI={username:!0,active:!0,role:!0,password:!0},iI=new Map,td=fI.searchByValue,mW=fI.searchByHash,pW=_W(lW.delete);async function SW(e){let t=EI.cleanAttributes(e,hI),r=dI.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 td(n),s=s&&Array.from(s)}catch(u){throw Oe.error("There was an error searching for a role in add user"),Oe.error(u),u}if(!s||s.length<1)throw Zn(new Error,jo.ROLE_NAME_NOT_FOUND(t.role),es.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Zn(new Error,jo.DUP_ROLES_FOUND(t.role),es.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=Tp.encrypt(t.password)),t.password=pp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await _I.insert(i)}catch(u){throw Oe.error("There was an error searching for a user."),Oe.error(u),u}Oe.debug(o);try{await Xo()}catch(u){throw Oe.error("Got an error setting users to global"),Oe.error(u),u}if(o.skipped_hashes.length===1)throw Zn(new Error,jo.USER_ALREADY_EXISTS(t.username),es.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],Sp.signalUserChange(new gp(process.pid)),`${c.username} successfully added`}a(SW,"addUser");async function TW(e){let t=EI.cleanAttributes(e,hI);if(Vr.isEmptyOrZeroLength(t.username))throw new Error(oI);if(Vr.isEmptyOrZeroLength(t.password)&&Vr.isEmptyOrZeroLength(t.role)&&Vr.isEmptyOrZeroLength(t.active))throw new Error(aI);if(!Vr.isEmpty(t.password)&&Vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(cI);if(!Vr.isEmpty(t.active)&&!Vr.isBoolean(t.active))throw new Error(lI);let r=gW(t.username);if(!Vr.isEmpty(t.password)&&!Vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Tp.encrypt(t.password)),t.password=pp.hash(t.password)),t.role==="")throw new Error(uI);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 td(i)||[])}catch(c){throw Oe.error("Got an error searching for a role."),Oe.error(c),c}if(!o||o.length===0){let c=jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Oe.error(c),Zn(new Error,c,es.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=jo.ALTER_USER_DUP_ROLES(t.role);throw Oe.error(c),Zn(new Error,c,es.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await _I.update(n)}catch(i){throw Oe.error("Error during update."),Oe.error(i),i}try{await Xo()}catch(i){throw Oe.error("Got an error setting users to global"),Oe.error(i),i}return Sp.signalUserChange(new gp(process.pid)),s}a(TW,"alterUser");function gW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(gW,"isClusterUser");async function RW(e){try{let t=dI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Vr.isEmpty(global.hdb_users.get(e.username)))throw Zn(new Error,jo.USER_NOT_EXIST(e.username),es.NOT_FOUND,void 0,void 0,!0);let n;try{n=await pW(r)}catch(s){throw Oe.error("Got an error deleting a user."),Oe.error(s),s}Oe.debug(n);try{await Xo()}catch(s){throw Oe.error("Got an error setting users to global."),Oe.error(s),s}return Sp.signalUserChange(new gp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(RW,"dropUser");async function AW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=mp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await mW(r)}catch(s){throw Oe.error("Got an error searching for a role."),Oe.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Oe.error(r),r}return t}a(AW,"userInfo");async function OW(){let e;try{e=await rd()}catch(t){throw Oe.error("Got an error listing users."),Oe.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(OW,"listUsersExternal");async function rd(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await td(e)}catch(o){throw Oe.error("Got an error searching for roles."),Oe.error(o),o}let r={};for(let o of t)r[o.id]=mp.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 td(n)}catch(o){throw Oe.error("Got an error searching for users."),Oe.error(o),o}let i=new Map;for(let o of s)o=mp.cloneDeep(o),o.role=r[o.role],bW(o.role),i.set(o.username,o);return i}catch(e){throw Oe.error("got an error listing users"),Oe.error(e),Vr.errorizeMessage(e)}return null}a(rd,"listUsers");function bW(e){try{if(!e){Oe.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(fW)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Oe.error("Got an error trying to set system permissions."),Oe.error(t)}}a(bW,"appendSystemTablesToRole");async function Xo(){try{let e=await rd();global.hdb_users=e}catch(e){throw Oe.error(e),e}}a(Xo,"setUsersToGlobal");async function mI(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,hp.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Zn(new Error,hp.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(iI.get(t)===n.password)return s;if(pp.validate(n.password,t))iI.set(t,n.password);else throw Zn(new Error,hp.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}return s}a(mI,"findAndValidateUser");async function yW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(yW,"getSuperUser");async function NW(){let e=await rd(),t=dW.getConfigFromFile(nI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Vr.isEmpty(r)&&r?.role?.role===nI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Tp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+sI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+sI.SERVER_SUFFIX.ADMIN,r}a(NW,"getClusterUser");var pI=[];Rp.invalidateUser=function(e){for(let t of pI)try{t(e)}catch(r){hW.error("Error invalidating user",r)}};Rp.onInvalidatedUser=function(e){pI.push(e)}});var zc=g((Ple,AI)=>{"use strict";var Xi=$(),$r=P(),IW=Jy(),Lle=bs(),Mle=Os(),wW=_n(),{validateEvent:TI}=Mn(),Qc=Cn(),CW=require("process"),{resetDatabases:DW}=(Ae(),ie(ke)),LW={[$r.ITC_EVENT_TYPES.SCHEMA]:MW,[$r.ITC_EVENT_TYPES.USER]:RI};async function MW(e){let t=TI(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await IW(e.message),await PW(e.message)}a(MW,"schemaHandler");async function PW(e){try{Qc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Qc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Qc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=DW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(PW,"syncSchemaMetadata");var gI=[];async function RI(e){try{try{Qc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Qc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Xi.warn(r)}let t=TI(e);if(t){Xi.error(t);return}Xi.trace(`ITC userHandler ${$r.HDB_ITC_CLIENT_PREFIX}${CW.pid} received user event:`,e),await wW.setUsersToGlobal();for(let r of gI)r()}catch(t){Xi.error(t)}}a(RI,"userHandler");RI.addListener=function(e){gI.push(e)};AI.exports=LW});var Mn=g((Gle,bI)=>{"use strict";var vle=$(),Ap=z(),UW=P(),{ITC_ERRORS:Jc}=Ur(),{parentPort:Ble,threadId:vW,isMainThread:BW,workerData:xle}=require("worker_threads"),{onMessageFromWorkers:xW,broadcast:Hle,broadcastWithAcknowledgement:HW}=We();bI.exports={sendItcEvent:GW,validateEvent:OI,SchemaEventMsg:qW,UserEventMsg:FW};var nd;xW(async(e,t)=>{nd=nd||zc(),OI(e),nd[e.type]&&await nd[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function GW(e){return!BW&&e.message&&(e.message.originator=vW),HW(e)}a(GW,"sendItcEvent");function OI(e){if(typeof e!="object")return Jc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Ap.isEmpty(e.type))return Jc.MISSING_TYPE;if(!e.hasOwnProperty("message")||Ap.isEmpty(e.message))return Jc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Ap.isEmpty(e.message.originator))return Jc.MISSING_ORIGIN;if(UW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Jc.INVALID_EVENT(e.type)}a(OI,"validateEvent");function qW(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(qW,"SchemaEventMsg");function FW(e){this.originator=e}a(FW,"UserEventMsg")});var ys=g((kle,wI)=>{"use strict";var yI=P(),Fle=z(),sd=$(),NI=Wy(),Zo,{sendItcEvent:II}=Mn();function kW(e){try{sd.trace("signalSchemaChange called with message:",e),Zo=Zo||zc();let t=new NI(yI.ITC_EVENT_TYPES.SCHEMA,e);return Zo.schema(t),II(t)}catch(t){sd.error(t)}}a(kW,"signalSchemaChange");function VW(e){try{sd.trace("signalUserChange called with message:",e),Zo=Zo||zc();let t=new NI(yI.ITC_EVENT_TYPES.USER,e);return Zo.user(t),II(t)}catch(t){sd.error(t)}}a(VW,"signalUserChange");wI.exports={signalSchemaChange:kW,signalUserChange:VW}});var id=g(($le,DI)=>{"use strict";var CI=z(),$W=P(),YW=$(),KW=P_(),WW=M_(),QW=ys(),{SchemaEventMsg:zW}=Mn(),JW="already exists in";DI.exports=jW;async function jW(e,t,r){if(CI.isEmptyOrZeroLength(r))return r;let n=[];CI.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 XW(e,t.schema,t.name,i)})),s}a(jW,"lmdbCheckForNewAttributes");async function XW(e,t,r,n){let s=new WW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await ZW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(JW))YW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(XW,"createNewAttribute");async function ZW(e){let t;return t=await KW(e),QW.signalSchemaChange(new zW(process.pid,$W.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(ZW,"createAttribute")});var ea=g((Kle,LI)=>{"use strict";var Op=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}};LI.exports=Op});var PI=g((Qle,MI)=>{"use strict";var eQ=ea(),tQ=P().OPERATIONS_ENUM,bp=class extends eQ{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(tQ.INSERT,r,n,s,i),this.records=t}};MI.exports=bp});var vI=g((Jle,UI)=>{"use strict";var rQ=ea(),nQ=P().OPERATIONS_ENUM,yp=class extends rQ{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(nQ.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};UI.exports=yp});var xI=g((Xle,BI)=>{"use strict";var sQ=ea(),iQ=P().OPERATIONS_ENUM,Np=class extends sQ{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(iQ.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};BI.exports=Np});var GI=g((e_e,HI)=>{"use strict";var oQ=ea(),aQ=P().OPERATIONS_ENUM,Ip=class extends oQ{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(aQ.DELETE,n,s,t,i),this.original_records=r}};HI.exports=Ip});var jc=g((n_e,VI)=>{"use strict";var r_e=require("path"),qI=Qe(),cQ=PI(),uQ=vI(),lQ=xI(),_Q=GI(),ta=ft(),FI=z(),{CONFIG_PARAMS:dQ}=P(),kI=ee();kI.initSync();var od=P().OPERATIONS_ENUM,{getTransactionAuditStorePath:fQ}=je();VI.exports=EQ;async function EQ(e,t){if(kI.get(dQ.LOGGING_AUDITLOG)===!1)return;let r=fQ(e.schema,e.table),n=await qI.openEnvironment(r,e.table,!0),s=hQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){qI.initializeDBIs(n,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),FI.isEmpty(s.user_name)||n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(EQ,"writeTransaction");function hQ(e,t){let r=FI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===od.INSERT)return new cQ(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===od.UPDATE)return new uQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===od.UPSERT)return new lQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===od.DELETE)return new _Q(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(hQ,"createTransactionObject")});var wp=g((o_e,$I)=>{"use strict";var mQ=Fc(),i_e=kc(),Xc=P(),pQ=Vc(),SQ=Yo().insertRecords,TQ=Qe(),gQ=$(),RQ=id(),{getSchemaPath:AQ}=je(),OQ=jc();$I.exports=bQ;async function bQ(e){try{let{schema_table:t,attributes:r}=mQ(e);pQ(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 RQ(e.hdb_auth_header,t,r),s=AQ(e.schema,e.table),i=await TQ.openEnvironment(s,e.table),o=await SQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await OQ(e,o)}catch(c){gQ.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(bQ,"lmdbCreateRecords")});var WI=g((c_e,KI)=>{"use strict";var YI=P(),yQ=wp(),NQ=kc(),IQ=require("fs-extra"),{getSchemaPath:wQ}=je();KI.exports=CQ;async function CQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new NQ(YI.SYSTEM_SCHEMA_NAME,YI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await yQ(r),await IQ.mkdirp(wQ(e.schema))}a(CQ,"lmdbCreateSchema")});var zI=g((l_e,QI)=>{"use strict";var Cp=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}};QI.exports=Cp});var ZI=g((h_e,XI)=>{"use strict";var JI=Qe(),Dp=vr(),Lp=Ur().LMDB_ERRORS_ENUM,DQ=ft(),jI=$(),d_e=z(),LQ=require("lmdb"),MQ=zI(),PQ=P(),{OVERFLOW_MARKER:f_e,MAX_SEARCH_KEY_LENGTH:E_e}=DQ,UQ=PQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function vQ(e,t,r,n){if(Dp.validateEnv(e),t===void 0)throw new Error(Lp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Lp.IDS_REQUIRED):new Error(Lp.IDS_MUST_BE_ITERABLE);try{let s=JI.listDBIs(e);JI.initializeDBIs(e,t,s);let i=new MQ,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[UQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,LQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let R=e.dbis[T],N=h[T];if(N!=null)try{let I=Dp.getIndexedValues(N);if(I)for(let H=0,U=I.length;H<U;H++)R.remove(I[H],o)}catch{jI.warn(`cannot delete from attribute: ${T}, ${N}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){jI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let E=0,f=l.length;E<f;E++)l[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),_.push(E));let d=0;for(let E=0;E<_.length;E++){let f=_[E];i.original_records.splice(f-d,1),d++}return i.txn_time=Dp.getNextMonotonicTime(),i}catch(s){throw s}}a(vQ,"deleteRecords");XI.exports={deleteRecords:vQ}});var Zc=g((p_e,tw)=>{"use strict";var ra=z(),BQ=ZI(),xQ=Qe(),{getSchemaPath:HQ}=je(),GQ=jc(),qQ=$();tw.exports=FQ;async function FQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ra.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ra.isEmptyOrZeroLength(e.hash_values)&&!ra.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ra.isEmpty(u)||e.hash_values.push(u)}}if(ra.isEmptyOrZeroLength(e.hash_values))return ew([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ra.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=HQ(e.schema,e.table),i=await xQ.openEnvironment(s,e.table),o=await BQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await GQ(e,o)}catch(c){qQ.error(`unable to write transaction due to ${c.message}`)}return ew(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(FQ,"lmdbDeleteRecords");function ew(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(ew,"createDeleteResponse")});var Pp=g((g_e,rw)=>{"use strict";var kQ=P(),T_e=vr();function Mp(e,t){let r=Object.create(null);if(t.length===1&&kQ.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(Mp,"parseRow");function VQ(e,t,r,n){let s=Mp(r,e);n.push(s)}a(VQ,"searchAll");function $Q(e,t,r,n){let s=Mp(r,e);n[t]=s}a($Q,"searchAllToMap");function YQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(YQ,"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 KQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Zi(t,r,n,s,i)}a(KQ,"endsWith");function WQ(e,t,r,n,s,i){t.toString().includes(e)&&Zi(t,r,n,s,i)}a(WQ,"contains");function QQ(e,t,r,n,s,i){t>e&&Zi(t,r,n,s,i)}a(QQ,"greaterThanCompare");function zQ(e,t,r,n,s,i){t>=e&&Zi(t,r,n,s,i)}a(zQ,"greaterThanEqualCompare");function JQ(e,t,r,n,s,i){t<e&&Zi(t,r,n,s,i)}a(JQ,"lessThanCompare");function jQ(e,t,r,n,s,i){t<=e&&Zi(t,r,n,s,i)}a(jQ,"lessThanEqualCompare");rw.exports={parseRow:Mp,searchAll:VQ,searchAllToMap:$Q,iterateDBI:YQ,endsWith:KQ,contains:WQ,greaterThanCompare:QQ,greaterThanEqualCompare:zQ,lessThanCompare:JQ,lessThanEqualCompare:jQ,pushResults:Zi}});var na=g((y_e,uw)=>{"use strict";var li=Qe(),A_e=$(),Yr=vr(),ad=ft(),ht=Ur().LMDB_ERRORS_ENUM,O_e=z(),XQ=P(),cd=Pp(),{parseRow:ZQ}=cd,b_e=require("lmdb"),{OVERFLOW_MARKER:nw,MAX_SEARCH_KEY_LENGTH:ez}=ad;function sw(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(sw,"iterateFullIndex");function eu(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return eo(e,t,r,(l,d,E,f)=>{let R={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return f===r?(R.values=!1,d.getRange(R).map(N=>({value:N}))):d.getRange(R)})}a(eu,"iterateRangeBetween");function eo(e,t,r,n){let s=e.database||e,i=li.openDBI(s,r);i[ad.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&li.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 iw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(nw)){if(!s)if(r)s=li.openDBI(e,r);else{let u=li.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=li.openDBI(e,u[_]),!s[ad.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(iw,"getOverflowCheck");function tz(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return eo(e,t,t,(o,c,u)=>(ud(r),r=tu(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>ZQ(_.value,r))))}a(tz,"searchAll");function rz(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);ud(r),r=tu(e.database||e,r);let o=new Map;for(let{key:c,value:u}of sw(e,t,t,n,s,i))o.set(c,cd.parseRow(u,r));return o}a(rz,"searchAllToMap");function nz(e,t,r=!1,n=void 0,s=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=sw(e,void 0,t,r,n,s),c=o.transaction,u=iw(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(nz,"iterateDBI");function sz(e,t){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return li.statDBI(e,t).entryCount}a(sz,"countAll");function iz(e,t,r,n,s=!1,i=void 0,o=void 0){return _i(e,r,n),eo(e,t,r,(c,u,_,l)=>(n=Yr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(iz,"equals");function oz(e,t,r){return _i(e,t,r),li.openDBI(e,t).getValuesCount(r)}a(oz,"count");function az(e,t,r,n,s=!1,i=void 0,o=void 0){return _i(e,r,n),eo(e,null,r,(c,u)=>{n=Yr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let E of u.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(n))return E;if(_===!0)return l.DONE}}),l.filter(E=>E)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(az,"startsWith");function cz(e,t,r,n,s=!1,i=void 0,o=void 0){return ow(e,t,r,n,s,i,o,!0)}a(cz,"endsWith");function ow(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return _i(e,r,n),eo(e,null,r,(u,_,l,d)=>{let E=iw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(nw)?_.getValues(f,{transaction:u}).map(p=>{let S=E(f,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[ad.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:u}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(ow,"contains");function uz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),eu(e,t,r,n,u,s,i,o,!0,!1)}a(uz,"greaterThan");function lz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),eu(e,t,r,n,u,s,i,o,!1,!1)}a(lz,"greaterThanEqual");function _z(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),eu(e,t,r,u,n,s,i,o,!1,!0)}a(_z,"lessThan");function dz(e,t,r,n,s=!1,i=void 0,o=void 0){_i(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),eu(e,t,r,u,n,s,i,o,!1,!1)}a(dz,"lessThanEqual");function fz(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Yr.validateEnv(e),r===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ht.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ht.END_VALUE_REQUIRED);if(n=Yr.convertKeyValueToWrite(n),s=Yr.convertKeyValueToWrite(s),n>s)throw new Error(ht.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return eu(e,t,r,n,s,i,o,c)}a(fz,"between");function Ez(e,t,r,n){Yr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(ud(r),r=tu(s,r),n===void 0)throw new Error(ht.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=cd.parseRow(c,r)),o}a(Ez,"searchByHash");function hz(e,t,r){Yr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(hz,"checkHashExists");function mz(e,t,r,n,s=[]){return cw(e,t,r,n,s),aw(e,t,r,n,s).map(i=>i[1])}a(mz,"batchSearchByHash");function pz(e,t,r,n,s=[]){cw(e,t,r,n,s);let i=new Map;for(let[o,c]of aw(e,t,r,n,s))i.set(o,c);return i}a(pz,"batchSearchByHashToMap");function aw(e,t,r,n,s=[]){return eo(e,t,t,(i,o,c)=>{r=tu(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,cd.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(aw,"batchHashSearch");function cw(e,t,r,n,s){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(ud(r),n==null)throw new Error(ht.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ht.IDS_MUST_BE_ITERABLE)}a(cw,"initializeBatchSearchByHash");function ud(e){if(!Array.isArray(e))throw e===void 0?new Error(ht.FETCH_ATTRIBUTES_REQUIRED):new Error(ht.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(ud,"validateFetchAttributes");function _i(e,t,r){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.SEARCH_VALUE_REQUIRED);if(r?.length>ez)throw new Error(ht.SEARCH_VALUE_TOO_LARGE)}a(_i,"validateComparisonFunctions");function tu(e,t){return t.length===1&&XQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=li.listDBIs(e)),t}a(tu,"setGetWholeRowAttributes");uw.exports={searchAll:tz,searchAllToMap:rz,count:oz,countAll:sz,equals:iz,startsWith:az,endsWith:cz,contains:ow,searchByHash:Ez,setGetWholeRowAttributes:tu,batchSearchByHash:mz,batchSearchByHashToMap:pz,checkHashExists:hz,iterateDBI:nz,greaterThan:uz,greaterThanEqual:lz,lessThan:_z,lessThanEqual:dz,between:fz}});var sa=g((I_e,Ew)=>{var lw=require("lodash"),_w=Xe(),he=require("joi"),Sz=z(),{hdb_schema_table:ru,checkValidTable:dw,hdb_table:fw,hdb_database:ld}=Jn(),{handleHDBError:Tz,hdb_errors:gz}=se(),{getDatabases:Rz}=(Ae(),ie(ke)),{HTTP_STATUS_CODES:Az}=gz,Oz=he.object({database:ld,schema:ld,table:fw,search_attribute:ru,search_value:he.any().required(),get_attributes:he.array().min(1).items(he.alternatives(ru,he.object())).optional(),desc:he.bool(),limit:he.number().integer().min(1),offset:he.number().integer().min(0)}),bz=he.object({database:ld,schema:ld,table:fw,operator:he.string().valid("and","or").default("and").lowercase(),offset:he.number().integer().min(0),limit:he.number().integer().min(1),get_attributes:he.array().min(1).items(he.alternatives(ru,he.object())).optional(),sort:he.object({attribute:he.alternatives(ru,he.array().min(1)),descending:he.bool().optional()}).optional(),conditions:he.array().min(1).items(he.alternatives(he.object({operator:he.string().valid("and","or").default("and").lowercase(),conditions:he.array()}),he.object({search_attribute:he.alternatives(ru,he.array().min(1)),search_type:he.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:he.when("search_type",{switch:[{is:"equals",then:he.any()},{is:"between",then:he.array().items(he.alternatives([he.string(),he.number()])).length(2)}],otherwise:he.alternatives(he.string(),he.number())}).required()}))).required()});Ew.exports=function(e,t){let r=null;switch(t){case"value":r=_w.validateBySchema(e,Oz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(dw("database",e.schema)),i(dw("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=_w.validateBySchema(e,bz);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=Sz.checkGlobalSchemaTable(e.schema,e.table);if(s)return Tz(new Error,s,Az.NOT_FOUND);let o=Rz()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,E=l.conditions.length;d<E;d++){let f=l.conditions[d];f.conditions?u(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=lw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!lw.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 Up=g((C_e,hw)=>{"use strict";var yz=Qe(),Nz=sa(),{getSchemaPath:Iz}=je();hw.exports=wz;function wz(e){let t=Nz(e,"hashes");if(t)throw t;let r=Iz(e.schema,e.table);return yz.openEnvironment(r,e.table)}a(wz,"initialize")});var vp=g((L_e,mw)=>{"use strict";var Cz=na(),Dz=Up();mw.exports=Lz;async function Lz(e){let t=await Dz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Cz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Lz,"lmdbGetDataByHash")});var ia=g((P_e,pw)=>{"use strict";var Bp=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};pw.exports=Bp});var Tw=g((B_e,Sw)=>{"use strict";var v_e=ia(),Mz=na(),Pz=Up();Sw.exports=Uz;async function Uz(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(Uz,"lmdbSearchByHash")});var ts=g((H_e,gw)=>{"use strict";var xp=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}};gw.exports=xp});var _d=g((q_e,Nw)=>{"use strict";var rr=na(),vz=Qe(),Bz=z(),me=ft(),to=P(),xz=ki(),Rw=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:Hz}=je(),Ns=to.SEARCH_WILDCARDS;async function Gz(e,t,r){let n;e.schema===to.SYSTEM_SCHEMA_NAME?n=xz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=yw(e,n.hash_attribute,r,t);return Ow(e,s,n.hash_attribute,r)}a(Gz,"prepSearch");async function Ow(e,t,r,n){let s=Hz(e.schema,e.table),i=await vz.openEnvironment(s,e.table),o=bw(i,e,t,r),c=o.transaction||i;if([me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,me.SEARCH_TYPES.SEARCH_ALL,me.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(qz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Aw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[l]:E.key}),"toObject");return n?Aw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?rr.batchSearchByHashToMap(c,r,e.get_attributes,_):rr.batchSearchByHash(c,r,e.get_attributes,_)}a(Ow,"executeSearch");function bw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case me.SEARCH_TYPES.EQUALS:s=rr.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.CONTAINS:s=rr.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.ENDS_WITH:case me.SEARCH_TYPES._ENDS_WITH:s=rr.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.STARTS_WITH:case me.SEARCH_TYPES._STARTS_WITH:s=rr.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return rr.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return rr.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case me.SEARCH_TYPES.SEARCH_ALL:return rr.searchAll(e,n,t.get_attributes,o,c,u);case me.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return rr.searchAllToMap(e,n,t.get_attributes,o,c,u);case me.SEARCH_TYPES.BETWEEN:s=rr.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case me.SEARCH_TYPES.GREATER_THAN:case me.SEARCH_TYPES._GREATER_THAN:s=rr.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.GREATER_THAN_EQUAL:case me.SEARCH_TYPES._GREATER_THAN_EQUAL:s=rr.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.LESS_THAN:case me.SEARCH_TYPES._LESS_THAN:s=rr.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.LESS_THAN_EQUAL:case me.SEARCH_TYPES._LESS_THAN_EQUAL:s=rr.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(bw,"searchByType");function Aw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Aw,"createMapFromIterable");function qz(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(qz,"checkToFetchMore");function yw(e,t,r,n){if(Bz.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Ns.indexOf(s)>-1)return r===!0?me.SEARCH_TYPES.SEARCH_ALL_TO_MAP:me.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Ns[0])<0&&s.indexOf(Ns[1])<0)return c===!0?r===!0?me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:me.SEARCH_TYPES.EQUALS;if(Ns.indexOf(i)>=0&&Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),me.SEARCH_TYPES.CONTAINS;if(Ns.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),me.SEARCH_TYPES.ENDS_WITH;if(Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),me.SEARCH_TYPES.STARTS_WITH;if(s.includes(Ns[0])||s.includes(Ns[1]))return me.SEARCH_TYPES.EQUALS;throw new Error(Rw.UNKNOWN_SEARCH_TYPE)}else switch(n){case to.VALUE_SEARCH_COMPARATORS.BETWEEN:return me.SEARCH_TYPES.BETWEEN;case to.VALUE_SEARCH_COMPARATORS.GREATER:return me.SEARCH_TYPES.GREATER_THAN;case to.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return me.SEARCH_TYPES.GREATER_THAN_EQUAL;case to.VALUE_SEARCH_COMPARATORS.LESS:return me.SEARCH_TYPES.LESS_THAN;case to.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return me.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Rw.UNKNOWN_SEARCH_TYPE)}}a(yw,"createSearchTypeFromSearchObject");Nw.exports={executeSearch:Ow,createSearchTypeFromSearchObject:yw,prepSearch:Gz,searchByType:bw}});var ww=g((V_e,Iw)=>{"use strict";var k_e=ts(),Fz=sa(),kz=z(),Vz=P(),$z=_d();Iw.exports=Yz;function Yz(e,t){if(!kz.isEmpty(t)&&Vz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Fz(e,"value");if(n)throw n;return $z.prepSearch(e,t,!0)}a(Yz,"lmdbGetDataByValue")});var nu=g((K_e,Cw)=>{"use strict";var Y_e=ts(),Kz=sa(),Wz=z(),Qz=P(),zz=_d();Cw.exports=Jz;async function Jz(e,t){if(!Wz.isEmpty(t)&&Qz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Kz(e,"value");if(n)throw n;return zz.prepSearch(e,t,!1)}a(Jz,"lmdbSearchByValue")});var Lw=g((z_e,Dw)=>{"use strict";var Q_e=ft(),Hp=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}},Gp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},qp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Dw.exports={SearchByConditionsObject:Hp,SearchCondition:Gp,SortAttribute:qp}});var Bw=g((Z_e,vw)=>{"use strict";var j_e=Lw().SearchByConditionsObject,jz=ts(),Xz=sa(),Fp=na(),dd=ft(),{Resource:X_e}=(cn(),ie(kp)),Uw=_d(),Zz=Pp(),e2=require("lodash"),{getSchemaPath:t2}=je(),Mw=Qe(),{handleHDBError:r2,hdb_errors:n2}=se(),{HTTP_STATUS_CODES:s2}=n2,i2=1e8;vw.exports=o2;async function o2(e){let t=Xz(e,"conditions");if(t)throw r2(t,t.message,s2.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=t2(e.schema,e.table),n=await Mw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Mw.openDBI(n,_.search_attribute);let i=e2.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===dd.SEARCH_TYPES.EQUALS?_.estimated_count=Fp.count(n,_.search_attribute,_.search_value):l===dd.SEARCH_TYPES.CONTAINS||l===dd.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=i2}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Pw(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(Uw.filterByType),d=l.length,E=Fp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!l[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>Zz.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await Pw(o,e,E,s.hash_attribute);c=c.concat(f)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Fp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(o2,"lmdbSearchByConditions");async function Pw(e,t,r,n){let s=new jz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===dd.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Uw.searchByType(e,s,i,n).map(o=>o.value)}a(Pw,"executeConditionSearch")});var oa=g((tde,xw)=>{"use strict";var a2=P().OPERATIONS_ENUM,Vp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=a2.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};xw.exports=Vp});var $p=g((nde,Yw)=>{"use strict";var Fw=ts(),kw=oa(),Vw=nu(),$w=Zc(),hr=P(),Hw=z(),Gw=Qe(),{getTransactionAuditStorePath:c2,getSchemaPath:u2}=je(),qw=$();Yw.exports=l2;async function l2(e){try{if(Hw.isEmpty(global.hdb_schema[e.schema])||Hw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await _2(e),await d2(e);let t=u2(e.schema,e.table);try{await Gw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")qw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=c2(e.schema,e.table);await Gw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")qw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(l2,"lmdbDropTable");async function _2(e){let t=new Fw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Vw(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 kw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await $w(s)}a(_2,"deleteAttributesFromSystem");async function d2(e){let t=new Fw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Vw(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 kw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await $w(s)}catch(i){throw i}}a(d2,"dropTableFromSystem")});var Ww=g((ide,Kw)=>{"use strict";var f2=require("fs-extra"),E2=ts(),h2=ia(),m2=oa(),p2=$p(),S2=Zc(),T2=vp(),g2=nu(),Is=P(),{getSchemaPath:R2}=je(),{handleHDBError:A2,hdb_errors:O2}=se(),{HDB_ERROR_MSGS:b2,HTTP_STATUS_CODES:y2}=O2;Kw.exports=N2;async function N2(e){let t;try{t=await I2(e.schema);let r=new E2(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await g2(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await p2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new m2(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await S2(s);let i=R2(t);await f2.remove(i)}catch(r){throw r}}a(N2,"lmdbDropSchema");async function I2(e){let t=new h2(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await T2(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw A2(new Error,b2.SCHEMA_NOT_FOUND(e),y2.NOT_FOUND,void 0,void 0,!0);return n}a(I2,"validateDropSchema")});var fd=g((ade,Qw)=>{"use strict";var Yp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Qw.exports=Yp});var Jw=g((lde,zw)=>{"use strict";var w2=require("fs-extra"),Ed=Qe(),{getTransactionAuditStorePath:C2}=je(),Kp=ft(),ude=fd();zw.exports=D2;async function D2(e){let t;try{let r=C2(e.schema,e.table);await w2.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,Kp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Ed.createDBI(t,Kp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Ed.createDBI(t,Kp.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(D2,"createTransactionsAuditEnvironment")});var eC=g((dde,Zw)=>{"use strict";var Wp=P(),jw=Qe(),L2=Yo(),{getSystemSchemaPath:M2,getSchemaPath:P2}=je(),U2=ki(),v2=P_(),Qp=M_(),B2=$(),x2=Jw(),Jp=U2.hdb_table,Xw=[];for(let e=0;e<Jp.attributes.length;e++)Xw.push(Jp.attributes[e].attribute);Zw.exports=H2;async function H2(e,t){let r=P2(t.schema,t.table),n=new Qp(t.schema,t.table,Wp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Qp(t.schema,t.table,Wp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Qp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await jw.createEnvironment(r,t.table),e!==void 0){let o=await jw.openEnvironment(M2(),Wp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await L2.insertRecords(o,Jp.hash_attribute,Xw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await zp(n),await zp(s),await zp(i)}await x2(t)}catch(o){throw o}}a(H2,"lmdbCreateTable");async function zp(e){try{await v2(e)}catch(t){B2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(zp,"createAttribute")});var rC=g((Ede,tC)=>{"use strict";var G2=Fc(),q2=Vc(),F2=id(),su=P(),k2=Yo().updateRecords,V2=Qe(),{getSchemaPath:$2}=je(),Y2=jc(),K2=$();tC.exports=W2;async function W2(e){try{let{schema_table:t,attributes:r}=G2(e);q2(e,r,t.hash_attribute),e.schema!==su.SYSTEM_SCHEMA_NAME&&(r.includes(su.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(su.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(su.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(su.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await F2(e.hdb_auth_header,t,r),s=$2(e.schema,e.table),i=await V2.openEnvironment(s,e.table),o=await k2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await Y2(e,o)}catch(c){K2.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(W2,"lmdbUpdateRecords")});var sC=g((mde,nC)=>{"use strict";var Q2=P().OPERATIONS_ENUM,jp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=Q2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};nC.exports=jp});var oC=g((Tde,iC)=>{"use strict";var Sde=sC(),z2=Fc(),J2=Vc(),j2=id(),iu=P(),X2=Yo().upsertRecords,Z2=Qe(),{getSchemaPath:eJ}=je(),tJ=jc(),rJ=$(),{handleHDBError:nJ,hdb_errors:sJ}=se();iC.exports=iJ;async function iJ(e){let t;try{t=z2(e)}catch(u){throw nJ(u,u.message,sJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;J2(e,n,r.hash_attribute),e.schema!==iu.SYSTEM_SCHEMA_NAME&&(n.includes(iu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(iu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(iu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(iu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await j2(e.hdb_auth_header,r,n),i=eJ(e.schema,e.table),o=await Z2.openEnvironment(i,e.table),c=await X2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await tJ(e,c)}catch(u){rJ.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(iJ,"lmdbUpsertRecords")});var cC=g((Rde,aC)=>{"use strict";var Xp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};aC.exports=Xp});var lC=g((Ode,uC)=>{"use strict";var Zp=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}};uC.exports=Zp});var fC=g((Nde,dC)=>{"use strict";var eS=Qe(),{getTransactionAuditStorePath:oJ}=je(),yde=cC(),ou=ft(),aJ=z(),_C=lC(),cJ=require("util").promisify,uJ=cJ(setTimeout),lJ=1e4,_J=100;dC.exports=dJ;async function dJ(e){let t=oJ(e.schema,e.table),r=await eS.openEnvironment(t,e.table,!0),n=eS.listDBIs(r);eS.initializeDBIs(r,ou.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new _C;do s=await fJ(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 uJ(_J);while(s.transactions_deleted>0);return i}a(dJ,"deleteAuditLogsBefore");async function fJ(e,t){let r=new _C;try{let n=e.dbis[ou.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[ou.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];aJ.isEmpty(c)||(s=e.dbis[ou.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[ou.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>lJ)break}return await s,r}catch(n){throw n}}a(fJ,"deleteTransactions")});var hC=g((wde,EC)=>{"use strict";var tS=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};EC.exports=tS});var pC=g((Lde,mC)=>{"use strict";var EJ=ts(),hJ=oa(),Dde=hC(),rs=P(),mJ=z(),rS=Qe(),pJ=ki(),SJ=nu(),TJ=Zc(),{getSchemaPath:gJ}=je();mC.exports=RJ;async function RJ(e,t=!0){let r;e.schema===rs.SYSTEM_SCHEMA_NAME?r=pJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await OJ(e),s=gJ(e.schema,e.table),i=await rS.openEnvironment(s,e.table);return t===!0&&await AJ(e,i,r.hash_attribute),rS.dropDBI(i,e.attribute),n}a(RJ,"lmdbDropAttribute");async function AJ(e,t,r){let n=rS.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(AJ,"removeAttributeFromAllObjects");async function OJ(e){let t=new EJ(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 SJ(t)).filter(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(mJ.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 hJ(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return TJ(i)}a(OJ,"dropAttributeFromSystem")});var OC=g((Ude,AC)=>{"use strict";var nS=Qe(),aa=ft(),Pde=vr(),sS=P(),SC=z(),{getTransactionAuditStorePath:bJ}=je(),yJ=na(),hd=ea(),NJ=$();AC.exports=IJ;async function IJ(e){let t=bJ(e.schema,e.table),r=await nS.openEnvironment(t,e.table,!0),n=nS.listDBIs(r);nS.initializeDBIs(r,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case sS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return TC(r,e.search_values);case sS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,CJ(r,e.search_values,s);case sS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return wJ(r,e.search_values);default:return TC(r)}}a(IJ,"readAuditLog");function TC(e,t=[0,Date.now()]){SC.isEmpty(t[0])&&(t[0]=0),SC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new hd,s))}a(TC,"searchTransactionsByTimestamp");function wJ(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,RC(e,i))}return Object.fromEntries(r)}a(wJ,"searchTransactionsByUsername");function CJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=yJ.equals(e,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,aa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=RC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);gC(u,"records",r,l,o),gC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(CJ,"searchTransactionsByHashValues");function gC(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 hd(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new hd(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(gC,"loopRecords");function RC(e,t){let r=[];try{let n=e.dbis[aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new hd,i);r.push(o)}}catch(i){NJ.warn(i)}return r}catch(n){throw n}}a(RC,"batchSearchTransactions")});var yC=g((Hde,bC)=>{"use strict";var{getSchemaPath:Bde}=je(),xde=Qe(),{database:DJ}=(Ae(),ie(ke));bC.exports={writeTransaction:LJ};async function LJ(e,t,r){return DJ({database:e,table:t}).transaction(r)}a(LJ,"writeTransaction")});var CC=g((qde,wC)=>{"use strict";var{getSchemaPath:NC}=je(),IC=Qe();wC.exports={flush:MJ,resetReadTxn:PJ};async function MJ(e,t){return(await IC.openEnvironment(NC(e,t),t.toString())).flushed}a(MJ,"flush");async function PJ(e,t){try{(await IC.openEnvironment(NC(e,t),t.toString())).resetReadTxn()}catch{}}a(PJ,"resetReadTxn")});var PC=g((kde,MC)=>{"use strict";var{Readable:UJ}=require("stream"),{getDatabases:vJ}=(Ae(),ie(ke)),{readSync:BJ,openSync:xJ,createReadStream:DC}=require("fs"),{open:HJ}=require("lmdb"),LC=Uc(),GJ=vc(),{AUDIT_STORE_OPTIONS:qJ}=(ri(),ie(UC)),{INTERNAL_DBIS_NAME:FJ,AUDIT_STORE_NAME:kJ}=ft();MC.exports=$J;var iS=32768,VJ=100;async function $J(e){let t=e.database||e.schema||"data",r=vJ()[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=HJ({noSync:!0,maxDbs:GJ.MAX_DBS}),E,f=d.openDB(FJ,new LC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(R,N){N.encoding="binary",N.encoder=void 0;let I=d.openDB(R,N),H=l.openDB(R,N);for(let{key:U,version:k,value:M}of H.getRange({start:null,transaction:h,versions:H.useVersions}))E=I.put(U,M,k),p++%VJ===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:N}of l.getRange({transaction:h,start:!1}))if(s.some(I=>R.startsWith?.(I+"/"))){f.put(R,N);let[,I]=R.split("/"),H=!I,U=new LC(!H,H);await S(R,U)}e.include_audit&&await S(kJ,Object.assign({},qJ)),await E;let T=DC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=xJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(iS);BJ(c,_,0,iS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=DC(null,{fd:c,start:iS}),E=new UJ.from(async function*(){yield _;for await(let f of d)l.openTimer&&(l.openTimer=0),yield f;l.done()}());return E.headers=u(),E});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a($J,"getBackup")});var xC=g(($de,BC)=>{"use strict";var YJ=$(),{handleHDBError:KJ}=se(),WJ=zb(),QJ=P_(),zJ=wp(),JJ=WI(),jJ=Zc(),XJ=vp(),ZJ=Tw(),e4=ww(),t4=nu(),r4=Bw(),n4=Ww(),s4=eC(),i4=rC(),o4=oC(),a4=fC(),c4=$p(),u4=pC(),l4=OC(),_4=yC(),vC=CC(),d4=PC(),oS=class extends WJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return r4(t)}async getDataByHash(t){return await XJ(t)}async searchByHash(t){return await ZJ(t)}async getDataByValue(t,r){return await e4(t,r)}async searchByValue(t){return await t4(t)}async createSchema(t){return await JJ(t)}async dropSchema(t){return await n4(t)}async createTable(t,r){return await s4(t,r)}async dropTable(t){return await c4(t)}async createAttribute(t){return await QJ(t)}async createRecords(t){return await zJ(t)}async updateRecords(t){return await i4(t)}async upsertRecords(t){try{return await o4(t)}catch(r){throw KJ(r,null,null,YJ.ERR,r)}}async deleteRecords(t){return await jJ(t)}async dropAttribute(t){return await u4(t)}async deleteAuditLogsBefore(t){return await a4(t)}async readAuditLog(t){return await l4(t)}writeTransaction(t,r,n){return _4.writeTransaction(t,r,n)}flush(t,r){return vC.flush(t,r)}resetReadTxn(t,r){return vC.resetReadTxn(t,r)}getBackup(t){return d4(t)}};BC.exports=oS});function m4(){h4=setInterval(function(){for(let e of aS)if(e.stale){let t=e[ye]?.url;FC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},E4).unref()}var cS,qC,FC,kC,VC,$C,HC,aS,f4,au,GC,ro,md,E4,h4,uS=Re(()=>{cS=x(vr()),qC=x(se()),FC=x($());cn();kC=x(ee()),VC=x(P()),$C=x(z()),HC=100,aS=new Set,f4=(0,$C.convertToMS)(kC.get(VC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,ro=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),aS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(aS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(au&&!this.overloadChecked&&performance.now()-GC>f4)throw new qC.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,cS.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let f=d;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=d;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let p=d;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let T=S[f===0?"before":"beforeIntermediate"];if(T){let R=T();h?h.push?h.push(R):h=[h,R]:h=R}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),u=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let E=d.store.ifVersion(d.key,d.entry?.version??null,u);s=s||E}else u();else for(let E of this.writes)c(E)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<HC>>n?u():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return au||(au=s,GC=performance.now(),au.then(()=>{au=null})),s.then(d=>d?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(_&&(_.retryRisk=(_.retryRisk||0)+HC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},md=class extends ro{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,cS.getNextMonotonicTime)())}getReadTxn(){}},E4=3e4;a(m4,"startMonitoringTxns");m4()});function Ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new 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 YC,no=Re(()=>{YC=require("../index");cn();uS();a(Ze,"transaction");(0,YC._assignPackageExport)("transaction",Ze);Ze.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ze.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 eD={};Fe(eD,{ResourceBridge:()=>dS});function fS({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 WC(e,t){let r=ns(e),n=fS(e,r);if(!r)throw new Pn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&Sd(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||S4,r=mr()[t];if(!r)throw(0,Pn.handleHDBError)(new Error,p4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function QC(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*zC(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 JC,pd,Pn,jC,XC,Un,lS,_S,ZC,p4,S4,T4,g4,KC,dS,tD=Re(()=>{"use strict";JC=x(xC()),pd=x(sa()),Pn=x(se());Ae();jC=x(Fc()),XC=x(Vc()),Un=x(P()),lS=x(ys()),_S=x(Mn()),ZC=x(z());no();Td();({HDB_ERROR_MSGS:p4}=Pn.hdb_errors),S4="data",T4=1e4,g4=10,dS=class extends JC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),KC=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,pd.default)(t,"conditions");if(r)throw(0,Pn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=ns(t);if(!n)throw new Pn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:fS(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Pn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}Et({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await ns(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=ns(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){ns(t).dropTable()}createSchema(t){return ca({database:t.schema,table:null}),lS.signalSchemaChange(new _S.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await ES(t.schema),lS.signalSchemaChange(new _S.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,KC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,jC.default)(t);(0,XC.default)(t,n,r.primaryKey);let s,i=mr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(E=>E.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=Sd(d));for(let E in l)if(Object.prototype.hasOwnProperty.call(l,E)){let f=l[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,l[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(l),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(l,E)||(l[E]=d[E]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=mr()[t.schema][t.table],n={user:t.hdb_user};return Ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return QC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=mr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Pn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,ZC.async_set_timeout)(g4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%T4===0&&await _();return u.length>0&&await _(),s?QC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,pd.default)(t,"hashes");if(r)throw r;return WC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of WC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,pd.default)(t,"value");if(n)throw n;let s=ns(t);if(!s)throw new Pn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Un.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:fS(t,s)})}async getDataByValue(t,r){let n=new Map,s=ns(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){ns({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return ns(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=ns(t),n={};switch(t.search_type){case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of zC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return zC(r,t.search_values?.[0],t.search_values?.[1])}}};a(fS,"getSelect");a(WC,"getRecords");a(ns,"getTable");a(QC,"createDeleteResponse");a(zC,"groupRecordsInHistory")});var Cn=g((ife,rD)=>{"use strict";var{ResourceBridge:R4}=(tD(),ie(eD)),A4=ee();A4.initSync();var gd;function O4(){return gd||(gd=new R4,gd)}a(O4,"getBridge");rD.exports=O4()});var oD=g((afe,iD)=>{"use strict";var nD=require("lodash"),cu=require("mathjs"),b4=require("jsonata"),sD=z();iD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?nD.uniqWith(e,nD.isEqual):e,searchJSON:y4,mad:uu.bind(null,cu.mad),mean:uu.bind(null,cu.mean),mode:uu.bind(null,cu.mode),prod:uu.bind(null,cu.prod),median:uu.bind(null,cu.median)};function uu(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(uu,"aggregateFunction");function y4(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(sD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),sD.isEmpty(this.__ala__.res[r])){let n=b4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(y4,"searchJSON")});var cD=g((ufe,aD)=>{"use strict";var Rt=require("moment"),hS="YYYY-MM-DDTHH:mm:ss.SSSZZ";Rt.suppressDeprecationWarnings=!0;aD.exports={current_date:()=>Rt().utc().format("YYYY-MM-DD"),current_time:()=>Rt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Rt(e).utc().format("YYYY");case"month":return Rt(e).utc().format("MM");case"day":return Rt(e).utc().format("DD");case"hour":return Rt(e).utc().format("HH");case"minute":return Rt(e).utc().format("mm");case"second":return Rt(e).utc().format("ss");case"millisecond":return Rt(e).utc().format("SSS");default:break}},date:e=>Rt(e).utc().format(hS),date_format:(e,t)=>Rt(e).utc().format(t),date_add:(e,t,r)=>Rt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Rt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=Rt(e).utc(),s=Rt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>Rt().utc().valueOf(),get_server_time:()=>Rt().format(hS),offset_utc:(e,t)=>Rt(e).utc().utcOffset(t).format(hS)}});var dD=g((lfe,_D)=>{"use strict";var N4=require("@turf/area"),I4=require("@turf/length"),w4=require("@turf/circle"),C4=require("@turf/difference"),D4=require("@turf/distance"),L4=require("@turf/boolean-contains"),M4=require("@turf/boolean-equal"),P4=require("@turf/boolean-disjoint"),U4=require("@turf/helpers"),uD=P(),Te=z(),ws=$();_D.exports={geoArea:v4,geoLength:B4,geoCircle:x4,geoDifference:H4,geoDistance:lD,geoNear:G4,geoContains:q4,geoEqual:F4,geoCrosses:k4,geoConvert:V4};function v4(e){if(Te.isEmpty(e))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return N4.default(e)}catch(t){return ws.trace(t,e),NaN}}a(v4,"geoArea");function B4(e,t){if(Te.isEmpty(e))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return I4.default(e,{units:t||"kilometers"})}catch(r){return ws.trace(r,e),NaN}}a(B4,"geoLength");function x4(e,t,r){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return w4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(x4,"geoCircle");function H4(e,t){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return C4(e,t)}catch(r){return ws.trace(r,e,t),NaN}}a(H4,"geoDifference");function lD(e,t,r){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return D4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(lD,"geoDistance");function G4(e,t,r,n){if(Te.isEmpty(e)||Te.isEmpty(t))return!1;if(Te.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return lD(e,t,n)<=r}catch(s){return ws.trace(s,e,t),!1}}a(G4,"geoNear");function q4(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return L4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(q4,"geoContains");function F4(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return M4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(F4,"geoEqual");function k4(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return!P4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(k4,"geoCrosses");function V4(e,t,r){if(Te.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Te.isEmpty(t))throw new Error("geo_type is required");if(Te.isEmpty(uD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(uD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Te.autoCastJSON(e)),U4[t](e,r)}a(V4,"geoConvert")});var Rd=g((dfe,fD)=>{var so=oD(),Kr=cD(),ss=dD();fD.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=Kr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Kr.current_time,e.fn.extract=e.fn.EXTRACT=Kr.extract,e.fn.date=e.fn.DATE=Kr.date,e.fn.date_format=e.fn.DATE_FORMAT=Kr.date_format,e.fn.date_add=e.fn.DATE_ADD=Kr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Kr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Kr.date_diff,e.fn.now=e.fn.NOW=Kr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Kr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Kr.get_server_time,e.fn.getdate=e.fn.GETDATE=Kr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Kr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ss.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ss.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ss.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ss.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ss.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ss.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ss.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ss.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ss.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ss.geoNear}});var pD=g((ffe,mD)=>{"use strict";var lu=require("lodash"),pr=require("alasql");pr.options.cache=!1;var $4=Rd(),ED=require("clone"),Ad=require("recursive-iterator"),fe=$(),Le=z(),ua=Cn(),Y4=P(),{hdb_errors:K4}=se(),{getDatabases:hD}=(Ae(),ie(ke)),W4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";$4(pr);var mS=class{static{a(this,"SQLSearch")}constructor(t,r){if(Le.isEmpty(t))throw fe.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),Le.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Le.isEmptyOrZeroLength(n))return fe.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw fe.error("Error thrown from checkEmptySQL in SQLSearch class method search."),fe.error(n),new Error(vn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw fe.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),fe.error(n),new Error(vn)}if(Object.keys(this.data).length===0)return fe.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw fe.error("Error thrown from processJoins in SQLSearch class method search."),fe.error(n),new Error(vn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw fe.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),fe.error(n),new Error(vn)}try{return t=await this._finalSQL(),t}catch(n){throw fe.error("Error thrown from finalSQL in SQLSearch class method search."),fe.error(n),new Error(vn)}}_getColumns(){let t=new Ad(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(ED(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=lu.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=hD()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Le.isEmpty(this.statement.where)){fe.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Ad(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Le.isEmpty(r)&&r.right)if(Le.isNotEmptyAndHasValue(r.right.value)){let n=Le.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new pr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Le.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new pr.yy.LogicValue({value:i}):n instanceof pr.yy.StringValue&&Le.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new pr.yy.NumValue({value:i}))});if(t){fe.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Ad(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(!Le.isEmpty(Y4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Le.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Le.isEmptyOrZeroLength(r.left.columnid)||Le.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(Le.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"=":!Le.isEmpty(r.right.value)||!Le.isEmpty(r.left.value)?n.add(Le.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(Le.isEmptyOrZeroLength(this.all_table_attributes)&&Le.isEmptyOrZeroLength(this.statement.from)&&Le.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&&lu.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(Le.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Le.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(Le.isEmptyOrZeroLength(this.all_table_attributes)&&!Le.isEmptyOrZeroLength(this.columns.columns))return t;if(Le.isEmptyOrZeroLength(this.all_table_attributes)&&Le.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pr.promise(r)}catch(r){throw fe.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),fe.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(ED(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(Le.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(W4)>-1&&this.tables.forEach(s=>{let i={columnid:hD()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=lu.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),!Le.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Le.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ua.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw fe.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),fe.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let E=await ua.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(l){throw fe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),fe.error(l),new Error(vn)}else if(!Le.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Le.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,E=l.length;d<E;d++){let f=l[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ua.getDataByValue(c,f.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw fe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),fe.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ua.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw fe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),fe.error(l),new Error(vn)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof pr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new pr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new pr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new pr.yy.FuncValue:new pr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,p=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${p}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${p}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await pr.promise(h,t),t=null}catch(f){throw fe.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),fe.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let p=E[f];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),p=lu.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let R=p[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[R]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new Ad(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=lu.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw fe.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),fe.error(i),new Error(vn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ua.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let E=o[l],f=u.get(E);for(let h=0;h<_;h++){let p=s.columns[h],S=f[p]===void 0?null:f[p];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw fe.error("Error thrown from getDataByHash function in SQLSearch class method getData."),fe.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();fe.trace(`Final SQL: ${s}`),n=await pr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),fe.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw fe.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),fe.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return fe.error(K4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),fe.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ua.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw fe.error("There was an error when processing this SQL operation. Check your logs"),fe.error(o),new Error(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};mD.exports=mS});var Gr=g((hfe,SD)=>{"use strict";var Q4=Wb();SD.exports={searchByConditions:J4,searchByHash:j4,searchByValue:X4,search:Z4};var pS=Cn(),{transformReq:SS}=z(),z4=pD();async function J4(e){return SS(e),pS.searchByConditions(e)}a(J4,"searchByConditions");async function j4(e){SS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of pS.searchByHash(e))r&&t.push(r);return t}a(j4,"searchByHash");async function X4(e){SS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of pS.searchByValue(e))t.push(r);return t}a(X4,"searchByValue");function Z4(e,t){try{let r=new Q4(e);r.validate(),new z4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(Z4,"search")});var Od=g((pfe,TD)=>{"use strict";var e3=Cn();TD.exports={writeTransaction:t3};function t3(e,t,r){return e3.writeTransaction(e,t,r)}a(t3,"writeTransaction")});var OD=g((gfe,AD)=>{"use strict";var r3=Gr(),n3=bs(),gD=$(),s3=qr(),Tfe=Od(),i3=require("clone"),gS=require("alasql"),o3=Rd(),RD=require("util"),a3=RD.promisify(n3.getTableSchema),c3=RD.promisify(r3.search),u3=P(),TS=z();o3(gS);AD.exports={update:_3};var l3="There was a problem performing this update. Please check the logs and try again.";async function _3({statement:e,hdb_user:t}){let r=await a3(e.table.databaseid,e.table.tableid),n=d3(e.columns);TS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=i3(s),c=TS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=gS.parse(u).statements[0],l=await c3(_),d=f3(n,l);return E3(o,d,t)}a(_3,"update");function d3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=gS.compile(`SELECT ${r.expression.toString()} AS [${u3.FUNC_VAL}] FROM ?`)}),t}catch(t){throw gD.error(t),new Error(l3)}}a(d3,"createUpdateRecord");function f3(e,t){return TS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(f3,"buildUpdateRecords");async function E3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await s3.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){gD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(E3,"updateRecords")});var yD=g((bfe,bD)=>{var h3=require("alasql"),m3=Gr(),p3=$(),S3=Cn(),AS=require("util"),RS=z(),T3=P(),g3=bs(),Afe=Od(),Ofe=qr(),R3="record",A3="successfully deleted",O3=AS.callbackify(I3),b3=AS.promisify(m3.search),y3=AS.promisify(g3.getTableSchema);bD.exports={convertDelete:O3};function N3(e){return`${e.deleted_hashes.length} ${R3}${e.deleted_hashes.length===1?"":"s"} ${A3}`}a(N3,"generateReturnMessage");async function I3({statement:e,hdb_user:t}){let r=await y3(e.table.databaseid,e.table.tableid);RS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=RS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=h3.parse(o).statements[0],u={operation:T3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await b3(c);let _=await S3.deleteRecords(u);return RS.isEmptyOrZeroLength(_.message)&&(_.message=N3(_)),delete _.txn_time,_}catch(_){throw p3.error(_),_.hdb_code?_.message:_}}a(I3,"convertDelete")});var DD=g((Nfe,CD)=>{"use strict";var w3=Os(),{hdb_errors:ND}=se(),{getDatabases:ID}=(Ae(),ie(ke));CD.exports={checkSchemaExists:wD,checkSchemaTableExists:C3,schema_describe:w3};async function wD(e){if(!ID()[e])return ND.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(wD,"checkSchemaExists");async function C3(e,t){let r=await wD(e);if(r)return r;if(!ID()[e][t])return ND.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(C3,"checkSchemaTableExists")});var _u=g((wfe,D3)=>{D3.exports={name:"harperdb",version:"4.3.22",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","enterprise","Fastify","NATS","HarperDB","Harper","clustering","replication","REST","WebSockets","decentralized","server-sent events","document store"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.635.0","@aws-sdk/lib-storage":"3.635.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.14",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.4.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.17.1",yaml:"2.4.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.22.11","newman-reporter-teamcity":"0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var mu={};Fe(mu,{addAnalyticsListener:()=>hu,recordAction:()=>Sr,recordActionBinary:()=>Wr,setAnalyticsEnabled:()=>L3});function L3(e){GD=e}function Sr(e,t,r,n,s){if(!GD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Nd.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},Nd.set(i,o)}bd||M3()}function Wr(e,t,r,n,s){Sr(!!e,t,r,n,s)}function hu(e){kD.push(e)}function M3(){bd=performance.now(),setTimeout(async()=>{let e=performance.now()-bd;bd=0;let t=[],r={time:Date.now(),period:e,threadId:io.threadId,metrics:t};for(let[s,i]of Nd){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 VD){let E=Math.floor(c*d),f=o[E-1];if(E>u){let h=E-u;if(f===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:f,count:h}:f),l=f;u=E}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await $D()}let n=process.memoryUsage();t.push({metric:"memory",threadId:io.threadId,byThread:!0,...n});for(let s of kD)s(t);Nd=new Map,io.parentPort?io.parentPort.postMessage({type:FD,report:r}):WD({report:r})},qD).unref()}async function P3(e,t=6e4){let r=yS(),n=YD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,du.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,du.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:R}=S;for(let N of T||[]){let{path:I,method:H,type:U,metric:k,count:M,total:Q,distribution:J,threads:j,...ae}=N;M||(M=1);let ce=k+(I?"-"+I:"");H!==void 0&&(ce+="-"+H),U!==void 0&&(ce+="-"+U);let de=c.get(ce);if(de){if(de.threads){let Ne=de.threads[R];if(Ne)de=Ne;else{de.threads[R]=Object.assign({},ae);continue}}de.count||(de.count=1);let Be=de.count;for(let Ne in ae){let xe=ae[Ne];typeof xe=="number"&&(de[Ne]=(de[Ne]*Be+xe*M)/(Be+M))}de.count+=M,Q>=0&&(de.total+=Q,de.ratio=de.total/de.count)}else de=Object.assign({period:t},N),delete de.distribution,c.set(ce,de),de.byThread&&(de.threads=[],de.threads[R]=Object.assign({},ae),_.push(de));if(J){J=J.map(Ne=>typeof Ne=="number"?{value:Ne,count:1}:Ne);let Be=u.get(ce);Be?Be.push(...J):u.set(ce,J)}}await $D()}for(let p of _){let{path:S,method:T,type:R,metric:N,count:I,total:H,distribution:U,threads:k,...M}=p;k=k.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let J=0;for(let j of k){let ae=j[Q];typeof ae=="number"&&(J+=ae)}p[Q]=J}p.count=k.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Ne,xe)=>Ne.value>xe.value?1:-1);let R=T.count-1,N=[],I=0,H=0,U;for(let Ne of VD){let xe=R*Ne;for(;I<xe;)U=S[H++],I+=U.count,H===1&&I--;let t_=S[H>1?H-2:0];U||(U=S[0]),N.push(U.value-(U.value-t_.value)*(I-xe)/U.count)}let[k,M,Q,J,j,ae,ce,de,Be]=N;Object.assign(T,{p1:k,p10:M,p25:Q,median:J,p75:j,p90:ae,p95:ce,p99:de,p999:Be})}let d;for(let[p,S]of c)S.id=(0,yd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(d||h*10>f){let p=(0,yd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-LD,active:h-MD,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}LD=f,MD=h}async function PD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function yS(){return UD||(UD=Et({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function YD(){return vD||(vD=Et({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function B3(){KD=!0;let e=(0,Eu.get)(bS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await P3(qD,e),await PD(yS(),U3),await PD(YD(),v3)},Math.min(e/2,2147483647)).unref()}function WD(e,t){let r=e.report;r.threadId=t?.threadId||io.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(BD+=n.mean*n.count);r.totalBytesProcessed=BD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(xD.get(t))}),xD.set(t,t.performance.eventLoopUtilization())),r.id=(0,yd.getNextMonotonicTime)(),yS().primaryStore.put(r.id,r),KD||B3(),x3&&(QD=G3(r))}async function G3(e){if(await QD,!di){let r=(0,fu.dirname)((0,du.getLogFilePath)());try{di=await(0,OS.open)((0,fu.join)(r,"analytics.log"),"r+")}catch{di=await(0,OS.open)((0,fu.join)(r,"analytics.log"),"w+")}}let t=(await di.stat()).size;if(t>H3){let r=Buffer.alloc(t);await di.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await di.write(r,{position:0}),await di.truncate(r.length),t=r.length}await di.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var io,HD,du,fu,OS,yd,Eu,bS,Nd,GD,bd,qD,FD,kD,VD,LD,MD,$D,U3,v3,UD,vD,KD,BD,xD,x3,QD,di,H3,Cs=Re(()=>{io=require("worker_threads"),HD=x(We());Ae();du=x($()),fu=require("path"),OS=require("fs/promises"),yd=x(vr()),Eu=x(ee()),bS=x(P());lr();(0,Eu.initSync)();Nd=new Map,GD=(0,Eu.get)(bS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(L3,"setAnalyticsEnabled");a(Sr,"recordAction");at.recordAnalytics=Sr;a(Wr,"recordActionBinary");bd=0,qD=1e3,FD="analytics-report",kD=[];a(hu,"addAnalyticsListener");VD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(M3,"sendAnalytics");a(P3,"aggregation");LD=0,MD=0,$D=a(()=>new Promise(setImmediate),"rest");a(PD,"cleanup");U3=36e5,v3=31536e6;a(yS,"getRawAnalyticsTable");a(YD,"getAnalyticsTable");(0,HD.setChildListenerByType)(FD,WD);a(B3,"startScheduledTasks");BD=0,xD=new Map,x3=!1;a(WD,"recordAnalytics");H3=1e6;a(G3,"logAnalytics")});var DS=g((Ffe,iL)=>{"use strict";var{decode:q3}=require("msgpackr"),{isMainThread:Hfe,parentPort:Gfe,threadId:qfe}=require("worker_threads"),Cd=ut(),la=Ve(),wS=P(),nr=$(),IS=ee(),F3=P(),{onMessageByType:k3}=We(),jD=As(),{recordAction:V3,recordActionBinary:$3}=(Cs(),ie(mu)),{publishToStream:Y3}=Cd,{ConsumerEvents:zD}=require("nats"),K3=Gr(),{promisify:W3}=require("util"),XD=W3(setTimeout),Dd=1e4,Ld,wd,Q3,z3,ZD,pu=new Map,_a=new Map;iL.exports={initialize:eL,ingestConsumer:CS,setSubscription:J3,setIgnoreOrigin:Z3,getDatabaseSubscriptions:X3,updateConsumer:tL};async function eL(){k3(wS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await tL(n)}),ZD=!0,nr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await Cd.getNATSReferences();Ld=e,wd=e.info.server_name,Q3=t,z3=r}a(eL,"initialize");async function tL(e){if(e.status==="start"){let{js:t,jsm:r}=await rL(e.node_domain_name);CS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=pu.get(e.stream_name+e.node_domain_name);t&&(nr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),pu.set(e.stream_name+e.node_domain_name,"close")),_a.get(e.node_domain_name)==="failed"&&_a.set(e.node_domain_name,"close")}}a(tL,"updateConsumer");var Md=new Map;function J3(e,t,r){let n=Md.get(e);n||Md.set(e,n=new Map),n.set(t,r),ZD||eL().then(j3)}a(J3,"setSubscription");async function j3(){let e=await K3.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+la.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await rL(r),!n))break;let{schema:o,table:c}=i,u=jD.createNatsTableStreamName(o,c);CS(u,n,s,r)}}}a(j3,"accessConsumers");async function rL(e){let t,r,n=1;for(;!r;)try{t=await Ld.jetstream({domain:e}),r=await Ld.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(_a.get(e)==="close")break;_a.set(e,"failed"),n%10===1&&nr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<Dd?n++*100:Dd;await XD(i)}return{js:t,jsm:r}}a(rL,"connectToRemoteJS");function X3(){return Md}a(X3,"getDatabaseSubscriptions");var nL;function Z3(e){nL=e}a(Z3,"setIgnoreOrigin");var sL=100,JD=new Array(sL),Id=0;async function CS(e,t,r,n){let{connection:s}=await Cd.getNATSReferences();Ld=s,wd=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,wd),nr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(_a.get(n)==="close")break;o%10===1&&nr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(nr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await Cd.createConsumer(r,e,wd,new Date(Date.now()).toISOString()));let l=o++*100<Dd?o++*100:Dd;await XD(l)}let c=!1,u;for(;!c;){if(pu.get(e+n)==="close"||_a.get(n)==="close"){pu.delete(e+n),c=!0;continue}u=await i.consume({max_messages:IS.get(wS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),pu.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===zD.ConsumerDeleted&&(await u.close(),c=!0),l.type===zD.HeartbeatsMissed){let d=l.data;nr.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===100&&(nr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await JD[Id],JD[Id]=ej(l).catch(d=>{nr.error(d)}),++Id>=sL&&(Id=0)}catch(l){l.message==="consumer deleted"?(nr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):nr.error("Error consuming clustering ingest, restarting consumer",l)}}}a(CS,"ingestConsumer");async function ej(e){let t=q3(e.data);V3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),nr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=IS.get(wS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(la.MSG_HEADERS.TRANSACTED_NODES)&&r.values(la.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(la.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!nL),$3(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(la.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:E,expiresAt:f}=t;nr.trace("processing message:",o,c,_,(l?"records: "+l.map(I=>I?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),nr.trace(`messageProcessor nats msg id: ${e.headers.get(la.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(I=>h=I),{timestamp:S,user:T,node_name:R}=E||{},N=Md.get(c)?.get(_);if(!N)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,N.send(t);else if(l.length===1&&!u)N.send({type:NS(o),value:l[0],id:d?.[0],expiresAt:f,timestamp:S,table:_,onCommit:h,user:T,nodeName:R});else{let I=l.map((H,U)=>({type:NS(o),value:H,expiresAt:f,id:d?.[U],table:_}));for(;u;)I.push({type:NS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;N.send({type:"transaction",writes:I,table:_,timestamp:S,onCommit:h,user:T,nodeName:R})}IS.get(F3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Y3(e.subject.split(".").slice(0,-1).join("."),jD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){nr.error(o)}e.ack()}a(ej,"messageProcessor");function NS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(NS,"convertOperation")});var ut=g((Qfe,AL)=>{"use strict";var xt=ee();xt.initSync();var tj=require("fs-extra"),rj=require("semver"),gu=require("path"),{monotonicFactory:nj}=require("ulidx"),aL=nj(),sj=require("util"),cL=require("child_process"),ij=sj.promisify(cL.exec),oj=cL.spawn,Kt=Ve(),Ie=P(),Pd=z(),Bn=$(),Ud=As(),aj=Od(),Su=Er(),{broadcast:cj,onMessageByType:uj,getWorkerIndex:lj}=We(),{isMainThread:uL}=require("worker_threads"),{Encoder:_j,decode:US}=require("msgpackr"),lL=new _j,{isEmpty:uo}=Pd,_L=_n(),Vfe=48*36e11;uL&&uj(Ie.ITC_EVENT_TYPES.RESTART,()=>{Tr=void 0,co=void 0});var{connect:dj,StorageType:fj,RetentionPolicy:Ej,AckPolicy:vS,DeliverPolicy:BS,DiscardPolicy:hj,NatsConnection:$fe,JetStreamManager:Yfe,JetStreamClient:Kfe,StringCodec:Wfe,JSONCodec:mj,createInbox:xS,headers:pj,ErrorCode:oL}=require("nats"),{PACKAGE_ROOT:Sj}=P(),Tj=_u(),{recordAction:gj}=(Cs(),ie(mu)),dL=mj(),Rj="clustering",Aj=Tj.engines[Kt.NATS_SERVER_NAME],Oj=gu.join(Sj,"dependencies"),PS=gu.join(Oj,`${process.platform}-${process.arch}`,Kt.NATS_BINARY_NAME),LS,MS,Tu,oo,ao;AL.exports={runCommand:fL,checkNATSServerInstalled:bj,createConnection:HS,getConnection:Ru,getJetStreamManager:Au,getJetStream:hL,getNATSReferences:is,getServerList:Nj,createLocalStream:GS,listStreams:mL,deleteLocalStream:Ij,getServerConfig:da,listRemoteStreams:wj,viewStream:Cj,viewStreamIterator:Dj,publishToStream:Lj,request:Uj,reloadNATS:qS,reloadNATSHub:vj,reloadNATSLeaf:Bj,extractServerName:Pj,requestErrorHandler:xj,createLocalTableStream:gL,createTableStreams:qj,purgeTableStream:RL,purgeSchemaTableStreams:Fj,getStreamInfo:kj,updateLocalStreams:$j,closeConnection:yj,getJsmServerName:vd,addNatsMsgHeader:pL,clearClientCache:EL,updateRemoteConsumer:Hj,createConsumer:SL,updateConsumerIterator:Gj};async function fL(e,t=void 0){let{stdout:r,stderr:n}=await ij(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(dL,"runCommand");async function A3(){try{await Zj.access(MS)}catch{return!1}let e=await dL(`${MS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return e3.eq(t,g3)}a(A3,"checkNATSServerInstalled");async function HS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await lL.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 l3({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),fL()}),i}a(HS,"createConnection");function fL(){Tr=void 0,oo=void 0,ao=void 0,co=void 0}a(fL,"clearClientCache");async function O3(){Tr&&(await Tr.drain(),Tr=void 0,oo=void 0,ao=void 0,co=void 0)}a(O3,"closeConnection");var Tr,co;async function gu(){return co||(co=HS(Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Tr=await co),Tr||co}a(gu,"getConnection");async function Ru(){if(oo)return oo;uo(Tr)&&await gu();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=await Tr.jetstreamManager({domain:e,timeout:6e4}),oo}a(Ru,"getJetStreamManager");async function EL(){if(ao)return ao;uo(Tr)&&await gu();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ao=Tr.jetstream({domain:e,timeout:6e4}),ao}a(EL,"getJetStream");async function is(){let e=Tr||await gu(),t=oo||await Ru(),r=ao||await EL();return{connection:e,jsm:t,js:r}}a(is,"getNATSReferences");async function b3(e){let t=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await lL.getClusterUser(),s=await HS(t,r,n),i=BS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=_L.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 Md.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(b3,"getServerList");async function xS(e,t){let{jsm:r}=await is(),n=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:_3.File,retention:d3.Limits,subjects:t,discard:f3.Old,max_msgs:s,max_bytes:i,max_age:n})}a(xS,"createLocalStream");async function hL(){let{jsm:e}=await is(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(hL,"listStreams");async function y3(e){let{jsm:t}=await is();await t.streams.delete(e)}a(y3,"deleteLocalStream");async function N3(e){let{connection:t}=await is(),r=[],n=BS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(_L.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(N3,"listRemoteStreams");async function I3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=oL(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=vS.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=PS(l.data),E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(E.origin=l.headers.get(Kt.MSG_HEADERS.ORIGIN)),_.push(E),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(I3,"viewStream");async function*w3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=oL(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=vS.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=PS(_.data);l[0]||(l=[l]);for(let d of l){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(Kt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(w3,"viewStreamIterator");async function C3(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=mL(n,r);let{js:s}=await is(),i=await Ud(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:uL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),S3(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 SL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await xS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(C3,"publishToStream");function mL(e,t){t===void 0&&(t=h3());let r=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Kt.MSG_HEADERS.ORIGIN)&&r&&t.append(Kt.MSG_HEADERS.ORIGIN,r),t}a(mL,"addNatsMsgHeader");function da(e){e=e.toLowerCase();let t=Tu.join(Ht.get(Ie.CONFIG_PARAMS.ROOTPATH),T3);if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return uo(LS)&&(LS={port:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.HUB,config_file:Kt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Tu.join(t,Kt.PID_FILES.HUB),hdb_nats_path:t}),LS;if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return uo(DS)&&(DS={port:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,config_file:Kt.NATS_CONFIG_FILES.LEAF_SERVER,domain:pu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,pid_file_path:Tu.join(t,Kt.PID_FILES.LEAF),hdb_nats_path:t}),DS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(da,"getServerConfig");async function pL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:US.Explicit,durable_name:r,deliver_policy:vS.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(pL,"createConsumer");async function D3(e,t,r){await e.consumers.delete(t,r)}a(D3,"removeConsumer");function L3(e){return e.split(".")[1]}a(L3,"extractServerName");async function M3(e,t,r=6e4,n=BS()){if(!Md.isObject(t))throw new Error("data param must be an object");let s=uL.encode(t),{connection:i}=await is(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return PS(c.data)}a(M3,"request");function GS(e){return new Promise(async(t,r)=>{let n=s3(MS,["--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(GS,"reloadNATS");async function P3(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await GS(e)}a(P3,"reloadNATSHub");async function U3(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await GS(e)}a(U3,"reloadNATSLeaf");function v3(e,t,r){let n;switch(e.code){case iL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case iL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(v3,"requestErrorHandler");async function B3(e,t){let r=t+Kt.SERVER_SUFFIX.LEAF,{connection:n}=await is(),{jsm:s}=await $3(r),{schema:i,table:o}=e,c=Pd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await SL(async()=>{if(e.subscribe===!0)await pL(s,c,n.info.server_name,u);else try{await D3(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(B3,"updateRemoteConsumer");async function H3(e,t,r,n){let s=Pd.createNatsTableStreamName(e,t),i=r+Kt.SERVER_SUFFIX.LEAF,o={type:Ie.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!cL&&c3()<Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=CS();await c(o)}await o3(o),n==="stop"&&await Md.async_set_timeout(1e3)}a(H3,"updateConsumerIterator");function SL(e){return i3.writeTransaction(Ie.SYSTEM_SCHEMA_NAME,Ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(SL,"exclusiveLock");async function TL(e,t){let r=Pd.createNatsTableStreamName(e,t),n=await Ud(),s=F3(e,t,n);await xS(r,[s])}a(TL,"createLocalTableStream");async function x3(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await TL(n,s)}}a(x3,"createTableStreams");async function gL(e,t,r=void 0){if(Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Pd.createNatsTableStreamName(e,t),{domain:s}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await gu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(gL,"purgeTableStream");async function G3(e,t){if(Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await gL(e,t[r])}a(G3,"purgeSchemaTableStreams");async function q3(e){return(await Ru()).streams.info(e)}a(q3,"getStreamInfo");function F3(e,t,r){return`${Kt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(F3,"createSubjectName");async function Ud(){if(Su)return Su;if(Su=(await Ru())?.nc?.info?.server_name,Su===void 0)throw new Error("Unable to get jetstream manager server name");return Su}a(Ud,"getJsmServerName");async function k3(){let e=await Ru(),t=await Ud(),r=await hL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=V3(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(k3,"updateLocalStreams");function V3(e){let{config:t}=e,r=!1,n=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Ht.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(V3,"updateStreamLimits");async function $3(e){let t,r;try{t=await Tr.jetstream({domain:e}),r=await Tr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a($3,"connectToRemoteJS")});var Au=g((zfe,yL)=>{"use strict";var fa=D_(),Ea=CD(),Y3=$(),K3=require("uuid").v4,Qfe=require("clone"),Bd=ys(),ha=P(),W3=require("util"),fi=Cn(),{handleHDBError:gr,hdb_errors:Q3}=ne(),{HDB_ERROR_MSGS:vd,HTTP_STATUS_CODES:Rr}=Q3,{SchemaEventMsg:Hd}=Mn(),AL=ut(),{getDatabases:z3}=(Ae(),ie(ke)),{transformReq:ma}=z();yL.exports={createSchema:J3,createSchemaStructure:OL,createTable:j3,createTableStructure:bL,createAttribute:rX,dropSchema:X3,dropTable:Z3,dropAttribute:eX,getBackup:nX};async function J3(e){let t=await OL(e);return Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),t}a(J3,"createSchema");async function OL(e){let t=fa.schema_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(ma(e),!await Ea.checkSchemaExists(e.schema))throw gr(new Error,vd.SCHEMA_EXISTS_ERR(e.schema),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,vd.SCHEMA_EXISTS_ERR(e.schema),!0);return await fi.createSchema(e),`database '${e.schema}' successfully created`}a(OL,"createSchemaStructure");async function j3(e){return ma(e),e.hash_attribute=e.primary_key??e.hash_attribute,await bL(e)}a(j3,"createTable");async function bL(e){let t=fa.create_table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(fa.validateTableResidence(e.residence),!await Ea.checkSchemaTableExists(e.schema,e.table))throw gr(new Error,vd.TABLE_EXISTS_ERR(e.schema,e.table),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,vd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:K3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await fi.createTable(n,e);else throw gr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Rr.BAD_REQUEST);else await fi.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(bL,"createTableStructure");async function X3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=fa.schema_object(e),n=t??r;if(n)throw gr(n,n.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let s=await Ea.checkSchemaExists(e.schema);if(s)throw gr(new Error,s,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,s,!0);let i=await Ea.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await fi.dropSchema(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),await AL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(X3,"dropSchema");async function Z3(e){let t=fa.table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);return await fi.dropTable(e),await AL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Z3,"dropTable");async function eX(e){let t=fa.attribute_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw gr(new Error,"You cannot drop a hash attribute",Rr.BAD_REQUEST,void 0,void 0,!0);if(ha.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw gr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Rr.BAD_REQUEST,void 0,void 0,!0);try{return await fi.dropAttribute(e),tX(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Y3.error(`Got an error deleting attribute ${W3.inspect(e)}.`),n}}a(eX,"dropAttribute");function tX(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(tX,"dropAttributeFromGlobal");async function rX(e){ma(e);let t=z3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw gr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Rr.BAD_REQUEST,void 0,void 0,!0);return await fi.createAttribute(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(rX,"createAttribute");function nX(e){return fi.getBackup(e)}a(nX,"getBackup")});var IL=g((jfe,NL)=>{"use strict";var{OPERATIONS_ENUM:sX}=P(),qS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=sX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};NL.exports=qS});var FS=g((eEe,ML)=>{"use strict";var iX=Cn(),Zfe=IL(),xd=z(),Gd=P(),oX=Z(),{handleHDBError:wL,hdb_errors:aX}=ne(),{HDB_ERROR_MSGS:CL,HTTP_STATUS_CODES:DL}=aX,cX=Object.values(Gd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),LL="To use this operation audit log must be enabled in harperdb-config.yaml";ML.exports=uX;async function uX(e){if(xd.isEmpty(e.schema))throw new Error(CL.SCHEMA_REQUIRED_ERR);if(xd.isEmpty(e.table))throw new Error(CL.TABLE_REQUIRED_ERR);if(!oX.get(Gd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw wL(new Error,LL,DL.BAD_REQUEST,Gd.LOG_LEVELS.ERROR,LL,!0);let t=xd.checkSchemaTableExist(e.schema,e.table);if(t)throw wL(new Error,t,DL.NOT_FOUND,Gd.LOG_LEVELS.ERROR,t,!0);if(!xd.isEmpty(e.search_type)&&cX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await iX.readAuditLog(e)}a(uX,"readAuditLog")});var UL=g((rEe,PL)=>{"use strict";var{OPERATIONS_ENUM:lX}=P(),kS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=lX.GET_BACKUP,this.schema=t,this.table=r}};PL.exports=kS});var HL=g((oEe,BL)=>{"use strict";var _X=Cn(),sEe=UL(),VS=z(),dX=P(),iEe=Z(),{handleHDBError:fX,hdb_errors:EX}=ne(),{HDB_ERROR_MSGS:vL,HTTP_STATUS_CODES:hX}=EX;BL.exports=mX;async function mX(e){if(VS.isEmpty(e.schema))throw new Error(vL.SCHEMA_REQUIRED_ERR);if(VS.isEmpty(e.table))throw new Error(vL.TABLE_REQUIRED_ERR);let t=VS.checkSchemaTableExist(e.schema,e.table);if(t)throw fX(new Error,t,hX.NOT_FOUND,dX.LOG_LEVELS.ERROR,t,!0);return await _X.getBackup(read_audit_log_object)}a(mX,"getBackup")});var VL=g((cEe,kL)=>{var Ei=require("validate.js"),GL=Xe(),pa=P(),{handleHDBError:pX,hdb_errors:SX}=ne(),{HDB_ERROR_MSGS:mt,HTTP_STATUS_CODES:TX}=SX,$S=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),gX={STRUCTURE_USER:"structure_user"},xL=Object.values(pa.ROLE_TYPES_ENUM),RX="attribute_permissions",AX="attribute_name",{PERMS_CRUD_ENUM:Sa}=pa,OX=[RX,...Object.values(Sa)],qL=[Sa.READ,Sa.INSERT,Sa.UPDATE],bX=[AX,...qL];function yX(e){let t=$S();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,FL(e,t)}a(yX,"addRoleValidation");function NX(e){let t=$S();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,FL(e,t)}a(NX,"alterRoleValidation");function IX(e){let t=$S();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,GL.validateObject(e,t)}a(IX,"dropRoleValidation");var wX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function FL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)wX.includes(n[o])||s.push(n[o]);s.length>0&&At(mt.INVALID_ROLE_JSON_KEYS(s),r);let i=GL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{At(o,r)}),e.permission){let o=CX(e);o&&At(o,r),xL.forEach(c=>{e.permission[c]&&!Ei.isBoolean(e.permission[c])&&At(mt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(xL.indexOf(o)<0){if(o===gX.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||At(mt.SCHEMA_NOT_FOUND(d),r)}continue}At(mt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){At(mt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){At(mt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{OX.includes(l)||At(mt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(Sa).forEach(l=>{Ei.isDefined(_[l])?Ei.isBoolean(_[l])||At(mt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):At(mt.TABLE_PERM_MISSING(l),r,o,u)}),Ei.isDefined(_.attribute_permissions)){if(!Ei.isArray(_.attribute_permissions)){At(mt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{At(mt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in _.attribute_permissions){let f=_.attribute_permissions[E];if(Object.keys(f).forEach(p=>{!bX.includes(p)&&p!==Sa.DELETE&&At(mt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!Ei.isDefined(f.attribute_name)){At(mt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!l.includes(h)){At(mt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}qL.forEach(p=>{Ei.isDefined(f[p])?Ei.isBoolean(f[p])||At(mt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):At(mt.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let E=`${o}.${u}`;At(mt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return DX(r)}a(FL,"customValidate");kL.exports={addRoleValidation:yX,alterRoleValidation:NX,dropRoleValidation:IX};function CX(e){let{operation:t,permission:r}=e;if(t===pa.OPERATIONS_ENUM.ADD_ROLE||t===pa.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return mt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?pa.ROLE_TYPES_ENUM.SUPER_USER:pa.ROLE_TYPES_ENUM.CLUSTER_USER;return mt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(CX,"validateNoSUPerms");function DX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:mt.ROLE_PERMS_ERROR,...e};return pX(new Error,n,TX.BAD_REQUEST)}else return null}a(DX,"generateRolePermResponse");function At(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(At,"addPermError")});var JS=g((lEe,WL)=>{"use strict";var $L=qr(),YL=Gr(),LX=ai(),KS=VL(),WS=ys(),MX=require("uuid").v4,PX=require("util"),qd=P(),UX=z(),QS=YL.searchByValue,vX=YL.searchByHash,BX=PX.promisify(LX.delete),HX=ts(),xX=ia(),{hdb_errors:GX,handleHDBError:lo}=ne(),{HDB_ERROR_MSGS:KL,HTTP_STATUS_CODES:Ou}=GX,{UserEventMsg:zS}=Mn();WL.exports={addRole:qX,alterRole:FX,dropRole:kX,listRoles:VX};function YS(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(YS,"scrubRoleDetails");async function qX(e){let t=KS.addRoleValidation(e);if(t)throw t;e=YS(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 QS(r)||[])}catch(i){throw lo(i)}if(n&&n.length>0)throw lo(new Error,KL.ROLE_ALREADY_EXISTS(e.role),Ou.CONFLICT,void 0,void 0,!0);e.id||(e.id=MX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await $L.insert(s),WS.signalUserChange(new zS(process.pid)),e=YS(e),e}a(qX,"addRole");async function FX(e){let t=KS.alterRoleValidation(e);if(t)throw t;e=YS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await $L.update(r)}catch(s){throw lo(s)}if(n&&n?.message==="updated 0 of 1 records")throw lo(new Error,"Invalid role id",Ou.BAD_REQUEST,void 0,void 0,!0);return await WS.signalUserChange(new zS(process.pid)),e}a(FX,"alterRole");async function kX(e){let t=KS.dropRoleValidation(e);if(t)throw lo(new Error,t,Ou.BAD_REQUEST,void 0,void 0,!0);let r=new xX(qd.SYSTEM_SCHEMA_NAME,qd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await vX(r));if(n.length===0)throw lo(new Error,KL.ROLE_NOT_FOUND,Ou.NOT_FOUND,void 0,void 0,!0);let s=new HX(qd.SYSTEM_SCHEMA_NAME,qd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await QS(s)),o=!1;if(UX.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`,Ou.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await BX(c),WS.signalUserChange(new zS(process.pid)),`${n[0].role} successfully deleted`}a(kX,"dropRole");async function VX(){return QS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(VX,"listRoles")});var jL=g((dEe,JL)=>{"use strict";var $X=Z(),hi=require("joi"),YX=Xe(),QL=require("moment"),KX=require("fs-extra"),jS=require("path"),WX=require("lodash"),bu=P(),{LOG_LEVELS:_o}=P(),QX="YYYY-MM-DD hh:mm:ss",zX=jS.resolve(__dirname,"../logs");JL.exports=function(e){return YX.validateBySchema(e,JX)};var JX=hi.object({from:hi.custom(zL),until:hi.custom(zL),level:hi.valid(_o.NOTIFY,_o.FATAL,_o.ERROR,_o.WARN,_o.INFO,_o.DEBUG,_o.TRACE),order:hi.valid("asc","desc"),limit:hi.number().min(1),start:hi.number().min(0),log_name:hi.custom(jX)});function zL(e,t){if(QL(e,QL.ISO_8601).format(QX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(zL,"validateDatetime");function jX(e,t){if(WX.invert(bu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=$X.get(bu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?bu.LOG_NAMES.HDB:e,i=s===bu.LOG_NAMES.INSTALL?jS.join(zX,bu.LOG_NAMES.INSTALL):jS.join(n,s);return KX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(jX,"validateReadLogPath")});var ZS=g((EEe,ZL)=>{"use strict";var Fd=P(),XX=$(),ZX=Z(),eZ=jL(),XS=require("path"),XL=require("fs-extra"),{once:tZ}=require("events"),{handleHDBError:rZ,hdb_errors:nZ}=ne(),{PACKAGE_ROOT:sZ}=P(),iZ=XS.join(sZ,"logs"),oZ=1e3,aZ=200;ZL.exports=cZ;async function cZ(e){let t=eZ(e);if(t)throw rZ(t,t.message,nZ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=ZX.get(Fd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Fd.LOG_NAMES.HDB:e.log_name,s=n===Fd.LOG_NAMES.INSTALL?XS.join(iZ,Fd.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?oZ:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,p=0;E==="desc"&&!u&&!l&&(p=Math.max(XL.statSync(s).size-(h+5)*aZ,0));let S=XL.createReadStream(s,{start:p});S.on("error",v=>{XX.error(v)});let T=0,R=[],b="",C;S.on("data",v=>{let F=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=b+v;let M=0,Q;for(;(Q=F.exec(v))&&!S.destroyed;){C&&(C.message=v.slice(M,Q.index),H(C));let[J,j,ae]=Q,ce=ae.split("] ["),ge=ce[0],Ge=ce[1];ce.splice(0,2),C={timestamp:j,thread:ge,level:Ge,tags:ce,message:""},M=Q.index+J.length}b=v.slice(M)}),S.on("end",v=>{S.destroyed||C&&(C.message=b.trim(),H(C))}),S.resume();function H(v){let F,M,Q;switch(!0){case(i&&c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),v.level===o&&F>=M&&F<=Q&&T<f?T++:v.level===o&&F>=M&&F<=Q&&(mi(v,E,R),T++,T===h&&S.destroy());break;case(i&&c):F=new Date(v.timestamp),M=new Date(u),v.level===o&&F>=M&&T<f?T++:v.level===o&&F>=M&&(mi(v,E,R),T++,T===h&&S.destroy());break;case(i&&_):F=new Date(v.timestamp),Q=new Date(l),v.level===o&&F<=Q&&T<f?T++:v.level===o&&F<=Q&&(mi(v,E,R),T++,T===h&&S.destroy());break;case(c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),F>=M&&F<=Q&&T<f?T++:F>=M&&F<=Q&&(mi(v,E,R),T++,T===h&&S.destroy());break;case i:v.level===o&&T<f?T++:v.level===o&&(mi(v,E,R),T++,T===h&&S.destroy());break;case c:F=new Date(v.timestamp),M=new Date(u),F>=M&&T<f?T++:F>=M&&T>=f&&(mi(v,E,R),T++,T===h&&S.destroy());break;case _:F=new Date(v.timestamp),Q=new Date(l),F<=Q&&T<f?T++:F<=Q&&T>=f&&(mi(v,E,R),T++,T===h&&S.destroy());break;default:T<f?T++:(mi(v,E,R),T++,T===h&&S.destroy())}}return a(H,"onLogMessage"),await tZ(S,"close"),R}a(cZ,"readLog");function mi(e,t,r){t==="desc"?uZ(e,r):t==="asc"?lZ(e,r):r.push(e)}a(mi,"pushLineToResult");function uZ(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(uZ,"insertDescending");function lZ(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(lZ,"insertAscending")});var kd=g((TEe,nM)=>{"use strict";var eT=require("joi"),{string:yu,boolean:eM,date:_Z}=eT.types(),dZ=Xe(),{validateSchemaExists:mEe,validateTableExists:pEe,validateSchemaName:SEe}=Jn(),fZ=P(),EZ=Ve(),tM=Z();tM.initSync();var hZ=yu.invalid(tM.get(fZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(EZ.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(),rM={operation:yu.valid("add_node","update_node","set_node_replication"),node_name:hZ,subscriptions:eT.array().items({table:yu.optional(),schema:yu.optional(),database:yu.optional(),subscribe:eM.required(),publish:eM.required().custom(pZ),start_time:_Z.iso()}).min(1).required()};function mZ(e){return dZ.validateBySchema(e,eT.object(rM))}a(mZ,"addUpdateNodeValidator");function pZ(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(pZ,"checkForFalsy");nM.exports={addUpdateNodeValidator:mZ,validation_schema:rM}});var iM=g((REe,sM)=>{var SZ=Xe(),TZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};sM.exports=function(e){return SZ.validateObject(e,TZ)}});var Vd=g((AEe,oM)=>{"use strict";var gZ=P().OPERATIONS_ENUM,tT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=gZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};oM.exports=tT});var cM=g((bEe,aM)=>{"use strict";var RZ={OPERATION:"operation",REFRESH:"refresh"},rT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},nT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};aM.exports={JWTTokens:rT,TOKEN_TYPE_ENUM:RZ,JWTRSAKeys:nT}});var wu=g((NEe,dM)=>{"use strict";var Iu=require("jsonwebtoken"),sT=require("fs-extra"),iT=z(),_n=P(),{handleHDBError:Ar,hdb_errors:AZ}=ne(),{HTTP_STATUS_CODES:Or,AUTHENTICATION_ERROR_MSGS:br}=AZ,Nu=$(),uM=Y_(),cT=ln(),OZ=qr().update,bZ=Vd(),yZ=ys(),{UserEventMsg:NZ}=Mn(),pi=Z();pi.initSync();var oT=require("path"),{JWTTokens:IZ,JWTRSAKeys:wZ,TOKEN_TYPE_ENUM:$d}=cM(),CZ=pi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?pi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",DZ=pi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?pi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Yd="RS256",aT;dM.exports={createTokens:LZ,validateOperationToken:PZ,refreshOperationToken:MZ,validateRefreshToken:_M};async function LZ(e){if(iT.isEmpty(e)||typeof e!="object")throw Ar(new Error,br.INVALID_AUTH_OBJECT,Or.BAD_REQUEST,void 0,void 0,!0);if(iT.isEmpty(e.username))throw Ar(new Error,br.USERNAME_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);if(iT.isEmpty(e.password))throw Ar(new Error,br.PASSWORD_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await cT.findAndValidateUser(e.username,e.password),!t)throw Ar(new Error,br.INVALID_CREDENTIALS,Or.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw Nu.error(E),Ar(new Error,br.INVALID_CREDENTIALS,Or.UNAUTHORIZED,void 0,void 0,!0)}let r=await Kd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await lM(i,r.private_key,r.passphrase),c=await Iu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:DZ,algorithm:Yd,subject:$d.REFRESH}),u=uM.hash(c),_=new bZ(_n.SYSTEM_SCHEMA_NAME,_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await OZ(_)}catch(E){Nu.error(E),d=E}if(d!==void 0||l.skipped_hashes.length>0)throw Ar(new Error,br.REFRESH_TOKEN_SAVE_FAILED,Or.INTERNAL_SERVER_ERROR);return yZ.signalUserChange(new NZ(process.pid)),new IZ(o,c)}a(LZ,"createTokens");async function lM(e,t,r){return await Iu.sign(e,{key:t,passphrase:r},{expiresIn:CZ,algorithm:Yd,subject:$d.OPERATION})}a(lM,"signOperationToken");async function Kd(){if(aT===void 0)try{let e=oT.join(pi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PASSPHRASE_NAME),t=oT.join(pi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=oT.join(pi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await sT.readFile(e)).toString(),s=(await sT.readFile(t)).toString(),i=(await sT.readFile(r)).toString();aT=new wZ(i,s,n)}catch(e){throw Nu.error(e),Ar(new Error,br.NO_ENCRYPTION_KEYS,Or.INTERNAL_SERVER_ERROR)}return aT}a(Kd,"getJWTRSAKeys");async function MZ(e){if(!e)throw Ar(new Error,br.INVALID_BODY,Or.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Ar(new Error,br.REFRESH_TOKEN_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);await _M(e.refresh_token);let t=await Kd(),r=await Iu.decode(e.refresh_token);return{operation_token:await lM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(MZ,"refreshOperationToken");async function PZ(e){try{let t=await Kd(),r=await Iu.verify(e,t.public_key,{algorithms:Yd,subject:$d.OPERATION});return await cT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Nu.warn(t),t.name&&t.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}}a(PZ,"validateOperationToken");async function _M(e){let t;try{let r=await Kd(),n=await Iu.verify(e,r.public_key,{algorithms:Yd,subject:$d.REFRESH});t=await cT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Nu.warn(r),r.name&&r.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}if(!uM.validate(t.refresh_token,e))throw Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED);return t}a(_M,"validateRefreshToken")});var uT=g((CEe,hM)=>{"use strict";var UZ=iM(),Ta=require("passport"),vZ=require("passport-local").Strategy,BZ=require("passport-http").BasicStrategy,HZ=require("util"),xZ=ln(),EM=HZ.callbackify(xZ.findAndValidateUser),wEe=Ur(),GZ=P(),fM=wu();Ta.use(new vZ(function(e,t,r){EM(e,t,r)}));Ta.use(new BZ(function(e,t,r){EM(e,t,r)}));Ta.serializeUser(function(e,t){t(null,e)});Ta.deserializeUser(function(e,t){t(null,e)});function qZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Ta.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===GZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?fM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):fM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Ta.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(qZ,"authorize");function FZ(e,t){let r=UZ(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(FZ,"checkPermissions");hM.exports={authorize:qZ,checkPermissions:FZ}});var Si=g((LEe,mM)=>{"use strict";var lT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},_T=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};mM.exports={Node:lT,NodeSubscription:_T}});var SM=g((PEe,pM)=>{"use strict";var kZ=P().OPERATIONS_ENUM,dT=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=kZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};pM.exports=dT});var Cu=g((vEe,TM)=>{"use strict";var fT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},ET=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)}};TM.exports={RemotePayloadObject:fT,RemotePayloadSubscription:ET}});var RM=g((HEe,gM)=>{"use strict";var hT=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}};gM.exports=hT});var bM=g((kEe,OM)=>{"use strict";var VZ=RM(),GEe=ft(),AM=Qe(),$Z=$(),{getSchemaPath:qEe,getTransactionAuditStorePath:FEe}=je(),{getDatabases:YZ}=(Ae(),ie(ke));OM.exports=KZ;async function KZ(e){let t=new VZ;try{let r=YZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await AM.environmentDataSize(schema_path,e.name),o=await AM.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){$Z.warn(`unable to stat table dbi due to ${r}`)}return t}a(KZ,"lmdbGetTableSize")});var NM=g(($Ee,yM)=>{"use strict";var mT=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}};yM.exports=mT});var ga=g((JEe,DM)=>{"use strict";var WZ=require("fs-extra"),QZ=require("path"),sr=require("systeminformation"),Ti=$(),IM=ut(),KEe=Ve(),Qd=P(),zZ=bM(),JZ=Os(),{getThreadInfo:wM}=We(),IT=Z();IT.initSync();var jZ=NM(),{openEnvironment:WEe}=Qe(),{getSchemaPath:QEe}=je(),{database:zEe,databases:pT}=(Ae(),ie(ke)),Wd;DM.exports={getHDBProcessInfo:RT,getNetworkInfo:OT,getDiskInfo:AT,getMemoryInfo:gT,getCPUInfo:TT,getTimeInfo:ST,getSystemInformation:bT,systemInformation:XZ,getTableSize:yT,getMetrics:NT};function ST(){return sr.time()}a(ST,"getTimeInfo");async function TT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await sr.cpu();l.cpu_speed=await sr.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...R}=await sr.currentLoad();return R.cpus=[],T.forEach(b=>{let{raw_load:C,raw_load_idle:H,raw_load_irq:v,raw_load_nice:F,raw_load_system:M,raw_load_user:Q,...J}=b;R.cpus.push(J)}),l.current_load=R,l}catch(e){return Ti.error(`error in getCPUInfo: ${e}`),{}}}a(TT,"getCPUInfo");async function gT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await sr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ti.error(`error in getMemoryInfo: ${e}`),{}}}a(gT,"getMemoryInfo");async function RT(){let e={core:[],clustering:[]};try{let t=await sr.processes(),r;try{r=Number.parseInt(await WZ.readFile(QZ.join(IT.get(Qd.CONFIG_PARAMS.ROOTPATH),Qd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Qd.NODE_ERROR_CODES.ENOENT)Ti.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 Ti.error(`error in getHDBProcessInfo: ${t}`),e}}a(RT,"getHDBProcessInfo");async function AT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await sr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await sr.fsStats();return e.read_write=_,e.size=await sr.fsSize(),e}catch(t){return Ti.error(`error in getDiskInfo: ${t}`),e}}a(AT,"getDiskInfo");async function OT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await sr.networkInterfaceDefault(),e.latency=await sr.inetChecksite("google.com"),(await sr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await sr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ti.error(`error in getNetworkInfo: ${t}`),e}}a(OT,"getNetworkInfo");async function bT(){if(Wd!==void 0)return Wd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await sr.osInfo();e=c;let u=await sr.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Wd=e,Wd}catch(t){return Ti.error(`error in getSystemInformation: ${t}`),e}}a(bT,"getSystemInformation");async function yT(){let e=[],t=await JZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await zZ(n));return e}a(yT,"getTableSize");async function NT(){let e={};for(let t in pT){let r=e[t]={},n=r.tables={};for(let s in pT[t])try{let i=pT[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(u=>{let[_,l,d]=u.trim().split(" ");return{pid:_,thread:l,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let u of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[u]=o[u];n[s]=c}catch(i){Ti.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(NT,"getMetrics");async function CM(){if(IT.get(Qd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await IM.getNATSReferences(),t=await IM.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(CM,"getNatsStreamInfo");async function XZ(e){let t=new jZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await bT(),t.time=ST(),t.cpu=await TT(),t.memory=await gT(),t.disk=await AT(),t.network=await OT(),t.harperdb_processes=await RT(),t.table_size=await yT(),t.metrics=await NT(),t.threads=await wM(),t.replication=await CM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await bT();break;case"time":t.time=ST();break;case"cpu":t.cpu=await TT();break;case"memory":t.memory=await gT();break;case"disk":t.disk=await AT();break;case"network":t.network=await OT();break;case"harperdb_processes":t.harperdb_processes=await RT();break;case"table_size":t.table_size=await yT();break;case"database_metrics":case"metrics":t.metrics=await NT();break;case"threads":t.threads=await wM();break;case"replication":t.replication=await CM();break;default:break}return t}a(XZ,"systemInformation")});var Jd=g((XEe,LM)=>{"use strict";LM.exports={version:ZZ,printVersion:e5};var zd=lu();function ZZ(){if(zd)return zd.version}a(ZZ,"version");function e5(){zd&&console.log(`HarperDB Version ${zd.version}`)}a(e5,"printVersion")});var dn=g((rhe,vM)=>{"use strict";var t5=qr(),wT=z(),r5=require("util"),fo=P(),MM=Z();MM.initSync();var n5=uT(),PM=Gr(),{Node:ehe,NodeSubscription:the}=Si(),s5=ia(),i5=SM(),{RemotePayloadObject:o5,RemotePayloadSubscription:a5}=Cu(),{handleHDBError:c5,hdb_errors:u5}=ne(),{HTTP_STATUS_CODES:l5,HDB_ERROR_MSGS:_5}=u5,d5=ts(),f5=ga(),E5=Jd(),{getDatabases:h5}=(Ae(),ie(ke)),m5=r5.promisify(n5.authorize),p5=PM.searchByHash,S5=PM.searchByValue;vM.exports={authHeaderToUser:T5,isEmpty:g5,getNodeRecord:R5,upsertNodeRecord:A5,buildNodePayloads:O5,checkClusteringEnabled:b5,getAllNodeRecords:y5,getSystemInfo:N5,reverseSubscription:UM};async function T5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await m5(t,null),e}a(T5,"authHeaderToUser");function g5(e){return e==null}a(g5,"isEmpty");async function R5(e){let t=new s5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return p5(t)}a(R5,"getNodeRecord");async function A5(e){let t=new i5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return t5.upsert(t)}a(A5,"upsertNodeRecord");function UM(e){if(wT.isEmpty(e.subscribe)||wT.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(UM,"reverseSubscription");function O5(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=wT.getTableHashAttribute(u,_),{subscribe:d,publish:E}=UM(c),f=h5()[u]?.[_],h=new a5(u,_,l,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new o5(r,t,s,n)}a(O5,"buildNodePayloads");function b5(){if(!MM.get(fo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw c5(new Error,_5.CLUSTERING_NOT_ENABLED,l5.BAD_REQUEST,void 0,void 0,!0)}a(b5,"checkClusteringEnabled");async function y5(){let e=new d5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await S5(e))}a(y5,"getAllNodeRecords");async function N5(){let e=await f5.getSystemInformation();return{hdb_version:E5.version(),node_version:e.node_version,platform:e.platform}}a(N5,"getSystemInfo")});var CT=g((she,VM)=>{"use strict";var jd=ut(),BM=z(),HM=Ve(),xM=P(),Xd=$(),GM=Au(),I5=dd(),{RemotePayloadObject:w5}=Cu(),{handleHDBError:qM,hdb_errors:C5}=ne(),{HTTP_STATUS_CODES:FM}=C5,{NodeSubscription:kM}=Si();VM.exports=D5;async function D5(e,t){let r;try{r=await jd.request(`${t}.${HM.REQUEST_SUFFIX}`,new w5(xM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Xd.trace("Response from remote describe all request:",r)}catch(o){Xd.error(`addNode received error from describe all request to remote node: ${o}`);let c=jd.requestErrorHandler(o,"add_node",t);throw qM(new Error,c,FM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===HM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw qM(new Error,o,FM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===xM.SYSTEM_SCHEMA_NAME){await jd.createLocalTableStream(u,c);let h=new kM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=BM.doesSchemaExist(u),l=n[u]!==void 0,d=c?BM.doesTableExist(u,c):!0,E=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!E){s.push(o);continue}if(!_&&l&&(Xd.trace(`addNode creating schema: ${u}`),await GM.createSchema({operation:"create_schema",schema:u})),!d&&E){Xd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new I5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await GM.createTable(h)}await jd.createLocalTableStream(u,c);let f=new kM(u,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(D5,"reviewSubscriptions")});var rf=g((ohe,KM)=>{"use strict";var{handleHDBError:Zd,hdb_errors:L5}=ne(),{HTTP_STATUS_CODES:ef}=L5,{addUpdateNodeValidator:M5}=kd(),tf=$(),YM=P(),$M=Ve(),P5=z(),Du=ut(),Lu=dn(),U5=Z(),v5=CT(),{Node:B5,NodeSubscription:H5}=Si(),{broadcast:x5}=We(),G5="Unable to create 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(YM.CONFIG_PARAMS.CLUSTERING_NODENAME);KM.exports=k5;async function k5(e,t=!1){tf.trace("addNode called with:",e),Lu.checkClusteringEnabled();let r=M5(e);if(r)throw Zd(r,r.message,ef.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Lu.getNodeRecord(n);if(!P5.isEmptyOrZeroLength(d))throw Zd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,ef.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await v5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=G5,o;let c=Lu.buildNodePayloads(s,F5,YM.OPERATIONS_ENUM.ADD_NODE,await Lu.getSystemInfo()),u=[];for(let d=0,E=s.length;d<E;d++){let f=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new H5(f.schema,f.table,f.publish,f.subscribe))}tf.trace("addNode sending remote payload:",c);let _;try{_=await Du.request(`${n}.${$M.REQUEST_SUFFIX}`,c)}catch(d){tf.error(`addNode received error from request: ${d}`);for(let f=0,h=s.length;f<h;f++){let p=s[f];p.publish=!1,p.subscribe=!1,await Du.updateRemoteConsumer(p,n)}let E=Du.requestErrorHandler(d,"add_node",n);throw Zd(new Error,E,ef.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===$M.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw Zd(new Error,d,ef.INTERNAL_SERVER_ERROR,"error",d)}tf.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await Du.updateRemoteConsumer(f,n),f.subscribe===!0&&await Du.updateConsumerIterator(f.schema,f.table,n,"start")}let l=new B5(n,u,_.system_info);return await Lu.upsertNodeRecord(l),x5({type:"nats_update"}),i.length>0?o.message=q5:o.message=`Successfully added '${n}' to manifest`,o}a(k5,"addNode")});var MT=g((uhe,zM)=>{"use strict";var{handleHDBError:DT,hdb_errors:V5}=ne(),{HTTP_STATUS_CODES:LT}=V5,{addUpdateNodeValidator:$5}=kd(),Mu=$(),QM=P(),WM=Ve(),che=z(),Pu=ut(),Uu=dn(),Y5=Z(),{cloneDeep:K5}=require("lodash"),W5=CT(),{Node:Q5,NodeSubscription:z5}=Si(),{broadcast:J5}=We(),j5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",X5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Z5=Y5.get(QM.CONFIG_PARAMS.CLUSTERING_NODENAME);zM.exports=e8;async function e8(e){Mu.trace("updateNode called with:",e),Uu.checkClusteringEnabled();let t=$5(e);if(t)throw DT(t,t.message,LT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Uu.getNodeRecord(r);s.length>0&&(n=K5(s));let{added:i,skipped:o}=await W5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=j5,c;let u=Uu.buildNodePayloads(i,Z5,QM.OPERATIONS_ENUM.UPDATE_NODE,await Uu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let E=i[l];Mu.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[l].start_time===void 0&&delete i[l].start_time}Mu.trace("updateNode sending remote payload:",u);let _;try{_=await Pu.request(`${r}.${WM.REQUEST_SUFFIX}`,u)}catch(l){Mu.error(`updateNode received error from request: ${l}`);let d=Pu.requestErrorHandler(l,"update_node",r);throw DT(new Error,d,LT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===WM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw DT(new Error,l,LT.INTERNAL_SERVER_ERROR,"error",l)}Mu.trace(_);for(let l=0,d=i.length;l<d;l++){let E=i[l];await Pu.updateRemoteConsumer(E,r),E.subscribe===!0?await Pu.updateConsumerIterator(E.schema,E.table,r,"start"):await Pu.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new Q5(r,[],_.system_info)]),await t8(n[0],i,_.system_info),o.length>0?c.message=X5:c.message=`Successfully updated '${r}'`,c}a(e8,"updateNode");async function t8(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 z5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Uu.upsertNodeRecord(n),J5({type:"nats_update"})}a(t8,"updateNodeTable")});var eP=g((_he,ZM)=>{"use strict";var XM=require("joi"),{string:JM}=XM.types(),r8=Xe(),jM=P(),n8=Z(),s8=Ve();ZM.exports=i8;function i8(e){let t=JM.invalid(n8.get(jM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(s8.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=XM.object({operation:JM.valid(jM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return r8.validateBySchema(e,r)}a(i8,"removeNodeValidator")});var sf=g((fhe,iP)=>{"use strict";var{handleHDBError:tP,hdb_errors:o8}=ne(),{HTTP_STATUS_CODES:rP}=o8,a8=eP(),vu=$(),nP=dn(),c8=z(),nf=P(),sP=Ve(),PT=ut(),u8=Z(),{RemotePayloadObject:l8}=Cu(),{NodeSubscription:_8}=Si(),d8=oa(),f8=ai(),{broadcast:E8}=We(),h8=u8.get(nf.CONFIG_PARAMS.CLUSTERING_NODENAME);iP.exports=m8;async function m8(e){vu.trace("removeNode called with:",e),nP.checkClusteringEnabled();let t=a8(e);if(t)throw tP(t,t.message,rP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await nP.getNodeRecord(r);if(c8.isEmptyOrZeroLength(n))throw tP(new Error,`Node '${r}' was not found.`,rP.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new l8(nf.OPERATIONS_ENUM.REMOVE_NODE,h8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await PT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await PT.updateRemoteConsumer(new _8(l.schema,l.table,!1,!1),r)}catch(d){vu.error(d)}}try{i=await PT.request(`${r}.${sP.REQUEST_SUFFIX}`,s),vu.trace("Remove node reply from remote node:",r,i)}catch(u){vu.error("removeNode received error from request:",u),o=!0}let c=new d8(nf.SYSTEM_SCHEMA_NAME,nf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await f8.deleteRecord(c),E8({type:"nats_update"}),i?.status===sP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(vu.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(m8,"removeNode")});var cP=g((hhe,aP)=>{"use strict";var oP=require("joi"),{string:p8,array:S8}=oP.types(),T8=Xe(),g8=kd();aP.exports=R8;function R8(e){let t=oP.object({operation:p8.valid("configure_cluster").required(),connections:S8.items(g8.validation_schema).required()});return T8.validateBySchema(e,t)}a(R8,"configureClusterValidator")});var UT=g((phe,fP)=>{"use strict";var A8=P(),of=$(),O8=z(),b8=sf(),y8=rf(),uP=dn(),N8=cP(),{handleHDBError:lP,hdb_errors:I8}=ne(),{HTTP_STATUS_CODES:_P}=I8,w8="Configure cluster complete.",C8="Failed to configure the cluster. Check the logs for more details.",D8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";fP.exports=L8;async function L8(e){of.trace("configure cluster called with:",e),uP.checkClusteringEnabled();let t=N8(e);if(t)throw lP(t,t.message,_P.BAD_REQUEST,void 0,void 0,!0);let r=await uP.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let E=await dP(b8,{operation:A8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(E)}of.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],E=await dP(y8,d,d.node_name);s.push(E)}of.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let E=_[l];E.status==="rejected"&&(of.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(u=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(O8.isEmptyOrZeroLength(o))return{message:w8,connections:c};if(u)return{message:D8,failed_nodes:o,connections:c};throw lP(new Error,C8,_P.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(L8,"configureCluster");async function dP(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(dP,"functionWrapper")});var pP=g((The,mP)=>{"use strict";var Bu=require("joi"),M8=Xe(),{validateSchemaExists:EP,validateTableExists:P8,validateSchemaName:hP}=Jn(),U8=Bu.object({operation:Bu.string().valid("purge_stream"),schema:Bu.string().custom(EP).custom(hP).optional(),database:Bu.string().custom(EP).custom(hP).optional(),table:Bu.string().custom(P8).required()});function v8(e){return M8.validateBySchema(e,U8)}a(v8,"purgeStreamValidator");mP.exports=v8});var vT=g((Rhe,SP)=>{"use strict";var{handleHDBError:B8,hdb_errors:H8}=ne(),{HTTP_STATUS_CODES:x8}=H8,G8=pP(),q8=ut(),F8=dn();SP.exports=k8;async function k8(e){e.schema=e.schema??e.database;let t=G8(e);if(t)throw B8(t,t.message,x8.BAD_REQUEST,void 0,void 0,!0);F8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await q8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(k8,"purgeStream")});var xT=g((Ohe,bP)=>{"use strict";var HT=dn(),V8=ut(),RP=Z(),af=P(),Eo=Ve(),$8=z(),BT=$(),{RemotePayloadObject:Y8}=Cu(),{ErrorCode:TP}=require("nats"),gP=RP.get(af.CONFIG_PARAMS.CLUSTERING_ENABLED),AP=RP.get(af.CONFIG_PARAMS.CLUSTERING_NODENAME);bP.exports={clusterStatus:K8,buildNodeStatus:OP};async function K8(){let e={node_name:AP,is_enabled:gP,connections:[]};if(!gP)return e;let t=await HT.getAllNodeRecords();if($8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(OP(t[n],e.connections));return await Promise.allSettled(r),e}a(K8,"clusterStatus");async function OP(e,t){let r=e.name,n=new Y8(af.OPERATIONS_ENUM.CLUSTER_STATUS,AP,void 0,await HT.getSystemInfo()),s,i,o=Eo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await V8.request(Eo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===Eo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Eo.CLUSTER_STATUS_STATUSES.CLOSED,BT.error(`Error getting node status from ${r} `,s))}catch(u){BT.warn(`Error getting node status from ${r}`,u),u.code===TP.NoResponders?o=Eo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===TP.Timeout?o=Eo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Eo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new W8(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!==af.PRE_4_0_0_VERSION&&await HT.upsertNodeRecord(u)}catch(u){BT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(OP,"buildNodeStatus");function W8(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(W8,"NodeStatusObject")});var qT=g((yhe,yP)=>{"use strict";var{handleHDBError:Q8,hdb_errors:z8}=ne(),{HTTP_STATUS_CODES:J8}=z8,j8=ut(),X8=dn(),GT=z(),cf=require("joi"),Z8=Xe(),e6=2e3,t6=cf.object({timeout:cf.number().min(1),connected_nodes:cf.boolean(),routes:cf.boolean()});yP.exports=r6;async function r6(e){X8.checkClusteringEnabled();let t=Z8.validateBySchema(e,t6);if(t)throw Q8(t,t.message,J8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||GT.autoCastBoolean(n),o=s===void 0||GT.autoCastBoolean(s),c={nodes:[]},u=await j8.getServerList(r??e6),_={};if(i)for(let l=0,d=u.length;l<d;l++){let E=u[l].statsz;E&&(_[u[l].server.name]=E.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let E=u[l].server,f=u[l].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[E.name]&&_[E.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(p=>({host:p.split(":")[0],port:GT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(r6,"clusterNetwork")});var CP=g((Ihe,wP)=>{"use strict";var FT=require("joi"),NP=Xe(),{route_constraints:IP}=np();wP.exports={setRoutesValidator:n6,deleteRoutesValidator:s6};function n6(e){let t=FT.object({server:FT.valid("hub","leaf").required(),routes:IP.required()});return NP.validateBySchema(e,t)}a(n6,"setRoutesValidator");function s6(e){let t=FT.object({routes:IP.required()});return NP.validateBySchema(e,t)}a(s6,"deleteRoutesValidator")});var VT=g((Che,PP)=>{"use strict";var ho=Er(),kT=z(),uf=P(),DP=CP(),{handleHDBError:LP,hdb_errors:i6}=ne(),{HTTP_STATUS_CODES:MP}=i6,o6="cluster routes successfully set",a6="cluster routes successfully deleted";PP.exports={setRoutes:c6,getRoutes:u6,deleteRoutes:l6};function c6(e){let t=DP.setRoutesValidator(e);if(t)throw LP(t,t.message,MP.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=kT.autoCast(_.port);let l=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:o6,set:o,skipped:i}}a(c6,"setRoutes");function u6(){let e=ho.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(u6,"getRoutes");function l6(e){let t=DP.deleteRoutesValidator(e);if(t)throw LP(t,t.message,MP.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[_],E=!1;for(let f=0,h=n.length;f<h;f++){let p=n[f];if(d.host===p.host&&d.port===p.port){n.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=kT.isEmptyOrZeroLength(n)?null:n,ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=kT.isEmptyOrZeroLength(s)?null:s,ho.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:a6,deleted:i,skipped:o}}a(l6,"deleteRoutes")});var vP=g((Lhe,UP)=>{"use strict";var Hu=require("alasql"),mo=require("recursive-iterator"),Hn=$(),_6=z(),xu=P(),$T=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,f6(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=>xu.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=>!xu.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][xu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=d6(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(_=>!xu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Hu.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 d6(e){return e.filter(t=>t[xu.PERMS_CRUD_ENUM.READ])}a(d6,"filterReadRestrictedAttrs");function f6(e,t,r,n,s){E6(e,t,r,n,s)}a(f6,"interpretAST");function Gu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Gu,"addSchemaTableToMap");function E6(e,t,r,n,s){if(!e){Hn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Hu.yy.Insert?S6(e,t,r):e instanceof Hu.yy.Select?h6(e,t,r,n,s):e instanceof Hu.yy.Update?m6(e,t,r):e instanceof Hu.yy.Delete?p6(e,t,r):Hn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(E6,"getRecordAttributesAST");function h6(e,t,r,n,s){if(!e){Hn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(_6.isEmptyOrZeroLength(i)){Hn.error("No schema specified");return}e.from.forEach(c=>{Gu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Gu(c.table,t,r,n,s)});let o=new 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{Hn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new 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{Hn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new 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{Hn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new 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{Hn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(h6,"getSelectAttributes");function m6(e,t,r){if(!e){Hn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new mo(e.columns),s=e.table.databaseid;Gu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(m6,"getUpdateAttributes");function p6(e,t,r){if(!e){Hn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new mo(e.where),s=e.table.databaseid;Gu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(p6,"getDeleteAttributes");function S6(e,t,r){if(!e){Hn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new mo(e.columns),s=e.into.databaseid;Gu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.into.tableid,s,i.columnid,t,r)}a(S6,"getInsertAttributes");function YT(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(YT,"pushAttribute");UP.exports=$T});var QT=g((Phe,GP)=>{var lf=ji(),BP=require("chalk"),Qr=$(),HP=require("prompt"),{promisify:T6}=require("util"),KT=P(),g6=require("fs-extra"),R6=require("path"),A6=z(),O6=Jd(),xP=Z();xP.initSync();var b6=require("moment"),y6=T6(HP.get),N6=R6.join(xP.getHdbBasePath(),KT.LICENSE_KEY_DIR_NAME,KT.LICENSE_FILE_NAME,KT.LICENSE_FILE_NAME);GP.exports={getFingerprint:w6,setLicense:I6,parseLicense:WT,register:C6,getRegistrationInfo:L6};async function I6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await WT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(I6,"setLicense");async function w6(){let e={};try{e=await lf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(w6,"getFingerprint");async function WT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=lf.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await g6.writeFile(N6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(WT,"parseLicense");async function C6(){let e=await D6();return WT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(C6,"register");async function D6(){let e=await lf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:BP.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:BP.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{HP.start()}catch(n){Qr.error(n)}let r;try{r=await y6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(D6,"promptForRegistration");async function L6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await lf.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(A6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=O6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=b6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(L6,"getRegistrationInfo")});var FP=g((vhe,qP)=>{"use strict";var M6=Ve(),zT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+M6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};qP.exports=zT});var $P=g((Hhe,VP)=>{"use strict";var kP=Ve(),JT=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+kP.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+kP.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"}};VP.exports=JT});var KP=g((Ghe,YP)=>{"use strict";var jT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};YP.exports=jT});var QP=g((Fhe,WP)=>{"use strict";var P6=Ve(),XT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+P6.SERVER_SUFFIX.ADMIN,this.password=r}};WP.exports=XT});var tg=g((Vhe,jP)=>{"use strict";var Ra=require("path"),ff=require("fs-extra"),U6=FP(),v6=$P(),B6=KP(),H6=QP(),ZT=ln(),Oa=z(),yr=Er(),df=P(),qu=Ve(),{CONFIG_PARAMS:pt}=df,ba=$(),Fu=Z(),zP=As(),eg=ut(),Aa="clustering",x6=1e4,JP=50;jP.exports={generateNatsConfig:q6,removeNatsConfig:F6,getHubConfigPath:G6};function G6(){let e=Fu.get(pt.ROOTPATH);return Ra.join(e,Aa,qu.NATS_CONFIG_FILES.HUB_SERVER)}a(G6,"getHubConfigPath");async function q6(e=!1,t=void 0){Fu.initSync();let r=Fu.get(pt.ROOTPATH),n=Ra.join(r,Aa,qu.PID_FILES.HUB),s=Ra.join(r,Aa,qu.PID_FILES.LEAF),i=yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ra.join(r,Aa,qu.NATS_CONFIG_FILES.HUB_SERVER),c=Ra.join(r,Aa,qu.NATS_CONFIG_FILES.LEAF_SERVER),u=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERTIFICATE),_=yr.getConfigFromFile(pt.CLUSTERING_TLS_PRIVATEKEY),l=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERT_AUTH),d=yr.getConfigFromFile(pt.CLUSTERING_TLS_INSECURE),E=yr.getConfigFromFile(pt.CLUSTERING_TLS_VERIFY),f=yr.getConfigFromFile(pt.CLUSTERING_NODENAME),h=yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await eg.checkNATSServerInstalled()||Ef("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await ZT.listUsers(),S=yr.getConfigFromFile(pt.CLUSTERING_USER),T=await ZT.getClusterUser();(Oa.isEmpty(T)||T.active!==!0)&&Ef(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await _f(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await _f(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await _f(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),await _f(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],b=[];for(let[J,j]of p.entries())j.role.role===df.ROLE_TYPES_ENUM.CLUSTER_USER&&j.active&&(R.push(new H6(j.username,zP.decrypt(j.hash))),b.push(new B6(j.username,zP.decrypt(j.hash))));let C=[],{hub_routes:H}=yr.getClusteringRoutes();if(!Oa.isEmptyOrZeroLength(H))for(let J of H)C.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${J.host}:${J.port}`);let v=new U6(yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,u,_,l,d,E,h,yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NAME),yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),C,R,b);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=Oa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===df.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await ff.writeJson(o,v),ba.trace(`Hub server config written to ${o}`));let F=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,M=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,Q=new v6(yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[F],[M],R,b,u,_,l,d);l==null&&delete Q.tls.ca_file,(t===void 0||t===df.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await ff.writeJson(c,Q),ba.trace(`Leaf server config written to ${c}`))}a(q6,"generateNatsConfig");async function _f(e){let t=Fu.get(e);return Oa.isEmpty(t)&&Ef(`port undefined for '${e}'`),await Oa.isPortTaken(t)&&Ef(`'${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(_f,"isPortAvailable");function Ef(e){let t=`Error generating clustering config: ${e}`;ba.error(t),console.error(t),process.exit(1)}a(Ef,"generateNatsConfigError");async function F6(e){let{port:t,config_file:r}=eg.getServerConfig(e),{username:n,decrypt_hash:s}=await ZT.getClusterUser(),i=0,o=2e3;for(;i<JP;){try{let l=await eg.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){ba.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=JP)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&ba.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Oa.async_set_timeout(_)}let c="0".repeat(x6),u=Ra.join(Fu.get(pt.ROOTPATH),Aa,r);await ff.writeFile(u,c),await ff.remove(u),ba.notify(e,"started.")}a(F6,"removeNatsConfig")});var nU=g((Yhe,rU)=>{"use strict";var zr=Z(),k6=ji(),he=P(),ku=Ve(),Ds=require("path"),{PACKAGE_ROOT:mf}=P(),XP=Z(),hf=z(),ya="/dev/null",V6=Ds.join(mf,"launchServiceScripts"),ZP=Ds.join(mf,"utility/scripts"),$6=Ds.join(ZP,he.HDB_RESTART_SCRIPT),eU=Ds.resolve(mf,"dependencies",`${process.platform}-${process.arch}`,ku.NATS_BINARY_NAME);function tU(){let t=k6.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 hf.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=hf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:mf}}a(tU,"generateMainServerConfig");var Y6=9930;function K6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",ku.NATS_CONFIG_FILES.HUB_SERVER),r=Ds.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=XP.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==Y6?"-"+n:""),script:eU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a(K6,"generateNatsHubServerConfig");var W6=9940;function Q6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",ku.NATS_CONFIG_FILES.LEAF_SERVER),r=Ds.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=XP.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==W6?"-"+n:""),script:eU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a(Q6,"generateNatsLeafServerConfig");function z6(){zr.initSync();let e=Ds.join(zr.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:V6,autorestart:!1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ya,t.error_file=ya),t}a(z6,"generateClusteringUpgradeV4ServiceConfig");function J6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return hf.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=hf.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:ZP},script:$6}}a(J6,"generateRestart");function j6(){return{apps:[tU()]}}a(j6,"generateAllServiceConfigs");rU.exports={generateAllServiceConfigs:j6,generateMainServerConfig:tU,generateRestart:J6,generateNatsHubServerConfig:K6,generateNatsLeafServerConfig:Q6,generateClusteringUpgradeV4ServiceConfig:z6}});var pU=g((Qhe,mU)=>{"use strict";var Ue=P(),X6=z(),Ms=tg(),pf=ut(),Ls=Ve(),gi=nU(),Sf=Z(),Ri=$(),Z6=dn(),{startWorker:sU,onMessageFromWorkers:e9}=We(),t9=ga(),Whe=require("util"),r9=require("child_process"),n9=require("fs"),{execFile:s9}=r9,we;mU.exports={enterPM2Mode:i9,start:Ai,stop:rg,reload:oU,restart:aU,list:ng,describe:uU,connect:Ps,kill:l9,startAllServices:_9,startService:sg,getUniqueServicesList:lU,restartAllServices:d9,isServiceRegistered:_U,reloadStopStart:dU,restartHdb:cU,deleteProcess:c9,startClusteringProcesses:EU,startClusteringThreads:hU,isHdbRestartRunning:u9,isClusteringRunning:E9,stopClustering:f9,reloadClustering:h9};var Vu=!1;e9(e=>{e.type==="restart"&&Sf.initSync(!0)});function i9(){Vu=!0}a(i9,"enterPM2Mode");function Ps(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{Ri.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ps,"connect");var Nr,o9=10,iU;function Ai(e,t=!1){if(Vu)return a9(e);let r=s9(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Nr.indexOf(r);o>-1&&Nr.splice(o,1),!iU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<o9&&(n9.existsSync(Ms.getHubConfigPath())?Ai(e):(await Ms.generateNatsConfig(!0),Ai(e),await new Promise(c=>setTimeout(c,3e3)),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Sf.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let f=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?Ri.OUTPUTS.STDERR:Ri.OUTPUTS.STDOUT;Ri.logCustomLevel(l||"info",f,n,i.slice(_,u.index).trim())}let[d,E]=u;_=u.index+d.length,l=Ls.LOG_LEVELS[E]}if(Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?Ri.OUTPUTS.STDERR:Ri.OUTPUTS.STDOUT;Ri.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Nr=[],!Nr&&!t){let i=a(()=>{iU=!0,Nr&&(Nr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}Nr.push(r)}a(Ai,"start");function a9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(a9,"startWithPM2");function rg(e){if(!Vu){for(let t of Nr||[])t.name===e&&(Nr.splice(Nr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(rg,"stop");function oU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(oU,"reload");function aU(e){if(!Vu)for(let t of Nr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(aU,"restart");function c9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(c9,"deleteProcess");async function cU(){await Ai(gi.generateRestart())}a(cU,"restartHdb");async function u9(){let e=await ng();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(u9,"isHdbRestartRunning");function ng(){return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(ng,"list");function uU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(uU,"describe");function l9(){if(!Vu){for(let e of Nr||[])e.kill();Nr=[];return}return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(l9,"kill");async function _9(){try{await EU(),await hU(),await Ai(gi.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(_9,"startAllServices");async function sg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=gi.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=gi.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=gi.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=gi.generateNatsHubServerConfig(),await Ai(r,t),await Ms.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=gi.generateNatsLeafServerConfig(),await Ai(r,t),await Ms.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=gi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ai(r)}catch(r){throw we?.disconnect(),r}}a(sg,"startService");async function lU(){try{let e=await ng(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(lU,"getUniqueServicesList");async function d9(e=[]){try{let t=!1,r=await lU();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Ue.PROCESS_DESCRIPTORS.HDB?t=!0:await aU(o))}t&&await dU(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(d9,"restartAllServices");async function _U(e){if(Nr?.find(r=>r.name===e))return!0;let t=await t9.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(_U,"isServiceRegistered");async function dU(e){let t=Sf.get(Ue.CONFIG_PARAMS.THREADS_COUNT)??Sf.get(Ue.CONFIG_PARAMS.THREADS),r=await uU(e),n=X6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await rg(e),await sg(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await cU():await oU(e)}a(dU,"reloadStopStart");var fU;async function EU(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await sg(r,e)}}a(EU,"startClusteringProcesses");async function hU(){fU=sU(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await pf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await pf.updateLocalStreams();let e=await Z6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){Ri.info("Starting clustering upgrade 4.0.0 process"),sU(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(hU,"startClusteringThreads");async function f9(){for(let e in Ue.CLUSTERING_PROCESSES)if(e!==Ue.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ue.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await fU.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await rg(t)}}a(f9,"stopClustering");async function E9(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await _U(t)===!1)return!1}return!0}a(E9,"isClusteringRunning");async function h9(){await Ms.generateNatsConfig(!0),await pf.reloadNATSHub(),await pf.reloadNATSLeaf(),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(h9,"reloadClustering")});var bU={};Fe(bU,{compactOnStart:()=>m9,copyDb:()=>OU});async function m9(){Yu.notify("Running compact on start"),console.log("Running compact on start");let e=(0,ig.get)(Oi.CONFIG_PARAMS.ROOTPATH),t=new Map,r=mr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,Tf.join)(e,"backup",n+".mdb"),o=(0,Tf.join)(e,Oi.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await SU(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 OU(n,o),console.log("Backing up",n,"to",i),await(0,po.move)(s,i,{overwrite:!0})}$u();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,Tf.join)(e,Oi.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));$u()}catch(n){Yu.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,og.updateConfigValue)(Oi.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 $u(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await SU(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
|
|
10
|
+
`,"")}a(fL,"runCommand");async function bj(){try{await tj.access(PS)}catch{return!1}let e=await fL(`${PS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return rj.eq(t,Aj)}a(bj,"checkNATSServerInstalled");async function HS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await _L.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 dj({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:xt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:xt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:xt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),EL()}),i}a(HS,"createConnection");function EL(){Tr=void 0,oo=void 0,ao=void 0,co=void 0}a(EL,"clearClientCache");async function yj(){Tr&&(await Tr.drain(),Tr=void 0,oo=void 0,ao=void 0,co=void 0)}a(yj,"closeConnection");var Tr,co;async function Ru(){return co||(co=HS(xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Tr=await co),Tr||co}a(Ru,"getConnection");async function Au(){if(oo)return oo;uo(Tr)&&await Ru();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=await Tr.jetstreamManager({domain:e,timeout:6e4}),oo}a(Au,"getJetStreamManager");async function hL(){if(ao)return ao;uo(Tr)&&await Ru();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ao=Tr.jetstream({domain:e,timeout:6e4}),ao}a(hL,"getJetStream");async function is(){let e=Tr||await Ru(),t=oo||await Au(),r=ao||await hL();return{connection:e,jsm:t,js:r}}a(is,"getNATSReferences");async function Nj(e){let t=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await _L.getClusterUser(),s=await HS(t,r,n),i=xS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=dL.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 Pd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(Nj,"getServerList");async function GS(e,t){let{jsm:r}=await is(),n=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:fj.File,retention:Ej.Limits,subjects:t,discard:hj.Old,max_msgs:s,max_bytes:i,max_age:n})}a(GS,"createLocalStream");async function mL(){let{jsm:e}=await is(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(mL,"listStreams");async function Ij(e){let{jsm:t}=await is();await t.streams.delete(e)}a(Ij,"deleteLocalStream");async function wj(e){let{connection:t}=await is(),r=[],n=xS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(dL.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(wj,"listRemoteStreams");async function Cj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=aL(),o={durable_name:i,ack_policy:vS.Explicit};t&&(o.deliver_policy=BS.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=US(l.data),E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(E.origin=l.headers.get(Kt.MSG_HEADERS.ORIGIN)),_.push(E),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Cj,"viewStream");async function*Dj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=aL(),o={durable_name:i,ack_policy:vS.Explicit};t&&(o.deliver_policy=BS.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=US(_.data);l[0]||(l=[l]);for(let d of l){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(Kt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(Dj,"viewStreamIterator");async function Lj(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=pL(n,r);let{js:s}=await is(),i=await vd(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:lL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),gj(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 TL(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 GS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(Lj,"publishToStream");function pL(e,t){t===void 0&&(t=pj());let r=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Kt.MSG_HEADERS.ORIGIN)&&r&&t.append(Kt.MSG_HEADERS.ORIGIN,r),t}a(pL,"addNatsMsgHeader");function da(e){e=e.toLowerCase();let t=gu.join(xt.get(Ie.CONFIG_PARAMS.ROOTPATH),Rj);if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return uo(MS)&&(MS={port:Su.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.HUB,config_file:Kt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:gu.join(t,Kt.PID_FILES.HUB),hdb_nats_path:t}),MS;if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return uo(LS)&&(LS={port:Su.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,config_file:Kt.NATS_CONFIG_FILES.LEAF_SERVER,domain:Su.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,pid_file_path:gu.join(t,Kt.PID_FILES.LEAF),hdb_nats_path:t}),LS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(da,"getServerConfig");async function SL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:vS.Explicit,durable_name:r,deliver_policy:BS.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(SL,"createConsumer");async function Mj(e,t,r){await e.consumers.delete(t,r)}a(Mj,"removeConsumer");function Pj(e){return e.split(".")[1]}a(Pj,"extractServerName");async function Uj(e,t,r=6e4,n=xS()){if(!Pd.isObject(t))throw new Error("data param must be an object");let s=lL.encode(t),{connection:i}=await is(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return US(c.data)}a(Uj,"request");function qS(e){return new Promise(async(t,r)=>{let n=oj(PS,["--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(qS,"reloadNATS");async function vj(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await qS(e)}a(vj,"reloadNATSHub");async function Bj(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await qS(e)}a(Bj,"reloadNATSLeaf");function xj(e,t,r){let n;switch(e.code){case oL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case oL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(xj,"requestErrorHandler");async function Hj(e,t){let r=t+Kt.SERVER_SUFFIX.LEAF,{connection:n}=await is(),{jsm:s}=await Kj(r),{schema:i,table:o}=e,c=Ud.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await TL(async()=>{if(e.subscribe===!0)await SL(s,c,n.info.server_name,u);else try{await Mj(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(Hj,"updateRemoteConsumer");async function Gj(e,t,r,n){let s=Ud.createNatsTableStreamName(e,t),i=r+Kt.SERVER_SUFFIX.LEAF,o={type:Ie.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!uL&&lj()<xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=DS();await c(o)}await cj(o),n==="stop"&&await Pd.async_set_timeout(1e3)}a(Gj,"updateConsumerIterator");function TL(e){return aj.writeTransaction(Ie.SYSTEM_SCHEMA_NAME,Ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(TL,"exclusiveLock");async function gL(e,t){let r=Ud.createNatsTableStreamName(e,t),n=await vd(),s=Vj(e,t,n);await GS(r,[s])}a(gL,"createLocalTableStream");async function qj(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await gL(n,s)}}a(qj,"createTableStreams");async function RL(e,t,r=void 0){if(xt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Ud.createNatsTableStreamName(e,t),{domain:s}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Ru()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(RL,"purgeTableStream");async function Fj(e,t){if(xt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await RL(e,t[r])}a(Fj,"purgeSchemaTableStreams");async function kj(e){return(await Au()).streams.info(e)}a(kj,"getStreamInfo");function Vj(e,t,r){return`${Kt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Vj,"createSubjectName");async function vd(){if(Tu)return Tu;if(Tu=(await Au())?.nc?.info?.server_name,Tu===void 0)throw new Error("Unable to get jetstream manager server name");return Tu}a(vd,"getJsmServerName");async function $j(){let e=await Au(),t=await vd(),r=await mL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=Yj(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($j,"updateLocalStreams");function Yj(e){let{config:t}=e,r=!1,n=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(Yj,"updateStreamLimits");async function Kj(e){let t,r;try{t=await Tr.jetstream({domain:e}),r=await Tr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Kj,"connectToRemoteJS")});var Ou=g((jfe,NL)=>{"use strict";var fa=L_(),Ea=DD(),Wj=$(),Qj=require("uuid").v4,Jfe=require("clone"),xd=ys(),ha=P(),zj=require("util"),fi=Cn(),{handleHDBError:gr,hdb_errors:Jj}=se(),{HDB_ERROR_MSGS:Bd,HTTP_STATUS_CODES:Rr}=Jj,{SchemaEventMsg:Hd}=Mn(),OL=ut(),{getDatabases:jj}=(Ae(),ie(ke)),{transformReq:ma}=z();NL.exports={createSchema:Xj,createSchemaStructure:bL,createTable:Zj,createTableStructure:yL,createAttribute:sX,dropSchema:eX,dropTable:tX,dropAttribute:rX,getBackup:iX};async function Xj(e){let t=await bL(e);return xd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),t}a(Xj,"createSchema");async function bL(e){let t=fa.schema_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(ma(e),!await Ea.checkSchemaExists(e.schema))throw gr(new Error,Bd.SCHEMA_EXISTS_ERR(e.schema),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,Bd.SCHEMA_EXISTS_ERR(e.schema),!0);return await fi.createSchema(e),`database '${e.schema}' successfully created`}a(bL,"createSchemaStructure");async function Zj(e){return ma(e),e.hash_attribute=e.primary_key??e.hash_attribute,await yL(e)}a(Zj,"createTable");async function yL(e){let t=fa.create_table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(fa.validateTableResidence(e.residence),!await Ea.checkSchemaTableExists(e.schema,e.table))throw gr(new Error,Bd.TABLE_EXISTS_ERR(e.schema,e.table),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,Bd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:Qj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await fi.createTable(n,e);else throw gr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Rr.BAD_REQUEST);else await fi.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(yL,"createTableStructure");async function eX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=fa.schema_object(e),n=t??r;if(n)throw gr(n,n.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let s=await Ea.checkSchemaExists(e.schema);if(s)throw gr(new Error,s,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,s,!0);let i=await Ea.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await fi.dropSchema(e),xd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),await OL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(eX,"dropSchema");async function tX(e){let t=fa.table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);return await fi.dropTable(e),await OL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(tX,"dropTable");async function rX(e){let t=fa.attribute_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw gr(new Error,"You cannot drop a hash attribute",Rr.BAD_REQUEST,void 0,void 0,!0);if(ha.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw gr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Rr.BAD_REQUEST,void 0,void 0,!0);try{return await fi.dropAttribute(e),nX(e),xd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Wj.error(`Got an error deleting attribute ${zj.inspect(e)}.`),n}}a(rX,"dropAttribute");function nX(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(nX,"dropAttributeFromGlobal");async function sX(e){ma(e);let t=jj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw gr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Rr.BAD_REQUEST,void 0,void 0,!0);return await fi.createAttribute(e),xd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(sX,"createAttribute");function iX(e){return fi.getBackup(e)}a(iX,"getBackup")});var wL=g((Zfe,IL)=>{"use strict";var{OPERATIONS_ENUM:oX}=P(),FS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=oX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};IL.exports=FS});var kS=g((rEe,PL)=>{"use strict";var aX=Cn(),tEe=wL(),Gd=z(),qd=P(),cX=ee(),{handleHDBError:CL,hdb_errors:uX}=se(),{HDB_ERROR_MSGS:DL,HTTP_STATUS_CODES:LL}=uX,lX=Object.values(qd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),ML="To use this operation audit log must be enabled in harperdb-config.yaml";PL.exports=_X;async function _X(e){if(Gd.isEmpty(e.schema))throw new Error(DL.SCHEMA_REQUIRED_ERR);if(Gd.isEmpty(e.table))throw new Error(DL.TABLE_REQUIRED_ERR);if(!cX.get(qd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw CL(new Error,ML,LL.BAD_REQUEST,qd.LOG_LEVELS.ERROR,ML,!0);let t=Gd.checkSchemaTableExist(e.schema,e.table);if(t)throw CL(new Error,t,LL.NOT_FOUND,qd.LOG_LEVELS.ERROR,t,!0);if(!Gd.isEmpty(e.search_type)&&lX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await aX.readAuditLog(e)}a(_X,"readAuditLog")});var vL=g((sEe,UL)=>{"use strict";var{OPERATIONS_ENUM:dX}=P(),VS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=dX.GET_BACKUP,this.schema=t,this.table=r}};UL.exports=VS});var HL=g((cEe,xL)=>{"use strict";var fX=Cn(),oEe=vL(),$S=z(),EX=P(),aEe=ee(),{handleHDBError:hX,hdb_errors:mX}=se(),{HDB_ERROR_MSGS:BL,HTTP_STATUS_CODES:pX}=mX;xL.exports=SX;async function SX(e){if($S.isEmpty(e.schema))throw new Error(BL.SCHEMA_REQUIRED_ERR);if($S.isEmpty(e.table))throw new Error(BL.TABLE_REQUIRED_ERR);let t=$S.checkSchemaTableExist(e.schema,e.table);if(t)throw hX(new Error,t,pX.NOT_FOUND,EX.LOG_LEVELS.ERROR,t,!0);return await fX.getBackup(read_audit_log_object)}a(SX,"getBackup")});var $L=g((lEe,VL)=>{var Ei=require("validate.js"),qL=Xe(),pa=P(),{handleHDBError:TX,hdb_errors:gX}=se(),{HDB_ERROR_MSGS:mt,HTTP_STATUS_CODES:RX}=gX,YS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),AX={STRUCTURE_USER:"structure_user"},GL=Object.values(pa.ROLE_TYPES_ENUM),OX="attribute_permissions",bX="attribute_name",{PERMS_CRUD_ENUM:Sa}=pa,yX=[OX,...Object.values(Sa)],FL=[Sa.READ,Sa.INSERT,Sa.UPDATE],NX=[bX,...FL];function IX(e){let t=YS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,kL(e,t)}a(IX,"addRoleValidation");function wX(e){let t=YS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,kL(e,t)}a(wX,"alterRoleValidation");function CX(e){let t=YS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,qL.validateObject(e,t)}a(CX,"dropRoleValidation");var DX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function kL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)DX.includes(n[o])||s.push(n[o]);s.length>0&&At(mt.INVALID_ROLE_JSON_KEYS(s),r);let i=qL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{At(o,r)}),e.permission){let o=LX(e);o&&At(o,r),GL.forEach(c=>{e.permission[c]&&!Ei.isBoolean(e.permission[c])&&At(mt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(GL.indexOf(o)<0){if(o===AX.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||At(mt.SCHEMA_NOT_FOUND(d),r)}continue}At(mt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){At(mt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){At(mt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{yX.includes(l)||At(mt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(Sa).forEach(l=>{Ei.isDefined(_[l])?Ei.isBoolean(_[l])||At(mt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):At(mt.TABLE_PERM_MISSING(l),r,o,u)}),Ei.isDefined(_.attribute_permissions)){if(!Ei.isArray(_.attribute_permissions)){At(mt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{At(mt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in _.attribute_permissions){let f=_.attribute_permissions[E];if(Object.keys(f).forEach(p=>{!NX.includes(p)&&p!==Sa.DELETE&&At(mt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!Ei.isDefined(f.attribute_name)){At(mt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!l.includes(h)){At(mt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}FL.forEach(p=>{Ei.isDefined(f[p])?Ei.isBoolean(f[p])||At(mt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):At(mt.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let E=`${o}.${u}`;At(mt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return MX(r)}a(kL,"customValidate");VL.exports={addRoleValidation:IX,alterRoleValidation:wX,dropRoleValidation:CX};function LX(e){let{operation:t,permission:r}=e;if(t===pa.OPERATIONS_ENUM.ADD_ROLE||t===pa.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return mt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?pa.ROLE_TYPES_ENUM.SUPER_USER:pa.ROLE_TYPES_ENUM.CLUSTER_USER;return mt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(LX,"validateNoSUPerms");function MX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:mt.ROLE_PERMS_ERROR,...e};return TX(new Error,n,RX.BAD_REQUEST)}else return null}a(MX,"generateRolePermResponse");function At(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(At,"addPermError")});var jS=g((dEe,QL)=>{"use strict";var YL=qr(),KL=Gr(),PX=ai(),WS=$L(),QS=ys(),UX=require("uuid").v4,vX=require("util"),Fd=P(),BX=z(),zS=KL.searchByValue,xX=KL.searchByHash,HX=vX.promisify(PX.delete),GX=ts(),qX=ia(),{hdb_errors:FX,handleHDBError:lo}=se(),{HDB_ERROR_MSGS:WL,HTTP_STATUS_CODES:bu}=FX,{UserEventMsg:JS}=Mn();QL.exports={addRole:kX,alterRole:VX,dropRole:$X,listRoles:YX};function KS(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(KS,"scrubRoleDetails");async function kX(e){let t=WS.addRoleValidation(e);if(t)throw t;e=KS(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 zS(r)||[])}catch(i){throw lo(i)}if(n&&n.length>0)throw lo(new Error,WL.ROLE_ALREADY_EXISTS(e.role),bu.CONFLICT,void 0,void 0,!0);e.id||(e.id=UX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await YL.insert(s),QS.signalUserChange(new JS(process.pid)),e=KS(e),e}a(kX,"addRole");async function VX(e){let t=WS.alterRoleValidation(e);if(t)throw t;e=KS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await YL.update(r)}catch(s){throw lo(s)}if(n&&n?.message==="updated 0 of 1 records")throw lo(new Error,"Invalid role id",bu.BAD_REQUEST,void 0,void 0,!0);return await QS.signalUserChange(new JS(process.pid)),e}a(VX,"alterRole");async function $X(e){let t=WS.dropRoleValidation(e);if(t)throw lo(new Error,t,bu.BAD_REQUEST,void 0,void 0,!0);let r=new qX(Fd.SYSTEM_SCHEMA_NAME,Fd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await xX(r));if(n.length===0)throw lo(new Error,WL.ROLE_NOT_FOUND,bu.NOT_FOUND,void 0,void 0,!0);let s=new GX(Fd.SYSTEM_SCHEMA_NAME,Fd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await zS(s)),o=!1;if(BX.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`,bu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await HX(c),QS.signalUserChange(new JS(process.pid)),`${n[0].role} successfully deleted`}a($X,"dropRole");async function YX(){return zS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(YX,"listRoles")});var XL=g((EEe,jL)=>{"use strict";var KX=ee(),hi=require("joi"),WX=Xe(),zL=require("moment"),QX=require("fs-extra"),XS=require("path"),zX=require("lodash"),yu=P(),{LOG_LEVELS:_o}=P(),JX="YYYY-MM-DD hh:mm:ss",jX=XS.resolve(__dirname,"../logs");jL.exports=function(e){return WX.validateBySchema(e,XX)};var XX=hi.object({from:hi.custom(JL),until:hi.custom(JL),level:hi.valid(_o.NOTIFY,_o.FATAL,_o.ERROR,_o.WARN,_o.INFO,_o.DEBUG,_o.TRACE),order:hi.valid("asc","desc"),limit:hi.number().min(1),start:hi.number().min(0),log_name:hi.custom(ZX)});function JL(e,t){if(zL(e,zL.ISO_8601).format(JX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(JL,"validateDatetime");function ZX(e,t){if(zX.invert(yu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=KX.get(yu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?yu.LOG_NAMES.HDB:e,i=s===yu.LOG_NAMES.INSTALL?XS.join(jX,yu.LOG_NAMES.INSTALL):XS.join(n,s);return QX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(ZX,"validateReadLogPath")});var eT=g((mEe,eM)=>{"use strict";var kd=P(),eZ=$(),tZ=ee(),rZ=XL(),ZS=require("path"),ZL=require("fs-extra"),{once:nZ}=require("events"),{handleHDBError:sZ,hdb_errors:iZ}=se(),{PACKAGE_ROOT:oZ}=P(),aZ=ZS.join(oZ,"logs"),cZ=1e3,uZ=200;eM.exports=lZ;async function lZ(e){let t=rZ(e);if(t)throw sZ(t,t.message,iZ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=tZ.get(kd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?kd.LOG_NAMES.HDB:e.log_name,s=n===kd.LOG_NAMES.INSTALL?ZS.join(aZ,kd.LOG_NAMES.INSTALL):ZS.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?cZ:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,p=0;E==="desc"&&!u&&!l&&(p=Math.max(ZL.statSync(s).size-(h+5)*uZ,0));let S=ZL.createReadStream(s,{start:p});S.on("error",U=>{eZ.error(U)});let T=0,R=[],N="",I;S.on("data",U=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;U=N+U;let M=0,Q;for(;(Q=k.exec(U))&&!S.destroyed;){I&&(I.message=U.slice(M,Q.index),H(I));let[J,j,ae]=Q,ce=ae.split("] ["),de=ce[0],Be=ce[1];ce.splice(0,2),I={timestamp:j,thread:de,level:Be,tags:ce,message:""},M=Q.index+J.length}N=U.slice(M)}),S.on("end",U=>{S.destroyed||I&&(I.message=N.trim(),H(I))}),S.resume();function H(U){let k,M,Q;switch(!0){case(i&&c&&_):k=new Date(U.timestamp),M=new Date(u),Q=new Date(l),U.level===o&&k>=M&&k<=Q&&T<f?T++:U.level===o&&k>=M&&k<=Q&&(mi(U,E,R),T++,T===h&&S.destroy());break;case(i&&c):k=new Date(U.timestamp),M=new Date(u),U.level===o&&k>=M&&T<f?T++:U.level===o&&k>=M&&(mi(U,E,R),T++,T===h&&S.destroy());break;case(i&&_):k=new Date(U.timestamp),Q=new Date(l),U.level===o&&k<=Q&&T<f?T++:U.level===o&&k<=Q&&(mi(U,E,R),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(U.timestamp),M=new Date(u),Q=new Date(l),k>=M&&k<=Q&&T<f?T++:k>=M&&k<=Q&&(mi(U,E,R),T++,T===h&&S.destroy());break;case i:U.level===o&&T<f?T++:U.level===o&&(mi(U,E,R),T++,T===h&&S.destroy());break;case c:k=new Date(U.timestamp),M=new Date(u),k>=M&&T<f?T++:k>=M&&T>=f&&(mi(U,E,R),T++,T===h&&S.destroy());break;case _:k=new Date(U.timestamp),Q=new Date(l),k<=Q&&T<f?T++:k<=Q&&T>=f&&(mi(U,E,R),T++,T===h&&S.destroy());break;default:T<f?T++:(mi(U,E,R),T++,T===h&&S.destroy())}}return a(H,"onLogMessage"),await nZ(S,"close"),R}a(lZ,"readLog");function mi(e,t,r){t==="desc"?_Z(e,r):t==="asc"?dZ(e,r):r.push(e)}a(mi,"pushLineToResult");function _Z(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(_Z,"insertDescending");function dZ(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(dZ,"insertAscending")});var Vd=g((REe,sM)=>{"use strict";var tT=require("joi"),{string:Nu,boolean:tM,date:fZ}=tT.types(),EZ=Xe(),{validateSchemaExists:SEe,validateTableExists:TEe,validateSchemaName:gEe}=Jn(),hZ=P(),mZ=Ve(),rM=ee();rM.initSync();var pZ=Nu.invalid(rM.get(hZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(mZ.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(),nM={operation:Nu.valid("add_node","update_node","set_node_replication"),node_name:pZ,subscriptions:tT.array().items({table:Nu.optional(),schema:Nu.optional(),database:Nu.optional(),subscribe:tM.required(),publish:tM.required().custom(TZ),start_time:fZ.iso()}).min(1).required()};function SZ(e){return EZ.validateBySchema(e,tT.object(nM))}a(SZ,"addUpdateNodeValidator");function TZ(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(TZ,"checkForFalsy");sM.exports={addUpdateNodeValidator:SZ,validation_schema:nM}});var oM=g((OEe,iM)=>{var gZ=Xe(),RZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};iM.exports=function(e){return gZ.validateObject(e,RZ)}});var $d=g((bEe,aM)=>{"use strict";var AZ=P().OPERATIONS_ENUM,rT=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}};aM.exports=rT});var uM=g((NEe,cM)=>{"use strict";var OZ={OPERATION:"operation",REFRESH:"refresh"},nT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},sT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};cM.exports={JWTTokens:nT,TOKEN_TYPE_ENUM:OZ,JWTRSAKeys:sT}});var Cu=g((wEe,fM)=>{"use strict";var wu=require("jsonwebtoken"),iT=require("fs-extra"),oT=z(),dn=P(),{handleHDBError:Ar,hdb_errors:bZ}=se(),{HTTP_STATUS_CODES:Or,AUTHENTICATION_ERROR_MSGS:br}=bZ,Iu=$(),lM=K_(),uT=_n(),yZ=qr().update,NZ=$d(),IZ=ys(),{UserEventMsg:wZ}=Mn(),pi=ee();pi.initSync();var aT=require("path"),{JWTTokens:CZ,JWTRSAKeys:DZ,TOKEN_TYPE_ENUM:Yd}=uM(),LZ=pi.get(dn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?pi.get(dn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",MZ=pi.get(dn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?pi.get(dn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Kd="RS256",cT;fM.exports={createTokens:PZ,validateOperationToken:vZ,refreshOperationToken:UZ,validateRefreshToken:dM};async function PZ(e){if(oT.isEmpty(e)||typeof e!="object")throw Ar(new Error,br.INVALID_AUTH_OBJECT,Or.BAD_REQUEST,void 0,void 0,!0);if(oT.isEmpty(e.username))throw Ar(new Error,br.USERNAME_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);if(oT.isEmpty(e.password))throw Ar(new Error,br.PASSWORD_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await uT.findAndValidateUser(e.username,e.password),!t)throw Ar(new Error,br.INVALID_CREDENTIALS,Or.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw Iu.error(E),Ar(new Error,br.INVALID_CREDENTIALS,Or.UNAUTHORIZED,void 0,void 0,!0)}let r=await Wd(),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 _M(i,r.private_key,r.passphrase),c=await wu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:MZ,algorithm:Kd,subject:Yd.REFRESH}),u=lM.hash(c),_=new NZ(dn.SYSTEM_SCHEMA_NAME,dn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await yZ(_)}catch(E){Iu.error(E),d=E}if(d!==void 0||l.skipped_hashes.length>0)throw Ar(new Error,br.REFRESH_TOKEN_SAVE_FAILED,Or.INTERNAL_SERVER_ERROR);return IZ.signalUserChange(new wZ(process.pid)),new CZ(o,c)}a(PZ,"createTokens");async function _M(e,t,r){return await wu.sign(e,{key:t,passphrase:r},{expiresIn:LZ,algorithm:Kd,subject:Yd.OPERATION})}a(_M,"signOperationToken");async function Wd(){if(cT===void 0)try{let e=aT.join(pi.getHdbBasePath(),dn.LICENSE_KEY_DIR_NAME,dn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=aT.join(pi.getHdbBasePath(),dn.LICENSE_KEY_DIR_NAME,dn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=aT.join(pi.getHdbBasePath(),dn.LICENSE_KEY_DIR_NAME,dn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await iT.readFile(e)).toString(),s=(await iT.readFile(t)).toString(),i=(await iT.readFile(r)).toString();cT=new DZ(i,s,n)}catch(e){throw Iu.error(e),Ar(new Error,br.NO_ENCRYPTION_KEYS,Or.INTERNAL_SERVER_ERROR)}return cT}a(Wd,"getJWTRSAKeys");async function UZ(e){if(!e)throw Ar(new Error,br.INVALID_BODY,Or.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Ar(new Error,br.REFRESH_TOKEN_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);await dM(e.refresh_token);let t=await Wd(),r=await wu.decode(e.refresh_token);return{operation_token:await _M({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(UZ,"refreshOperationToken");async function vZ(e){try{let t=await Wd(),r=await wu.verify(e,t.public_key,{algorithms:Kd,subject:Yd.OPERATION});return await uT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Iu.warn(t),t.name&&t.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}}a(vZ,"validateOperationToken");async function dM(e){let t;try{let r=await Wd(),n=await wu.verify(e,r.public_key,{algorithms:Kd,subject:Yd.REFRESH});t=await uT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Iu.warn(r),r.name&&r.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}if(!lM.validate(t.refresh_token,e))throw Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED);return t}a(dM,"validateRefreshToken")});var lT=g((LEe,mM)=>{"use strict";var BZ=oM(),Ta=require("passport"),xZ=require("passport-local").Strategy,HZ=require("passport-http").BasicStrategy,GZ=require("util"),qZ=_n(),hM=GZ.callbackify(qZ.findAndValidateUser),DEe=Ur(),FZ=P(),EM=Cu();Ta.use(new xZ(function(e,t,r){hM(e,t,r)}));Ta.use(new HZ(function(e,t,r){hM(e,t,r)}));Ta.serializeUser(function(e,t){t(null,e)});Ta.deserializeUser(function(e,t){t(null,e)});function kZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Ta.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===FZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?EM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):EM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Ta.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(kZ,"authorize");function VZ(e,t){let r=BZ(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(VZ,"checkPermissions");mM.exports={authorize:kZ,checkPermissions:VZ}});var Si=g((PEe,pM)=>{"use strict";var _T=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},dT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};pM.exports={Node:_T,NodeSubscription:dT}});var TM=g((vEe,SM)=>{"use strict";var $Z=P().OPERATIONS_ENUM,fT=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=$Z.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};SM.exports=fT});var Du=g((xEe,gM)=>{"use strict";var ET=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},hT=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)}};gM.exports={RemotePayloadObject:ET,RemotePayloadSubscription:hT}});var AM=g((GEe,RM)=>{"use strict";var mT=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}};RM.exports=mT});var yM=g(($Ee,bM)=>{"use strict";var YZ=AM(),FEe=ft(),OM=Qe(),KZ=$(),{getSchemaPath:kEe,getTransactionAuditStorePath:VEe}=je(),{getDatabases:WZ}=(Ae(),ie(ke));bM.exports=QZ;async function QZ(e){let t=new YZ;try{let r=WZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await OM.environmentDataSize(schema_path,e.name),o=await OM.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){KZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(QZ,"lmdbGetTableSize")});var IM=g((KEe,NM)=>{"use strict";var pT=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}};NM.exports=pT});var ga=g((XEe,LM)=>{"use strict";var zZ=require("fs-extra"),JZ=require("path"),sr=require("systeminformation"),Ti=$(),wM=ut(),QEe=Ve(),zd=P(),jZ=yM(),XZ=Os(),{getThreadInfo:CM}=We(),wT=ee();wT.initSync();var ZZ=IM(),{openEnvironment:zEe}=Qe(),{getSchemaPath:JEe}=je(),{database:jEe,databases:ST}=(Ae(),ie(ke)),Qd;LM.exports={getHDBProcessInfo:AT,getNetworkInfo:bT,getDiskInfo:OT,getMemoryInfo:RT,getCPUInfo:gT,getTimeInfo:TT,getSystemInformation:yT,systemInformation:e5,getTableSize:NT,getMetrics:IT};function TT(){return sr.time()}a(TT,"getTimeInfo");async function gT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await sr.cpu();l.cpu_speed=await sr.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...R}=await sr.currentLoad();return R.cpus=[],T.forEach(N=>{let{raw_load:I,raw_load_idle:H,raw_load_irq:U,raw_load_nice:k,raw_load_system:M,raw_load_user:Q,...J}=N;R.cpus.push(J)}),l.current_load=R,l}catch(e){return Ti.error(`error in getCPUInfo: ${e}`),{}}}a(gT,"getCPUInfo");async function RT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await sr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ti.error(`error in getMemoryInfo: ${e}`),{}}}a(RT,"getMemoryInfo");async function AT(){let e={core:[],clustering:[]};try{let t=await sr.processes(),r;try{r=Number.parseInt(await zZ.readFile(JZ.join(wT.get(zd.CONFIG_PARAMS.ROOTPATH),zd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===zd.NODE_ERROR_CODES.ENOENT)Ti.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 Ti.error(`error in getHDBProcessInfo: ${t}`),e}}a(AT,"getHDBProcessInfo");async function OT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await sr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await sr.fsStats();return e.read_write=_,e.size=await sr.fsSize(),e}catch(t){return Ti.error(`error in getDiskInfo: ${t}`),e}}a(OT,"getDiskInfo");async function bT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await sr.networkInterfaceDefault(),e.latency=await sr.inetChecksite("google.com"),(await sr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await sr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ti.error(`error in getNetworkInfo: ${t}`),e}}a(bT,"getNetworkInfo");async function yT(){if(Qd!==void 0)return Qd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await sr.osInfo();e=c;let u=await sr.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Qd=e,Qd}catch(t){return Ti.error(`error in getSystemInformation: ${t}`),e}}a(yT,"getSystemInformation");async function NT(){let e=[],t=await XZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await jZ(n));return e}a(NT,"getTableSize");async function IT(){let e={};for(let t in ST){let r=e[t]={},n=r.tables={};for(let s in ST[t])try{let i=ST[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(u=>{let[_,l,d]=u.trim().split(" ");return{pid:_,thread:l,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let u of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[u]=o[u];n[s]=c}catch(i){Ti.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(IT,"getMetrics");async function DM(){if(wT.get(zd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await wM.getNATSReferences(),t=await wM.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(DM,"getNatsStreamInfo");async function e5(e){let t=new ZZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await yT(),t.time=TT(),t.cpu=await gT(),t.memory=await RT(),t.disk=await OT(),t.network=await bT(),t.harperdb_processes=await AT(),t.table_size=await NT(),t.metrics=await IT(),t.threads=await CM(),t.replication=await DM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await yT();break;case"time":t.time=TT();break;case"cpu":t.cpu=await gT();break;case"memory":t.memory=await RT();break;case"disk":t.disk=await OT();break;case"network":t.network=await bT();break;case"harperdb_processes":t.harperdb_processes=await AT();break;case"table_size":t.table_size=await NT();break;case"database_metrics":case"metrics":t.metrics=await IT();break;case"threads":t.threads=await CM();break;case"replication":t.replication=await DM();break;default:break}return t}a(e5,"systemInformation")});var jd=g((ehe,MM)=>{"use strict";MM.exports={version:t5,printVersion:r5};var Jd=_u();function t5(){if(Jd)return Jd.version}a(t5,"version");function r5(){Jd&&console.log(`HarperDB Version ${Jd.version}`)}a(r5,"printVersion")});var fn=g((she,BM)=>{"use strict";var n5=qr(),CT=z(),s5=require("util"),fo=P(),PM=ee();PM.initSync();var i5=lT(),UM=Gr(),{Node:rhe,NodeSubscription:nhe}=Si(),o5=ia(),a5=TM(),{RemotePayloadObject:c5,RemotePayloadSubscription:u5}=Du(),{handleHDBError:l5,hdb_errors:_5}=se(),{HTTP_STATUS_CODES:d5,HDB_ERROR_MSGS:f5}=_5,E5=ts(),h5=ga(),m5=jd(),{getDatabases:p5}=(Ae(),ie(ke)),S5=s5.promisify(i5.authorize),T5=UM.searchByHash,g5=UM.searchByValue;BM.exports={authHeaderToUser:R5,isEmpty:A5,getNodeRecord:O5,upsertNodeRecord:b5,buildNodePayloads:y5,checkClusteringEnabled:N5,getAllNodeRecords:I5,getSystemInfo:w5,reverseSubscription:vM};async function R5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await S5(t,null),e}a(R5,"authHeaderToUser");function A5(e){return e==null}a(A5,"isEmpty");async function O5(e){let t=new o5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return T5(t)}a(O5,"getNodeRecord");async function b5(e){let t=new a5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return n5.upsert(t)}a(b5,"upsertNodeRecord");function vM(e){if(CT.isEmpty(e.subscribe)||CT.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(vM,"reverseSubscription");function y5(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=CT.getTableHashAttribute(u,_),{subscribe:d,publish:E}=vM(c),f=p5()[u]?.[_],h=new u5(u,_,l,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new c5(r,t,s,n)}a(y5,"buildNodePayloads");function N5(){if(!PM.get(fo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw l5(new Error,f5.CLUSTERING_NOT_ENABLED,d5.BAD_REQUEST,void 0,void 0,!0)}a(N5,"checkClusteringEnabled");async function I5(){let e=new E5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await g5(e))}a(I5,"getAllNodeRecords");async function w5(){let e=await h5.getSystemInformation();return{hdb_version:m5.version(),node_version:e.node_version,platform:e.platform}}a(w5,"getSystemInfo")});var DT=g((ohe,$M)=>{"use strict";var Xd=ut(),xM=z(),HM=Ve(),GM=P(),Zd=$(),qM=Ou(),C5=fd(),{RemotePayloadObject:D5}=Du(),{handleHDBError:FM,hdb_errors:L5}=se(),{HTTP_STATUS_CODES:kM}=L5,{NodeSubscription:VM}=Si();$M.exports=M5;async function M5(e,t){let r;try{r=await Xd.request(`${t}.${HM.REQUEST_SUFFIX}`,new D5(GM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Zd.trace("Response from remote describe all request:",r)}catch(o){Zd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Xd.requestErrorHandler(o,"add_node",t);throw FM(new Error,c,kM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===HM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw FM(new Error,o,kM.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===GM.SYSTEM_SCHEMA_NAME){await Xd.createLocalTableStream(u,c);let h=new VM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=xM.doesSchemaExist(u),l=n[u]!==void 0,d=c?xM.doesTableExist(u,c):!0,E=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!E){s.push(o);continue}if(!_&&l&&(Zd.trace(`addNode creating schema: ${u}`),await qM.createSchema({operation:"create_schema",schema:u})),!d&&E){Zd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new C5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await qM.createTable(h)}await Xd.createLocalTableStream(u,c);let f=new VM(u,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(M5,"reviewSubscriptions")});var nf=g((che,WM)=>{"use strict";var{handleHDBError:ef,hdb_errors:P5}=se(),{HTTP_STATUS_CODES:tf}=P5,{addUpdateNodeValidator:U5}=Vd(),rf=$(),KM=P(),YM=Ve(),v5=z(),Lu=ut(),Mu=fn(),B5=ee(),x5=DT(),{Node:H5,NodeSubscription:G5}=Si(),{broadcast:q5}=We(),F5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",k5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",V5=B5.get(KM.CONFIG_PARAMS.CLUSTERING_NODENAME);WM.exports=$5;async function $5(e,t=!1){rf.trace("addNode called with:",e),Mu.checkClusteringEnabled();let r=U5(e);if(r)throw ef(r,r.message,tf.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Mu.getNodeRecord(n);if(!v5.isEmptyOrZeroLength(d))throw ef(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,tf.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await x5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=F5,o;let c=Mu.buildNodePayloads(s,V5,KM.OPERATIONS_ENUM.ADD_NODE,await Mu.getSystemInfo()),u=[];for(let d=0,E=s.length;d<E;d++){let f=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new G5(f.schema,f.table,f.publish,f.subscribe))}rf.trace("addNode sending remote payload:",c);let _;try{_=await Lu.request(`${n}.${YM.REQUEST_SUFFIX}`,c)}catch(d){rf.error(`addNode received error from request: ${d}`);for(let f=0,h=s.length;f<h;f++){let p=s[f];p.publish=!1,p.subscribe=!1,await Lu.updateRemoteConsumer(p,n)}let E=Lu.requestErrorHandler(d,"add_node",n);throw ef(new Error,E,tf.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===YM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw ef(new Error,d,tf.INTERNAL_SERVER_ERROR,"error",d)}rf.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await Lu.updateRemoteConsumer(f,n),f.subscribe===!0&&await Lu.updateConsumerIterator(f.schema,f.table,n,"start")}let l=new H5(n,u,_.system_info);return await Mu.upsertNodeRecord(l),q5({type:"nats_update"}),i.length>0?o.message=k5:o.message=`Successfully added '${n}' to manifest`,o}a($5,"addNode")});var PT=g((_he,JM)=>{"use strict";var{handleHDBError:LT,hdb_errors:Y5}=se(),{HTTP_STATUS_CODES:MT}=Y5,{addUpdateNodeValidator:K5}=Vd(),Pu=$(),zM=P(),QM=Ve(),lhe=z(),Uu=ut(),vu=fn(),W5=ee(),{cloneDeep:Q5}=require("lodash"),z5=DT(),{Node:J5,NodeSubscription:j5}=Si(),{broadcast:X5}=We(),Z5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",e8="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",t8=W5.get(zM.CONFIG_PARAMS.CLUSTERING_NODENAME);JM.exports=r8;async function r8(e){Pu.trace("updateNode called with:",e),vu.checkClusteringEnabled();let t=K5(e);if(t)throw LT(t,t.message,MT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await vu.getNodeRecord(r);s.length>0&&(n=Q5(s));let{added:i,skipped:o}=await z5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=Z5,c;let u=vu.buildNodePayloads(i,t8,zM.OPERATIONS_ENUM.UPDATE_NODE,await vu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let E=i[l];Pu.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[l].start_time===void 0&&delete i[l].start_time}Pu.trace("updateNode sending remote payload:",u);let _;try{_=await Uu.request(`${r}.${QM.REQUEST_SUFFIX}`,u)}catch(l){Pu.error(`updateNode received error from request: ${l}`);let d=Uu.requestErrorHandler(l,"update_node",r);throw LT(new Error,d,MT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===QM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw LT(new Error,l,MT.INTERNAL_SERVER_ERROR,"error",l)}Pu.trace(_);for(let l=0,d=i.length;l<d;l++){let E=i[l];await Uu.updateRemoteConsumer(E,r),E.subscribe===!0?await Uu.updateConsumerIterator(E.schema,E.table,r,"start"):await Uu.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new J5(r,[],_.system_info)]),await n8(n[0],i,_.system_info),o.length>0?c.message=e8:c.message=`Successfully updated '${r}'`,c}a(r8,"updateNode");async function n8(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 j5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await vu.upsertNodeRecord(n),X5({type:"nats_update"})}a(n8,"updateNodeTable")});var tP=g((fhe,eP)=>{"use strict";var ZM=require("joi"),{string:jM}=ZM.types(),s8=Xe(),XM=P(),i8=ee(),o8=Ve();eP.exports=a8;function a8(e){let t=jM.invalid(i8.get(XM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(o8.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=ZM.object({operation:jM.valid(XM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return s8.validateBySchema(e,r)}a(a8,"removeNodeValidator")});var of=g((hhe,oP)=>{"use strict";var{handleHDBError:rP,hdb_errors:c8}=se(),{HTTP_STATUS_CODES:nP}=c8,u8=tP(),Bu=$(),sP=fn(),l8=z(),sf=P(),iP=Ve(),UT=ut(),_8=ee(),{RemotePayloadObject:d8}=Du(),{NodeSubscription:f8}=Si(),E8=oa(),h8=ai(),{broadcast:m8}=We(),p8=_8.get(sf.CONFIG_PARAMS.CLUSTERING_NODENAME);oP.exports=S8;async function S8(e){Bu.trace("removeNode called with:",e),sP.checkClusteringEnabled();let t=u8(e);if(t)throw rP(t,t.message,nP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await sP.getNodeRecord(r);if(l8.isEmptyOrZeroLength(n))throw rP(new Error,`Node '${r}' was not found.`,nP.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new d8(sf.OPERATIONS_ENUM.REMOVE_NODE,p8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await UT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await UT.updateRemoteConsumer(new f8(l.schema,l.table,!1,!1),r)}catch(d){Bu.error(d)}}try{i=await UT.request(`${r}.${iP.REQUEST_SUFFIX}`,s),Bu.trace("Remove node reply from remote node:",r,i)}catch(u){Bu.error("removeNode received error from request:",u),o=!0}let c=new E8(sf.SYSTEM_SCHEMA_NAME,sf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await h8.deleteRecord(c),m8({type:"nats_update"}),i?.status===iP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Bu.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 uP=g((phe,cP)=>{"use strict";var aP=require("joi"),{string:T8,array:g8}=aP.types(),R8=Xe(),A8=Vd();cP.exports=O8;function O8(e){let t=aP.object({operation:T8.valid("configure_cluster").required(),connections:g8.items(A8.validation_schema).required()});return R8.validateBySchema(e,t)}a(O8,"configureClusterValidator")});var vT=g((The,EP)=>{"use strict";var b8=P(),af=$(),y8=z(),N8=of(),I8=nf(),lP=fn(),w8=uP(),{handleHDBError:_P,hdb_errors:C8}=se(),{HTTP_STATUS_CODES:dP}=C8,D8="Configure cluster complete.",L8="Failed to configure the cluster. Check the logs for more details.",M8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";EP.exports=P8;async function P8(e){af.trace("configure cluster called with:",e),lP.checkClusteringEnabled();let t=w8(e);if(t)throw _P(t,t.message,dP.BAD_REQUEST,void 0,void 0,!0);let r=await lP.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let E=await fP(N8,{operation:b8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(E)}af.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],E=await fP(I8,d,d.node_name);s.push(E)}af.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let E=_[l];E.status==="rejected"&&(af.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(u=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(y8.isEmptyOrZeroLength(o))return{message:D8,connections:c};if(u)return{message:M8,failed_nodes:o,connections:c};throw _P(new Error,L8,dP.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(P8,"configureCluster");async function fP(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(fP,"functionWrapper")});var SP=g((Rhe,pP)=>{"use strict";var xu=require("joi"),U8=Xe(),{validateSchemaExists:hP,validateTableExists:v8,validateSchemaName:mP}=Jn(),B8=xu.object({operation:xu.string().valid("purge_stream"),schema:xu.string().custom(hP).custom(mP).optional(),database:xu.string().custom(hP).custom(mP).optional(),table:xu.string().custom(v8).required()});function x8(e){return U8.validateBySchema(e,B8)}a(x8,"purgeStreamValidator");pP.exports=x8});var BT=g((Ohe,TP)=>{"use strict";var{handleHDBError:H8,hdb_errors:G8}=se(),{HTTP_STATUS_CODES:q8}=G8,F8=SP(),k8=ut(),V8=fn();TP.exports=$8;async function $8(e){e.schema=e.schema??e.database;let t=F8(e);if(t)throw H8(t,t.message,q8.BAD_REQUEST,void 0,void 0,!0);V8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await k8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a($8,"purgeStream")});var GT=g((yhe,yP)=>{"use strict";var HT=fn(),Y8=ut(),AP=ee(),cf=P(),Eo=Ve(),K8=z(),xT=$(),{RemotePayloadObject:W8}=Du(),{ErrorCode:gP}=require("nats"),RP=AP.get(cf.CONFIG_PARAMS.CLUSTERING_ENABLED),OP=AP.get(cf.CONFIG_PARAMS.CLUSTERING_NODENAME);yP.exports={clusterStatus:Q8,buildNodeStatus:bP};async function Q8(){let e={node_name:OP,is_enabled:RP,connections:[]};if(!RP)return e;let t=await HT.getAllNodeRecords();if(K8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(bP(t[n],e.connections));return await Promise.allSettled(r),e}a(Q8,"clusterStatus");async function bP(e,t){let r=e.name,n=new W8(cf.OPERATIONS_ENUM.CLUSTER_STATUS,OP,void 0,await HT.getSystemInfo()),s,i,o=Eo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await Y8.request(Eo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===Eo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Eo.CLUSTER_STATUS_STATUSES.CLOSED,xT.error(`Error getting node status from ${r} `,s))}catch(u){xT.warn(`Error getting node status from ${r}`,u),u.code===gP.NoResponders?o=Eo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===gP.Timeout?o=Eo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Eo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new z8(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!==cf.PRE_4_0_0_VERSION&&await HT.upsertNodeRecord(u)}catch(u){xT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(bP,"buildNodeStatus");function z8(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(z8,"NodeStatusObject")});var FT=g((Ihe,NP)=>{"use strict";var{handleHDBError:J8,hdb_errors:j8}=se(),{HTTP_STATUS_CODES:X8}=j8,Z8=ut(),e6=fn(),qT=z(),uf=require("joi"),t6=Xe(),r6=2e3,n6=uf.object({timeout:uf.number().min(1),connected_nodes:uf.boolean(),routes:uf.boolean()});NP.exports=s6;async function s6(e){e6.checkClusteringEnabled();let t=t6.validateBySchema(e,n6);if(t)throw J8(t,t.message,X8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||qT.autoCastBoolean(n),o=s===void 0||qT.autoCastBoolean(s),c={nodes:[]},u=await Z8.getServerList(r??r6),_={};if(i)for(let l=0,d=u.length;l<d;l++){let E=u[l].statsz;E&&(_[u[l].server.name]=E.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let E=u[l].server,f=u[l].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[E.name]&&_[E.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(p=>({host:p.split(":")[0],port:qT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(s6,"clusterNetwork")});var DP=g((Che,CP)=>{"use strict";var kT=require("joi"),IP=Xe(),{route_constraints:wP}=sp();CP.exports={setRoutesValidator:i6,deleteRoutesValidator:o6};function i6(e){let t=kT.object({server:kT.valid("hub","leaf").required(),routes:wP.required()});return IP.validateBySchema(e,t)}a(i6,"setRoutesValidator");function o6(e){let t=kT.object({routes:wP.required()});return IP.validateBySchema(e,t)}a(o6,"deleteRoutesValidator")});var $T=g((Lhe,UP)=>{"use strict";var ho=Er(),VT=z(),lf=P(),LP=DP(),{handleHDBError:MP,hdb_errors:a6}=se(),{HTTP_STATUS_CODES:PP}=a6,c6="cluster routes successfully set",u6="cluster routes successfully deleted";UP.exports={setRoutes:l6,getRoutes:_6,deleteRoutes:d6};function l6(e){let t=LP.setRoutesValidator(e);if(t)throw MP(t,t.message,PP.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=VT.autoCast(_.port);let l=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?ho.updateConfigValue(lf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):ho.updateConfigValue(lf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:c6,set:o,skipped:i}}a(l6,"setRoutes");function _6(){let e=ho.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(_6,"getRoutes");function d6(e){let t=LP.deleteRoutesValidator(e);if(t)throw MP(t,t.message,PP.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[_],E=!1;for(let f=0,h=n.length;f<h;f++){let p=n[f];if(d.host===p.host&&d.port===p.port){n.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=VT.isEmptyOrZeroLength(n)?null:n,ho.updateConfigValue(lf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=VT.isEmptyOrZeroLength(s)?null:s,ho.updateConfigValue(lf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:u6,deleted:i,skipped:o}}a(d6,"deleteRoutes")});var BP=g((Phe,vP)=>{"use strict";var Hu=require("alasql"),mo=require("recursive-iterator"),xn=$(),f6=z(),Gu=P(),YT=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,h6(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=>Gu.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=>!Gu.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][Gu.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(_=>!Gu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Hu.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[Gu.PERMS_CRUD_ENUM.READ])}a(E6,"filterReadRestrictedAttrs");function h6(e,t,r,n,s){m6(e,t,r,n,s)}a(h6,"interpretAST");function qu(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(qu,"addSchemaTableToMap");function m6(e,t,r,n,s){if(!e){xn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Hu.yy.Insert?g6(e,t,r):e instanceof Hu.yy.Select?p6(e,t,r,n,s):e instanceof Hu.yy.Update?S6(e,t,r):e instanceof Hu.yy.Delete?T6(e,t,r):xn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(m6,"getRecordAttributesAST");function p6(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(f6.isEmptyOrZeroLength(i)){xn.error("No schema specified");return}e.from.forEach(c=>{qu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),qu(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(p6,"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;qu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&KT(e.table.tableid,s,i.columnid,t,r)}a(S6,"getUpdateAttributes");function T6(e,t,r){if(!e){xn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new mo(e.where),s=e.table.databaseid;qu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&KT(e.table.tableid,s,i.columnid,t,r)}a(T6,"getDeleteAttributes");function g6(e,t,r){if(!e){xn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new mo(e.columns),s=e.into.databaseid;qu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&KT(e.into.tableid,s,i.columnid,t,r)}a(g6,"getInsertAttributes");function KT(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(KT,"pushAttribute");vP.exports=YT});var zT=g((vhe,qP)=>{var _f=ji(),xP=require("chalk"),Qr=$(),HP=require("prompt"),{promisify:R6}=require("util"),WT=P(),A6=require("fs-extra"),O6=require("path"),b6=z(),y6=jd(),GP=ee();GP.initSync();var N6=require("moment"),I6=R6(HP.get),w6=O6.join(GP.getHdbBasePath(),WT.LICENSE_KEY_DIR_NAME,WT.LICENSE_FILE_NAME,WT.LICENSE_FILE_NAME);qP.exports={getFingerprint:D6,setLicense:C6,parseLicense:QT,register:L6,getRegistrationInfo:P6};async function C6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await QT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(C6,"setLicense");async function D6(){let e={};try{e=await _f.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(D6,"getFingerprint");async function QT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=_f.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await A6.writeFile(w6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(QT,"parseLicense");async function L6(){let e=await M6();return QT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(L6,"register");async function M6(){let e=await _f.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:xP.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:xP.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{HP.start()}catch(n){Qr.error(n)}let r;try{r=await I6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(M6,"promptForRegistration");async function P6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await _f.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(b6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=y6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=N6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(P6,"getRegistrationInfo")});var kP=g((xhe,FP)=>{"use strict";var U6=Ve(),JT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+U6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};FP.exports=JT});var YP=g((Ghe,$P)=>{"use strict";var VP=Ve(),jT=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+VP.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+VP.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"}};$P.exports=jT});var WP=g((Fhe,KP)=>{"use strict";var XT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};KP.exports=XT});var zP=g((Vhe,QP)=>{"use strict";var v6=Ve(),ZT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+v6.SERVER_SUFFIX.ADMIN,this.password=r}};QP.exports=ZT});var rg=g((Yhe,XP)=>{"use strict";var Ra=require("path"),Ef=require("fs-extra"),B6=kP(),x6=YP(),H6=WP(),G6=zP(),eg=_n(),Oa=z(),yr=Er(),ff=P(),Fu=Ve(),{CONFIG_PARAMS:pt}=ff,ba=$(),ku=ee(),JP=As(),tg=ut(),Aa="clustering",q6=1e4,jP=50;XP.exports={generateNatsConfig:k6,removeNatsConfig:V6,getHubConfigPath:F6};function F6(){let e=ku.get(pt.ROOTPATH);return Ra.join(e,Aa,Fu.NATS_CONFIG_FILES.HUB_SERVER)}a(F6,"getHubConfigPath");async function k6(e=!1,t=void 0){ku.initSync();let r=ku.get(pt.ROOTPATH),n=Ra.join(r,Aa,Fu.PID_FILES.HUB),s=Ra.join(r,Aa,Fu.PID_FILES.LEAF),i=yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ra.join(r,Aa,Fu.NATS_CONFIG_FILES.HUB_SERVER),c=Ra.join(r,Aa,Fu.NATS_CONFIG_FILES.LEAF_SERVER),u=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERTIFICATE),_=yr.getConfigFromFile(pt.CLUSTERING_TLS_PRIVATEKEY),l=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERT_AUTH),d=yr.getConfigFromFile(pt.CLUSTERING_TLS_INSECURE),E=yr.getConfigFromFile(pt.CLUSTERING_TLS_VERIFY),f=yr.getConfigFromFile(pt.CLUSTERING_NODENAME),h=yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await tg.checkNATSServerInstalled()||hf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await eg.listUsers(),S=yr.getConfigFromFile(pt.CLUSTERING_USER),T=await eg.getClusterUser();(Oa.isEmpty(T)||T.active!==!0)&&hf(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await df(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await df(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await df(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),await df(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],N=[];for(let[J,j]of p.entries())j.role.role===ff.ROLE_TYPES_ENUM.CLUSTER_USER&&j.active&&(R.push(new G6(j.username,JP.decrypt(j.hash))),N.push(new H6(j.username,JP.decrypt(j.hash))));let I=[],{hub_routes:H}=yr.getClusteringRoutes();if(!Oa.isEmptyOrZeroLength(H))for(let J of H)I.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${J.host}:${J.port}`);let U=new B6(yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,u,_,l,d,E,h,yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NAME),yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),I,R,N);l==null&&(delete U.tls.ca_file,delete U.leafnodes.tls.ca_file),t=Oa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===ff.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Ef.writeJson(o,U),ba.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,M=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,Q=new x6(yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[k],[M],R,N,u,_,l,d);l==null&&delete Q.tls.ca_file,(t===void 0||t===ff.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Ef.writeJson(c,Q),ba.trace(`Leaf server config written to ${c}`))}a(k6,"generateNatsConfig");async function df(e){let t=ku.get(e);return Oa.isEmpty(t)&&hf(`port undefined for '${e}'`),await Oa.isPortTaken(t)&&hf(`'${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(df,"isPortAvailable");function hf(e){let t=`Error generating clustering config: ${e}`;ba.error(t),console.error(t),process.exit(1)}a(hf,"generateNatsConfigError");async function V6(e){let{port:t,config_file:r}=tg.getServerConfig(e),{username:n,decrypt_hash:s}=await eg.getClusterUser(),i=0,o=2e3;for(;i<jP;){try{let l=await tg.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){ba.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=jP)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&ba.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Oa.async_set_timeout(_)}let c="0".repeat(q6),u=Ra.join(ku.get(pt.ROOTPATH),Aa,r);await Ef.writeFile(u,c),await Ef.remove(u),ba.notify(e,"started.")}a(V6,"removeNatsConfig")});var sU=g((Whe,nU)=>{"use strict";var zr=ee(),$6=ji(),pe=P(),Vu=Ve(),Ds=require("path"),{PACKAGE_ROOT:pf}=P(),ZP=ee(),mf=z(),ya="/dev/null",Y6=Ds.join(pf,"launchServiceScripts"),eU=Ds.join(pf,"utility/scripts"),K6=Ds.join(eU,pe.HDB_RESTART_SCRIPT),tU=Ds.resolve(pf,"dependencies",`${process.platform}-${process.arch}`,Vu.NATS_BINARY_NAME);function rU(){let t=$6.licenseSearch().ram_allocation||pe.RAM_ALLOCATION_ENUM.DEFAULT,r=pe.MEM_SETTING_KEY+t,n={[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return mf.noBootFile()&&(n[pe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=mf.getEnvCliRootPath()),{name:pe.PROCESS_DESCRIPTORS.HDB,script:pe.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:pf}}a(rU,"generateMainServerConfig");var W6=9930;function Q6(){zr.initSync(!0);let e=zr.get(pe.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",Vu.NATS_CONFIG_FILES.HUB_SERVER),r=Ds.join(zr.get(pe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),pe.LOG_NAMES.HDB),n=ZP.get(pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Vu.LOG_LEVEL_FLAGS[zr.get(pe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==W6?"-"+n:""),script:tU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a(Q6,"generateNatsHubServerConfig");var z6=9940;function J6(){zr.initSync(!0);let e=zr.get(pe.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",Vu.NATS_CONFIG_FILES.LEAF_SERVER),r=Ds.join(zr.get(pe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),pe.LOG_NAMES.HDB),n=ZP.get(pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Vu.LOG_LEVEL_FLAGS[zr.get(pe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==z6?"-"+n:""),script:tU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a(J6,"generateNatsLeafServerConfig");function j6(){zr.initSync();let e=Ds.join(zr.get(pe.CONFIG_PARAMS.LOGGING_ROOT),pe.LOG_NAMES.HDB),t={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:pe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Y6,autorestart:!1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ya,t.error_file=ya),t}a(j6,"generateClusteringUpgradeV4ServiceConfig");function X6(){let e={[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.RESTART_HDB};return mf.noBootFile()&&(e[pe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=mf.getEnvCliRootPath()),{...{name:pe.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:eU},script:K6}}a(X6,"generateRestart");function Z6(){return{apps:[rU()]}}a(Z6,"generateAllServiceConfigs");nU.exports={generateAllServiceConfigs:Z6,generateMainServerConfig:rU,generateRestart:X6,generateNatsHubServerConfig:Q6,generateNatsLeafServerConfig:J6,generateClusteringUpgradeV4ServiceConfig:j6}});var SU=g((Jhe,pU)=>{"use strict";var ve=P(),e9=z(),Ms=rg(),Sf=ut(),Ls=Ve(),gi=sU(),Tf=ee(),Ri=$(),t9=fn(),{startWorker:iU,onMessageFromWorkers:r9}=We(),n9=ga(),zhe=require("util"),s9=require("child_process"),i9=require("fs"),{execFile:o9}=s9,we;pU.exports={enterPM2Mode:a9,start:Ai,stop:ng,reload:aU,restart:cU,list:sg,describe:lU,connect:Ps,kill:d9,startAllServices:f9,startService:ig,getUniqueServicesList:_U,restartAllServices:E9,isServiceRegistered:dU,reloadStopStart:fU,restartHdb:uU,deleteProcess:l9,startClusteringProcesses:hU,startClusteringThreads:mU,isHdbRestartRunning:_9,isClusteringRunning:m9,stopClustering:h9,reloadClustering:p9};var $u=!1;r9(e=>{e.type==="restart"&&Tf.initSync(!0)});function a9(){$u=!0}a(a9,"enterPM2Mode");function Ps(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{Ri.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ps,"connect");var Nr,c9=10,oU;function Ai(e,t=!1){if($u)return u9(e);let r=o9(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Nr.indexOf(r);o>-1&&Nr.splice(o,1),!oU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<c9&&(i9.existsSync(Ms.getHubConfigPath())?Ai(e):(await Ms.generateNatsConfig(!0),Ai(e),await new Promise(c=>setTimeout(c,3e3)),await Ms.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ms.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Tf.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let f=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?Ri.OUTPUTS.STDERR:Ri.OUTPUTS.STDOUT;Ri.logCustomLevel(l||"info",f,n,i.slice(_,u.index).trim())}let[d,E]=u;_=u.index+d.length,l=Ls.LOG_LEVELS[E]}if(Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?Ri.OUTPUTS.STDERR:Ri.OUTPUTS.STDOUT;Ri.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Nr=[],!Nr&&!t){let i=a(()=>{oU=!0,Nr&&(Nr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}Nr.push(r)}a(Ai,"start");function u9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(u9,"startWithPM2");function ng(e){if(!$u){for(let t of Nr||[])t.name===e&&(Nr.splice(Nr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(ng,"stop");function aU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(aU,"reload");function cU(e){if(!$u)for(let t of Nr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(cU,"restart");function l9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(l9,"deleteProcess");async function uU(){await Ai(gi.generateRestart())}a(uU,"restartHdb");async function _9(){let e=await sg();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(_9,"isHdbRestartRunning");function sg(){return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(sg,"list");function lU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(lU,"describe");function d9(){if(!$u){for(let e of Nr||[])e.kill();Nr=[];return}return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(d9,"kill");async function f9(){try{await hU(),await mU(),await Ai(gi.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(f9,"startAllServices");async function ig(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=gi.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=gi.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=gi.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=gi.generateNatsHubServerConfig(),await Ai(r,t),await Ms.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=gi.generateNatsLeafServerConfig(),await Ai(r,t),await Ms.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=gi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ai(r)}catch(r){throw we?.disconnect(),r}}a(ig,"startService");async function _U(){try{let e=await sg(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(_U,"getUniqueServicesList");async function E9(e=[]){try{let t=!1,r=await _U();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await cU(o))}t&&await fU(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(E9,"restartAllServices");async function dU(e){if(Nr?.find(r=>r.name===e))return!0;let t=await n9.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(dU,"isServiceRegistered");async function fU(e){let t=Tf.get(ve.CONFIG_PARAMS.THREADS_COUNT)??Tf.get(ve.CONFIG_PARAMS.THREADS),r=await lU(e),n=e9.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await ng(e),await ig(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await uU():await aU(e)}a(fU,"reloadStopStart");var EU;async function hU(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await ig(r,e)}}a(hU,"startClusteringProcesses");async function mU(){EU=iU(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await Sf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await Sf.updateLocalStreams();let e=await t9.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){Ri.info("Starting clustering upgrade 4.0.0 process"),iU(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(mU,"startClusteringThreads");async function h9(){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 EU.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await ng(t)}}a(h9,"stopClustering");async function m9(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await dU(t)===!1)return!1}return!0}a(m9,"isClusteringRunning");async function p9(){await Ms.generateNatsConfig(!0),await Sf.reloadNATSHub(),await Sf.reloadNATSLeaf(),await Ms.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ms.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(p9,"reloadClustering")});var yU={};Fe(yU,{compactOnStart:()=>S9,copyDb:()=>bU});async function S9(){Ku.notify("Running compact on start"),console.log("Running compact on start");let e=(0,og.get)(Oi.CONFIG_PARAMS.ROOTPATH),t=new Map,r=mr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,gf.join)(e,"backup",n+".mdb"),o=(0,gf.join)(e,Oi.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await TU(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 bU(n,o),console.log("Backing up",n,"to",i),await(0,po.move)(s,i,{overwrite:!0})}Yu();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,gf.join)(e,Oi.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Yu()}catch(n){Ku.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,ag.updateConfigValue)(Oi.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 Yu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await TU(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
|
|
11
11
|
Total record count before compaction: ${i}, total after: ${c}.
|
|
12
|
-
Database backup has not been removed and can be found here: ${s}`;
|
|
13
|
-
${r.stack}`;throw dg.error(n),MU(new Error)}}}a(L9,"getRolePermissions");function M9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Ir.SYSTEM_SCHEMA_NAME]=n[Ir.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=P9(t[i]);return}r[i]=BU(),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],_=U9(c,u);r[i].describe||xU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=fg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=fg()})}),r}a(M9,"translateRolePermissions");function P9(e){let t=BU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=fg(!0,!0,!0,!0,!0)}),t}a(P9,"createStructureUserPermissions");function U9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,E=l;return Ir.TIME_STAMP_NAMES.includes(d)&&(E=UU(d,l[Ju])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=PU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=qU(l),s.attribute_permissions.push(l),c||v9(l,u)}else if(_!==o){let l;Ir.TIME_STAMP_NAMES.includes(_)?l=UU(_):l=PU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=vU(s),s}else return e.describe=vU(e),e}a(U9,"getTableAttrPerms");function vU(e){return xU.filter(t=>e[t]).length>0}a(vU,"getSchemaTableDescribePerm");function qU(e){return GU.filter(t=>e[t]).length>0}a(qU,"getAttributeDescribePerm");function v9(e,t){GU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(v9,"checkForHashPerms")});var VU={};Fe(VU,{Resources:()=>Nf,keyArrayToString:()=>Ia,resetResources:()=>B9,resources:()=>bi});function B9(){return bi=new Nf}function Ia(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Nf,bi,ju=Re(()=>{no();Nf=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(B9,"resetResources");a(Ia,"keyArrayToString")});var $U={};Fe($U,{Headers:()=>yi,appendHeader:()=>mg});function mg(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 yi,Xu=Re(()=>{yi=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(mg,"appendHeader")});var Zu={};Fe(Zu,{authentication:()=>XU,bypassAuth:()=>V9,login:()=>Y9,logout:()=>K9,start:()=>$9});function V9(){jU=!0}async function XU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?q9?G9:[]:x9?H9:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new yi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return If&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),If&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(If){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(f)){let S=p.indexOf(";");u=p.slice(f.length,S===-1?p.length:S),_=await KU.get(u);break}e.session=_||(_={})}let l=a((f,h,p)=>{let S=new wa.AuthAuditLog(f,h,xt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===xt.AUTH_AUDIT_STATUS.SUCCESS?YU.notify(S):YU.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await at.getUser(f,null,null),l(f,xt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,wa.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=To.get(n),!d){let f=n.indexOf(" "),h=n.slice(0,f),p=n.slice(f+1),S,T;try{switch(h){case"Basic":let R=atob(p),b=R.indexOf(":");S=R.slice(0,b),T=R.slice(b+1),d=S||T?await at.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,wf.validateOperationToken)(p)}catch(C){if(C.message==="invalid token")try{return await(0,wf.validateRefreshToken)(p),c({status:-1})}catch{throw C}}break}}catch(R){return k9&&(To.get(p)||(To.set(p,p),l(S,xt.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:go({error:R.message},e)})}To.set(n,d),F9&&l(d.username,xt.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await at.getUser(_.user,null,e):(jU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,QU.getSuperUser)());If&&(e.session.update=function(f){if(!u){u=(0,zU.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):E?.headers?.set&&E.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=u,KU.put(f)},e.login=async function(f,h){e.user=await at.getUser(f,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&bi.loginPath?(E.status=302,E.headers.set("Location",bi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new yi);for(let d=0;d<_;){let E=o[d++];l.set(E,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function $9({server:e,port:t}){e.http(XU,{port:t||"all"}),WU||(WU=!0,setInterval(()=>{To=new Map},En.get(xt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),JU.user.addListener(()=>{To=new Map}))}async function Y9(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function K9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var QU,wf,zU,En,xt,wa,JU,YU,H9,x9,G9,q9,KU,If,jU,F9,k9,To,WU,Cf=Re(()=>{QU=B(ln());lr();ju();wf=B(wu());Ae();zU=require("uuid"),En=B(Z()),xt=B(P()),wa=B($()),JU=B(Qc());Xu();Ca();YU=(0,wa.loggerWithTag)("auth-event");En.initSync();H9=En.get(xt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),x9=En.get(xt.CONFIG_PARAMS.HTTP_CORS),G9=En.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),q9=En.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),KU=Et({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),If=En.get(xt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,jU=En.get(xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,F9=En.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,k9=En.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,To=new Map;at.onInvalidatedUser(()=>{To=new Map});a(V9,"bypassAuth");a(XU,"authentication");a($9,"start");a(Y9,"login");a(K9,"logout")});var iv=g((hme,sv)=>{"use strict";var Ce=require("joi"),ZU=require("fs-extra"),ev=require("path"),vs=Xe(),tv=Z(),rv=P(),nv=$(),{hdb_errors:W9}=ne(),{HDB_ERROR_MSGS:ir}=W9,Us=/^[a-zA-Z0-9-_]+$/;sv.exports={getDropCustomFunctionValidator:z9,setCustomFunctionValidator:J9,addComponentValidator:e7,dropCustomFunctionProjectValidator:t7,packageComponentValidator:r7,deployComponentValidator:n7,setComponentFileValidator:j9,getComponentFileValidator:Z9,dropComponentFileValidator:X9};function Df(e,t,r){try{let n=tv.get(rv.CONFIG_PARAMS.COMPONENTSROOT),s=ev.join(n,t);return ZU.existsSync(s)?e?t:r.message(ir.PROJECT_EXISTS):e?r.message(ir.NO_PROJECT):t}catch(n){return nv.error(n),r.message(ir.VALIDATION_ERR)}}a(Df,"checkProjectExists");function el(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(el,"checkFilePath");function Q9(e,t,r,n){try{let s=tv.get(rv.CONFIG_PARAMS.COMPONENTSROOT),i=ev.join(s,e,t,r+".js");return ZU.existsSync(i)?r:n.message(ir.NO_FILE)}catch(s){return nv.error(s),n.message(ir.VALIDATION_ERR)}}a(Q9,"checkFileExists");function z9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().pattern(Us).custom(Q9.bind(null,e.project,e.type)).custom(el).required().messages({"string.pattern.base":ir.BAD_FILE_NAME})});return vs.validateBySchema(e,t)}a(z9,"getDropCustomFunctionValidator");function J9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().custom(el).required(),function_content:Ce.string().required()});return vs.validateBySchema(e,t)}a(J9,"setCustomFunctionValidator");function j9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(el).required(),payload:Ce.string().allow("").optional(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(j9,"setComponentFileValidator");function X9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(el).optional()});return vs.validateBySchema(e,t)}a(X9,"dropComponentFileValidator");function Z9(e){let t=Ce.object({project:Ce.string().required(),file:Ce.string().custom(el).required(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(Z9,"getComponentFileValidator");function e7(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!1)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(e7,"addComponentValidator");function t7(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(t7,"dropCustomFunctionProjectValidator");function r7(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),skip_node_modules:Ce.boolean()});return vs.validateBySchema(e,t)}a(r7,"packageComponentValidator");function n7(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),payload:Ce.string().optional().messages({"string.pattern.base":ir.BAD_PACKAGE}),package:Ce.string().optional()});return vs.validateBySchema(e,t)}a(n7,"deployComponentValidator")});var Uf=g((pme,dv)=>{"use strict";var Lf=require("joi"),Mf=require("path"),ov=require("fs-extra"),{exec:s7}=require("child_process"),i7=require("util"),av=i7.promisify(s7),tl=P(),{handleHDBError:Da,hdb_errors:o7}=ne(),{HTTP_STATUS_CODES:La}=o7,rl=Z(),a7=Xe(),Ma=$();rl.initSync();var pg=rl.get(tl.CONFIG_PARAMS.COMPONENTSROOT),cv="npm install --omit=dev --json",c7=`${cv} --dry-run`;dv.exports={installModules:d7,auditModules:f7,installAllRootModules:u7,uninstallRootModule:l7,linkHarperdb:_7};async function u7(e=!1){await Pf(),await nl(e?"npm install --ignore-scripts":"npm install",rl.get(tl.CONFIG_PARAMS.ROOTPATH))}a(u7,"installAllRootModules");async function l7(e){await nl(`npm uninstall ${e}`,rl.get(tl.CONFIG_PARAMS.ROOTPATH))}a(l7,"uninstallRootModule");async function _7(){await Pf(),await nl(`npm link ${tl.PACKAGE_ROOT}`,rl.get(tl.CONFIG_PARAMS.ROOTPATH))}a(_7,"linkHarperdb");async function nl(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await av(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
12
|
+
Database backup has not been removed and can be found here: ${s}`;Ku.error(u),console.error(u)}(0,og.get)(Oi.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,po.remove)(s))}(0,ag.updateConfigValue)(Oi.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function TU(e){let t=await(0,OU.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function bU(e,t){console.log("copyDb start");let r=mr()[e],n;for(let d in r){n=r[d].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,gU.open)(new RU.default(t)),c=o.openDB(Rf.INTERNAL_DBIS_NAME),u,_=0,l=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:l})){let p=h.is_hash_attribute||h.isPrimaryKey,S,T;if(p&&(S=h.compression,T=Of(),T?h.compression=T:delete h.compression,S?.dictionary?.toString()===T?.dictionary?.toString()&&(S=null,T=null)),c.put(f,h),!(p||h.indexed))continue;let R=new AU.default(!p,p);R.encoding="binary",R.compression=S;let N=n.openDB(f,R);N.decoder=null,R.compression=T;let I=o.openDB(f,R);I.encoder=null,console.log("copying",f,"from",e,"to",t),await E(N,I,p,l)}let d=n.openDB(Rf.AUDIT_STORE_NAME,Af);console.log("copying audit log"),E(i,d,!1,l);async function E(f,h,p,S){let T=0,R=0;for(let{key:N,value:I,version:H}of f.getRange({start:null,versions:p,transaction:S}))u=h.put(N,I,H),T++,S.openTimer&&(S.openTimer=0),R+=(N?.length||10)+I.length,_++>5e3&&(await u,console.log("copied",T,"entries",R,"bytes"),_=0);console.log("finish copying, copied",T,"entries",R,"bytes")}a(E,"copyDbi"),await u,console.log("copied database "+e+" to "+t)}finally{l.done(),o.close()}}var gU,gf,po,og,RU,AU,Rf,Oi,OU,ag,Ku,NU=Re(()=>{Ae();gU=require("lmdb"),gf=require("path"),po=require("fs-extra"),og=x(ee()),RU=x(vc()),AU=x(Uc()),Rf=x(ft()),Oi=x(P());ri();OU=x(Os()),ag=x(Er()),Ku=x($());a(S9,"compactOnStart");a(TU,"getTotalDBRecordCount");a(bU,"copyDb")});var Ju=g((nme,MU)=>{"use strict";var T9=require("minimist"),{isMainThread:lg,parentPort:cg,threadId:tme}=require("worker_threads"),nt=P(),{PROCESS_DESCRIPTORS_VALIDATE:Wu}=nt,os=$(),_g=z(),yf=rg(),bf=ut(),rme=Ve(),CU=Er(),as=SU(),IU=ga(),{compactOnStart:g9}=(NU(),ie(yU)),R9=xh(),{restartWorkers:Nf,onMessageByType:A9}=We(),{handleHDBError:O9,hdb_errors:b9}=se(),{HTTP_STATUS_CODES:y9}=b9,zu=ee();zu.initSync();var Qu=`Restarting HarperDB. This may take up to ${nt.RESTART_TIMEOUT_MS/1e3} seconds.`,N9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",wU="Clustering is not enabled so cannot be restarted",I9="Invalid service",Na,En;MU.exports={restart:DU,restartService:dg};lg&&A9(nt.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await dg({service:e.workerType}):DU({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function DU(e){En=Object.keys(e).length===0,Na=await as.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR);let t=T9(process.argv);if(t.service){await dg(t);return}if(En&&!Na){console.error(N9);return}if(En&&console.log(Qu),Na){as.enterPM2Mode(),os.notify(Qu);let r=R9(Object.keys(nt.CONFIG_PARAM_MAP),!0);return _g.isEmptyOrZeroLength(Object.keys(r))||CU.updateConfigValue(void 0,void 0,r,!0,!0),w9(),Qu}return lg?(os.notify(Qu),zu.get(nt.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await g9(),setTimeout(()=>{Nf()},50)):cg.postMessage({type:nt.ITC_EVENT_TYPES.RESTART}),Qu}a(DU,"restart");async function dg(e){let{service:t}=e;if(nt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw O9(new Error,I9,y9.BAD_REQUEST,void 0,void 0,!0);if(Na=await as.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR),!lg)return cg.postMessage({type:nt.ITC_EVENT_TYPES.RESTART,workerType:t}),new Promise(n=>{cg.on("message",s=>{s.type==="restart-complete"&&n()})});let r;switch(t){case Wu.clustering:if(!zu.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=wU;break}En&&console.log("Restarting clustering"),os.notify("Restarting clustering"),await LU();break;case Wu.clustering_config:case Wu["clustering config"]:if(!zu.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=wU;break}En&&console.log("Restarting clustering_config"),os.notify("Restarting clustering_config"),await as.reloadClustering();break;case"custom_functions":case"custom functions":case Wu.harperdb:case Wu.http_workers:if(En&&!Na){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}En&&console.log("Restarting http_workers"),os.notify("Restarting http_workers"),En?await as.restart(nt.HDB_PROC_DESCRIPTOR):await Nf("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(os.error(r),En&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(dg,"restartService");async function w9(){await LU(),await as.restart(nt.HDB_PROC_DESCRIPTOR),await _g.async_set_timeout(2e3),zu.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await ug(),En&&(await bf.closeConnection(),process.exit(0))}a(w9,"restartPM2Mode");async function LU(){if(!CU.getConfigFromFile(nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await IU.getHDBProcessInfo()).clustering.length===0)os.trace("Clustering not running, restart will start clustering services"),await yf.generateNatsConfig(!0),await as.startClusteringProcesses(),await as.startClusteringThreads(),await ug(),En&&await bf.closeConnection();else{await yf.generateNatsConfig(!0),Na?(os.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await as.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await as.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await IU.getHDBProcessInfo()).clustering.forEach(s=>{os.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await _g.async_set_timeout(3e3),await ug(),await bf.updateLocalStreams(),En&&await bf.closeConnection(),os.trace("Restart clustering restarting ingest and reply service threads");let t=Nf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Nf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(LU,"restartClustering");async function ug(){await yf.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await yf.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(ug,"removeNatsConfig")});var VU=g((ome,kU)=>{"use strict";var ime=require("lodash"),Ir=P(),{handleHDBError:PU,hdb_errors:C9}=se(),{HDB_ERROR_MSGS:D9,HTTP_STATUS_CODES:L9}=C9,fg=$();kU.exports={getRolePermissions:P9};var So=Object.create(null),M9=a(e=>({key:e,perms:{}}),"perms_template_obj"),xU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),HU=a((e=!1,t=!1,r=!1,n=!1)=>({[Ir.PERMS_CRUD_ENUM.READ]:e,[Ir.PERMS_CRUD_ENUM.INSERT]:t,[Ir.PERMS_CRUD_ENUM.UPDATE]:r,[Ir.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),Eg=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...HU(t,r,n,s)}),"table_perms_template"),UU=a((e,t=HU())=>({attribute_name:e,describe:FU(t),[ju]:t[ju],[hg]:t[hg],[mg]:t[mg]}),"attr_perms_template"),vU=a((e,t=!1)=>({attribute_name:e,describe:t,[ju]:t}),"timestamp_attr_perms_template"),{READ:ju,INSERT:hg,UPDATE:mg}=Ir.PERMS_CRUD_ENUM,GU=Object.values(Ir.PERMS_CRUD_ENUM),qU=[ju,hg,mg];function P9(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[Ir.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(So[t]&&So[t].key===n)return So[t].perms;let s=U9(e,r);return So[t]?So[t].key=n:So[t]=M9(n),So[t].perms=s,s}catch(r){if(!e[Ir.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Ir.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Ir.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw fg.error(n),fg.debug(r),PU(new Error,D9.OUTDATED_PERMS_TRANSLATION_ERROR,L9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
13
|
+
${r.stack}`;throw fg.error(n),PU(new Error)}}}a(P9,"getRolePermissions");function U9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Ir.SYSTEM_SCHEMA_NAME]=n[Ir.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=v9(t[i]);return}r[i]=xU(),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],_=B9(c,u);r[i].describe||GU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=Eg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=Eg()})}),r}a(U9,"translateRolePermissions");function v9(e){let t=xU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=Eg(!0,!0,!0,!0,!0)}),t}a(v9,"createStructureUserPermissions");function B9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,E=l;return Ir.TIME_STAMP_NAMES.includes(d)&&(E=vU(d,l[ju])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=UU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=FU(l),s.attribute_permissions.push(l),c||x9(l,u)}else if(_!==o){let l;Ir.TIME_STAMP_NAMES.includes(_)?l=vU(_):l=UU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=BU(s),s}else return e.describe=BU(e),e}a(B9,"getTableAttrPerms");function BU(e){return GU.filter(t=>e[t]).length>0}a(BU,"getSchemaTableDescribePerm");function FU(e){return qU.filter(t=>e[t]).length>0}a(FU,"getAttributeDescribePerm");function x9(e,t){qU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(x9,"checkForHashPerms")});var $U={};Fe($U,{Resources:()=>If,keyArrayToString:()=>Ia,resetResources:()=>H9,resources:()=>bi});function H9(){return bi=new If}function Ia(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var If,bi,Xu=Re(()=>{no();If=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&&c.indexOf(".")>-1){let _=c.split(".");u=this.get(_[0])}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&&o.indexOf(".")>-1&&(s=this.get(o.split(".")[0])),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(H9,"resetResources");a(Ia,"keyArrayToString")});var YU={};Fe(YU,{Headers:()=>yi,appendHeader:()=>pg});function pg(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 yi,Zu=Re(()=>{yi=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(pg,"appendHeader")});var el={};Fe(el,{authentication:()=>ZU,bypassAuth:()=>Y9,login:()=>W9,logout:()=>Q9,start:()=>K9});function Y9(){XU=!0}async function ZU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?k9?F9:[]:q9?G9:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new yi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return wf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),wf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(wf){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(f)){let S=p.indexOf(";");u=p.slice(f.length,S===-1?p.length:S),_=await WU.get(u);break}e.session=_||(_={})}let l=a((f,h,p)=>{let S=new wa.AuthAuditLog(f,h,Ht.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Ht.AUTH_AUDIT_STATUS.SUCCESS?KU.notify(S):KU.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await at.getUser(f,null,null),l(f,Ht.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,wa.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=To.get(n),!d){let f=n.indexOf(" "),h=n.slice(0,f),p=n.slice(f+1),S,T;try{switch(h){case"Basic":let R=atob(p),N=R.indexOf(":");S=R.slice(0,N),T=R.slice(N+1),d=S||T?await at.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,Cf.validateOperationToken)(p)}catch(I){if(I.message==="invalid token")try{return await(0,Cf.validateRefreshToken)(p),c({status:-1})}catch{throw I}}break}}catch(R){return $9&&(To.get(p)||(To.set(p,p),l(S,Ht.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:go({error:R.message},e)})}To.set(n,d),V9&&l(d.username,Ht.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await at.getUser(_.user,null,e):(XU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,zU.getSuperUser)());wf&&(e.session.update=function(f){if(!u){u=(0,JU.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):E?.headers?.set&&E.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=u,WU.put(f)},e.login=async function(f,h){e.user=await at.getUser(f,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&bi.loginPath?(E.status=302,E.headers.set("Location",bi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new yi);for(let d=0;d<_;){let E=o[d++];l.set(E,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function K9({server:e,port:t}){e.http(ZU,{port:t||"all"}),QU||(QU=!0,setInterval(()=>{To=new Map},hn.get(Ht.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),jU.user.addListener(()=>{To=new Map}))}async function W9(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 Q9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var zU,Cf,JU,hn,Ht,wa,jU,KU,G9,q9,F9,k9,WU,wf,XU,V9,$9,To,QU,Df=Re(()=>{zU=x(_n());lr();Xu();Cf=x(Cu());Ae();JU=require("uuid"),hn=x(ee()),Ht=x(P()),wa=x($()),jU=x(zc());Zu();Ca();KU=(0,wa.loggerWithTag)("auth-event");hn.initSync();G9=hn.get(Ht.CONFIG_PARAMS.HTTP_CORSACCESSLIST),q9=hn.get(Ht.CONFIG_PARAMS.HTTP_CORS),F9=hn.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),k9=hn.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),WU=Et({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),wf=hn.get(Ht.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,XU=hn.get(Ht.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,V9=hn.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,$9=hn.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,To=new Map;at.onInvalidatedUser(()=>{To=new Map});a(Y9,"bypassAuth");a(ZU,"authentication");a(K9,"start");a(W9,"login");a(Q9,"logout")});var ov=g((pme,iv)=>{"use strict";var Ce=require("joi"),ev=require("fs-extra"),tv=require("path"),vs=Xe(),rv=ee(),nv=P(),sv=$(),{hdb_errors:z9}=se(),{HDB_ERROR_MSGS:ir}=z9,Us=/^[a-zA-Z0-9-_]+$/;iv.exports={getDropCustomFunctionValidator:j9,setCustomFunctionValidator:X9,addComponentValidator:r7,dropCustomFunctionProjectValidator:n7,packageComponentValidator:s7,deployComponentValidator:i7,setComponentFileValidator:Z9,getComponentFileValidator:t7,dropComponentFileValidator:e7};function Lf(e,t,r){try{let n=rv.get(nv.CONFIG_PARAMS.COMPONENTSROOT),s=tv.join(n,t);return ev.existsSync(s)?e?t:r.message(ir.PROJECT_EXISTS):e?r.message(ir.NO_PROJECT):t}catch(n){return sv.error(n),r.message(ir.VALIDATION_ERR)}}a(Lf,"checkProjectExists");function tl(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(tl,"checkFilePath");function J9(e,t,r,n){try{let s=rv.get(nv.CONFIG_PARAMS.COMPONENTSROOT),i=tv.join(s,e,t,r+".js");return ev.existsSync(i)?r:n.message(ir.NO_FILE)}catch(s){return sv.error(s),n.message(ir.VALIDATION_ERR)}}a(J9,"checkFileExists");function j9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Lf.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().pattern(Us).custom(J9.bind(null,e.project,e.type)).custom(tl).required().messages({"string.pattern.base":ir.BAD_FILE_NAME})});return vs.validateBySchema(e,t)}a(j9,"getDropCustomFunctionValidator");function X9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Lf.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().custom(tl).required(),function_content:Ce.string().required()});return vs.validateBySchema(e,t)}a(X9,"setCustomFunctionValidator");function Z9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(tl).required(),payload:Ce.string().allow("").optional(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(Z9,"setComponentFileValidator");function e7(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(tl).optional()});return vs.validateBySchema(e,t)}a(e7,"dropComponentFileValidator");function t7(e){let t=Ce.object({project:Ce.string().required(),file:Ce.string().custom(tl).required(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(t7,"getComponentFileValidator");function r7(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Lf.bind(null,!1)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(r7,"addComponentValidator");function n7(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Lf.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(n7,"dropCustomFunctionProjectValidator");function s7(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),skip_node_modules:Ce.boolean()});return vs.validateBySchema(e,t)}a(s7,"packageComponentValidator");function i7(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),payload:Ce.string().optional().messages({"string.pattern.base":ir.BAD_PACKAGE}),package:Ce.string().optional()});return vs.validateBySchema(e,t)}a(i7,"deployComponentValidator")});var vf=g((Tme,fv)=>{"use strict";var Mf=require("joi"),Pf=require("path"),av=require("fs-extra"),{exec:o7}=require("child_process"),a7=require("util"),cv=a7.promisify(o7),rl=P(),{handleHDBError:Da,hdb_errors:c7}=se(),{HTTP_STATUS_CODES:La}=c7,nl=ee(),u7=Xe(),Ma=$();nl.initSync();var Sg=nl.get(rl.CONFIG_PARAMS.COMPONENTSROOT),uv="npm install --omit=dev --json",l7=`${uv} --dry-run`;fv.exports={installModules:E7,auditModules:h7,installAllRootModules:_7,uninstallRootModule:d7,linkHarperdb:f7};async function _7(e=!1){await Uf(),await sl(e?"npm install --ignore-scripts":"npm install",nl.get(rl.CONFIG_PARAMS.ROOTPATH))}a(_7,"installAllRootModules");async function d7(e){await sl(`npm uninstall ${e}`,nl.get(rl.CONFIG_PARAMS.ROOTPATH))}a(d7,"uninstallRootModule");async function f7(){await Uf(),await sl(`npm link ${rl.PACKAGE_ROOT}`,nl.get(rl.CONFIG_PARAMS.ROOTPATH))}a(f7,"linkHarperdb");async function sl(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await cv(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
14
14
|
`,""))}return n&&!n.includes("Debugger listening")&&Ma.error("Error running NPM command:",e,n),Ma.trace(r,n),r?.replace(`
|
|
15
|
-
`,"")}a(
|
|
15
|
+
`,"")}a(sl,"runCommand");async function E7(e){Ma.info(`starting installModules for request: ${e}`);let t=dv(e);if(t)throw Da(t,t.message,La.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?l7:uv;await Uf(),await _v(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 _=Pf.join(Sg,u),l,d=null;try{let{stdout:E,stderr:f}=await cv(s,{cwd:_});l=E?E.replace(`
|
|
16
16
|
`,""):null,d=f?f.replace(`
|
|
17
|
-
`,""):null}catch(E){E.stderr?i[u].npm_error=
|
|
18
|
-
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(uv,"parseNPMStdErr");async function f7(e){Ma.info(`starting auditModules for request: ${e}`);let t=_v(e);if(t)throw Da(t,t.message,La.BAD_REQUEST);let{projects:r}=e;await Pf(),await lv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Mf.join(pg,o);n[o]={npm_output:null,npm_error:null};try{let u=await nl("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=uv(u.stderr)}}return Ma.info(`finished auditModules with response ${n}`),n}a(f7,"auditModules");async function Pf(){try{return await nl("npm -v"),!0}catch{throw Da(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",La.BAD_REQUEST,void 0,void 0,!0)}}a(Pf,"checkNPMInstalled");async function lv(e){if(!Array.isArray(e)||e.length===0)throw Da(new Error,"projects argument must be an array with at least 1 element",La.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Mf.join(pg,i.toString());if(!await ov.pathExists(o)){t.push(i);continue}let u=Mf.join(o,"package.json");await ov.pathExists(u)||r.push(i)}if(t.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,La.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,La.BAD_REQUEST,void 0,void 0,!0)}a(lv,"checkProjectPaths");function _v(e){let t=Lf.object({projects:Lf.array().min(1).items(Lf.string()).required(),dry_run:Lf.boolean().default(!1)});return a7.validateBySchema(e,t)}a(_v,"modulesValidator")});var Tg=g((Tme,pv)=>{"use strict";var Pa=require("fs-extra"),Sg=require("path"),vf=$(),fv=z(),Bf=P(),mv=Z(),E7=Er();pv.exports=h7;async function h7(){let e=m7(),t=mv.get(Bf.CONFIG_PARAMS.ROOTPATH),r=Sg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Bf.PACKAGE_ROOT}},s=Sg.join(t,"node_modules");await Pa.ensureDir(s);let i,o=!0,c=!1;try{i=await Pa.readJson(r)}catch(u){if(fv.isEmptyOrZeroLength(e))return;if(u.code!==Bf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!fv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await Ev(_);n.dependencies[u]=l+_}if(!o){vf.notify("Installing components"),await hv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await Ev(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(vf.notify("Removing component",u),c=!0);c&&(vf.notify("Updating components."),await hv(r,n,i))}a(h7,"installComponents");function m7(){let e=E7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(m7,"getComponentsConfig");async function Ev(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":Sg.extname(e)||await Pa.pathExists(e)?"file:":"github:"}a(Ev,"getPkgPrefix");async function hv(e,t,r){vf.trace("npm installing components package.json",t),await Pa.writeFile(e,JSON.stringify(t,null," "));try{await Uf().installAllRootModules(mv.get(Bf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Pa.writeFile(e,JSON.stringify(r,null," ")):await Pa.unlink(e),n}}a(hv,"installPackages")});var Ag=g((Ame,Rv)=>{"use strict";var $e=require("fs-extra"),gg=require("fast-glob"),Te=require("path"),Tv=require("tar-fs"),Rme=require("uuid").v4,Rg=require("normalize-path"),cs=iv(),Ct=$(),ze=P(),Ot=Z(),sl=Er(),p7=z(),{PACKAGE_ROOT:S7}=P(),{handleHDBError:Gt,hdb_errors:T7}=ne(),{basename:g7}=require("path"),R7=Tg(),gv=Z(),A7=P(),{Readable:O7}=require("stream"),{isMainThread:b7}=require("worker_threads"),{HDB_ERROR_MSGS:Ro,HTTP_STATUS_CODES:qt}=T7,y7=Te.join(S7,"application-template"),Sv=Te.join(Ot.get(ze.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function N7(){Ct.trace("getting custom api status");let e={};try{e={port:Ot.get(ze.CONFIG_PARAMS.HTTP_PORT),directory:Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Gt(new Error,Ro.FUNCTION_STATUS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,t)}return e}a(N7,"customFunctionsStatus");function I7(){Ct.trace("getting custom api endpoints");let e={},t=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT);try{gg.sync(Rg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:gg.sync(Rg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:gg.sync(Rg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Gt(new Error,Ro.GET_FUNCTIONS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,r)}return e}a(I7,"getCustomFunctions");function w7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("getting custom api endpoint file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return $e.readFileSync(o,{encoding:"utf8"})}catch(c){throw Gt(new Error,Ro.GET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(w7,"getCustomFunction");function C7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.setCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("setting custom function file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return $e.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Gt(new Error,Ro.SET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(C7,"setCustomFunction");function D7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function file");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return $e.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Gt(new Error,Ro.DROP_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,o)}}a(D7,"dropCustomFunction");function L7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.addComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("adding component");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return $e.mkdirSync(s,{recursive:!0}),$e.copySync(y7,s),`Successfully added project: ${n}`}catch(s){throw Gt(new Error,Ro.ADD_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,s)}}a(L7,"addComponent");function M7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.dropCustomFunctionProjectValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function project");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Ot.get(ze.CONFIG_PARAMS.APPS);if(!p7.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 sl.updateConfigValue(ze.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return $e.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Gt(new Error,Ro.DROP_FUNCTION_PROJECT,qt.INTERNAL_SERVER_ERROR,Ct.ERR,i)}}a(M7,"dropCustomFunctionProject");async function P7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.packageComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ct.trace("packaging component",n);let s;try{s=await $e.realpath(Te.join(r,n))}catch(u){if(u.code!==ze.NODE_ERROR_CODES.ENOENT)throw u;try{s=await $e.realpath(Te.join(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===ze.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await $e.ensureDir(Sv);let i=Te.join(Sv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),Tv.pack(s,o).pipe($e.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=$e.readFileSync(i,{encoding:"base64"});return await $e.remove(i),{project:n,payload:c}}a(P7,"packageComponent");async function U7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.deployComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Ct.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await $e.emptyDir(o);let E=O7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(Tv.extract(o,{finish:h})).on("error",p)});let f=await $e.readdir(o);f.length===1&&f[0]==="package"&&(await $e.copy(Te.join(o,"package"),o),await $e.remove(Te.join(o,"package")))}if(await sl.addConfig(n,{package:i}),!s){await R7();let E=gv.get(A7.CONFIG_PARAMS.ROOTPATH);o=Te.join(E,"node_modules",n)}if(b7)return;let c=new Map;c.isWorker=!0;let u=(xf(),ie(Hf)),_;u.setErrorReporter(E=>_=E);let l=g7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Ct.info("Installed component"),`Successfully deployed: ${n}`}a(U7,"deployComponent");async function v7(){let e=sl.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await $e.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Te.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let E={name:l,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await $e.stat(d),f={name:Te.basename(l),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(u){return Ct.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{name:Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(xf(),ie(Hf)).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(v7,"getComponents");async function B7(e){let t=cs.getComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let n=sl.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(gv.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules"):Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await $e.stat(Te.join(n,e.project,e.file));return{message:await $e.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===ze.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(B7,"getComponentFile");async function H7(e){let t=cs.setComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await $e.ensureFile(n),await $e.outputFile(n,e.payload,r)):await $e.ensureDir(n),"Successfully set component: "+e.file}a(H7,"setComponentFile");async function x7(e){let t=cs.dropComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),r);return await $e.pathExists(n)&&await $e.remove(n),sl.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(x7,"dropComponent");Rv.exports={customFunctionsStatus:N7,getCustomFunctions:I7,getCustomFunction:w7,setCustomFunction:C7,dropCustomFunction:D7,addComponent:L7,dropCustomFunctionProject:M7,packageComponent:P7,deployComponent:U7,getComponents:v7,getComponentFile:B7,setComponentFile:H7,dropComponent:x7}});var Og=g((bme,Ov)=>{"use strict";var us=require("joi"),Av=Xe();Ov.exports={readTransactionLogValidator:G7,deleteTransactionLogsBeforeValidator:q7};function G7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),from:us.date().timestamp(),to:us.date().timestamp(),limit:us.number().min(1)});return Av.validateBySchema(e,t)}a(G7,"readTransactionLogValidator");function q7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),timestamp:us.date().timestamp().required()});return Av.validateBySchema(e,t)}a(q7,"deleteTransactionLogsBeforeValidator")});var Gf=g((Nme,wv)=>{"use strict";var bg=P(),il=ut(),bv=z(),yv=Z(),Nv=As(),{handleHDBError:Ua,hdb_errors:F7}=ne(),{HTTP_STATUS_CODES:va}=F7,{readTransactionLogValidator:k7,deleteTransactionLogsBeforeValidator:V7}=Og(),Iv="This operation relies on clustering and cannot run with it disable.",$7="Logs successfully deleted from transaction log.",Y7="All logs successfully deleted from transaction log.";wv.exports={readTransactionLog:K7,deleteTransactionLogsBefore:W7};async function*K7(e){let t=k7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!yv.get(bg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,Iv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=bv.checkSchemaTableExist(r,n);if(s)throw Ua(new Error,s,va.NOT_FOUND,void 0,void 0,!0);let i=Nv.createNatsTableStreamName(r,n),o=await il.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===bg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(K7,"readTransactionLog");async function W7(e){let t=V7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!yv.get(bg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,Iv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=bv.checkSchemaTableExist(r,n);if(i)throw Ua(new Error,i,va.NOT_FOUND,void 0,void 0,!0);let o=Nv.createNatsTableStreamName(r,n),{jsm:c}=await il.getNATSReferences(),u=await il.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=$7,d,E=new Date(u.state.last_ts).getTime();return s>E?(d=u.state.last_seq+1,l=Y7):d=(await il.viewStream(o,parseInt(s),1))[0].nats_sequence,await il.purgeTableStream(r,n,{seq:d}),l}a(W7,"deleteTransactionLogsBefore")});var Dv=g((wme,Cv)=>{"use strict";var yg=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}};Cv.exports=yg});var Mv=g((Dme,Lv)=>{"use strict";var Ng=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Lv.exports=Ng});var wg=g((Mme,Uv)=>{"use strict";var Pv=Dv(),Q7=Mv(),{HDB_ERROR_MSGS:z7}=Ur(),Ig=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=z7.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 Pv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new Q7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Pv(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}};Uv.exports=Ig});var Vf=g((Ume,Jv)=>{"use strict";var Cg=qr(),qf=Gr(),mn=Au(),cl=Os(),Dg=ai(),J7=FS(),j7=HL(),ul=ln(),Ff=JS(),Dt=$(),X7=ZS(),Z7=rf(),eee=MT(),tee=sf(),ree=UT(),nee=vT(),see=xT(),iee=qT(),Lg=VT(),Bs=z(),oee=vP(),Mg=QT(),Hv=zu(),hn=P(),xv=kU(),aee=ga(),Gv=wu(),qv=(Cf(),ie(Zu)),Fv=Er(),Jr=Ag(),cee=require("alasql"),kv=Gf(),Vv=Uf(),$v=wg(),{handleHDBError:wr,hdb_errors:Yv}=ne(),{HDB_ERROR_MSGS:Wt,HTTP_STATUS_CODES:ol}=Yv,V=new Map,Kv="delete",Ni="insert",Hs="read",Ao="update",al="describe",vv=cl.describeSchema.name,Bv=cl.describeTable.name,Wv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},uee="catchup",lee="handleGetJob",_ee="handleGetJobsByStartDate",kf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},dee=[mn.createTable.name,mn.createAttribute.name,mn.dropTable.name,mn.dropAttribute.name],Qv={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(Cg.insert.name,new W(!1,[Ni]));V.set(Cg.update.name,new W(!1,[Ao]));V.set(Cg.upsert.name,new W(!1,[Ni,Ao]));V.set(qf.searchByConditions.name,new W(!1,[Hs]));V.set(qf.searchByHash.name,new W(!1,[Hs]));V.set(qf.searchByValue.name,new W(!1,[Hs]));V.set(qf.search.name,new W(!1,[Hs]));V.set(mn.createSchema.name,new W(!0,[]));V.set(mn.createTable.name,new W(!0,[]));V.set(mn.createAttribute.name,new W(!1,[Ni]));V.set(mn.dropSchema.name,new W(!0,[]));V.set(mn.dropTable.name,new W(!0,[]));V.set(mn.dropAttribute.name,new W(!0,[]));V.set(cl.describeSchema.name,new W(!1,[Hs]));V.set(cl.describeTable.name,new W(!1,[Hs]));V.set(Dg.deleteRecord.name,new W(!1,[Kv]));V.set(ul.addUser.name,new W(!0,[]));V.set(ul.alterUser.name,new W(!0,[]));V.set(ul.dropUser.name,new W(!0,[]));V.set(ul.listUsersExternal.name,new W(!0,[]));V.set(Ff.listRoles.name,new W(!0,[]));V.set(Ff.addRole.name,new W(!0,[]));V.set(Ff.alterRole.name,new W(!0,[]));V.set(Ff.dropRole.name,new W(!0,[]));V.set(X7.name,new W(!0,[]));V.set(Z7.name,new W(!0,[]));V.set(eee.name,new W(!0,[]));V.set(tee.name,new W(!0,[]));V.set(ree.name,new W(!0,[]));V.set(nee.name,new W(!0,[]));V.set(Lg.setRoutes.name,new W(!0,[]));V.set(Lg.getRoutes.name,new W(!0,[]));V.set(Lg.deleteRoutes.name,new W(!0,[]));V.set(Fv.setConfiguration.name,new W(!0,[]));V.set(see.clusterStatus.name,new W(!0,[]));V.set(iee.name,new W(!0,[]));V.set(Mg.getFingerprint.name,new W(!0,[]));V.set(Mg.setLicense.name,new W(!0,[]));V.set(Dg.deleteFilesBefore.name,new W(!0,[]));V.set(Dg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Hv.restart.name,new W(!0,[]));V.set(Hv.restartService.name,new W(!0,[]));V.set(J7.name,new W(!0,[]));V.set(j7.name,new W(!0,[Hs]));V.set(aee.systemInformation.name,new W(!0,[]));V.set(Fv.getConfiguration.name,new W(!0,[]));V.set(kv.readTransactionLog.name,new W(!0,[]));V.set(kv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Vv.installModules.name,new W(!0,[]));V.set(Vv.auditModules.name,new W(!0,[]));V.set(Gv.createTokens.name,new W(!1,[]));V.set(Gv.refreshOperationToken.name,new W(!1,[]));V.set(qv.login.name,new W(!1,[]));V.set(qv.logout.name,new W(!1,[]));V.set(Jr.customFunctionsStatus.name,new W(!0,[]));V.set(Jr.getCustomFunctions.name,new W(!0,[]));V.set(Jr.getComponents.name,new W(!0,[]));V.set(Jr.getComponentFile.name,new W(!0,[]));V.set(Jr.setComponentFile.name,new W(!0,[]));V.set(Jr.dropComponent.name,new W(!0,[]));V.set(Jr.getCustomFunction.name,new W(!0,[]));V.set(Jr.setCustomFunction.name,new W(!0,[]));V.set(Jr.dropCustomFunction.name,new W(!0,[]));V.set(Jr.addComponent.name,new W(!0,[]));V.set(Jr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Jr.packageComponent.name,new W(!0,[]));V.set(Jr.deployComponent.name,new W(!0,[]));V.set(Mg.getRegistrationInfo.name,new W(!1,[]));V.set(ul.userInfo.name,new W(!1,[]));V.set(cl.describeAll.name,new W(!1,[]));V.set(lee,new W(!1,[]));V.set(_ee,new W(!0,[]));V.set(uee,new W(!0,[]));V.set(kf.CSV_DATA_LOAD,new W(!1,[Ni,Ao]));V.set(kf.CSV_URL_LOAD,new W(!1,[Ni,Ao]));V.set(kf.CSV_FILE_LOAD,new W(!1,[Ni,Ao]));V.set(kf.IMPORT_FROM_S3,new W(!1,[Ni,Ao]));V.set(Qv.EXPORT_TO_S3,new W(!0,[]));V.set(Qv.EXPORT_LOCAL,new W(!0,[]));V.set(hn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Kv]));V.set(hn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Hs]));V.set(hn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Ni]));V.set(hn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ao]));Jv.exports={verifyPerms:Eee,verifyPermsAst:fee,verifyBulkLoadAttributePerms:mee};function fee(e,t,r){if(Bs.isEmptyOrZeroLength(e))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(t))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(r))throw Dt.info("verify_perms_ast has a null operation parameter"),wr(new Error);try{let n=new $v,s=new oee(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Dt.info("No schemas defined in verifyPermsAst(), will not continue."),wr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Wv[r])throw wr(new Error,Wt.DROP_SYSTEM,ol.FORBIDDEN);if(c&&!u)return null;let _=xv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof cee.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let E=s.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let l=zv(t,r,o,n);return l||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=Ug(t.role.permission,E,d[f]);Pg(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw wr(n)}}a(fee,"verifyPermsAst");function Eee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Dt.info("null required parameter in verifyPerms"),wr(new Error,Wt.DEFAULT_INVALID_REQUEST,ol.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 $v;if(Bs.isEmptyOrZeroLength(e.hdb_user.role)||Bs.isEmptyOrZeroLength(e.hdb_user.role.permission))return Dt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Wt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(hn.SYSTEM_SCHEMA_NAME)||s===hn.SYSTEM_SCHEMA_NAME;if(l&&Wv[r])throw wr(new Error,Wt.DROP_SYSTEM,ol.FORBIDDEN);if(u&&!l||_===!0&&(r===mn.createSchema.name||r===mn.dropSchema.name))return null;if(dee.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=xv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===vv||r===Bv){if(s===hn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Wt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===vv&&(!d[s]||!d[s][al]))return c.handleInvalidItem(Wt.SCHEMA_NOT_FOUND(s));if(r===Bv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][al]))return c.handleInvalidItem(Wt.TABLE_NOT_FOUND(s,i))}}let E=zv(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&hn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[hn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[hn.PERMS_CRUD_ENUM.READ]).forEach(R=>{p.push(R.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let f=hee(e),h=Ug(e.hdb_user.role.permission,s,i);return Pg(f,h,r,i,s,c,n),c.getPermsResponse()}a(Eee,"verifyPerms");function zv(e,t,r,n,s){if(Bs.arrayHasEmptyValues([e,t,r]))throw Dt.info("hasPermissions has an invalid parameter"),wr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw Dt.info(`operation ${t} not found.`),wr(new Error,Wt.OP_NOT_FOUND(t),ol.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Dt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Wt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][al]===!1){n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[al]===!1)n.addInvalidItem(Wt.TABLE_NOT_FOUND(u,l));else try{let E=[],f=V.get(t).perms;!Bs.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let p=f[h],S=d[p];(S==null||S===!1)&&(Dt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(u,l,E)}catch(E){let f=Wt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Dt.error(f),Dt.error(E),wr(Yv.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(zv,"hasPermissions");function Pg(e,t,r,n,s,i,o){if(!e||!t)throw Dt.info("no attributes specified in checkAttributePerms."),wr(new Error);let c=V.get(r).perms;if(!c||c==="")throw Dt.info(`no permissions found for ${r} in checkAttributePerms().`),wr(new Error);if(Bs.isEmptyOrZeroLength(t))return Dt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[al]===!1){i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let E of c){if(hn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Hs)throw wr(new Error,Wt.SYSTEM_TIMESTAMP_PERMS_ERR,ol.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Pg,"checkAttributePerms");function hee(e){let t=new Set;try{if(e.action)return t;if(e.operation===hn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Dt.info(r)}return t}a(hee,"getRecordAttributes");function Ug(e,t,r){let n=new Map;if(Bs.isEmpty(e))return Dt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Dt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Ug,"getAttributePermissions");function mee(e,t,r,n,s,i,o){let c=new Set(i),u=Ug(e,n,s);Pg(c,u,t,s,n,o,r)}a(mee,"verifyBulkLoadAttributePerms")});var Yf=g((Bme,t0)=>{"use strict";t0.exports={evaluateSQL:Cee,processAST:e0,convertSQLToAST:Zv,checkASTPermissions:Xv};var pee=qr(),jv=require("util"),See=jv.callbackify(pee.insert),Tee=Gr().search,gee=AD().update,Ree=jv.callbackify(gee),Aee=bD().convertDelete,Ii=require("alasql"),Oee=Vf(),$f=$(),bee=gd(),yee=z(),ll=P(),{hdb_errors:Nee,handleHDBError:vg}=ne(),{HTTP_STATUS_CODES:Bg}=Nee;bee(Ii);var Iee=403,wee="There was a problem performing this insert. Please check the logs and try again.",Hg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Cee(e,t){let r=e.parsed_sql_object;if(!r){r=Zv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ii.yy.Insert?n=s.into.databaseid:s instanceof Ii.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ii.yy.Update||s instanceof Ii.yy.Delete?n=s.table.databaseid:$f.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ii.yy.Select)&&yee.isEmptyOrZeroLength(n))return t("No schema specified",null)}e0(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Cee,"evaluateSQL");function Xv(e,t){let r;try{r=Oee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Xv,"checkASTPermissions");function Zv(e){let t=new Hg;if(!e)throw vg(new Error,"The 'sql' parameter is missing from the request body",Bg.BAD_REQUEST);try{let r=e.trim(),n=Ii.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
-
`);throw n[1]?vg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Bg.BAD_REQUEST):vg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Bg.BAD_REQUEST)}return t}a(Zv,"convertSQLToAST");function e0(e,t,r){try{let n=Dee;if(!e.bypass_auth&&!t.permissions_checked){let i=Xv(e,t);if(i&&i.length>0)return r(Iee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ll.VALID_SQL_OPS_ENUM.SELECT:n=Tee,s=t.ast.statements[0];break;case ll.VALID_SQL_OPS_ENUM.INSERT:n=Lee;break;case ll.VALID_SQL_OPS_ENUM.UPDATE:n=Ree;break;case ll.VALID_SQL_OPS_ENUM.DELETE:n=Aee;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(e0,"processAST");function Dee(e,t){$f.info(e),t("unknown sql statement")}a(Dee,"nullFunction");function Lee({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=Mee(i,e.values)}catch(o){return r(o)}See(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){$f.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Lee,"convertInsert");function Mee(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]]=Ii.compile(`SELECT ${s.toString()} AS [${ll.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw $f.error(r),new Error(wee)}}a(Mee,"createDataObjects")});var xg=g((xme,n0)=>{"use strict";var{S3:Pee,GetObjectCommand:Uee}=require("@aws-sdk/client-s3");n0.exports={getFileStreamFromS3:vee,getS3AuthObj:r0};async function vee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await r0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Uee(r))).Body}a(vee,"getFileStreamFromS3");function r0(e,t,r){return new Pee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(r0,"getS3AuthObj")});var Kf=g((qme,d0)=>{"use strict";var qg=Gr(),Bee=Yf(),Hee=xg(),{AsyncParser:xee,Transform:Gee}=require("json2csv"),dl=require("stream"),jr=z(),Gg=require("fs-extra"),qee=require("path"),pn=$(),{promisify:o0}=require("util"),_l=z(),{handleHDBError:bt,hdb_errors:Fee}=ne(),{HDB_ERROR_MSGS:Cr,HTTP_STATUS_CODES:yt}=Fee,{streamAsJSON:kee}=(nm(),ie(Pb)),{Upload:Vee}=require("@aws-sdk/lib-storage"),s0=["search_by_value","search_by_hash","sql","search_by_conditions"],i0=["json","csv"],a0="json",c0="csv",$ee="Successfully exported JSON locally.",Yee="Successfully exported CSV locally.",Kee=1e3,Wee=qg.searchByHash,Qee=qg.searchByValue,zee=o0(Bee.evaluateSQL),Jee=o0(dl.finished);d0.exports={export_to_s3:ete,export_local:jee,toCsvStream:u0};async function jee(e){pn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=l0(e);if(!jr.isEmpty(t))throw pn.error(t),bt(new Error,t,yt.BAD_REQUEST,void 0,void 0,!0);if(jr.isEmpty(e.path))throw pn.error(Cr.MISSING_VALUE("path")),bt(new Error,Cr.MISSING_VALUE("path"),yt.BAD_REQUEST,void 0,void 0,!0);let r=(jr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(qee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=jr.buildFolderPath(e.path,r);await Xee(e.path);let s=await _0(e);return await Zee(n,e.format,s)}a(jee,"export_local");async function Xee(e){if(pn.trace("in confirmPath"),jr.isEmptyOrZeroLength(e))throw bt(new Error,`Invalid path: ${e}`,yt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Gg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,pn.error(n),bt(new Error,n,yt.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw pn.error(r),bt(new Error,r,yt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Xee,"confirmPath");async function Zee(e,t,r){if(pn.trace("in saveToLocal"),_l.isEmptyOrZeroLength(e))throw bt(new Error,Cr.INVALID_VALUE("file_path"),yt.BAD_REQUEST,void 0,void 0,!0);if(_l.isEmptyOrZeroLength(t))throw bt(new Error,Cr.INVALID_VALUE("Source format"),yt.BAD_REQUEST,void 0,void 0,!0);if(_l.isEmpty(r))throw bt(new Error,Cr.NOT_FOUND("Data"),yt.BAD_REQUEST,void 0,void 0,!0);if(t===a0){let n=Gg.createWriteStream(e);return kee(r).pipe(n),await Jee(n),{message:$ee,path:e}}else if(t===c0){let n=Gg.createWriteStream(e),s=dl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new xee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Yee,path:e}}throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST)}a(Zee,"saveToLocal");async function ete(e){if(!e.s3||Object.keys(e.s3).length===0)throw bt(new Error,Cr.MISSING_VALUE("S3 object"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw bt(new Error,Cr.MISSING_VALUE("aws_access_key_id"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw bt(new Error,Cr.MISSING_VALUE("aws_secret_access_key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.bucket))throw bt(new Error,Cr.MISSING_VALUE("bucket"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.key))throw bt(new Error,Cr.MISSING_VALUE("key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.region))throw bt(new Error,Cr.MISSING_VALUE("region"),yt.BAD_REQUEST);let t=l0(e);if(!jr.isEmpty(t))throw bt(new Error,t,yt.BAD_REQUEST);pn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await _0(e)}catch(u){throw pn.error(u),u}let n,s=await Hee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new dl.PassThrough;if(e.format===c0){i=e.s3.key+".csv";let u=u0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===a0){i=e.s3.key+".json";let u=new dl.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";l+=f,d!==0&&d%Kee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST);return new Vee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(ete,"export_to_s3");function u0(e,t){let r=dl.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 Gee(n,s);return r.pipe(i)}a(u0,"toCsvStream");function l0(e){if(pn.trace("in exportCoreValidation"),jr.isEmpty(e.format))return"format missing";if(i0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${i0.join(", ")}`;let t=e.search_operation.operation;if(jr.isEmpty(t))return"search_operation.operation missing";if(s0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${s0.join(", ")}`}a(l0,"exportCoreValidation");async function _0(e){pn.trace("in getRecords");let t,r;if(_l.isEmpty(e.search_operation)||_l.isEmptyOrZeroLength(e.search_operation.operation))throw bt(new Error,Cr.INVALID_VALUE("Search operation"),yt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Qee;break;case"search_by_hash":t=Wee;break;case"search_by_conditions":t=qg.searchByConditions;break;case"sql":t=zee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,pn.error(r),bt(new Error,r,yt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(_0,"getRecords")});var R0={};Fe(R0,{contentTypes:()=>$g,findBestSerializer:()=>zf,getDeserializer:()=>bo,registerContentHandlers:()=>Yg,serialize:()=>Jf,serializeMessage:()=>go});function tte(e){try{return e?.[0]===123?Vg(e):e}catch{return e}}function Yg(e){e.register(nte,{serializers:[{regex:/^application\/json$/,serializer:Ic},{regex:/^application\/cbor$/,serializer:function(t){return new Oo.EncoderStream(El).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Qf.Readable.from((0,ls.encodeIter)(t,El)):(0,ls.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Wf.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,ls.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Oo.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function zf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,E={q:1};for(let h of l){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}d=+E.q;let f=Ft.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)throw new m0.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Ft.keys()).join(", "),406);n=Ft.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Jf(e,t,r){let n=E0&&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=zf(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,xs.createBrotliCompress)({params:{[xs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?xs.constants.BROTLI_MODE_TEXT:xs.constants.BROTLI_MODE_GENERIC,[xs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>E0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,xs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function go(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return fl(e);let r=t.serialize;if(r)return r(e);let n=zf(t);return r=t.serialize=n.serializer.serialize,r(e)}function ste(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 bo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Ft.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Ft.get(e)?.deserialize||h0(e,n);return o=>ste(o).then(i)}return e&&Ft.get(e)?.deserialize||h0(e,n)}function h0(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 Vg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function ite(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 Wf,ls,Oo,xs,m0,Qf,p0,Fg,kg,S0,T0,fl,Vg,El,Ft,$g,f0,g0,rte,nte,E0,Ca=Re(()=>{nm();Wf=B(Kf()),ls=require("msgpackr"),Oo=require("cbor-x"),xs=require("zlib"),m0=B(ne()),Qf=require("stream");lr();p0=require("../index"),Fg=B(Z()),kg=B(P()),S0=B(require("yaml")),T0=Fg.default.get(kg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,fl=T0?Gi:JSON.stringify,Vg=T0?rm:JSON.parse,El={useRecords:!1,useToJSON:!0},Ft=new Map,$g=Ft;at.contentTypes=$g;(0,p0._assignPackageExport)("contentTypes",$g);Ft.set("application/json",{serializeStream:Ic,serialize:fl,deserialize:Vg,q:.8});f0=new Oo.Encoder(El);Ft.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Oo.EncoderStream(El).end(e)},serialize:f0.encode,deserialize:f0.decode,q:1});Ft.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Qf.Readable.from((0,ls.encodeIter)(e,El)):(0,ls.pack)(e)},serialize:ls.pack,deserialize:ls.unpack,q:.9});Ft.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Wf.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,Wf.toCsvStream)(e,e?.getColumns?.())},q:.1});Ft.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Ft.set("text/yaml",{serialize(e){return S0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Ft.set("text/event-stream",{serializeStream:function(e){return Qf.Readable.from(ite(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
20
|
-
`),e.data){let r=e.data;typeof r=="object"&&(r=
|
|
17
|
+
`,""):null}catch(E){E.stderr?i[u].npm_error=lv(E.stderr):i[u].npm_error=E.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return Ma.info(`finished installModules with response ${i}`),i}a(E7,"installModules");function lv(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(lv,"parseNPMStdErr");async function h7(e){Ma.info(`starting auditModules for request: ${e}`);let t=dv(e);if(t)throw Da(t,t.message,La.BAD_REQUEST);let{projects:r}=e;await Uf(),await _v(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Pf.join(Sg,o);n[o]={npm_output:null,npm_error:null};try{let u=await sl("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=lv(u.stderr)}}return Ma.info(`finished auditModules with response ${n}`),n}a(h7,"auditModules");async function Uf(){try{return await sl("npm -v"),!0}catch{throw Da(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",La.BAD_REQUEST,void 0,void 0,!0)}}a(Uf,"checkNPMInstalled");async function _v(e){if(!Array.isArray(e)||e.length===0)throw Da(new Error,"projects argument must be an array with at least 1 element",La.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Pf.join(Sg,i.toString());if(!await av.pathExists(o)){t.push(i);continue}let u=Pf.join(o,"package.json");await av.pathExists(u)||r.push(i)}if(t.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,La.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,La.BAD_REQUEST,void 0,void 0,!0)}a(_v,"checkProjectPaths");function dv(e){let t=Mf.object({projects:Mf.array().min(1).items(Mf.string()).required(),dry_run:Mf.boolean().default(!1)});return u7.validateBySchema(e,t)}a(dv,"modulesValidator")});var gg=g((Rme,Sv)=>{"use strict";var Pa=require("fs-extra"),Tg=require("path"),Bf=$(),Ev=z(),xf=P(),pv=ee(),m7=Er();Sv.exports=p7;async function p7(){let e=S7(),t=pv.get(xf.CONFIG_PARAMS.ROOTPATH),r=Tg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+xf.PACKAGE_ROOT}},s=Tg.join(t,"node_modules");await Pa.ensureDir(s);let i,o=!0,c=!1;try{i=await Pa.readJson(r)}catch(u){if(Ev.isEmptyOrZeroLength(e))return;if(u.code!==xf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!Ev.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await hv(_);n.dependencies[u]=l+_}if(!o){Bf.notify("Installing components"),await mv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await hv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Bf.notify("Removing component",u),c=!0);c&&(Bf.notify("Updating components."),await mv(r,n,i))}a(p7,"installComponents");function S7(){let e=m7.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 hv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":Tg.extname(e)||await Pa.pathExists(e)?"file:":"github:"}a(hv,"getPkgPrefix");async function mv(e,t,r){Bf.trace("npm installing components package.json",t),await Pa.writeFile(e,JSON.stringify(t,null," "));try{await vf().installAllRootModules(pv.get(xf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Pa.writeFile(e,JSON.stringify(r,null," ")):await Pa.unlink(e),n}}a(mv,"installPackages")});var Og=g((bme,Av)=>{"use strict";var $e=require("fs-extra"),Rg=require("fast-glob"),ge=require("path"),gv=require("tar-fs"),Ome=require("uuid").v4,Ag=require("normalize-path"),cs=ov(),Ct=$(),ze=P(),Ot=ee(),il=Er(),T7=z(),{PACKAGE_ROOT:g7}=P(),{handleHDBError:Gt,hdb_errors:R7}=se(),{basename:A7}=require("path"),O7=gg(),Rv=ee(),b7=P(),{Readable:y7}=require("stream"),{isMainThread:N7}=require("worker_threads"),{HDB_ERROR_MSGS:Ro,HTTP_STATUS_CODES:qt}=R7,I7=ge.join(g7,"application-template"),Tv=ge.join(Ot.get(ze.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function w7(){Ct.trace("getting custom api status");let e={};try{e={port:Ot.get(ze.CONFIG_PARAMS.HTTP_PORT),directory:Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Gt(new Error,Ro.FUNCTION_STATUS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,t)}return e}a(w7,"customFunctionsStatus");function C7(){Ct.trace("getting custom api endpoints");let e={},t=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT);try{Rg.sync(Ag(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:Rg.sync(Ag(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:Rg.sync(Ag(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Gt(new Error,Ro.GET_FUNCTIONS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,r)}return e}a(C7,"getCustomFunctions");function D7(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("getting custom api endpoint file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=ge.join(r,n,s,i+".js");try{return $e.readFileSync(o,{encoding:"utf8"})}catch(c){throw Gt(new Error,Ro.GET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(D7,"getCustomFunction");function L7(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=cs.setCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("setting custom function file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return $e.outputFileSync(ge.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Gt(new Error,Ro.SET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(L7,"setCustomFunction");function M7(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function file");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return $e.unlinkSync(ge.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Gt(new Error,Ro.DROP_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,o)}}a(M7,"dropCustomFunction");function P7(e){e.project&&(e.project=ge.parse(e.project).name);let t=cs.addComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("adding component");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=ge.join(r,n);return $e.mkdirSync(s,{recursive:!0}),$e.copySync(I7,s),`Successfully added project: ${n}`}catch(s){throw Gt(new Error,Ro.ADD_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,s)}}a(P7,"addComponent");function U7(e){e.project&&(e.project=ge.parse(e.project).name);let t=cs.dropCustomFunctionProjectValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function project");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Ot.get(ze.CONFIG_PARAMS.APPS);if(!T7.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 il.updateConfigValue(ze.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=ge.join(r,n);return $e.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Gt(new Error,Ro.DROP_FUNCTION_PROJECT,qt.INTERNAL_SERVER_ERROR,Ct.ERR,i)}}a(U7,"dropCustomFunctionProject");async function v7(e){e.project&&(e.project=ge.parse(e.project).name);let t=cs.packageComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ct.trace("packaging component",n);let s;try{s=await $e.realpath(ge.join(r,n))}catch(u){if(u.code!==ze.NODE_ERROR_CODES.ENOENT)throw u;try{s=await $e.realpath(ge.join(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===ze.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await $e.ensureDir(Tv);let i=ge.join(Tv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(ge.join(s,"node_modules"))}),gv.pack(s,o).pipe($e.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=$e.readFileSync(i,{encoding:"base64"});return await $e.remove(i),{project:n,payload:c}}a(v7,"packageComponent");async function B7(e){e.project&&(e.project=ge.parse(e.project).name);let t=cs.deployComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Ct.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=ge.join(r,n),i="file:"+o,await $e.emptyDir(o);let E=y7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(gv.extract(o,{finish:h})).on("error",p)});let f=await $e.readdir(o);f.length===1&&f[0]==="package"&&(await $e.copy(ge.join(o,"package"),o),await $e.remove(ge.join(o,"package")))}if(await il.addConfig(n,{package:i}),!s){await O7();let E=Rv.get(b7.CONFIG_PARAMS.ROOTPATH);o=ge.join(E,"node_modules",n)}if(N7)return;let c=new Map;c.isWorker=!0;let u=(Gf(),ie(Hf)),_;u.setErrorReporter(E=>_=E);let l=A7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Ct.info("Installed component"),`Successfully deployed: ${n}`}a(B7,"deployComponent");async function x7(){let e=il.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await $e.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=ge.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let E={name:l,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await $e.stat(d),f={name:ge.basename(l),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(u){return Ct.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{name:Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT).split(ge.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(ge.join(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(Gf(),ie(Hf)).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(x7,"getComponents");async function H7(e){let t=cs.getComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let n=il.getConfigObj()[e.project]||e.project==="harperdb"?ge.join(Rv.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules"):Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await $e.stat(ge.join(n,e.project,e.file));return{message:await $e.readFile(ge.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===ze.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${ge.join(e.project,e.file)}'`):i}}a(H7,"getComponentFile");async function G7(e){let t=cs.setComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=ge.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await $e.ensureFile(n),await $e.outputFile(n,e.payload,r)):await $e.ensureDir(n),"Successfully set component: "+e.file}a(G7,"setComponentFile");async function q7(e){let t=cs.dropComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.file?ge.join(e.project,e.file):e.project,n=ge.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),r);return await $e.pathExists(n)&&await $e.remove(n),il.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(q7,"dropComponent");Av.exports={customFunctionsStatus:w7,getCustomFunctions:C7,getCustomFunction:D7,setCustomFunction:L7,dropCustomFunction:M7,addComponent:P7,dropCustomFunctionProject:U7,packageComponent:v7,deployComponent:B7,getComponents:x7,getComponentFile:H7,setComponentFile:G7,dropComponent:q7}});var bg=g((Nme,bv)=>{"use strict";var us=require("joi"),Ov=Xe();bv.exports={readTransactionLogValidator:F7,deleteTransactionLogsBeforeValidator:k7};function F7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),from:us.date().timestamp(),to:us.date().timestamp(),limit:us.number().min(1)});return Ov.validateBySchema(e,t)}a(F7,"readTransactionLogValidator");function k7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),timestamp:us.date().timestamp().required()});return Ov.validateBySchema(e,t)}a(k7,"deleteTransactionLogsBeforeValidator")});var qf=g((wme,Cv)=>{"use strict";var yg=P(),ol=ut(),yv=z(),Nv=ee(),Iv=As(),{handleHDBError:Ua,hdb_errors:V7}=se(),{HTTP_STATUS_CODES:va}=V7,{readTransactionLogValidator:$7,deleteTransactionLogsBeforeValidator:Y7}=bg(),wv="This operation relies on clustering and cannot run with it disable.",K7="Logs successfully deleted from transaction log.",W7="All logs successfully deleted from transaction log.";Cv.exports={readTransactionLog:Q7,deleteTransactionLogsBefore:z7};async function*Q7(e){let t=$7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!Nv.get(yg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,wv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=yv.checkSchemaTableExist(r,n);if(s)throw Ua(new Error,s,va.NOT_FOUND,void 0,void 0,!0);let i=Iv.createNatsTableStreamName(r,n),o=await ol.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===yg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(Q7,"readTransactionLog");async function z7(e){let t=Y7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!Nv.get(yg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,wv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=yv.checkSchemaTableExist(r,n);if(i)throw Ua(new Error,i,va.NOT_FOUND,void 0,void 0,!0);let o=Iv.createNatsTableStreamName(r,n),{jsm:c}=await ol.getNATSReferences(),u=await ol.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=K7,d,E=new Date(u.state.last_ts).getTime();return s>E?(d=u.state.last_seq+1,l=W7):d=(await ol.viewStream(o,parseInt(s),1))[0].nats_sequence,await ol.purgeTableStream(r,n,{seq:d}),l}a(z7,"deleteTransactionLogsBefore")});var Lv=g((Dme,Dv)=>{"use strict";var Ng=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}};Dv.exports=Ng});var Pv=g((Mme,Mv)=>{"use strict";var Ig=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Mv.exports=Ig});var Cg=g((Ume,vv)=>{"use strict";var Uv=Lv(),J7=Pv(),{HDB_ERROR_MSGS:j7}=Ur(),wg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=j7.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 Uv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new J7(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 Uv(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}};vv.exports=wg});var $f=g((Bme,jv)=>{"use strict";var Dg=qr(),Ff=Gr(),pn=Ou(),ul=Os(),Lg=ai(),X7=kS(),Z7=HL(),ll=_n(),kf=jS(),Dt=$(),eee=eT(),tee=nf(),ree=PT(),nee=of(),see=vT(),iee=BT(),oee=GT(),aee=FT(),Mg=$T(),Bs=z(),cee=BP(),Pg=zT(),Hv=Ju(),mn=P(),Gv=VU(),uee=ga(),qv=Cu(),Fv=(Df(),ie(el)),kv=Er(),Jr=Og(),lee=require("alasql"),Vv=qf(),$v=vf(),Yv=Cg(),{handleHDBError:wr,hdb_errors:Kv}=se(),{HDB_ERROR_MSGS:Wt,HTTP_STATUS_CODES:al}=Kv,V=new Map,Wv="delete",Ni="insert",xs="read",Ao="update",cl="describe",Bv=ul.describeSchema.name,xv=ul.describeTable.name,Qv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},_ee="catchup",dee="handleGetJob",fee="handleGetJobsByStartDate",Vf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},Eee=[pn.createTable.name,pn.createAttribute.name,pn.dropTable.name,pn.dropAttribute.name],zv={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(Dg.insert.name,new W(!1,[Ni]));V.set(Dg.update.name,new W(!1,[Ao]));V.set(Dg.upsert.name,new W(!1,[Ni,Ao]));V.set(Ff.searchByConditions.name,new W(!1,[xs]));V.set(Ff.searchByHash.name,new W(!1,[xs]));V.set(Ff.searchByValue.name,new W(!1,[xs]));V.set(Ff.search.name,new W(!1,[xs]));V.set(pn.createSchema.name,new W(!0,[]));V.set(pn.createTable.name,new W(!0,[]));V.set(pn.createAttribute.name,new W(!1,[Ni]));V.set(pn.dropSchema.name,new W(!0,[]));V.set(pn.dropTable.name,new W(!0,[]));V.set(pn.dropAttribute.name,new W(!0,[]));V.set(ul.describeSchema.name,new W(!1,[xs]));V.set(ul.describeTable.name,new W(!1,[xs]));V.set(Lg.deleteRecord.name,new W(!1,[Wv]));V.set(ll.addUser.name,new W(!0,[]));V.set(ll.alterUser.name,new W(!0,[]));V.set(ll.dropUser.name,new W(!0,[]));V.set(ll.listUsersExternal.name,new W(!0,[]));V.set(kf.listRoles.name,new W(!0,[]));V.set(kf.addRole.name,new W(!0,[]));V.set(kf.alterRole.name,new W(!0,[]));V.set(kf.dropRole.name,new W(!0,[]));V.set(eee.name,new W(!0,[]));V.set(tee.name,new W(!0,[]));V.set(ree.name,new W(!0,[]));V.set(nee.name,new W(!0,[]));V.set(see.name,new W(!0,[]));V.set(iee.name,new W(!0,[]));V.set(Mg.setRoutes.name,new W(!0,[]));V.set(Mg.getRoutes.name,new W(!0,[]));V.set(Mg.deleteRoutes.name,new W(!0,[]));V.set(kv.setConfiguration.name,new W(!0,[]));V.set(oee.clusterStatus.name,new W(!0,[]));V.set(aee.name,new W(!0,[]));V.set(Pg.getFingerprint.name,new W(!0,[]));V.set(Pg.setLicense.name,new W(!0,[]));V.set(Lg.deleteFilesBefore.name,new W(!0,[]));V.set(Lg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Hv.restart.name,new W(!0,[]));V.set(Hv.restartService.name,new W(!0,[]));V.set(X7.name,new W(!0,[]));V.set(Z7.name,new W(!0,[xs]));V.set(uee.systemInformation.name,new W(!0,[]));V.set(kv.getConfiguration.name,new W(!0,[]));V.set(Vv.readTransactionLog.name,new W(!0,[]));V.set(Vv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set($v.installModules.name,new W(!0,[]));V.set($v.auditModules.name,new W(!0,[]));V.set(qv.createTokens.name,new W(!1,[]));V.set(qv.refreshOperationToken.name,new W(!1,[]));V.set(Fv.login.name,new W(!1,[]));V.set(Fv.logout.name,new W(!1,[]));V.set(Jr.customFunctionsStatus.name,new W(!0,[]));V.set(Jr.getCustomFunctions.name,new W(!0,[]));V.set(Jr.getComponents.name,new W(!0,[]));V.set(Jr.getComponentFile.name,new W(!0,[]));V.set(Jr.setComponentFile.name,new W(!0,[]));V.set(Jr.dropComponent.name,new W(!0,[]));V.set(Jr.getCustomFunction.name,new W(!0,[]));V.set(Jr.setCustomFunction.name,new W(!0,[]));V.set(Jr.dropCustomFunction.name,new W(!0,[]));V.set(Jr.addComponent.name,new W(!0,[]));V.set(Jr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Jr.packageComponent.name,new W(!0,[]));V.set(Jr.deployComponent.name,new W(!0,[]));V.set(Pg.getRegistrationInfo.name,new W(!1,[]));V.set(ll.userInfo.name,new W(!1,[]));V.set(ul.describeAll.name,new W(!1,[]));V.set(dee,new W(!1,[]));V.set(fee,new W(!0,[]));V.set(_ee,new W(!0,[]));V.set(Vf.CSV_DATA_LOAD,new W(!1,[Ni,Ao]));V.set(Vf.CSV_URL_LOAD,new W(!1,[Ni,Ao]));V.set(Vf.CSV_FILE_LOAD,new W(!1,[Ni,Ao]));V.set(Vf.IMPORT_FROM_S3,new W(!1,[Ni,Ao]));V.set(zv.EXPORT_TO_S3,new W(!0,[]));V.set(zv.EXPORT_LOCAL,new W(!0,[]));V.set(mn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Wv]));V.set(mn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[xs]));V.set(mn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Ni]));V.set(mn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ao]));jv.exports={verifyPerms:mee,verifyPermsAst:hee,verifyBulkLoadAttributePerms:See};function hee(e,t,r){if(Bs.isEmptyOrZeroLength(e))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(t))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(r))throw Dt.info("verify_perms_ast has a null operation parameter"),wr(new Error);try{let n=new Yv,s=new cee(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Dt.info("No schemas defined in verifyPermsAst(), will not continue."),wr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Qv[r])throw wr(new Error,Wt.DROP_SYSTEM,al.FORBIDDEN);if(c&&!u)return null;let _=Gv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof lee.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let E=s.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let l=Jv(t,r,o,n);return l||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=vg(t.role.permission,E,d[f]);Ug(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw wr(n)}}a(hee,"verifyPermsAst");function mee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Dt.info("null required parameter in verifyPerms"),wr(new Error,Wt.DEFAULT_INVALID_REQUEST,al.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 Yv;if(Bs.isEmptyOrZeroLength(e.hdb_user.role)||Bs.isEmptyOrZeroLength(e.hdb_user.role.permission))return Dt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Wt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(mn.SYSTEM_SCHEMA_NAME)||s===mn.SYSTEM_SCHEMA_NAME;if(l&&Qv[r])throw wr(new Error,Wt.DROP_SYSTEM,al.FORBIDDEN);if(u&&!l||_===!0&&(r===pn.createSchema.name||r===pn.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=Gv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Bv||r===xv){if(s===mn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Wt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Bv&&(!d[s]||!d[s][cl]))return c.handleInvalidItem(Wt.SCHEMA_NOT_FOUND(s));if(r===xv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][cl]))return c.handleInvalidItem(Wt.TABLE_NOT_FOUND(s,i))}}let E=Jv(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&mn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[mn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[mn.PERMS_CRUD_ENUM.READ]).forEach(R=>{p.push(R.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let f=pee(e),h=vg(e.hdb_user.role.permission,s,i);return Ug(f,h,r,i,s,c,n),c.getPermsResponse()}a(mee,"verifyPerms");function Jv(e,t,r,n,s){if(Bs.arrayHasEmptyValues([e,t,r]))throw Dt.info("hasPermissions has an invalid parameter"),wr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw Dt.info(`operation ${t} not found.`),wr(new Error,Wt.OP_NOT_FOUND(t),al.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Dt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Wt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][cl]===!1){n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[cl]===!1)n.addInvalidItem(Wt.TABLE_NOT_FOUND(u,l));else try{let E=[],f=V.get(t).perms;!Bs.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let p=f[h],S=d[p];(S==null||S===!1)&&(Dt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(u,l,E)}catch(E){let f=Wt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Dt.error(f),Dt.error(E),wr(Kv.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(Jv,"hasPermissions");function Ug(e,t,r,n,s,i,o){if(!e||!t)throw Dt.info("no attributes specified in checkAttributePerms."),wr(new Error);let c=V.get(r).perms;if(!c||c==="")throw Dt.info(`no permissions found for ${r} in checkAttributePerms().`),wr(new Error);if(Bs.isEmptyOrZeroLength(t))return Dt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[cl]===!1){i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let E of c){if(mn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==xs)throw wr(new Error,Wt.SYSTEM_TIMESTAMP_PERMS_ERR,al.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Ug,"checkAttributePerms");function pee(e){let t=new Set;try{if(e.action)return t;if(e.operation===mn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Dt.info(r)}return t}a(pee,"getRecordAttributes");function vg(e,t,r){let n=new Map;if(Bs.isEmpty(e))return Dt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Dt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(vg,"getAttributePermissions");function See(e,t,r,n,s,i,o){let c=new Set(i),u=vg(e,n,s);Ug(c,u,t,s,n,o,r)}a(See,"verifyBulkLoadAttributePerms")});var Kf=g((Hme,r0)=>{"use strict";r0.exports={evaluateSQL:Lee,processAST:t0,convertSQLToAST:e0,checkASTPermissions:Zv};var Tee=qr(),Xv=require("util"),gee=Xv.callbackify(Tee.insert),Ree=Gr().search,Aee=OD().update,Oee=Xv.callbackify(Aee),bee=yD().convertDelete,Ii=require("alasql"),yee=$f(),Yf=$(),Nee=Rd(),Iee=z(),_l=P(),{hdb_errors:wee,handleHDBError:Bg}=se(),{HTTP_STATUS_CODES:xg}=wee;Nee(Ii);var Cee=403,Dee="There was a problem performing this insert. Please check the logs and try again.",Hg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Lee(e,t){let r=e.parsed_sql_object;if(!r){r=e0(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ii.yy.Insert?n=s.into.databaseid:s instanceof Ii.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ii.yy.Update||s instanceof Ii.yy.Delete?n=s.table.databaseid:Yf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ii.yy.Select)&&Iee.isEmptyOrZeroLength(n))return t("No schema specified",null)}t0(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Lee,"evaluateSQL");function Zv(e,t){let r;try{r=yee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Zv,"checkASTPermissions");function e0(e){let t=new Hg;if(!e)throw Bg(new Error,"The 'sql' parameter is missing from the request body",xg.BAD_REQUEST);try{let r=e.trim(),n=Ii.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
+
`);throw n[1]?Bg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,xg.BAD_REQUEST):Bg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",xg.BAD_REQUEST)}return t}a(e0,"convertSQLToAST");function t0(e,t,r){try{let n=Mee;if(!e.bypass_auth&&!t.permissions_checked){let i=Zv(e,t);if(i&&i.length>0)return r(Cee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case _l.VALID_SQL_OPS_ENUM.SELECT:n=Ree,s=t.ast.statements[0];break;case _l.VALID_SQL_OPS_ENUM.INSERT:n=Pee;break;case _l.VALID_SQL_OPS_ENUM.UPDATE:n=Oee;break;case _l.VALID_SQL_OPS_ENUM.DELETE:n=bee;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(t0,"processAST");function Mee(e,t){Yf.info(e),t("unknown sql statement")}a(Mee,"nullFunction");function Pee({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=Uee(i,e.values)}catch(o){return r(o)}gee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Yf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Pee,"convertInsert");function Uee(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]]=Ii.compile(`SELECT ${s.toString()} AS [${_l.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Yf.error(r),new Error(Dee)}}a(Uee,"createDataObjects")});var Gg=g((qme,s0)=>{"use strict";var{S3:vee,GetObjectCommand:Bee}=require("@aws-sdk/client-s3");s0.exports={getFileStreamFromS3:xee,getS3AuthObj:n0};async function xee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await n0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Bee(r))).Body}a(xee,"getFileStreamFromS3");function n0(e,t,r){return new vee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(n0,"getS3AuthObj")});var Wf=g((kme,f0)=>{"use strict";var Fg=Gr(),Hee=Kf(),Gee=Gg(),{AsyncParser:qee,Transform:Fee}=require("json2csv"),fl=require("stream"),jr=z(),qg=require("fs-extra"),kee=require("path"),Sn=$(),{promisify:a0}=require("util"),dl=z(),{handleHDBError:bt,hdb_errors:Vee}=se(),{HDB_ERROR_MSGS:Cr,HTTP_STATUS_CODES:yt}=Vee,{streamAsJSON:$ee}=(sm(),ie(Ub)),{Upload:Yee}=require("@aws-sdk/lib-storage"),i0=["search_by_value","search_by_hash","sql","search_by_conditions"],o0=["json","csv"],c0="json",u0="csv",Kee="Successfully exported JSON locally.",Wee="Successfully exported CSV locally.",Qee=1e3,zee=Fg.searchByHash,Jee=Fg.searchByValue,jee=a0(Hee.evaluateSQL),Xee=a0(fl.finished);f0.exports={export_to_s3:rte,export_local:Zee,toCsvStream:l0};async function Zee(e){Sn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=_0(e);if(!jr.isEmpty(t))throw Sn.error(t),bt(new Error,t,yt.BAD_REQUEST,void 0,void 0,!0);if(jr.isEmpty(e.path))throw Sn.error(Cr.MISSING_VALUE("path")),bt(new Error,Cr.MISSING_VALUE("path"),yt.BAD_REQUEST,void 0,void 0,!0);let r=(jr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(kee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=jr.buildFolderPath(e.path,r);await ete(e.path);let s=await d0(e);return await tte(n,e.format,s)}a(Zee,"export_local");async function ete(e){if(Sn.trace("in confirmPath"),jr.isEmptyOrZeroLength(e))throw bt(new Error,`Invalid path: ${e}`,yt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await qg.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,Sn.error(n),bt(new Error,n,yt.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw Sn.error(r),bt(new Error,r,yt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(ete,"confirmPath");async function tte(e,t,r){if(Sn.trace("in saveToLocal"),dl.isEmptyOrZeroLength(e))throw bt(new Error,Cr.INVALID_VALUE("file_path"),yt.BAD_REQUEST,void 0,void 0,!0);if(dl.isEmptyOrZeroLength(t))throw bt(new Error,Cr.INVALID_VALUE("Source format"),yt.BAD_REQUEST,void 0,void 0,!0);if(dl.isEmpty(r))throw bt(new Error,Cr.NOT_FOUND("Data"),yt.BAD_REQUEST,void 0,void 0,!0);if(t===c0){let n=qg.createWriteStream(e);return $ee(r).pipe(n),await Xee(n),{message:Kee,path:e}}else if(t===u0){let n=qg.createWriteStream(e),s=fl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new qee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Wee,path:e}}throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST)}a(tte,"saveToLocal");async function rte(e){if(!e.s3||Object.keys(e.s3).length===0)throw bt(new Error,Cr.MISSING_VALUE("S3 object"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw bt(new Error,Cr.MISSING_VALUE("aws_access_key_id"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw bt(new Error,Cr.MISSING_VALUE("aws_secret_access_key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.bucket))throw bt(new Error,Cr.MISSING_VALUE("bucket"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.key))throw bt(new Error,Cr.MISSING_VALUE("key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.region))throw bt(new Error,Cr.MISSING_VALUE("region"),yt.BAD_REQUEST);let t=_0(e);if(!jr.isEmpty(t))throw bt(new Error,t,yt.BAD_REQUEST);Sn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await d0(e)}catch(u){throw Sn.error(u),u}let n,s=await Gee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new fl.PassThrough;if(e.format===u0){i=e.s3.key+".csv";let u=l0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===c0){i=e.s3.key+".json";let u=new fl.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";l+=f,d!==0&&d%Qee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST);return new Yee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(rte,"export_to_s3");function l0(e,t){let r=fl.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 Fee(n,s);return r.pipe(i)}a(l0,"toCsvStream");function _0(e){if(Sn.trace("in exportCoreValidation"),jr.isEmpty(e.format))return"format missing";if(o0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${o0.join(", ")}`;let t=e.search_operation.operation;if(jr.isEmpty(t))return"search_operation.operation missing";if(i0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${i0.join(", ")}`}a(_0,"exportCoreValidation");async function d0(e){Sn.trace("in getRecords");let t,r;if(dl.isEmpty(e.search_operation)||dl.isEmptyOrZeroLength(e.search_operation.operation))throw bt(new Error,Cr.INVALID_VALUE("Search operation"),yt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Jee;break;case"search_by_hash":t=zee;break;case"search_by_conditions":t=Fg.searchByConditions;break;case"sql":t=jee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Sn.error(r),bt(new Error,r,yt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(d0,"getRecords")});var A0={};Fe(A0,{contentTypes:()=>Yg,findBestSerializer:()=>Jf,getDeserializer:()=>bo,registerContentHandlers:()=>Kg,serialize:()=>jf,serializeMessage:()=>go});function nte(e){try{return e?.[0]===123?$g(e):e}catch{return e}}function Kg(e){e.register(ite,{serializers:[{regex:/^application\/json$/,serializer:wc},{regex:/^application\/cbor$/,serializer:function(t){return new Oo.EncoderStream(hl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?zf.Readable.from((0,ls.encodeIter)(t,hl)):(0,ls.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Qf.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,ls.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Oo.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Jf(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,E={q:1};for(let h of l){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}d=+E.q;let f=Ft.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)throw new p0.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Ft.keys()).join(", "),406);n=Ft.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function jf(e,t,r){let n=h0&&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=Jf(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>h0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function go(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return El(e);let r=t.serialize;if(r)return r(e);let n=Jf(t);return r=t.serialize=n.serializer.serialize,r(e)}function ote(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 bo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Ft.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Ft.get(e)?.deserialize||m0(e,n);return o=>ote(o).then(i)}return e&&Ft.get(e)?.deserialize||m0(e,n)}function m0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return $g(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function ate(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 Qf,ls,Oo,Hs,p0,zf,S0,kg,Vg,T0,g0,El,$g,hl,Ft,Yg,E0,R0,ste,ite,h0,Ca=Re(()=>{sm();Qf=x(Wf()),ls=require("msgpackr"),Oo=require("cbor-x"),Hs=require("zlib"),p0=x(se()),zf=require("stream");lr();S0=require("../index"),kg=x(ee()),Vg=x(P()),T0=x(require("yaml")),g0=kg.default.get(Vg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,El=g0?Gi:JSON.stringify,$g=g0?nm:JSON.parse,hl={useRecords:!1,useToJSON:!0},Ft=new Map,Yg=Ft;at.contentTypes=Yg;(0,S0._assignPackageExport)("contentTypes",Yg);Ft.set("application/json",{serializeStream:wc,serialize:El,deserialize:$g,q:.8});E0=new Oo.Encoder(hl);Ft.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Oo.EncoderStream(hl).end(e)},serialize:E0.encode,deserialize:E0.decode,q:1});Ft.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?zf.Readable.from((0,ls.encodeIter)(e,hl)):(0,ls.pack)(e)},serialize:ls.pack,deserialize:ls.unpack,q:.9});Ft.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Qf.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,Qf.toCsvStream)(e,e?.getColumns?.())},q:.1});Ft.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Ft.set("text/yaml",{serialize(e){return T0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Ft.set("text/event-stream",{serializeStream:function(e){return zf.Readable.from(ate(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=El(r)),t+="data: "+r+`
|
|
21
21
|
`}return e.id&&(t+="id: "+e.id+`
|
|
22
22
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
23
23
|
`),t+`
|
|
24
|
-
`}else return typeof e=="object"?`data: ${
|
|
24
|
+
`}else return typeof e=="object"?`data: ${El(e)}
|
|
25
25
|
|
|
26
26
|
`:`data: ${e}
|
|
27
27
|
|
|
28
|
-
`},compressible:!1,q:.8});Ft.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});g0={type:"application/json",serializeStream:Ic,serialize:fl,deserialize:tte,q:.5};Ft.set("*/*",g0);Ft.set("",g0);a(tte,"tryJSONParse");a(Yg,"registerContentHandlers");rte=require("fastify-plugin"),nte=rte(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=zf(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(zf,"findBestSerializer");E0=Fg.default.get(kg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Jf,"serialize");a(go,"serializeMessage");a(ste,"streamToBuffer");a(bo,"getDeserializer");a(h0,"deserializerUnknownType");a(ite,"transformIterable")});function Qg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let f=1;f<e.length;f++){let h=e[f],p=_(h);d=d.concat(p)}let E=new Set;return d.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let d=_(u),E=l(e.slice(1),!0,u.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Qg(d.conditions,d.operator,r,n,s,i,o,c):xa(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,E,f){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",b=l(h.conditions,!R,f);return R?(C,H)=>b.some(v=>v(C,H)):(C,H)=>b.every(v=>v(C,H))}let S=(h.attribute||h[0])===r.primaryKey,T=Jg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=Ete(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function xa(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],b=qs(n.attributes,R);if(b.relationship){if(o.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let C=b.definition?.tableClass||b.elements?.definition?.tableClass,H=new Map,v=xa({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,C,s,H);if(b.relationship.to){i[o[0]]=H;let F=!!qs(C.attributes,b.relationship.to)?.elements;v=lte(v,b,C.primaryStore,F,H)}if(b.relationship.from){let F=a(M=>xa({attribute:b.relationship.from,value:M},t,r,n,s,H),"searchEntry");b.elements?(i[o[0]]=H,v=_te(v,b,C.primaryStore,H,F)):v=v.flatMap(F)}return v}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,E;c instanceof Date&&(c=c.getTime());let f;switch(zg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,E=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=_s.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,E=!0;break}case"sort":case"contains":case"ends_with":_=!0,f=!0;break;default:throw new Xr.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!E,E=!d,d=R}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||f||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Xr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Xr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Xr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Xr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Jg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(T).map(S?function({key:b,value:C}){return this.isSync?C&&S(C)?b:wi.SKIP:new Promise((H,v)=>setImmediate(()=>{try{H(C&&S(C)?b:wi.SKIP)}catch(F){v(F)}}))}:b=>b.value==null?wi.SKIP:b);return R.hasEntries=!0,R}else return p?p.getRange(T).map(S?function({key:R,value:b}){return this.isSync?S({[o]:R})?b:wi.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(S({[o]:R})?b:wi.SKIP)}catch(v){H(v)}}))}:({value:R})=>R):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:b}){return this.isSync?b&&S(b)?R:wi.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(b&&S(b)?R:wi.SKIP)}catch(v){H(v)}}))})}function qs(e,t){if(Array.isArray(t))if(t.length>1){let r=qs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?qs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function lte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let E=l;Array.isArray(l)&&(E=xn(l),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),l!==E&&(f.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),E=d?.[u];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],l);else _(E,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function _te(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=xn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(xn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(E=>!E(d)))continue}_.set(xn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Jg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=qs(t.attributes,l),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[l],h=Jg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},E,r,f?.[l]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((R,b)=>{let C,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let F of h.idFilter.idSet)e={attribute:p.from,value:F};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(R);return S.idFilter&&(T.idFilter=S.idFilter),v}H=p(R,r,b),C=H?.value}else C=R[l];return C?Array.isArray(C)?C.some(h):h(C,H):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),zg[o]||o){case Kg.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,E=u.length;d<E;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,_s.compareKeys)(l,u[0])>=0&&(0,_s.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,_s.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,_s.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,_s.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,_s.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,_s.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,E,f){let h;E=E&&!s&&t?.indices[l]&&i>3,E&&(e.estimated_count==null&&Xf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(R){let b=R[l],C;if(typeof b!="object"||!b||f?C=d(b):Array.isArray(b)?C=b.some(d):b instanceof Date&&(C=d(b.getTime())),E&&(S++,!C&&!T.idFilter&&++p/S*(i-S)>h)){let H=xa(e,r.transaction.getReadTxn(),!1,t).map(xn),v=new Set(H);T.idFilter=F=>v.has(xn(F)),T.idFilter.idSet=v}return C}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function Xf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Gs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=zg[n]||n,n===Kg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=qs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Xf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Gs(e.indices[i.relationship.from])/(Gs(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Gs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=cte*Gs(e.primaryStore)+1:n==="between"?r.estimated_count=ate*Gs(e.primaryStore)+1:n==="sort"?r.estimated_count=Gs(e.primaryStore)+1:r.estimated_count=ote*Gs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Zf(e){if(e)if(Ci=e,Ba.lastIndex=0,dte.test(e))try{let t=hl(new Ha,"");if(Dr!==Ci.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${Dr} in '${Ci}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function hl(e,t){let r=Ba,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(Ci);){Dr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=A0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=ml(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=ute[d],u=Wg[i]?A0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=ml(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"&&O0(h,l),jf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(ml(l)),s=void 0;break;case"(":Ba.lastIndex=Dr;let f=hl(l?[]:new Ha,")");switch(l){case"":jf(e,_),e.conditions.push(f);break;case"limit":switch(f.length){case 1:e.limit=+f[0];break;case 2:e.offset=+f[0],e.limit=f[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(f[0])&&f.length===1&&!f[0].name?(e.select=f[0],e.select.asArray=!0):f.length===1?e.select=f[0]:f.length===2&&f[1]===""?e.select=f.slice(0,1):e.select=f;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=b0(f);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Ci[Dr]===","?r.lastIndex=++Dr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Ba.lastIndex=Dr,E=hl([],"}"),E.name=l,e.push(E),Ci[Dr]===","?r.lastIndex=++Dr:o=!0;break;case"[":Ba.lastIndex=Dr,l?(E=hl(new Ha,"]"),E.name=l):E=hl(e.conditions?new Ha:[],"]"),e.conditions?(jf(e,_),e.conditions.push(E),s=null):e.push(E),Ci[Dr]===","?r.lastIndex=++Dr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&O0(h,l),jf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(ml(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?fte:Ba,r.lastIndex=Dr),Dr===Ci.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function ml(e){return e.indexOf(".")>-1?e.split(".").map(ml):decodeURIComponent(e)}function A0(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function O0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function b0(e){let t=y0(e[0]);return e.length>1&&(t.next=b0(e.slice(1))),t}function y0(e){if(Array.isArray(e)){let t=y0(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function xn(e){return Array.isArray(e)?e.join("\0"):e}function Gs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function Ete(e,t,r){return t*r/Gs(e)}var Xr,Kg,_s,wi,ote,ate,cte,ute,Wg,zg,dte,Ba,fte,Dr,Ci,Ha,eE=Re(()=>{Xr=B(ne()),Kg=B(ft()),_s=require("ordered-binary"),wi=require("lmdb"),ote=.3,ate=.1,cte=.05,ute={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Wg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Qg,"executeConditions");a(xa,"searchByIndex");a(qs,"findAttribute");a(lte,"joinTo");a(_te,"joinFrom");zg={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(Jg,"filterByType");a(Xf,"estimateCondition");dte=/[()[\]|!<>.]|(=\w*=)/,Ba=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,fte=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Zf,"parseQuery");a(hl,"parseBlock");a(jf,"assignOperator");a(ml,"decodeProperty");a(A0,"typedDecoding");a(O0,"wildcardDecoding");a(b0,"toSortObject");a(y0,"toSortEntry");Ha=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(xn,"flattenKey");a(Gs,"estimatedEntryCount");a(Ete,"intersectionEstimate")});function D0(e){let t={openapi:hte,info:{title:"HarperDB HTTP REST interface",version:(0,C0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:b,name:C,elements:H,relationship:v,definition:F}of o){if(v)b==="array"?_[C]={type:"array",items:{$ref:Di+H.type}}:_[C]={$ref:Di+b};else{let M=F??H?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(J=>{Q[J.name]=new eR(jg[J.type],J.type)}),t.components.schemas[M.type]=new w0(Q)}b==="array"?_[C]={type:"array",items:{$ref:Di+M.type}}:_[C]={$ref:Di+M.type}}else b==="array"?H.type==="Any"||H.type=="ID"?_[C]={type:"array",items:{format:H.type}}:_[C]={type:"array",items:new eR(jg[H.type],H.type)}:b==="Any"||b=="ID"?_[C]={format:b}:_[C]=new eR(jg[b],b)}l.push(new tR(C,"query",_[C]))}let d=Object.keys(_),E=new tR(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new tR("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new w0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",R="/"+s+"/";h&&(t.paths[R]={},t.paths[R].post=new mte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new Xg(l,r,{200:new Zg({$ref:Di+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new I0(l,r,"delete all the records that match the provided query",{204:new N0})),R="/"+s+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new Xg([E],r,{200:new Zg({$ref:Di+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new pte([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new I0([E],r,"delete a record with the given primary key",{204:new N0})),S&&f.schema.enum.length>0&&(R="/"+s+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new Xg([E,f],r,{200:new Zg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function mte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Di+e}}}},this.security=t,this.responses={200:{description:rR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Xg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Zg(e){this.description=rR,this.content={"application/json":{schema:e}}}function N0(){this.description="successfully processed request, no content returned to client"}function pte(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Di+r}}}},this.responses={200:{description:rR}}}function I0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function w0(e){this.type="object",this.properties=e}function eR(e,t){this.type=e,this.format=t}function tR(e,t,r){this.name=e,this.in=t,this.schema=r}var C0,hte,jg,Di,rR,L0=Re(()=>{C0=B(Jd()),hte="3.0.3",jg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Di="#/components/schemas/",rR="successful operation";a(D0,"generateJsonApi");a(mte,"Post");a(Xg,"Get");a(Zg,"Response200");a(N0,"Response204");a(pte,"Put");a(I0,"Delete");a(w0,"ResourceSchema");a(eR,"Type");a(tR,"Parameter")});var rE={};Fe(rE,{start:()=>gte});async function Tte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Zf(e);let s=new yi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==M0){let h=tE.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Ze(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=bo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Ga.ClientError(h,400)}if(e.authorize=!0,i===M0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return D0(tE);throw new Ga.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new Ga.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ga.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,nR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){Ste[0]=d;let h=String.fromCharCode(34,(Qt[0]&63)+62,(Qt[0]>>6)+(Qt[1]<<2&63)+62,(Qt[1]>>4)+(Qt[2]<<4&63)+62,(Qt[2]>>2)+62,(Qt[3]&63)+62,(Qt[3]>>6)+(Qt[4]<<2&63)+62,(Qt[4]>>4)+(Qt[5]<<4&63)+62,(Qt[5]>>2)+62,(Qt[6]&63)+62,(Qt[6]>>6)+(Qt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),nR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:l,headers:s,body:void 0},f=_?.wasLoadedFromSource?.();return f!==void 0&&(E.wasCacheMiss=f,!f&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(E.body=Jf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?yo.warn(i):yo.info(i):yo.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=Jf(i.contentType?i:i.toString(),e,o),o}}function gte(e){nR=e,!P0&&(P0=!0,tE=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Tte(t,r)},e),e.server.ws(async(t,r,n)=>{pl++;let s=new yn;U0||(U0=!0,Eu(u=>{pl>0&&u.push({metric:"ws-connections",connections:pl,byThread:!0})}));let i;t.on("error",u=>{i=!0,yo.warn(u)});let o;t.on("message",a(function(_){o||(o=bo(r.headers.asObject["content-type"]));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{pl--,Wr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=tE.getMatch(u);if(Wr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,Sr(h=>({count:h.count,total:pl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=go(f.value,r);t.send(h),Sr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(Rte[u.statusCode]||1011,u.toString()),t.close("login fialed")}t.close()},e))}var yo,Ga,Qt,Ste,nR,M0,P0,tE,U0,pl,Rte,v0=Re(()=>{Ca();Cs();yo=B($()),Ga=B(ne());eE();yc();no();Xu();L0();Qt=new Uint8Array(8),Ste=new Float64Array(Qt.buffer,0,1),nR={},M0="openapi";a(Tte,"http");pl=0;a(gte,"start");Rte={401:3e3,403:3003}});var sR=g((spe,B0)=>{var{recordAction:nE,recordActionBinary:Ate}=(Cs(),ie(hu)),Ote=require("fastify-plugin"),bte=200;B0.exports=Ote(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),nE(o,"duration",_,d,l),Ate(s.raw.statusCode<400,"success",_,d,l);let E=bte;i?.pipe?(i.on("data",S=>{E+=S.length}),i.on("end",()=>{nE(performance.now()-c,"transfer",_,d,l),nE(E,"bytes-sent",_,d,l)})):(E+=i?.length||0,nE(E,"bytes-sent",_,d,l));let f=o.toFixed(3),h=s.getHeader("Server-Timing"),p=`db;dur=${f}`;s.header("Server-Timing",h?`${h}, ${p}`:p)}),r()},{name:"hdb-request-time"})});var lR=g((ape,q0)=>{var aE=require("clone"),cE=Xe(),yte=z(),iE=P(),ipe=$(),iR=require("fs"),aR=require("joi"),{string:oE}=aR.types(),{hdb_errors:Nte,handleHDBError:sE}=ne(),{HDB_ERROR_MSGS:ope,HTTP_STATUS_CODES:oR}=Nte,{common_validators:qa}=Jn(),H0=" is required",Ite=["insert","update","upsert"],cR={database:{presence:!1,format:qa.schema_format,length:qa.schema_length},schema:{presence:!1,format:qa.schema_format,length:qa.schema_length},table:{presence:!0,format:qa.schema_format,length:qa.schema_length},action:{inclusion:{within:Ite,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},wte={schema:oE.required(),table:oE.required(),action:oE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Cte,AWS_SECRET:Dte,AWS_BUCKET:Lte,AWS_FILE_KEY:Mte,REGION:Pte}=iE.S3_BUCKET_AUTH_KEYS,Ute={s3:{presence:!0},[`s3.${Cte}`]:{presence:!0,type:"String"},[`s3.${Dte}`]:{presence:!0,type:"String"},[`s3.${Lte}`]:{presence:!0,type:"String"},[`s3.${Mte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Pte}`]:{presence:!0,type:"String"}},x0=aE(cR);x0.data.presence={message:H0};var G0=aE(cR);G0.file_path.presence={message:H0};var vte=Object.assign(aE(cR),Ute),uR=aE(wte);uR.csv_url=oE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();uR.passthrough_headers=aR.object();function Bte(e){let t=cE.validateObject(e,x0);return uE(e,t)}a(Bte,"dataObject");function Hte(e){let t=cE.validateBySchema(e,aR.object(uR));return uE(e,t)}a(Hte,"urlObject");function xte(e){let t=cE.validateObject(e,G0);return uE(e,t)}a(xte,"fileObject");function Gte(e){let t=cE.validateObject(e,vte);return uE(e,t)}a(Gte,"s3FileObject");function uE(e,t){if(!t){let r=yte.checkGlobalSchemaTable(e.schema,e.table);if(r)return sE(new Error,r,oR.BAD_REQUEST);if(e.operation===iE.OPERATIONS_ENUM.CSV_FILE_LOAD)try{iR.accessSync(e.file_path,iR.constants.R_OK|iR.constants.F_OK)}catch(n){return n.code===iE.NODE_ERROR_CODES.ENOENT?sE(n,`No such file or directory ${n.path}`,oR.BAD_REQUEST):n.code===iE.NODE_ERROR_CODES.EACCES?sE(n,`Permission denied ${n.path}`,oR.BAD_REQUEST):sE(n)}}return t}a(uE,"postValidateChecks");q0.exports={dataObject:Bte,urlObject:Hte,fileObject:xte,s3FileObject:Gte}});var _R=g((upe,F0)=>{"use strict";var Sl=$(),lE=P();async function qte(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===lE.OPERATIONS_ENUM.INSERT||t.operation===lE.OPERATIONS_ENUM.UPDATE||t.operation===lE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===lE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(Sl.info(i.message),i):i.http_resp_msg?(Sl.error(`Error calling operation: ${e.name}`),Sl.error(i.http_resp_msg),i):(Sl.error(`Error calling operation: ${e.name}`),Sl.error(i),i)}}a(qte,"callOperationFunctionAsAwait");F0.exports={callOperationFunctionAsAwait:qte}});var V0=g((_pe,k0)=>{"use strict";var dR=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}},fR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};k0.exports={BulkLoadFileObject:dR,BulkLoadDataObject:fR}});var Y0=g((fpe,$0)=>{"use strict";var ER=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};$0.exports=ER});var gR=g((Tpe,cB)=>{"use strict";var _E=qr(),fE=lR(),Fte=require("needle"),Gn=P(),hpe=Ve(),Fa=z(),{handleHDBError:lt,hdb_errors:eB}=ne(),{HTTP_STATUS_CODES:zt,HDB_ERROR_MSGS:Lt,CHECK_LOGS_WRAPPER:Io}=eB,ka=$(),hR=require("papaparse");Fa.promisifyPapaParse();var qn=require("fs-extra"),kte=require("path"),{chain:K0}=require("stream-chain"),W0=require("stream-json/streamers/StreamArray"),Q0=require("stream-json/utils/Batch"),z0=require("stream-chain/utils/comp"),{finished:J0}=require("stream"),Vte=Z(),tB=_R(),$te=xg(),{BulkLoadFileObject:pR,BulkLoadDataObject:Yte}=V0(),SR=wg(),{verifyBulkLoadAttributePerms:rB}=Vf(),mpe=Y0(),ppe=ut(),Spe=As(),{databases:Kte}=(Ae(),ie(ke)),{coerceType:Wte}=(EE(),ie(RR)),j0="No records parsed from csv file.",No=`${Vte.get("HDB_ROOT")}/tmp`,{schema_regex:Qte}=Jn(),X0=1024*1024*2,Z0=5e3,zte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};cB.exports={csvDataLoad:Jte,csvURLLoad:jte,csvFileLoad:Xte,importFromS3:Zte};async function Jte(e,t){let r=fE.dataObject(e);if(r)throw lt(r,r.message,zt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=iB(e.schema,e.table),i=hR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:mR.bind(null,s),dynamicTyping:!1}),o=new SR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&rB(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw lt(new Error,c,zt.BAD_REQUEST,void 0,void 0,!0);let u=new Yte(e.action,e.schema,e.table,i.data);return n=await tB.callOperationFunctionAsAwait(oB,u,null),n.message===j0?j0:aB(n.records,n.number_written)}catch(s){throw wo(s)}}a(Jte,"csvDataLoad");async function jte(e){let t=fE.urlObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${No}/${r}`;try{await ere(e,r)}catch(s){throw ka.error(Lt.DOWNLOAD_FILE_ERR(r)+" - "+s),lt(s,Io(Lt.DOWNLOAD_FILE_ERR(r)))}try{let s=new pR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await TR(s);return await dE(n),i}catch(s){throw await dE(n),wo(s)}}a(jte,"csvURLLoad");async function Xte(e){let t=fE.fileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=new pR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await TR(r)}catch(n){throw wo(n)}}a(Xte,"csvFileLoad");async function Zte(e){let t=fE.s3FileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=kte.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${No}/${s}`;let i=new pR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await tre(s,e);let o=await TR(i);return await dE(r),o}catch(n){throw await dE(r),wo(n)}}a(Zte,"importFromS3");async function ere(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Fte("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw lt(n,s,n.statusCode,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}nre(r,e.csv_url),await rre(t,r.raw)}a(ere,"downloadCSVFile");async function tre(e,t){try{let r=`${No}/${e}`;await qn.mkdirp(No),await qn.writeFile(`${No}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await $te.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){ka.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw ka.error(Lt.S3_DOWNLOAD_ERR+" - "+r),lt(r,Io(Lt.S3_DOWNLOAD_ERR))}}a(tre,"downloadFileFromS3");async function rre(e,t){try{await qn.mkdirp(No),await qn.writeFile(`${No}/${e}`,t)}catch(r){throw ka.error(Lt.WRITE_TEMP_FILE_ERR),lt(r,Io(Lt.DEFAULT_BULK_LOAD_ERR))}}a(rre,"writeFileToTempFolder");async function dE(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{ka.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(dE,"deleteTempFile");function nre(e,t){if(e.statusCode!==eB.HTTP_STATUS_CODES.OK)throw lt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,zt.BAD_REQUEST);if(!zte[e.headers["content-type"]])throw lt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,zt.BAD_REQUEST);if(!e.raw)throw lt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,zt.BAD_REQUEST)}a(nre,"validateURLResponse");async function TR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await sre(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await ire(e);break;default:throw lt(new Error,Lt.DEFAULT_BULK_LOAD_ERR,zt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_FILE_EXT_ERR(e))}return aB(t.records,t.number_written)}catch(t){throw wo(t)}}a(TR,"fileLoad");async function nB(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 _E.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&rB(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=lt(c);r(u)}}a(nB,"validateChunk");async function sB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Fa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Fa.isEmpty(c)&&!Fa.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await tB.callOperationFunctionAsAwait(oB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=lt(c,Io(Lt.INSERT_CSV_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_CSV_ERR+" - "+c);r(u)}}a(sB,"insertChunk");async function sre(e){let t={records:0,number_written:0},r=iB(e.schema,e.table);try{let n=new SR,s=qn.createReadStream(e.file_path,{highWaterMark:X0});s.setEncoding("utf8"),await hR.parsePromise(s,nB.bind(null,e,n),mR.bind(null,r));let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:X0}),s.setEncoding("utf8"),await hR.parsePromise(s,sB.bind(null,e,t),mR.bind(null,r)),s.destroy(),t}catch(n){throw lt(n,Io(Lt.PAPA_PARSE_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.PAPA_PARSE_ERR+n)}}a(sre,"callPapaParse");function iB(e,t){let r=Kte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Wte(i,s));return n}a(iB,"createTransformMap");function mR(e,t,r){let n=e.get(r);return n?n(t):Fa.autoCast(t)}a(mR,"typeFunction");async function ire(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new SR,s=K0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),W0.withParser(),c=>c.value,new Q0({batchSize:Z0}),z0(async c=>{await nB(e,n,r,c)})]);await new Promise((c,u)=>{J0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);let o=K0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),W0.withParser(),c=>c.value,new Q0({batchSize:Z0}),z0(async c=>{await sB(e,t,r,c)})]);return await new Promise((c,u)=>{J0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw lt(n,Io(Lt.INSERT_JSON_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_JSON_ERR+n)}}a(ire,"insertJson");async function oB(e){let t={};try{e.data&&e.data.length>0&&ore(e.data[0])?t=await are(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",ka.info(t.message))}catch(r){throw wo(r)}return t}a(oB,"callBulkFileLoad");function ore(e){let t=Object.keys(e);for(let r of t)if(!Qte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(ore,"validateColumnNames");async function are(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=_E.insert;break;case"update":i=_E.update;break;case"upsert":i=_E.upsert;break;default:throw lt(new Error,Lt.INVALID_ACTION_PARAM_ERR(n),zt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Fa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw wo(o)}}a(are,"bulkFileLoad");function aB(e,t){return`successfully loaded ${t} of ${e} records`}a(aB,"buildResponseMsg");function wo(e){return lt(e,Io(Lt.DEFAULT_BULK_LOAD_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(wo,"buildTopLevelErrMsg")});var lB=g((Rpe,uB)=>{"use strict";var AR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};uB.exports=AR});var fB=g((Ope,dB)=>{"use strict";var cre=P(),_B=require("moment"),ure=require("uuid").v4,OR=class{static{a(this,"JobObject")}constructor(){this.id=ure(),this.type=void 0,this.start_datetime=_B().valueOf(),this.created_datetime=_B().valueOf(),this.end_datetime=void 0,this.status=cre.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};dB.exports=OR});var bR=g((ype,RB)=>{"use strict";var lre=require("uuid").v4,SB=qr(),TB=Gr(),_re=ts(),dre=ia(),fre=lB(),et=P(),Ere=fB(),hre=Vd(),Sn=$(),mre=Fc(),Va=z(),{promisify:pre}=require("util"),Co=require("moment"),Sre=Yf(),hE=lR(),EB=Qm(),{deleteTransactionLogsBeforeValidator:Tre}=Og(),{handleHDBError:hB,hdb_errors:gre}=ne(),{HTTP_STATUS_CODES:mB}=gre,pB=TB.searchByValue,Rre=TB.searchByHash,Are=SB.insert,Ore=pre(Sre.evaluateSQL),bre=SB.update;RB.exports={addJob:Ire,updateJob:Cre,handleGetJob:yre,handleGetJobsByStartDate:Nre,getJobById:gB};async function yre(e){try{let t=await gB(e.id);return Va.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw Sn.error("There was an error getting job",t),new Error(r)}}a(yre,"handleGetJob");async function Nre(e){try{let t=await wre(e);if(Sn.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=Co(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Co(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw Sn.error(r),new Error(r)}}a(Nre,"handleGetJobsByStartDate");async function Ire(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Va.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Sn.info(l),t.error=l,t}if(!et.JOB_TYPE_ENUM[e.operation])return Sn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case et.OPERATIONS_ENUM.CSV_FILE_LOAD:n=hE.fileObject(e);break;case et.OPERATIONS_ENUM.CSV_URL_LOAD:n=hE.urlObject(e);break;case et.OPERATIONS_ENUM.CSV_DATA_LOAD:n=hE.dataObject(e);break;case et.OPERATIONS_ENUM.IMPORT_FROM_S3:n=hE.s3FileObject(e);break;case et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=EB(e,"date");break;case et.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=EB(e,"timestamp");break;case et.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Tre(e);break;case et.OPERATIONS_ENUM.RESTART_SERVICE:if(et.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw hB(new Error,"Invalid service",mB.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw hB(n,n.message,mB.BAD_REQUEST,void 0,void 0,!0);let s=new Ere;s.type=e.operation===et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new _re(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await pB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=lre();try{o=await pB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Sn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new mre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await Are(u)}catch(l){return Sn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,Sn.trace(l)}return t}a(Ire,"addJob");async function wre(e){let t=Co(e.from_date,Co.ISO_8601),r=Co(e.to_date,Co.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 fre(n,e.hdb_user);try{return await Ore(s)}catch(i){throw Sn.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(wre,"getJobsInDateRange");async function gB(e){if(Va.isEmptyOrZeroLength(e))return Va.errorizeMessage("Invalid job ID specified.");let t=new dre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Rre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Sn.error(n),Va.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(gB,"getJobById");async function Cre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Va.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===et.JOB_STATUS_ENUM.COMPLETE||e.status===et.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Co().valueOf());let t=new hre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await bre(t),r}a(Cre,"updateJob")});var CB=g((Ipe,wB)=>{"use strict";var AB=z(),Mt=P(),Dre=require("moment"),mE=gR(),Tl=$(),OB=bR(),bB=Kf(),yB=ai(),NB=We(),Lre=Gf(),Mre=zu(),{parentPort:Pre,isMainThread:IB}=require("worker_threads"),{onMessageByType:Ure}=We(),yR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function vre(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(AB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(AB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Mt.JOB_TYPE_ENUM.csv_file_load:await ds(e,mE.csvFileLoad);break;case Mt.JOB_TYPE_ENUM.csv_url_load:await ds(e,mE.csvURLLoad);break;case Mt.JOB_TYPE_ENUM.csv_data_load:await ds(e,mE.csvDataLoad);break;case Mt.JOB_TYPE_ENUM.import_from_s3:await ds(e,mE.importFromS3);break;case Mt.JOB_TYPE_ENUM.empty_trash:break;case Mt.JOB_TYPE_ENUM.export_local:await ds(e,bB.export_local);break;case Mt.JOB_TYPE_ENUM.export_to_s3:await ds(e,bB.export_to_s3);break;case Mt.JOB_TYPE_ENUM.delete_files_before:case Mt.JOB_TYPE_ENUM.delete_records_before:await ds(e,yB.deleteFilesBefore);break;case Mt.JOB_TYPE_ENUM.delete_audit_logs_before:await ds(e,yB.deleteAuditLogsBefore);break;case Mt.JOB_TYPE_ENUM.delete_transaction_logs_before:await ds(e,Lre.deleteTransactionLogsBefore);break;case Mt.JOB_TYPE_ENUM.restart_service:return await ds(e,Mre.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(vre,"parseMessage");async function ds(e,t){try{e.job.status=Mt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Dre().valueOf(),await OB.updateJob(e.job),await Bre(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):Tl.error(`There was an error running ${t.name} job with id ${e.job.id}`),Tl.error(n),e.job.message=n,e.job.status=Mt.JOB_STATUS_ENUM.ERROR;try{await OB.updateJob(e.job)}catch(s){throw Tl.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(ds,"runJob");async function Bre(e){Tl.trace("launching job thread:",e),IB?NB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})}):Pre.postMessage({type:Mt.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(Bre,"launchJobThread");IB&&Ure(Mt.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{NB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`})})}catch(r){Tl.error(r)}});wB.exports={parseMessage:vre,RunnerMessage:yR}});var LB=g((Cpe,DB)=>{"use strict";var NR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};DB.exports=NR});var QB=g((Lpe,MR)=>{"use strict";var RE=Gr(),CR=Yf(),pE=gR(),Fs=Au(),SE=Os(),Rl=ai(),Hre=FS(),gl=ln(),TE=JS(),Jt=Ag(),gE=$(),xre=ZS(),Gre=rf(),MB=MT(),qre=sf(),Fre=UT(),kre=vT(),Vre=xT(),$re=qT(),IR=VT(),PB=Kf(),Yre=Vf(),DR=bR(),q=P(),{hdb_errors:Ol,handleHDBError:Al}=ne(),{HTTP_STATUS_CODES:UB}=Ol,wR=QT(),vB=zu(),$B=require("util"),$a=qr(),Kre=bs(),Wre=ga(),BB=CB(),HB=wu(),xB=(Cf(),ie(Zu)),GB=Er(),qB=Gf(),FB=Uf(),{setServerUtilities:Qre}=(EE(),ie(RR)),{CONTEXT:zre}=(Nn(),ie(Fp)),{_assignPackageExport:Jre}=require("../index"),{transformReq:jre}=z(),{server:Xre}=(lr(),ie(xi)),or=gE.loggerWithTag("operation"),Zre=_R(),kB=RE.searchByHash,ene=RE.searchByValue,tne=$B.promisify(RE.search),rne=$B.promisify(CR.evaluateSQL),nne={[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=LB();async function YB(e,t){try{if(e.body.operation!=="read_log"&&(gE.log_level===q.LOG_LEVELS.INFO||gE.log_level===q.LOG_LEVELS.DEBUG||gE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;or.info(o)}}catch(n){or.error(n)}let r=await Zre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return nne[e.body.operation]&&Kre.setSchemaDataToGlobal(n=>{n&&or.error(n)}),r}a(YB,"processLocalTransaction");var VB=ine();MR.exports={chooseOperation:KB,getOperationFunction:WB,operation:LR,processLocalTransaction:YB};Qre(MR.exports);Xre.operation=LR;function KB(e){let t;try{t=WB(e)}catch(s){throw or.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=CR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=CR.checkASTPermissions(e,i);if(o)throw or.error(`${UB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Al(new Error,o,Ol.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=Yre.verifyPerms(i,s);if(o)throw or.error(`${UB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Al(new Error,o,Ol.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw Al(s,"There was an error when trying to choose an operation path")}return r}a(KB,"chooseOperation");function WB(e){if(or.trace(`getOperationFunction with operation: ${e.operation}`),VB.has(e.operation))return VB.get(e.operation);throw Al(new Error,Ol.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Ol.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(WB,"getOperationFunction");Jre("operation",LR);function LR(e,t){e.hdb_user=this[zre]?.user,e.bypass_auth=!t;let r=KB(e);return YB({body:e},r)}a(LR,"operation");async function sne(e){or.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await $a.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await $a.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await $a.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await Rl.deleteRecord(i);break;default:or.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){or.info("Invalid operation in transaction"),or.error(o)}}a(sne,"catchup");async function Fn(e){jre(e);let t,r;try{r=await DR.addJob(e),t=r.createdJob,or.info("addJob result",r);let n=new BB.RunnerMessage(t,e);return{message:await BB.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw or.error(s),Al(n,s)}}a(Fn,"executeJob");function ine(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y($a.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y($a.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y($a.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(RE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(kB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(kB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(ene)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(tne)),e.set(q.OPERATIONS_ENUM.SQL,new Y(rne)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(Fn,pE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(Fn,pE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(Fn,pE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(Fn,pE.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(SE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(SE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(SE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(SE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(Rl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(gl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(gl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(gl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(gl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(TE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(TE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(TE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(TE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(gl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(xre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Gre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(MB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(MB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(qre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Fre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(kre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(GB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Vre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y($re)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(IR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(IR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(IR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(Fn,PB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(Fn,Rl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(Fn,Rl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(Fn,PB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(DR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(DR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(wR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(wR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(wR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(vB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(Fn,vB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(sne)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Wre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(Fn,Rl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Hre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(HB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(HB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(xB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(xB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(GB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Jt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Jt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Jt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Jt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Jt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Jt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Jt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Jt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Jt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Jt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Jt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Jt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Jt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Jt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Jt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Jt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(qB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(Fn,qB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(FB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(FB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(ine,"initializeOperationFunctionMap")});var OE=g((Ppe,jB)=>{"use strict";var PR=P(),one=z(),bl=$(),{handleHDBError:UR,hdb_errors:AE}=ne(),{isMainThread:ane}=require("worker_threads"),{Readable:cne}=require("stream"),zB=require("os"),une=require("util"),lne=uT(),_ne=une.promisify(lne.authorize),JB=QB(),{createGzip:dne,constants:fne}=require("zlib");function Ene(e){let t=`Found an uncaught exception with message: ${e.message}. ${zB.EOL}Stack: ${e.stack} ${zB.EOL}Terminating ${ane?"HDB":"thread"}.`;console.error(t),bl.fatal(t),process.exit(1)}a(Ene,"handleServerUncaughtException");function hne(e,t,r){if(bl[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:AE.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(hne,"serverErrorHandler");function mne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=UR(new Error,"Invalid JSON.",AE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(one.isEmpty(e.body.operation)){let n=UR(new Error,"Request body must include an 'operation' property.",AE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(mne,"reqBodyValidationHandler");function pne(e,t,r){let n;e.body.operation!==PR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==PR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==PR.OPERATIONS_ENUM.LOGOUT?_ne(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{bl.warn(s),bl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(UR(s,i,AE.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(pne,"authHandler");async function Sne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=JB.chooseOperation(e.body);let s=await JB.processLocalTransaction(e,n);if(s instanceof cne&&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(dne({level:fne.Z_BEST_SPEED})))}return s}catch(s){throw bl.error(s),s}}a(Sne,"handlePostRequest");jB.exports={authHandler:pne,handlePostRequest:Sne,handleServerUncaughtException:Ene,serverErrorHandler:hne,reqBodyValidationHandler:mne}});var tH=g((vpe,eH)=>{"use strict";var Tne=require("fastify-plugin"),{handlePostRequest:XB,authHandler:gne,reqBodyValidationHandler:Rne}=OE();async function Ane(e){e.decorate("hdbCore",{preValidation:[Rne,gne],request:t=>ZB(XB(t,response)),requestWithoutAuthentication:(t,r)=>ZB(XB(t,r,!0))})}a(Ane,"hdbCore");async function ZB(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(ZB,"convertAsyncIterators");eH.exports=Tne(Ane)});var sH=g((xpe,nH)=>{"use strict";var Hpe=require("fs"),vR=Z();vR.initSync();var{CONFIG_PARAMS:rH}=P(),One=1024*1024*1024;function bne(e){let t=vR.get(rH.HTTP_TIMEOUT),r=vR.get(rH.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:One,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(bne,"getServerOptions");nH.exports=bne});var aH=g((qpe,oH)=>{"use strict";var BR=Z();BR.initSync();var{CONFIG_PARAMS:iH}=P();function yne(){let e=BR.get(iH.HTTP_CORSACCESSLIST),t=BR.get(iH.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(yne,"getCORSOptions");oH.exports=yne});var lH=g((kpe,uH)=>{"use strict";var cH=Z();cH.initSync();var Nne=P();function Ine(){return cH.get(Nne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Ine,"getHeaderTimeoutConfig");uH.exports=Ine});var xR={};Fe(xR,{customFunctionsServer:()=>Dne,ready:()=>yH,start:()=>Cne});function Cne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=bH(t),at.http((await ks).server));let o=await ks,c=(0,HR.dirname)(s),u=(0,HR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!_H.has(c)){_H.add(c);try{o.register(Mne(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ye.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:yH}}async function Dne(){try{Ye.info("In Custom Functions Fastify server"+process.cwd()),Ye.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ye.debug(`Custom Functions server process ${process.pid} starting up.`),await Lne();let e=pH.get(SH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await bH(e)}catch(r){throw Ye.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ye.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ye.error(`Custom Functions ${process.pid} Error: ${e}`),Ye.error(e),process.exit(1)}}async function Lne(){try{Ye.info("Custom Functions starting configuration."),await TH.setUsersToGlobal(),Ye.info("Custom Functions completed configuration.")}catch(e){Ye.error(e)}}function Mne(e,t){return async function(r){try{Ye.info("Custom Functions starting buildRoutes"),Ye.trace("Loading fastify routes folder "+e),(0,dH.existsSync)(e)&&r.register(mH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ye.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ye.error(s.message):s&&Ye.error(s),o()})}catch(n){Ye.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function bH(e){Ye.info("Custom Functions starting buildServer.");let t=(0,gH.default)(e),r=(0,fH.default)(t);r.server.headersTimeout=(0,AH.default)(),r.setErrorHandler(OH.serverErrorHandler);let n=(0,RH.default)();return n&&r.register(EH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(hH.default),await r.register(wne),await r.after(),Yg(r),Ye.info("Custom Functions completed buildServer."),r}function yH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var HR,dH,fH,EH,hH,mH,pH,SH,Ye,wne,TH,gH,RH,AH,OH,ks,_H,NH=Re(()=>{HR=require("path"),dH=require("fs"),fH=B(require("fastify")),EH=B(require("@fastify/cors")),hH=B(sR()),mH=B(require("@fastify/autoload")),pH=B(Z()),SH=B(P()),Ye=B($()),wne=B(tH()),TH=B(ln()),gH=B(sH()),RH=B(aH()),AH=B(lH()),OH=B(OE());Ca();lr();_H=new Set;a(Cne,"start");a(Dne,"customFunctionsServer");a(Lne,"setUp");a(Mne,"buildRouteFolder");a(bH,"buildServer");a(yH,"ready")});var GR={};Fe(GR,{start:()=>Pne});function Pne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,LH.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){wH||(wH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=IH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,CH.default)(s,(0,DH.realpathSync)(o))}}return i(s)},{runFirst:!0})),IH.set(r,n)}}}var CH,DH,LH,IH,wH,MH=Re(()=>{CH=B(require("send")),DH=require("fs"),LH=B(require("serve-static")),IH=new Map;a(Pne,"start")});function Bne(){let e=(0,BH.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),FR=setInterval(()=>{NE.notify(e)},vne).unref())}function Hne(e,t=1,r){if(qR++,(0,Vs.startWorker)("server/threads/threadServer.js",{name:za.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===za.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Une.push(s),await s,Ya.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=yE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Ya.indexOf(n);o>-1&&Ya.splice(o,1)}if(a(i,"removeWorker"),Ka){let o=Ka;Ka=[];for(let c of o)HH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{kR?kR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Vs.shutdownWorkers)(),qR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function xH(e=0,t){if(typeof e=="string")try{(0,IE.existsSync)(e)&&(0,IE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=xne:r=Gne(t):r=VR;let n=(0,Wa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=HH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),kR=!0,r(o,(c,u)=>{if(!c){if(PH){let l=o._socket||new Wa.Socket({handle:o,writable:!0,readable:!0});PH.deliverSocket(l,e,u),l.resume()}else qR>0?(Ka.length===0&&setTimeout(()=>{Ka.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Ka.push(o)):(console.log("start up a dynamic thread to handle request"),Hne(0));Sr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Wa.Socket({handle:o,writable:!0,readable:!0});Vne(l,c,e)}Sr(!0,"socket-routed")})};let s=lu();NE.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 VR(e,t){let r,n=0;for(let s of Ya){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=bE)return bE=i,t(r);n=i}bE=0,t(r)}function xne(e,t){let r={};e.getpeername(r);let n=r.address,s=Qa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);VR(e,o=>{Qa.set(n,{worker:o,lastUsed:i}),t(o)})}function Gne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Wa.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Qa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);VR(n,d=>{Qa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Fne(){bE=0;for(let e of Ya)e.expectedIdle=e.recentELU.idle+qne,e.requests=1;Ya.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Vne(e,t,r){let n=kne++;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(),yE.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")),yE.delete(n)),s.event=="destroy"&&(e.destroy(),yE.delete(n))})}var Vs,Wa,za,NE,IE,vH,BH,Ya,Ka,HH,PH,qR,Une,FR,vne,kR,bE,UH,Qa,qne,yE,kne,GH=Re(()=>{Vs=B(We()),Wa=require("net"),za=B(P()),NE=B($()),IE=require("fs");Cs();vH=require("worker_threads"),BH=B(ji()),Ya=[],Ka=[],HH=[],qR=0,Une=[];vH.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,Vs.onMessageFromWorkers)(e=>{e.type===za.ITC_EVENT_TYPES.RESTART&&FR&&(clearInterval(FR),Bne())}));vne=6e5;a(Bne,"licenseWarning");a(Hne,"startHTTPWorker");a(xH,"startSocketServer");bE=0;a(VR,"findMostIdleWorker");UH=36e5,Qa=new Map;a(xne,"findByRemoteAddressAffinity");a(Gne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Qa)r.lastUsed+UH<e&&Qa.delete(t)},UH).unref();qne=1e3;a(Fne,"updateWorkerIdleness");(0,Vs.setMonitorListener)(Fne);yE=new Map,kne=1;a(Vne,"proxySocket")});var WR={};Fe(WR,{Request:()=>$R,createReuseportFd:()=>wE});var qH,$R,YR,KR,wE,CE=Re(()=>{qH=require("os"),$R=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 KR(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 YR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},YR=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)}},KR=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,qH.platform)()!="win32"&&(wE=require("node-unix-socket").createReuseportFd)});var $H=g((nSe,VH)=>{"use strict";var $ne=require("cluster"),Do=Z();Do.initSync();var kH=P(),Xpe=require("util"),$s=$(),Zpe=require("fs"),Yne=require("fastify"),eSe=lu(),Kne=require("@fastify/cors"),Wne=require("@fastify/compress"),Qne=require("@fastify/static"),zne=sR(),Jne=require("path"),{PACKAGE_ROOT:jne}=P(),Xne=bs(),Zne=z(),ese=ln(),tse=ji(),{server:rse}=(lr(),ie(xi)),{node_request_key:tSe}=(CE(),ie(WR)),{authHandler:nse,handlePostRequest:sse,serverErrorHandler:ise,reqBodyValidationHandler:ose}=OE(),rSe=require("net"),{registerContentHandlers:ase}=(Ca(),ie(R0)),cse=6e4,use=1024*1024*1024,lse="TRUE",{CONFIG_PARAMS:yl}=kH,Ja;VH.exports={hdbServer:FH,start:FH};async function FH(e){try{$s.info("In Fastify server"+process.cwd()),$s.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),$s.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=$ne.isMaster,await _se();let t=e.securePort>0;Ja=dse(t),await Ja.ready(),e||(e={}),e.isOperationsServer=!0;try{rse.http(Ja.server,e),Ja.server.closeIdleConnections||await Ja.listen({port:0,host:"::"})}catch(r){throw Ja.close(),$s.error(r),$s.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),$s.fatal(t),process.exit(1)}}a(FH,"operationsServer");async function _se(){$s.trace("Configuring HarperDB process."),Xne.setSchemaDataToGlobal(),await ese.setUsersToGlobal(),await tse.getLicense()}a(_se,"setUp");function dse(e){$s.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=fse(e),r=Yne(t);r.server.headersTimeout=hse(),r.setErrorHandler(ise);let n=Ese();n&&r.register(Kne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(zne),r.register(Wne),r.register(Qne,{root:Jne.join(jne,"studio/build-local")}),ase(r);let s=Do.get(kH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Zne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[ose,nse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),sse(i,o)}),r.get("/health",()=>"HarperDB is running."),$s.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(dse,"buildServer");function fse(e){let t=Do.get(yl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(yl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:use,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(fse,"getServerOptions");function Ese(){let e=Do.get(yl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(yl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===lse)&&(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 hse(){return Do.get(yl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??cse}a(hse,"getHeaderTimeoutConfig")});var ZR={};Fe(ZR,{disableNATS:()=>pse,publishToStream:()=>ME,setNATSReplicator:()=>QR,setPublishToStream:()=>Sse,setSubscription:()=>XR,start:()=>mse});function mse(){Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&gse()}function pse(e=!0){zH=e}function Sse(e,t){ME=e,XR=t}function gse(){if(zH||process.env._DISABLE_NATS)return;let e=mr(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];QR(s,r,i)}}eA((r,n)=>{QR(r.tableName,r.databaseName,r),n&&jH(r)}),!YH&&(YH=!0)}function QR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends $t{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){jH(i)}static subscribe(){let i=new yn;return XR(t,e,i),i}static subscribeOnThisThread(i){return i<(Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Tse)}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 DE(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=JH;return i}a(n,"getNATSTransaction")}function jH(e){let t=Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_NODENAME);ME(`${JR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,jR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var KH,JR,jR,WH,QH,Nl,Il,LE,zH,ME,XR,Tse,JH,YH,DE,zR,XH=Re(()=>{Ae();Nn();KH=B(ut()),JR=B(Ve()),jR=B(As());yc();WH=B(CS()),QH=B(vr()),Nl=B(Z()),Il=B(P()),LE=B($());a(mse,"start");a(pse,"disableNATS");ME=KH.publishToStream,XR=WH.setSubscription;a(Sse,"setPublishToStream");Tse=2;a(gse,"assignReplicationSource");a(QR,"setNATSReplicator");a(jH,"publishSchema");DE=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=Nl.default.get(Il.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,E=l.operation=="put"?"upsert":l.operation;u||(LE.trace(`Sending transaction event ${E}`),_=u={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&E!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(l.record),c.push(l.id)):_=_.next={operation:E,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(ME(`${JR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,jR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw LE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},zR=class extends DE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,QH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};JH=new zR});var dx=g(Li=>{"use strict";var{isMainThread:nA,parentPort:Cl,threadId:PE}=require("worker_threads"),{Socket:Rse,createServer:Ase}=require("net"),{createServer:Ose,IncomingMessage:bse}=require("http"),{createServer:yse}=require("https"),{readFileSync:Nse,unlinkSync:ZH,existsSync:Ise}=require("fs"),Pt=$(),xe=Z(),_t=P(),{server:BE}=(lr(),ie(xi)),{WebSocketServer:wse}=require("ws"),{createSecureContext:Cse,createServer:Dse}=require("node:tls"),{getTicketKeys:nx,restartNumber:Lse,getWorkerIndex:Dl}=We(),{Headers:sx,appendHeader:Mse}=(Xu(),ie($U)),{recordAction:wl,recordActionBinary:Pse}=(Cs(),ie(hu)),{Request:ix,createReuseportFd:ex}=(CE(),ie(WR)),{checkMemoryLimit:Use}=ji(),{X509Certificate:vse}=require("crypto"),ox=require("tls"),Bse=ox.createSecureContext,ja;ox.createSecureContext=function(e){return ja||Bse(e)};var ax=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG);if(ax){let e;if(nA)e=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Pt.info("Could not close debugger",t)}});else{let t=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&Dl()>=0&&(e=t+Dl())}if(e){let t=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=xe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Pt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&nA)try{require("inspector").open(9229)}catch(e){Lse<=1&&Pt.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:lSe,CONFIG_PARAMS:Hse}=_t;xe.initSync();var xse=xe.get(Hse.HTTP_SESSIONAFFINITY),Es={};Li.registerServer=aA;Li.httpServer=cA;Li.deliverSocket=oA;Li.startServers=cx;Li.when_components_loaded=null;Li.createSNICallback=uA;BE.http=cA;BE.request=kse;BE.socket=Vse;BE.ws=$se;var tA={},UE={},Gse,Ys={},vE={},qse=[],sA=[];function cx(){return Li.when_components_loaded=lA().loadRootComponents(!0).then(()=>{Cl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)oA(n,r,s);else if(t.requestId)Fse(t);else if(t.type===_t.ITC_EVENT_TYPES.SHUTDOWN){Pt.trace("received shutdown request",PE);for(let i in Es){let o=Es[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),l=0,d=setInterval(()=>{l++;let E=l>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}l===1?Pt.info(`Closing ${f.length} idle connections`):E&&Pt.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,p=f.length;h<p;h++){let S=f[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
|
|
28
|
+
`},compressible:!1,q:.8});Ft.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});R0={type:"application/json",serializeStream:wc,serialize:El,deserialize:nte,q:.5};Ft.set("*/*",R0);Ft.set("",R0);a(nte,"tryJSONParse");a(Kg,"registerContentHandlers");ste=require("fastify-plugin"),ite=ste(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Jf(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(Jf,"findBestSerializer");h0=kg.default.get(Vg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(jf,"serialize");a(go,"serializeMessage");a(ote,"streamToBuffer");a(bo,"getDeserializer");a(m0,"deserializerUnknownType");a(ate,"transformIterable")});function Jg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let f=1;f<e.length;f++){let h=e[f],p=_(h);d=d.concat(p)}let E=new Set;return d.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let d=_(u),E=l(e.slice(1),!0,u.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Jg(d.conditions,d.operator,r,n,s,i,o,c):Ha(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,E,f){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",N=l(h.conditions,!R,f);return R?(I,H)=>N.some(U=>U(I,H)):(I,H)=>N.every(U=>U(I,H))}let S=(h.attribute||h[0])===r.primaryKey,T=Xg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=mte(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ha(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],N=qs(n.attributes,R);if(N.relationship){if(o.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let I=N.definition?.tableClass||N.elements?.definition?.tableClass,H=new Map,U=Ha({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,I,s,H);if(N.relationship.to){i[o[0]]=H;let k=!!qs(I.attributes,N.relationship.to)?.elements;U=dte(U,N,I.primaryStore,k,H)}if(N.relationship.from){let k=a(M=>Ha({attribute:N.relationship.from,value:M},t,r,n,s,H),"searchEntry");N.elements?(i[o[0]]=H,U=fte(U,N,I.primaryStore,H,k)):U=U.flatMap(k)}return U}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,E;c instanceof Date&&(c=c.getTime());let f;switch(jg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,E=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=_s.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,E=!0;break}case"sort":case"contains":case"ends_with":_=!0,f=!0;break;default:throw new Xr.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!E,E=!d,d=R}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||f||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Xr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Xr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Xr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Xr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Xg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(T).map(S?function({key:N,value:I}){return this.isSync?I&&S(I)?N:wi.SKIP:new Promise((H,U)=>setImmediate(()=>{try{H(I&&S(I)?N:wi.SKIP)}catch(k){U(k)}}))}:N=>N.value==null?wi.SKIP:N);return R.hasEntries=!0,R}else return p?p.getRange(T).map(S?function({key:R,value:N}){return this.isSync?S({[o]:R})?N:wi.SKIP:new Promise((I,H)=>setImmediate(()=>{try{I(S({[o]:R})?N:wi.SKIP)}catch(U){H(U)}}))}:({value:R})=>R):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:N}){return this.isSync?N&&S(N)?R:wi.SKIP:new Promise((I,H)=>setImmediate(()=>{try{I(N&&S(N)?R:wi.SKIP)}catch(U){H(U)}}))})}function qs(e,t){if(Array.isArray(t))if(t.length>1){let r=qs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?qs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function dte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let E=l;Array.isArray(l)&&(E=Hn(l),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),l!==E&&(f.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),E=d?.[u];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],l);else _(E,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function fte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Hn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Hn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(E=>!E(d)))continue}_.set(Hn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Xg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=qs(t.attributes,l),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[l],h=Xg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},E,r,f?.[l]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((R,N)=>{let I,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 U=S(R);return S.idFilter&&(T.idFilter=S.idFilter),U}H=p(R,r,N),I=H?.value}else I=R[l];return I?Array.isArray(I)?I.some(h):h(I,H):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),jg[o]||o){case Qg.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,E=u.length;d<E;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,_s.compareKeys)(l,u[0])>=0&&(0,_s.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,_s.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,_s.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,_s.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,_s.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,_s.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,E,f){let h;E=E&&!s&&t?.indices[l]&&i>3,E&&(e.estimated_count==null&&Zf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(R){let N=R[l],I;if(typeof N!="object"||!N||f?I=d(N):Array.isArray(N)?I=N.some(d):N instanceof Date&&(I=d(N.getTime())),E&&(S++,!I&&!T.idFilter&&++p/S*(i-S)>h)){let H=Ha(e,r.transaction.getReadTxn(),!1,t).map(Hn),U=new Set(H);T.idFilter=k=>U.has(Hn(k)),T.idFilter.idSet=U}return I}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function Zf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Gs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=jg[n]||n,n===Qg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=qs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Zf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Gs(e.indices[i.relationship.from])/(Gs(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Gs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=lte*Gs(e.primaryStore)+1:n==="between"?r.estimated_count=ute*Gs(e.primaryStore)+1:n==="sort"?r.estimated_count=Gs(e.primaryStore)+1:r.estimated_count=cte*Gs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function eE(e){if(e)if(Ci=e,Ba.lastIndex=0,Ete.test(e))try{let t=ml(new xa,"");if(Dr!==Ci.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${Dr} in '${Ci}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function ml(e,t){let r=Ba,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(Ci);){Dr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=Wg}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=pl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=_te[d],u=zg[i]?Wg:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=pl(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"&&O0(h,l),Xf(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(pl(l)),s=void 0;break;case"(":Ba.lastIndex=Dr;let f=ml(l?[]:new xa,")");switch(l){case"":Xf(e,_),e.conditions.push(f);break;case"limit":switch(f.length){case 1:e.limit=+f[0];break;case 2:e.offset=+f[0],e.limit=f[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(f[0])&&f.length===1&&!f[0].name?(e.select=f[0],e.select.asArray=!0):f.length===1?e.select=f[0]:f.length===2&&f[1]===""?e.select=f.slice(0,1):e.select=f;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=b0(f);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Ci[Dr]===","?r.lastIndex=++Dr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Ba.lastIndex=Dr,E=ml([],"}"),E.name=l,e.push(E),Ci[Dr]===","?r.lastIndex=++Dr:o=!0;break;case"[":Ba.lastIndex=Dr,l?(E=ml(new xa,"]"),E.name=l):E=ml(e.conditions?new xa:[],"]"),e.conditions?(Xf(e,_),e.conditions.push(E),s=null):e.push(E),Ci[Dr]===","?r.lastIndex=++Dr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&O0(h,l),Xf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(pl(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?hte:Ba,r.lastIndex=Dr),Dr===Ci.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Xf(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 pl(e){return e.indexOf(".")>-1?e.split(".").map(pl):decodeURIComponent(e)}function Wg(e){if(e==="null")return null;if(e.indexOf("/")>-1){let t=e.split("/"),r=new Ga(t.length);for(let n=0,s=t.length;n<s;n++)r[n]=Wg(t[n]);return r}if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function O0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function b0(e){let t=y0(e[0]);return e.length>1&&(t.next=b0(e.slice(1))),t}function y0(e){if(Array.isArray(e)){let t=y0(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function Hn(e){return Array.isArray(e)?e.join("\0"):e}function Gs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function mte(e,t,r){return t*r/Gs(e)}var Xr,Qg,_s,wi,cte,ute,lte,_te,zg,jg,Ete,Ba,hte,Dr,Ci,xa,tE=Re(()=>{Xr=x(se()),Qg=x(ft()),_s=require("ordered-binary"),wi=require("lmdb");cn();cte=.3,ute=.1,lte=.05,_te={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},zg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Jg,"executeConditions");a(Ha,"searchByIndex");a(qs,"findAttribute");a(dte,"joinTo");a(fte,"joinFrom");jg={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(Xg,"filterByType");a(Zf,"estimateCondition");Ete=/[()[\]|!<>.]|(=\w*=)/,Ba=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,hte=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(eE,"parseQuery");a(ml,"parseBlock");a(Xf,"assignOperator");a(pl,"decodeProperty");a(Wg,"typedDecoding");a(O0,"wildcardDecoding");a(b0,"toSortObject");a(y0,"toSortEntry");xa=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(Hn,"flattenKey");a(Gs,"estimatedEntryCount");a(mte,"intersectionEstimate")});function D0(e){let t={openapi:pte,info:{title:"HarperDB HTTP REST interface",version:(0,C0.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:N,name:I,elements:H,relationship:U,definition:k}of o){if(U)N==="array"?_[I]={type:"array",items:{$ref:Di+H.type}}:_[I]={$ref:Di+N};else{let M=k??H?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(J=>{Q[J.name]=new rR(Zg[J.type],J.type)}),t.components.schemas[M.type]=new w0(Q)}N==="array"?_[I]={type:"array",items:{$ref:Di+M.type}}:_[I]={$ref:Di+M.type}}else N==="array"?H.type==="Any"||H.type=="ID"?_[I]={type:"array",items:{format:H.type}}:_[I]={type:"array",items:new rR(Zg[H.type],H.type)}:N==="Any"||N=="ID"?_[I]={format:N}:_[I]=new rR(Zg[N],N)}l.push(new nR(I,"query",_[I]))}let d=Object.keys(_),E=new nR(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new nR("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new w0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",R="/"+s+"/";h&&(t.paths[R]={},t.paths[R].post=new Ste(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new eR(l,r,{200:new tR({$ref:Di+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new I0(l,r,"delete all the records that match the provided query",{204:new N0})),R="/"+s+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new eR([E],r,{200:new tR({$ref:Di+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new Tte([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new I0([E],r,"delete a record with the given primary key",{204:new N0})),S&&f.schema.enum.length>0&&(R="/"+s+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new eR([E,f],r,{200:new tR({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:Di+e}}}},this.security=t,this.responses={200:{description:sR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function eR(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function tR(e){this.description=sR,this.content={"application/json":{schema:e}}}function N0(){this.description="successfully processed request, no content returned to client"}function Tte(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Di+r}}}},this.responses={200:{description:sR}}}function I0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function w0(e){this.type="object",this.properties=e}function rR(e,t){this.type=e,this.format=t}function nR(e,t,r){this.name=e,this.in=t,this.schema=r}var C0,pte,Zg,Di,sR,L0=Re(()=>{C0=x(jd()),pte="3.0.3",Zg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Di="#/components/schemas/",sR="successful operation";a(D0,"generateJsonApi");a(Ste,"Post");a(eR,"Get");a(tR,"Response200");a(N0,"Response204");a(Tte,"Put");a(I0,"Delete");a(w0,"ResourceSchema");a(rR,"Type");a(nR,"Parameter")});var nE={};Fe(nE,{start:()=>Ate});async function Rte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&eE(e);let s=new yi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==M0){let h=rE.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Ze(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=bo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new qa.ClientError(h,400)}if(e.authorize=!0,i===M0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return D0(rE);throw new qa.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 qa.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new qa.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,iR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){gte[0]=d;let h=String.fromCharCode(34,(Qt[0]&63)+62,(Qt[0]>>6)+(Qt[1]<<2&63)+62,(Qt[1]>>4)+(Qt[2]<<4&63)+62,(Qt[2]>>2)+62,(Qt[3]&63)+62,(Qt[3]>>6)+(Qt[4]<<2&63)+62,(Qt[4]>>4)+(Qt[5]<<4&63)+62,(Qt[5]>>2)+62,(Qt[6]&63)+62,(Qt[6]>>6)+(Qt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),iR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:l,headers:s,body:void 0},f=_?.wasLoadedFromSource?.();return f!==void 0&&(E.wasCacheMiss=f,!f&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(E.body=jf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?yo.warn(i):yo.info(i):yo.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=jf(i.contentType?i:i.toString(),e,o),o}}function Ate(e){iR=e,!P0&&(P0=!0,rE=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Rte(t,r)},e),e.server.ws(async(t,r,n)=>{Sl++;let s=new Nn;U0||(U0=!0,hu(u=>{Sl>0&&u.push({metric:"ws-connections",connections:Sl,byThread:!0})}));let i;t.on("error",u=>{i=!0,yo.warn(u)});let o;t.on("message",a(function(_){o||(o=bo(r.requestedContentType??r.headers.asObject["content-type"],!1));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{Sl--,Wr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=rE.getMatch(u);if(Wr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,Sr(h=>({count:h.count,total:Sl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=go(f.value,r);t.send(h),Sr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(Ote[u.statusCode]||1011,u.toString()),t.close("login failed")}t.close()},e))}var yo,qa,Qt,gte,iR,M0,P0,rE,U0,Sl,Ote,v0=Re(()=>{Ca();Cs();yo=x($()),qa=x(se());tE();Nc();no();Zu();L0();Qt=new Uint8Array(8),gte=new Float64Array(Qt.buffer,0,1),iR={},M0="openapi";a(Rte,"http");Sl=0;a(Ate,"start");Ote={401:3e3,403:3003}});var oR=g((ape,B0)=>{var{recordAction:sE,recordActionBinary:bte}=(Cs(),ie(mu)),yte=require("fastify-plugin"),Nte=200;B0.exports=yte(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),sE(o,"duration",_,d,l),bte(s.raw.statusCode<400,"success",_,d,l);let E=Nte;i?.pipe?(i.on("data",S=>{E+=S.length}),i.on("end",()=>{sE(performance.now()-c,"transfer",_,d,l),sE(E,"bytes-sent",_,d,l)})):(E+=i?.length||0,sE(E,"bytes-sent",_,d,l));let f=o.toFixed(3),h=s.getHeader("Server-Timing"),p=`db;dur=${f}`;s.header("Server-Timing",h?`${h}, ${p}`:p)}),r()},{name:"hdb-request-time"})});var dR=g((lpe,q0)=>{var cE=require("clone"),uE=Xe(),Ite=z(),oE=P(),cpe=$(),aR=require("fs"),uR=require("joi"),{string:aE}=uR.types(),{hdb_errors:wte,handleHDBError:iE}=se(),{HDB_ERROR_MSGS:upe,HTTP_STATUS_CODES:cR}=wte,{common_validators:Fa}=Jn(),x0=" is required",Cte=["insert","update","upsert"],lR={database:{presence:!1,format:Fa.schema_format,length:Fa.schema_length},schema:{presence:!1,format:Fa.schema_format,length:Fa.schema_length},table:{presence:!0,format:Fa.schema_format,length:Fa.schema_length},action:{inclusion:{within:Cte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Dte={schema:aE.required(),table:aE.required(),action:aE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Lte,AWS_SECRET:Mte,AWS_BUCKET:Pte,AWS_FILE_KEY:Ute,REGION:vte}=oE.S3_BUCKET_AUTH_KEYS,Bte={s3:{presence:!0},[`s3.${Lte}`]:{presence:!0,type:"String"},[`s3.${Mte}`]:{presence:!0,type:"String"},[`s3.${Pte}`]:{presence:!0,type:"String"},[`s3.${Ute}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${vte}`]:{presence:!0,type:"String"}},H0=cE(lR);H0.data.presence={message:x0};var G0=cE(lR);G0.file_path.presence={message:x0};var xte=Object.assign(cE(lR),Bte),_R=cE(Dte);_R.csv_url=aE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();_R.passthrough_headers=uR.object();function Hte(e){let t=uE.validateObject(e,H0);return lE(e,t)}a(Hte,"dataObject");function Gte(e){let t=uE.validateBySchema(e,uR.object(_R));return lE(e,t)}a(Gte,"urlObject");function qte(e){let t=uE.validateObject(e,G0);return lE(e,t)}a(qte,"fileObject");function Fte(e){let t=uE.validateObject(e,xte);return lE(e,t)}a(Fte,"s3FileObject");function lE(e,t){if(!t){let r=Ite.checkGlobalSchemaTable(e.schema,e.table);if(r)return iE(new Error,r,cR.BAD_REQUEST);if(e.operation===oE.OPERATIONS_ENUM.CSV_FILE_LOAD)try{aR.accessSync(e.file_path,aR.constants.R_OK|aR.constants.F_OK)}catch(n){return n.code===oE.NODE_ERROR_CODES.ENOENT?iE(n,`No such file or directory ${n.path}`,cR.BAD_REQUEST):n.code===oE.NODE_ERROR_CODES.EACCES?iE(n,`Permission denied ${n.path}`,cR.BAD_REQUEST):iE(n)}}return t}a(lE,"postValidateChecks");q0.exports={dataObject:Hte,urlObject:Gte,fileObject:qte,s3FileObject:Fte}});var fR=g((dpe,F0)=>{"use strict";var Tl=$(),_E=P();async function kte(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===_E.OPERATIONS_ENUM.INSERT||t.operation===_E.OPERATIONS_ENUM.UPDATE||t.operation===_E.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===_E.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(Tl.info(i.message),i):i.http_resp_msg?(Tl.error(`Error calling operation: ${e.name}`),Tl.error(i.http_resp_msg),i):(Tl.error(`Error calling operation: ${e.name}`),Tl.error(i),i)}}a(kte,"callOperationFunctionAsAwait");F0.exports={callOperationFunctionAsAwait:kte}});var V0=g((Epe,k0)=>{"use strict";var ER=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}},hR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};k0.exports={BulkLoadFileObject:ER,BulkLoadDataObject:hR}});var Y0=g((mpe,$0)=>{"use strict";var mR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};$0.exports=mR});var AR=g((Ape,cB)=>{"use strict";var dE=qr(),EE=dR(),Vte=require("needle"),Gn=P(),Spe=Ve(),ka=z(),{handleHDBError:lt,hdb_errors:eB}=se(),{HTTP_STATUS_CODES:zt,HDB_ERROR_MSGS:Lt,CHECK_LOGS_WRAPPER:Io}=eB,Va=$(),pR=require("papaparse");ka.promisifyPapaParse();var qn=require("fs-extra"),$te=require("path"),{chain:K0}=require("stream-chain"),W0=require("stream-json/streamers/StreamArray"),Q0=require("stream-json/utils/Batch"),z0=require("stream-chain/utils/comp"),{finished:J0}=require("stream"),Yte=ee(),tB=fR(),Kte=Gg(),{BulkLoadFileObject:TR,BulkLoadDataObject:Wte}=V0(),gR=Cg(),{verifyBulkLoadAttributePerms:rB}=$f(),Tpe=Y0(),gpe=ut(),Rpe=As(),{databases:Qte}=(Ae(),ie(ke)),{coerceType:zte}=(hE(),ie(OR)),j0="No records parsed from csv file.",No=`${Yte.get("HDB_ROOT")}/tmp`,{schema_regex:Jte}=Jn(),X0=1024*1024*2,Z0=5e3,jte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};cB.exports={csvDataLoad:Xte,csvURLLoad:Zte,csvFileLoad:ere,importFromS3:tre};async function Xte(e,t){let r=EE.dataObject(e);if(r)throw lt(r,r.message,zt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=iB(e.schema,e.table),i=pR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:SR.bind(null,s),dynamicTyping:!1}),o=new gR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&rB(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw lt(new Error,c,zt.BAD_REQUEST,void 0,void 0,!0);let u=new Wte(e.action,e.schema,e.table,i.data);return n=await tB.callOperationFunctionAsAwait(oB,u,null),n.message===j0?j0:aB(n.records,n.number_written)}catch(s){throw wo(s)}}a(Xte,"csvDataLoad");async function Zte(e){let t=EE.urlObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${No}/${r}`;try{await rre(e,r)}catch(s){throw Va.error(Lt.DOWNLOAD_FILE_ERR(r)+" - "+s),lt(s,Io(Lt.DOWNLOAD_FILE_ERR(r)))}try{let s=new TR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await RR(s);return await fE(n),i}catch(s){throw await fE(n),wo(s)}}a(Zte,"csvURLLoad");async function ere(e){let t=EE.fileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=new TR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await RR(r)}catch(n){throw wo(n)}}a(ere,"csvFileLoad");async function tre(e){let t=EE.s3FileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=$te.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${No}/${s}`;let i=new TR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await nre(s,e);let o=await RR(i);return await fE(r),o}catch(n){throw await fE(r),wo(n)}}a(tre,"importFromS3");async function rre(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Vte("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw lt(n,s,n.statusCode,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}ire(r,e.csv_url),await sre(t,r.raw)}a(rre,"downloadCSVFile");async function nre(e,t){try{let r=`${No}/${e}`;await qn.mkdirp(No),await qn.writeFile(`${No}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await Kte.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(){Va.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Va.error(Lt.S3_DOWNLOAD_ERR+" - "+r),lt(r,Io(Lt.S3_DOWNLOAD_ERR))}}a(nre,"downloadFileFromS3");async function sre(e,t){try{await qn.mkdirp(No),await qn.writeFile(`${No}/${e}`,t)}catch(r){throw Va.error(Lt.WRITE_TEMP_FILE_ERR),lt(r,Io(Lt.DEFAULT_BULK_LOAD_ERR))}}a(sre,"writeFileToTempFolder");async function fE(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{Va.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(fE,"deleteTempFile");function ire(e,t){if(e.statusCode!==eB.HTTP_STATUS_CODES.OK)throw lt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,zt.BAD_REQUEST);if(!jte[e.headers["content-type"]])throw lt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,zt.BAD_REQUEST);if(!e.raw)throw lt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,zt.BAD_REQUEST)}a(ire,"validateURLResponse");async function RR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await ore(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await are(e);break;default:throw lt(new Error,Lt.DEFAULT_BULK_LOAD_ERR,zt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_FILE_EXT_ERR(e))}return aB(t.records,t.number_written)}catch(t){throw wo(t)}}a(RR,"fileLoad");async function nB(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 dE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&rB(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=lt(c);r(u)}}a(nB,"validateChunk");async function sB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;ka.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!ka.isEmpty(c)&&!ka.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 tB.callOperationFunctionAsAwait(oB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=lt(c,Io(Lt.INSERT_CSV_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_CSV_ERR+" - "+c);r(u)}}a(sB,"insertChunk");async function ore(e){let t={records:0,number_written:0},r=iB(e.schema,e.table);try{let n=new gR,s=qn.createReadStream(e.file_path,{highWaterMark:X0});s.setEncoding("utf8"),await pR.parsePromise(s,nB.bind(null,e,n),SR.bind(null,r));let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:X0}),s.setEncoding("utf8"),await pR.parsePromise(s,sB.bind(null,e,t),SR.bind(null,r)),s.destroy(),t}catch(n){throw lt(n,Io(Lt.PAPA_PARSE_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.PAPA_PARSE_ERR+n)}}a(ore,"callPapaParse");function iB(e,t){let r=Qte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>zte(i,s));return n}a(iB,"createTransformMap");function SR(e,t,r){let n=e.get(r);return n?n(t):ka.autoCast(t)}a(SR,"typeFunction");async function are(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new gR,s=K0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),W0.withParser(),c=>c.value,new Q0({batchSize:Z0}),z0(async c=>{await nB(e,n,r,c)})]);await new Promise((c,u)=>{J0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);let o=K0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),W0.withParser(),c=>c.value,new Q0({batchSize:Z0}),z0(async c=>{await sB(e,t,r,c)})]);return await new Promise((c,u)=>{J0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw lt(n,Io(Lt.INSERT_JSON_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_JSON_ERR+n)}}a(are,"insertJson");async function oB(e){let t={};try{e.data&&e.data.length>0&&cre(e.data[0])?t=await ure(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Va.info(t.message))}catch(r){throw wo(r)}return t}a(oB,"callBulkFileLoad");function cre(e){let t=Object.keys(e);for(let r of t)if(!Jte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(cre,"validateColumnNames");async function ure(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=dE.insert;break;case"update":i=dE.update;break;case"upsert":i=dE.upsert;break;default:throw lt(new Error,Lt.INVALID_ACTION_PARAM_ERR(n),zt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=ka.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw wo(o)}}a(ure,"bulkFileLoad");function aB(e,t){return`successfully loaded ${t} of ${e} records`}a(aB,"buildResponseMsg");function wo(e){return lt(e,Io(Lt.DEFAULT_BULK_LOAD_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(wo,"buildTopLevelErrMsg")});var lB=g((bpe,uB)=>{"use strict";var bR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};uB.exports=bR});var fB=g((Npe,dB)=>{"use strict";var lre=P(),_B=require("moment"),_re=require("uuid").v4,yR=class{static{a(this,"JobObject")}constructor(){this.id=_re(),this.type=void 0,this.start_datetime=_B().valueOf(),this.created_datetime=_B().valueOf(),this.end_datetime=void 0,this.status=lre.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};dB.exports=yR});var NR=g((wpe,RB)=>{"use strict";var dre=require("uuid").v4,SB=qr(),TB=Gr(),fre=ts(),Ere=ia(),hre=lB(),et=P(),mre=fB(),pre=$d(),Tn=$(),Sre=kc(),$a=z(),{promisify:Tre}=require("util"),Co=require("moment"),gre=Kf(),mE=dR(),EB=zm(),{deleteTransactionLogsBeforeValidator:Rre}=bg(),{handleHDBError:hB,hdb_errors:Are}=se(),{HTTP_STATUS_CODES:mB}=Are,pB=TB.searchByValue,Ore=TB.searchByHash,bre=SB.insert,yre=Tre(gre.evaluateSQL),Nre=SB.update;RB.exports={addJob:Cre,updateJob:Lre,handleGetJob:Ire,handleGetJobsByStartDate:wre,getJobById:gB};async function Ire(e){try{let t=await gB(e.id);return $a.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 Tn.error("There was an error getting job",t),new Error(r)}}a(Ire,"handleGetJob");async function wre(e){try{let t=await Dre(e);if(Tn.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=Co(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Co(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 Tn.error(r),new Error(r)}}a(wre,"handleGetJobsByStartDate");async function Cre(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||$a.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Tn.info(l),t.error=l,t}if(!et.JOB_TYPE_ENUM[e.operation])return Tn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case et.OPERATIONS_ENUM.CSV_FILE_LOAD:n=mE.fileObject(e);break;case et.OPERATIONS_ENUM.CSV_URL_LOAD:n=mE.urlObject(e);break;case et.OPERATIONS_ENUM.CSV_DATA_LOAD:n=mE.dataObject(e);break;case et.OPERATIONS_ENUM.IMPORT_FROM_S3:n=mE.s3FileObject(e);break;case et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=EB(e,"date");break;case et.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=EB(e,"timestamp");break;case et.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Rre(e);break;case et.OPERATIONS_ENUM.RESTART_SERVICE:if(et.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw hB(new Error,"Invalid service",mB.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw hB(n,n.message,mB.BAD_REQUEST,void 0,void 0,!0);let s=new mre;s.type=e.operation===et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new fre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await pB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Tn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=dre();try{o=await pB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Tn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Tn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new Sre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await bre(u)}catch(l){return Tn.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,Tn.trace(l)}return t}a(Cre,"addJob");async function Dre(e){let t=Co(e.from_date,Co.ISO_8601),r=Co(e.to_date,Co.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 hre(n,e.hdb_user);try{return await yre(s)}catch(i){throw Tn.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(Dre,"getJobsInDateRange");async function gB(e){if($a.isEmptyOrZeroLength(e))return $a.errorizeMessage("Invalid job ID specified.");let t=new Ere(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Ore(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Tn.error(n),$a.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(gB,"getJobById");async function Lre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if($a.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===et.JOB_STATUS_ENUM.COMPLETE||e.status===et.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Co().valueOf());let t=new pre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Nre(t),r}a(Lre,"updateJob")});var CB=g((Dpe,wB)=>{"use strict";var AB=z(),Mt=P(),Mre=require("moment"),pE=AR(),gl=$(),OB=NR(),bB=Wf(),yB=ai(),NB=We(),Pre=qf(),Ure=Ju(),{parentPort:vre,isMainThread:IB}=require("worker_threads"),{onMessageByType:Bre}=We(),IR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function xre(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(AB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(AB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Mt.JOB_TYPE_ENUM.csv_file_load:await ds(e,pE.csvFileLoad);break;case Mt.JOB_TYPE_ENUM.csv_url_load:await ds(e,pE.csvURLLoad);break;case Mt.JOB_TYPE_ENUM.csv_data_load:await ds(e,pE.csvDataLoad);break;case Mt.JOB_TYPE_ENUM.import_from_s3:await ds(e,pE.importFromS3);break;case Mt.JOB_TYPE_ENUM.empty_trash:break;case Mt.JOB_TYPE_ENUM.export_local:await ds(e,bB.export_local);break;case Mt.JOB_TYPE_ENUM.export_to_s3:await ds(e,bB.export_to_s3);break;case Mt.JOB_TYPE_ENUM.delete_files_before:case Mt.JOB_TYPE_ENUM.delete_records_before:await ds(e,yB.deleteFilesBefore);break;case Mt.JOB_TYPE_ENUM.delete_audit_logs_before:await ds(e,yB.deleteAuditLogsBefore);break;case Mt.JOB_TYPE_ENUM.delete_transaction_logs_before:await ds(e,Pre.deleteTransactionLogsBefore);break;case Mt.JOB_TYPE_ENUM.restart_service:return await ds(e,Ure.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(xre,"parseMessage");async function ds(e,t){try{e.job.status=Mt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Mre().valueOf(),await OB.updateJob(e.job),await Hre(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):gl.error(`There was an error running ${t.name} job with id ${e.job.id}`),gl.error(n),e.job.message=n,e.job.status=Mt.JOB_STATUS_ENUM.ERROR;try{await OB.updateJob(e.job)}catch(s){throw gl.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(ds,"runJob");async function Hre(e){gl.trace("launching job thread:",e),IB?NB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})}):vre.postMessage({type:Mt.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(Hre,"launchJobThread");IB&&Bre(Mt.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{NB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`})})}catch(r){gl.error(r)}});wB.exports={parseMessage:xre,RunnerMessage:IR}});var LB=g((Mpe,DB)=>{"use strict";var wR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};DB.exports=wR});var QB=g((Upe,UR)=>{"use strict";var AE=Gr(),LR=Kf(),SE=AR(),Fs=Ou(),TE=Os(),Al=ai(),Gre=kS(),Rl=_n(),gE=jS(),Jt=Og(),RE=$(),qre=eT(),Fre=nf(),MB=PT(),kre=of(),Vre=vT(),$re=BT(),Yre=GT(),Kre=FT(),CR=$T(),PB=Wf(),Wre=$f(),MR=NR(),F=P(),{hdb_errors:bl,handleHDBError:Ol}=se(),{HTTP_STATUS_CODES:UB}=bl,DR=zT(),vB=Ju(),$B=require("util"),Ya=qr(),Qre=bs(),zre=ga(),BB=CB(),xB=Cu(),HB=(Df(),ie(el)),GB=Er(),qB=qf(),FB=vf(),{setServerUtilities:Jre}=(hE(),ie(OR)),{CONTEXT:jre}=(cn(),ie(kp)),{_assignPackageExport:Xre}=require("../index"),{transformReq:Zre}=z(),{server:ene}=(lr(),ie(Hi)),or=RE.loggerWithTag("operation"),tne=fR(),kB=AE.searchByHash,rne=AE.searchByValue,nne=$B.promisify(AE.search),sne=$B.promisify(LR.evaluateSQL),ine={[F.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.CREATE_TABLE]:!0,[F.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[F.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.DROP_TABLE]:!0,[F.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=LB();async function YB(e,t){try{if(e.body.operation!=="read_log"&&(RE.log_level===F.LOG_LEVELS.INFO||RE.log_level===F.LOG_LEVELS.DEBUG||RE.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;or.info(o)}}catch(n){or.error(n)}let r=await tne.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return ine[e.body.operation]&&Qre.setSchemaDataToGlobal(n=>{n&&or.error(n)}),r}a(YB,"processLocalTransaction");var VB=ane();UR.exports={chooseOperation:KB,getOperationFunction:WB,operation:PR,processLocalTransaction:YB};Jre(UR.exports);ene.operation=PR;function KB(e){let t;try{t=WB(e)}catch(s){throw or.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=LR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=LR.checkASTPermissions(e,i);if(o)throw or.error(`${UB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Ol(new Error,o,bl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==F.OPERATIONS_ENUM.LOGIN&&e.operation!==F.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Wre.verifyPerms(i,s);if(o)throw or.error(`${UB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Ol(new Error,o,bl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw Ol(s,"There was an error when trying to choose an operation path")}return r}a(KB,"chooseOperation");function WB(e){if(or.trace(`getOperationFunction with operation: ${e.operation}`),VB.has(e.operation))return VB.get(e.operation);throw Ol(new Error,bl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),bl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(WB,"getOperationFunction");Xre("operation",PR);function PR(e,t){e.hdb_user=this[jre]?.user,e.bypass_auth=!t;let r=KB(e);return YB({body:e},r)}a(PR,"operation");async function one(e){or.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await Ya.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await Ya.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await Ya.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await Al.deleteRecord(i);break;default:or.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){or.info("Invalid operation in transaction"),or.error(o)}}a(one,"catchup");async function Fn(e){Zre(e);let t,r;try{r=await MR.addJob(e),t=r.createdJob,or.info("addJob result",r);let n=new BB.RunnerMessage(t,e);return{message:await BB.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw or.error(s),Ol(n,s)}}a(Fn,"executeJob");function ane(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new Y(Ya.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new Y(Ya.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new Y(Ya.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(AE.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(kB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(kB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(rne)),e.set(F.OPERATIONS_ENUM.SEARCH,new Y(nne)),e.set(F.OPERATIONS_ENUM.SQL,new Y(sne)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(Fn,SE.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(Fn,SE.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(Fn,SE.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(Fn,SE.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(TE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(TE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(TE.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(TE.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new Y(Al.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new Y(Rl.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new Y(Rl.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new Y(Rl.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new Y(Rl.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new Y(gE.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new Y(gE.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new Y(gE.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new Y(gE.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new Y(Rl.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new Y(qre)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new Y(Fre)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new Y(MB)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(MB)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new Y(kre)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Vre)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new Y($re)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(GB.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Yre.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Kre)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(CR.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(CR.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(CR.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(Fn,PB.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(Fn,Al.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(Fn,Al.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(Fn,PB.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(MR.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new Y(MR.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(DR.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new Y(DR.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(DR.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new Y(vB.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new Y(Fn,vB.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new Y(one)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(zre.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(Fn,Al.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Gre)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(xB.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(xB.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new Y(HB.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new Y(HB.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(GB.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Jt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Jt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Jt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Jt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Jt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Jt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Jt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Jt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Jt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Jt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Jt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Jt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Jt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Jt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Jt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Jt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(qB.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(Fn,qB.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(FB.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(FB.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(ane,"initializeOperationFunctionMap")});var bE=g((Bpe,jB)=>{"use strict";var vR=P(),cne=z(),yl=$(),{handleHDBError:BR,hdb_errors:OE}=se(),{isMainThread:une}=require("worker_threads"),{Readable:lne}=require("stream"),zB=require("os"),_ne=require("util"),dne=lT(),fne=_ne.promisify(dne.authorize),JB=QB(),{createGzip:Ene,constants:hne}=require("zlib");function mne(e){let t=`Found an uncaught exception with message: ${e.message}. ${zB.EOL}Stack: ${e.stack} ${zB.EOL}Terminating ${une?"HDB":"thread"}.`;console.error(t),yl.fatal(t),process.exit(1)}a(mne,"handleServerUncaughtException");function pne(e,t,r){if(yl[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:OE.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(pne,"serverErrorHandler");function Sne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=BR(new Error,"Invalid JSON.",OE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(cne.isEmpty(e.body.operation)){let n=BR(new Error,"Request body must include an 'operation' property.",OE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(Sne,"reqBodyValidationHandler");function Tne(e,t,r){let n;e.body.operation!==vR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==vR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==vR.OPERATIONS_ENUM.LOGOUT?fne(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{yl.warn(s),yl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(BR(s,i,OE.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(Tne,"authHandler");async function gne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=JB.chooseOperation(e.body);let s=await JB.processLocalTransaction(e,n);if(s instanceof lne&&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(Ene({level:hne.Z_BEST_SPEED})))}return s}catch(s){throw yl.error(s),s}}a(gne,"handlePostRequest");jB.exports={authHandler:Tne,handlePostRequest:gne,handleServerUncaughtException:mne,serverErrorHandler:pne,reqBodyValidationHandler:Sne}});var tx=g((Hpe,ex)=>{"use strict";var Rne=require("fastify-plugin"),{handlePostRequest:XB,authHandler:Ane,reqBodyValidationHandler:One}=bE();async function bne(e){e.decorate("hdbCore",{preValidation:[One,Ane],request:t=>ZB(XB(t,response)),requestWithoutAuthentication:(t,r)=>ZB(XB(t,r,!0))})}a(bne,"hdbCore");async function ZB(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(ZB,"convertAsyncIterators");ex.exports=Rne(bne)});var sx=g((Fpe,nx)=>{"use strict";var qpe=require("fs"),xR=ee();xR.initSync();var{CONFIG_PARAMS:rx}=P(),yne=1024*1024*1024;function Nne(e){let t=xR.get(rx.HTTP_TIMEOUT),r=xR.get(rx.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:yne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Nne,"getServerOptions");nx.exports=Nne});var ax=g((Vpe,ox)=>{"use strict";var HR=ee();HR.initSync();var{CONFIG_PARAMS:ix}=P();function Ine(){let e=HR.get(ix.HTTP_CORSACCESSLIST),t=HR.get(ix.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(Ine,"getCORSOptions");ox.exports=Ine});var lx=g((Ype,ux)=>{"use strict";var cx=ee();cx.initSync();var wne=P();function Cne(){return cx.get(wne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Cne,"getHeaderTimeoutConfig");ux.exports=Cne});var qR={};Fe(qR,{customFunctionsServer:()=>Mne,ready:()=>yx,start:()=>Lne});function Lne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=bx(t),at.http((await ks).server));let o=await ks,c=(0,GR.dirname)(s),u=(0,GR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!_x.has(c)){_x.add(c);try{o.register(Une(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ye.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:yx}}async function Mne(){try{Ye.info("In Custom Functions Fastify server"+process.cwd()),Ye.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ye.debug(`Custom Functions server process ${process.pid} starting up.`),await Pne();let e=px.get(Sx.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await bx(e)}catch(r){throw Ye.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ye.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ye.error(`Custom Functions ${process.pid} Error: ${e}`),Ye.error(e),process.exit(1)}}async function Pne(){try{Ye.info("Custom Functions starting configuration."),await Tx.setUsersToGlobal(),Ye.info("Custom Functions completed configuration.")}catch(e){Ye.error(e)}}function Une(e,t){return async function(r){try{Ye.info("Custom Functions starting buildRoutes"),Ye.trace("Loading fastify routes folder "+e),(0,dx.existsSync)(e)&&r.register(mx.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ye.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ye.error(s.message):s&&Ye.error(s),o()})}catch(n){Ye.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function bx(e){Ye.info("Custom Functions starting buildServer.");let t=(0,gx.default)(e),r=(0,fx.default)(t);r.server.headersTimeout=(0,Ax.default)(),r.setErrorHandler(Ox.serverErrorHandler);let n=(0,Rx.default)();return n&&r.register(Ex.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(hx.default),await r.register(Dne),await r.after(),Kg(r),Ye.info("Custom Functions completed buildServer."),r}function yx(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var GR,dx,fx,Ex,hx,mx,px,Sx,Ye,Dne,Tx,gx,Rx,Ax,Ox,ks,_x,Nx=Re(()=>{GR=require("path"),dx=require("fs"),fx=x(require("fastify")),Ex=x(require("@fastify/cors")),hx=x(oR()),mx=x(require("@fastify/autoload")),px=x(ee()),Sx=x(P()),Ye=x($()),Dne=x(tx()),Tx=x(_n()),gx=x(sx()),Rx=x(ax()),Ax=x(lx()),Ox=x(bE());Ca();lr();_x=new Set;a(Lne,"start");a(Mne,"customFunctionsServer");a(Pne,"setUp");a(Une,"buildRouteFolder");a(bx,"buildServer");a(yx,"ready")});var FR={};Fe(FR,{start:()=>vne});function vne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,Lx.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){wx||(wx=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=Ix.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,Cx.default)(s,(0,Dx.realpathSync)(o))}}return i(s)},{runFirst:!0})),Ix.set(r,n)}}}var Cx,Dx,Lx,Ix,wx,Mx=Re(()=>{Cx=x(require("send")),Dx=require("fs"),Lx=x(require("serve-static")),Ix=new Map;a(vne,"start")});function Hne(){let e=(0,Bx.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),VR=setInterval(()=>{IE.notify(e)},xne).unref())}function Gne(e,t=1,r){if(kR++,(0,Vs.startWorker)("server/threads/threadServer.js",{name:Ja.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===Ja.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Bne.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=NE.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"),Wa){let o=Wa;Wa=[];for(let c of o)xx[c.localPort](null,c)}}}),r){let n=setInterval(()=>{$R?$R=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Vs.shutdownWorkers)(),kR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function Hx(e=0,t){if(typeof e=="string")try{(0,wE.existsSync)(e)&&(0,wE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=qne:r=Fne(t):r=YR;let n=(0,Qa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=xx[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),$R=!0,r(o,(c,u)=>{if(!c){if(Px){let l=o._socket||new Qa.Socket({handle:o,writable:!0,readable:!0});Px.deliverSocket(l,e,u),l.resume()}else kR>0?(Wa.length===0&&setTimeout(()=>{Wa.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,Wa.push(o)):(console.log("start up a dynamic thread to handle request"),Gne(0));Sr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Qa.Socket({handle:o,writable:!0,readable:!0});Yne(l,c,e)}Sr(!0,"socket-routed")})};let s=_u();IE.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 YR(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>=yE)return yE=i,t(r);n=i}yE=0,t(r)}function qne(e,t){let r={};e.getpeername(r);let n=r.address,s=za.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);YR(e,o=>{za.set(n,{worker:o,lastUsed:i}),t(o)})}function Fne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Qa.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=za.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);YR(n,d=>{za.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Vne(){yE=0;for(let e of Ka)e.expectedIdle=e.recentELU.idle+kne,e.requests=1;Ka.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Yne(e,t,r){let n=$ne++;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(),NE.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")),NE.delete(n)),s.event=="destroy"&&(e.destroy(),NE.delete(n))})}var Vs,Qa,Ja,IE,wE,vx,Bx,Ka,Wa,xx,Px,kR,Bne,VR,xne,$R,yE,Ux,za,kne,NE,$ne,Gx=Re(()=>{Vs=x(We()),Qa=require("net"),Ja=x(P()),IE=x($()),wE=require("fs");Cs();vx=require("worker_threads"),Bx=x(ji()),Ka=[],Wa=[],xx=[],kR=0,Bne=[];vx.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,Vs.onMessageFromWorkers)(e=>{e.type===Ja.ITC_EVENT_TYPES.RESTART&&VR&&(clearInterval(VR),Hne())}));xne=6e5;a(Hne,"licenseWarning");a(Gne,"startHTTPWorker");a(Hx,"startSocketServer");yE=0;a(YR,"findMostIdleWorker");Ux=36e5,za=new Map;a(qne,"findByRemoteAddressAffinity");a(Fne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of za)r.lastUsed+Ux<e&&za.delete(t)},Ux).unref();kne=1e3;a(Vne,"updateWorkerIdleness");(0,Vs.setMonitorListener)(Vne);NE=new Map,$ne=1;a(Yne,"proxySocket")});var zR={};Fe(zR,{Request:()=>KR,createReuseportFd:()=>CE});var qx,KR,WR,QR,CE,DE=Re(()=>{qx=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 QR(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 WR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},WR=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)}},QR=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,qx.platform)()!="win32"&&(CE=require("node-unix-socket").createReuseportFd)});var $x=g((oSe,Vx)=>{"use strict";var Kne=require("cluster"),Do=ee();Do.initSync();var kx=P(),tSe=require("util"),$s=$(),rSe=require("fs"),Wne=require("fastify"),nSe=_u(),Qne=require("@fastify/cors"),zne=require("@fastify/compress"),Jne=require("@fastify/static"),jne=oR(),Xne=require("path"),{PACKAGE_ROOT:Zne}=P(),ese=bs(),tse=z(),rse=_n(),nse=ji(),{server:sse}=(lr(),ie(Hi)),{node_request_key:sSe}=(DE(),ie(zR)),{authHandler:ise,handlePostRequest:ose,serverErrorHandler:ase,reqBodyValidationHandler:cse}=bE(),iSe=require("net"),{registerContentHandlers:use}=(Ca(),ie(A0)),lse=6e4,_se=1024*1024*1024,dse="TRUE",{CONFIG_PARAMS:Nl}=kx,ja;Vx.exports={hdbServer:Fx,start:Fx};async function Fx(e){try{$s.info("In Fastify server"+process.cwd()),$s.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),$s.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Kne.isMaster,await fse();let t=e.securePort>0;ja=Ese(t),await ja.ready(),e||(e={}),e.isOperationsServer=!0;try{sse.http(ja.server,e),ja.server.closeIdleConnections||await ja.listen({port:0,host:"::"})}catch(r){throw ja.close(),$s.error(r),$s.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),$s.fatal(t),process.exit(1)}}a(Fx,"operationsServer");async function fse(){$s.trace("Configuring HarperDB process."),ese.setSchemaDataToGlobal(),await rse.setUsersToGlobal(),await nse.getLicense()}a(fse,"setUp");function Ese(e){$s.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=hse(e),r=Wne(t);r.server.headersTimeout=pse(),r.setErrorHandler(ase);let n=mse();n&&r.register(Qne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(jne),r.register(zne),r.register(Jne,{root:Xne.join(Zne,"studio/build-local")}),use(r);let s=Do.get(kx.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!tse.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[cse,ise],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."),$s.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Ese,"buildServer");function hse(e){let t=Do.get(Nl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(Nl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:_se,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(hse,"getServerOptions");function mse(){let e=Do.get(Nl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(Nl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===dse)&&(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(mse,"getCORSOpts");function pse(){return Do.get(Nl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??lse}a(pse,"getHeaderTimeoutConfig")});var tA={};Fe(tA,{disableNATS:()=>Tse,publishToStream:()=>PE,setNATSReplicator:()=>JR,setPublishToStream:()=>gse,setSubscription:()=>eA,start:()=>Sse});function Sse(){Il.default.get(wl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Ase()}function Tse(e=!0){zx=e}function gse(e,t){PE=e,eA=t}function Ase(){if(zx||process.env._DISABLE_NATS)return;let e=mr(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];JR(s,r,i)}}rA((r,n)=>{JR(r.tableName,r.databaseName,r),n&&jx(r)}),!Yx&&(Yx=!0)}function JR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends $t{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[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){jx(i)}static subscribe(){let i=new Nn;return eA(t,e,i),i}static subscribeOnThisThread(i){return i<(Il.default.get(wl.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Rse)}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 LE(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=Jx;return i}a(n,"getNATSTransaction")}function jx(e){let t=Il.default.get(wl.default.CONFIG_PARAMS.CLUSTERING_NODENAME);PE(`${XR.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 Kx,XR,ZR,Wx,Qx,Il,wl,ME,zx,PE,eA,Rse,Jx,Yx,LE,jR,Xx=Re(()=>{Ae();cn();Kx=x(ut()),XR=x(Ve()),ZR=x(As());Nc();Wx=x(DS()),Qx=x(vr()),Il=x(ee()),wl=x(P()),ME=x($());a(Sse,"start");a(Tse,"disableNATS");PE=Kx.publishToStream,eA=Wx.setSubscription;a(gse,"setPublishToStream");Rse=2;a(Ase,"assignReplicationSource");a(JR,"setNATSReplicator");a(jx,"publishSchema");LE=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=Il.default.get(wl.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,E=l.operation=="put"?"upsert":l.operation;u||(ME.trace(`Sending transaction event ${E}`),_=u={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&E!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(l.record),c.push(l.id)):_=_.next={operation:E,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(PE(`${XR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,ZR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw ME.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},jR=class extends LE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,Qx.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};Jx=new jR});var dH=g(Li=>{"use strict";var{isMainThread:iA,parentPort:Dl,threadId:UE}=require("worker_threads"),{Socket:Ose,createServer:bse}=require("net"),{createServer:yse,IncomingMessage:Nse}=require("http"),{createServer:Ise}=require("https"),{readFileSync:wse,unlinkSync:Zx,existsSync:Cse}=require("fs"),Pt=$(),qe=ee(),_t=P(),{server:xE}=(lr(),ie(Hi)),{WebSocketServer:Dse}=require("ws"),{createSecureContext:Lse,createServer:Mse}=require("node:tls"),{getTicketKeys:nH,restartNumber:Pse,getWorkerIndex:Ll}=We(),{Headers:sH,appendHeader:Use}=(Zu(),ie(YU)),{recordAction:Cl,recordActionBinary:vse}=(Cs(),ie(mu)),{Request:iH,createReuseportFd:eH}=(DE(),ie(zR)),{checkMemoryLimit:Bse}=ji(),{X509Certificate:xse}=require("crypto"),oH=require("tls"),Hse=oH.createSecureContext,Xa;oH.createSecureContext=function(e){return Xa||Hse(e)};var aH=qe.get(_t.CONFIG_PARAMS.THREADS_DEBUG);if(aH){let e;if(iA)e=qe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Pt.info("Could not close debugger",t)}});else{let t=qe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&Ll()>=0&&(e=t+Ll())}if(e){let t=qe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=qe.get(_t.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Pt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&iA)try{require("inspector").open(9229)}catch(e){Pse<=1&&Pt.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:fSe,CONFIG_PARAMS:Gse}=_t;qe.initSync();var qse=qe.get(Gse.HTTP_SESSIONAFFINITY),Es={};Li.registerServer=uA;Li.httpServer=lA;Li.deliverSocket=cA;Li.startServers=cH;Li.when_components_loaded=null;Li.createSNICallback=_A;xE.http=lA;xE.request=$se;xE.socket=Yse;xE.ws=Kse;var nA={},vE={},Fse,Ys={},BE={},kse=[],oA=[];function cH(){return Li.when_components_loaded=dA().loadRootComponents(!0).then(()=>{Dl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)cA(n,r,s);else if(t.requestId)Vse(t);else if(t.type===_t.ITC_EVENT_TYPES.SHUTDOWN){Pt.trace("received shutdown request",UE);for(let i in Es){let o=Es[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),l=0,d=setInterval(()=>{l++;let E=l>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}l===1?Pt.info(`Closing ${f.length} idle connections`):E&&Pt.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,p=f.length;h<p;h++){let S=f[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
|
|
29
29
|
Connection: close\r
|
|
30
30
|
\r
|
|
31
|
-
`))}},25).unref()}o.close?.(()=>{if(
|
|
32
|
-
`)}a(rx,"defaultNotFound");function rA(e){return e.startsWith("-----BEGIN")?e:Nse(e)}a(rA,"readPEM");function uA(e){let t=[];for(let o=0;e[o];o++)t.push(e[o]);t.length||t.push(e);let r=new Map,n,s,i=!1;for(let o of t){let c=rA(o.privateKey),u=rA(o.certificate),_=o.certificateAuthority&&rA(o.certificateAuthority);if(!c||!u)throw new Error("Missing private key or certificate for secure server");let l={ciphers:o.ciphers,ca:_,ticketKeys:nx()},d=Cse(l);d.options=l,l.instantiatedContext=d,d.context.setCert(u),d.context.setKey(c,void 0),l.cert=u,l.key=c,d.certStart=u.slice(0,100).toString(),n||(n=d);let E=new vse(u);d.subject=E.subject;let f=o.hostname??o.host??o.hostnames??o.hosts??(E.subjectAltName?E.subjectAltName.split(",").map(h=>{let p=h.indexOf(":");return h.slice(p+1)}):[E.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(f)||(f=[f]);for(let h of f)h?(h[0]==="*"&&(i=!0,h=h.slice(1)),r.has(h)||r.set(h,d),!s&&h.match(/\d+\.\d+\.\d+\.\d+/)&&(s=d)):Pt.error("No hostname found for certificate at",o.certificate)}return(o,c)=>{let u=o;for(;;){let _=r.get(u);if(_)return Pt.debug("Found certificate for",o,_.certStart),c(null,_);if(i&&u){let l=u.indexOf(".",1);l<0?u="":u=u.slice(l)}else break}Pt.debug("No certificate found to match",o,"using the first certificate"),o?c(null,n):c(null,s)}}a(uA,"createSNICallback")});async function mx({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await _A.get(e,{returnNonexistent:!0});i=new EA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await _A.get(e);o&&o.delete()}i=new xE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Ll.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function dA(){return HE++,HE>65500&&(HE=1),HE}function fA(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=bi.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var fx,Mi,Ex,hx,_A,Ll,HE,xE,EA,px=Re(()=>{Ae();ju();fx=B(vr()),Mi=B($());no();Ex=B(We()),hx=B(dx());lr();_A=Et({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),Ll=Et({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,Ex.getWorkerIndex)()===0&&(async()=>{await hx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Ll.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await at.getUser(r.user.username)),Ze(r,()=>{try{fA(r,t,r)}catch{(0,Mi.warn)("Failed to publish will",t)}Ll.delete(e.id,r)})}})();a(mx,"getSession");HE=1;a(dA,"getNextMessageId");xE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let E={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Mi.trace)("Resuming subscription from",s,"from",o);let f=bi.getMatch(_);if(!f){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let T=E.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,T.indexOf("+")===T.length-1)E.onlyChildren=!0,E.url="/"+T.slice(0,T.length-1);else{let R=T.split("/"),b;for(let v=0;v<R.length;v++)if(R[v].indexOf("+")>-1)if(R[v]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let C=!0;R[R.length-1]==="#"&&(R.length--,C=!1),b&&(n=a(v=>{let F=v.id;if(!Array.isArray(F)||C&&F.length!==R.length)return!1;for(let M=0;M<R.length;M++)if(R[M]!=="+"&&R[M]!==F[M])return!1;return!0},"filter"));let H=R.indexOf("+");E.url="/"+(H>-1?R.slice(0,H):R).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Ze(E,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let R=await p.subscribe(E,T);if(!R)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let b of R)try{let C;if(b.type&&b.type!=="put"&&b.type!=="delete"&&b.type!=="message"&&b.type!=="patch"||n&&!n(b))continue;r?(b.topic=s,C=this.needsAcknowledge(b)):(b.acknowledge?.(),C=dA());let H=b.id;Array.isArray(H)&&(H=Ia(H)),H==null&&(H=""),this.listener(h+"/"+H,b.value,C,t)}catch(C){(0,Mi.warn)(C)}})(),R});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=dA();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return fA(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Ze(r,async()=>{try{if(!t){let n=await Ll.get(this.sessionId);n?.doesExist()&&await fA(n,n.data,r)}}finally{await Ll.delete(this.sessionId)}}).catch(n=>{(0,Mi.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(fA,"publish");EA=class extends xE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=dA(),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,Mi.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,fx.getNextMonotonicTime)()),(0,Mi.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),_A.put(this.sessionRecord)}}});var mA={};Fe(mA,{bypassAuth:()=>Yse,start:()=>Kse});function Yse(){Ax=!0}function Kse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Rx.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),jt.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=Tx(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",E),_.on("close",f),_.on("error",h=>{jt.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(o.events.emit("connection",_),jt.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let f=u.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{l=await e.getUser(f,null,null),(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&qE.notify({username:l?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&qE.error({username:f,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else jt.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),jt.error(f)}else if(u.required)return jt.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&Ax&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,gx.getSuperUser)(),jt.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:E}=Tx(_,f=>_.write(f),null,l,o);_.on("data",d),_.on("close",E),_.on("error",f=>{jt.info("Socket error",f)})},{port:t,securePort:s,mtls:u})),c}function Tx(e,t,r,n,s){Sx||(Sx=!0,Eu(d=>{GE>0&&d.push({metric:"mqtt-connections",connections:GE,byThread:!0})}));let i;GE++;let o,c={protocolVersion:4},u=(0,FE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){GE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!1,"connection","mqtt","disconnect"),jt.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;let E=d.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;Sr(d.length,"bytes-received",h,S(d),"mqtt");try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await at.getUser(d.username,d.password.toString(),r),(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&qE.notify({username:n?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Xa.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&qE.error({username:d.username,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let M=e.deserialize||(e.deserialize=bo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=mx({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return jt.error(M),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Wr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,J,j)=>{try{let ae=M.indexOf("/",1),ce=ae>0?M.slice(0,ae):M;p({cmd:"publish",topic:M,payload:T(Q),messageId:J||Math.floor(Math.random()*1e8),qos:j.qos},ce)}catch(ae){jt.error(ae),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let R=[];for(let M of d.subscriptions){let Q;try{Q=(await o.addSubscription(M,M.qos>=1)).qos||0}catch(J){s.events.emit("error",J,e,M,o),jt.error(J),Q=c.protocolVersion<5?128:J.statusCode===403?135:J.statusCode===404?143:128}R.push(Q)}await o.committed,p({cmd:"suback",granted:R,messageId:d.messageId});break;case"unsubscribe":{let M=[];for(let Q of d.unsubscriptions)M.push(o.removeSubscription(Q)?0:17);p({cmd:"unsuback",granted:M,messageId:d.messageId});break}case"pubrel":p({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let b=d.qos===2?"pubrec":"puback",C=e.deserialize||(e.deserialize=bo(r?.headers.get?.("content-type"))),v=(d.payload?.length||0)>0?C(d.payload):void 0,F;try{F=await o.publish(d,v)}catch(M){s.events.emit("error",M,e,d,o),jt.warn(M),d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:F===!1?144:0},d.topic);break;case"pubrec":p({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":p({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!0,"connection","mqtt","disconnect"),jt.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(R){s.events.emit("error",R,e,d,o),jt.error(R),p({cmd:"disconnect"})}function p(R,b){let C=(0,FE.generate)(R,c);t(C),Sr(C.length,"bytes-sent",b,S(R),"mqtt")}a(p,"sendPacket");function S(R){return R.qos>0?R.cmd+",qos="+R.qos:R.cmd}a(S,"packetMethodName");function T(R){return go(R,r)}a(T,"serialize")}),u.on("error",d=>{jt.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:_,onClose:l}}var FE,gx,Xa,Xt,hA,Rx,qE,jt,Ax,Sx,GE,Ox=Re(()=>{FE=require("mqtt-packet");px();gx=B(ln());Ca();Cs();lr();Xa=B(Z()),Xt=B(P()),hA=B($()),Rx=require("events"),qE=(0,hA.loggerWithTag)("auth-event"),jt=(0,hA.loggerWithTag)("mqtt"),Ax=(0,Xa.get)(Xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Yse,"bypassAuth");a(Kse,"start");GE=0;a(Tx,"onSocket")});var Hf={};Fe(Hf,{component_errors:()=>ec,loadComponent:()=>kE,loadComponentDirectories:()=>Mx,setErrorReporter:()=>Jse});function Mx(e,t){t&&(SA=t),e&&(TA=e);let r=[];if((0,tt.existsSync)(pA)){let s=(0,tt.readdirSync)(pA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,st.join)(pA,o);r.push(kE(c,SA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(kE(n,SA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Lx=!0})}function Jse(e){Ml=e}async function kE(e,t,r,n,s,i){let o=(0,tt.realpathSync)(e);if(!yx.has(o)){yx.set(o,!0),s&&(TA=s);try{let c;n&&(ec=new Map);let u=(0,st.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,tt.existsSync)(u)?c=n?(0,Dx.getConfigObj)():(0,Nx.parseDocument)((0,tt.readFileSync)(u,"utf8"),{simpleKeys:!0}).toJSON():c=gA;let _=(0,st.join)(e,"node_modules","harperdb");try{Lo.isMainThread&&(n||(0,tt.existsSync)(_)&&(0,tt.realpathSync)(rc.PACKAGE_ROOT)!==(0,tt.realpathSync)(_))&&((0,tt.rmSync)(_,{recursive:!0,force:!0}),(0,tt.existsSync)((0,st.join)(e,"node_modules"))||(0,tt.mkdirSync)((0,st.join)(e,"node_modules")),(0,tt.symlinkSync)(rc.PACKAGE_ROOT,_,"dir"))}catch(E){Za.default.error("Error symlinking harperdb module",E)}let l=[],d=n;for(let E in c){let f=c[E];if(ec.set(n?E:(0,st.basename)(e),!1),!f)continue;let h,p=f.package;try{if(p){let C=e,H;for(;!(0,tt.existsSync)(H=(0,st.join)(C,"node_modules",E));)if(C=(0,st.dirname)(C),C.length<(0,Cx.getHdbBasePath)().length){H=null;break}if(H)h=await kE(H,t,r,!1),d=!0;else throw new Error(`Unable to find package ${E}:${p}`)}else h=zse[E];if(!h)continue;l.push(h);let S=a(C=>(C.origin=r,Et(C)),"ensureTable"),T=f.network||(f.port||f.securePort)&&f,R=T?.securePort||T?.https&&T.port,b=!T?.https&&T?.port;if(Lo.isMainThread&&(h=await h.startOnMainThread?.({server:at,ensureTable:S,port:b,securePort:R,resources:t,...f})||h,n&&T))for(let C of[b,R])try{if(+C&&!bx.includes(C)){let H=RA.get(rc.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);H&&Za.default.warn("Session affinity is not recommended and may cause memory leaks"),(H||!wE)&&(bx.push(C),xH(C,H))}}catch(H){console.error("Error listening on socket",C,H,E)}if(t.isWorker&&(h=await h.start?.({server:at,ensureTable:S,port:b,securePort:R,resources:t,...f})||h),TA.set(h,!0),(h.handleFile||h.handleDirectory)&&f.files){if(f.files.includes(".."))throw(0,wx.handleHDBError)("Can not reference parent directories");let C=(0,st.join)(e,f.files).replace(/\\/g,"/"),H=C.indexOf("/*");if(H>-1&&f.files!==gA[E]?.files&&!(0,tt.existsSync)(C.slice(0,H)))throw new Error(`The path '${C.slice(0,H)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let v=(0,st.basename)(e),F=f.path||"/";F=F.startsWith("/")?F:F.startsWith("./")?"/"+v+F.slice(2):F==="."?"/"+v:"/"+v+"/"+F;let M,Q,J;if(f.root){let ae=f.root;ae.startsWith("/")&&(ae=ae.slice(1)),ae.endsWith("/")&&(ae=ae.slice(0,-1)),ae+="/",Q=(0,st.join)(e,ae)}else(J=C.indexOf("/*"))>-1&&(Q=C.slice(0,J+1),M=(0,st.relative)(e,Q));let j=!1;if(Lo.isMainThread&&h.setupDirectory&&(j=await h.setupDirectory?.(F,Q,t)),t.isWorker&&h.handleDirectory&&(j=await h.handleDirectory?.(F,Q,t)),j)continue;for(let ae of await(0,Ix.default)(C,{onlyFiles:!1,objectMode:!0})){let{path:ce,dirent:ge}=ae;d=!0;let Ge=(0,st.relative)(e,ce).replace(/\\/g,"/");if(M)if(Ge.startsWith(M))Ge=Ge.slice(M.length+1);else throw new Error(`The root path '${f.root}' does not reference a valid part of the file path '${Ge}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let Ne=F+(F.endsWith("/")?"":"/")+Ge;try{if(ge.isFile()){let ve=await Qse(ce);Lo.isMainThread&&await h.setupFile?.(ve,Ne,ce,t),t.isWorker&&await h.handleFile?.(ve,Ne,ce,t)}else Lo.isMainThread&&await h.setupDirectory?.(Ne,ce,t),t.isWorker&&await h.handleDirectory?.(Ne,ce,t)}catch(ve){ve.message=`Could not load ${ge.isFile()?"file":"directory"} '${ce}'${f.module?" using '"+f.module+"'":""} for application '${e}' due to: ${ve.message}`,Ml?.(ve),((0,tc.getWorkerIndex)()===0?console:Za.default).error(ve),t.set(f.path||"/",new Pl(ve)),ec.set(n?E:(0,st.basename)(e),ve.message)}}}}catch(S){S.message=`Could not load component '${E}' for application '${(0,st.basename)(e)}' due to: ${S.message}`,Ml?.(S),((0,tc.getWorkerIndex)()===0?console:Za.default).error(S),t.set(f.path||"/",new Pl(S),null,!0),ec.set(n?E:(0,st.basename)(e),S.message)}}if(Lo.isMainThread&&!Lx&&i&&(0,tc.watchDir)(e,async()=>Mx()),c.extensionModule)return await m_((0,st.join)(e,c.extensionModule));if(!d&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;Ml?.(new Error(E)),((0,tc.getWorkerIndex)()===0?console:Za.default).error(E),ec.set((0,st.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Ml?.(c),t.set("",new Pl(c))}}}var tt,st,Lo,Nx,RA,rc,Ix,tc,Za,wx,Cx,Wse,Dx,Qse,pA,TA,Lx,SA,ec,zse,gA,bx,yx,Ml,Pl,xf=Re(()=>{tt=require("fs"),st=require("path"),Lo=require("worker_threads"),Nx=require("yaml"),RA=B(Z()),rc=B(P());Rb();yb();Nb();v0();NH();MH();Ix=B(require("fast-glob")),tc=B(We()),Za=B($());Jh();lr();wx=B(ne());Nn();Ae();GH();Cx=B(Z()),Wse=B($H());Cf();XH();Ox();Dx=B(Er());CE();({readFile:Qse}=tt.promises),pA=RA.get(rc.CONFIG_PARAMS.COMPONENTSROOT),TA=new Map,ec=new Map;a(Mx,"loadComponentDirectories");zse={REST:rE,rest:rE,graphqlSchema:zh,jsResource:Xh,fastifyRoutes:xR,login:em,static:GR,operationsApi:Wse,customFunctions:{},http:{},clustering:ZR,authentication:Zu,mqtt:mA},gA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(gA,"static",{value:{files:"web/**"}});bx=[],yx=new Map;a(Jse,"setErrorReporter");a(kE,"loadComponent");Pl=class extends $t{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var lA=g((PSe,Ux)=>{var{isMainThread:Px}=require("worker_threads"),{getTables:jse}=(Ae(),ie(ke)),{loadComponentDirectories:Xse,loadComponent:Zse}=(xf(),ie(Hf)),{resetResources:eie}=(ju(),ie(VU)),tie=Tg(),rie=Er(),{dirname:nie}=require("path"),{getConnection:sie}=ut(),iie=Z(),oie=P(),AA=new Map;async function aie(e=!1){!Px&&iie.get(oie.CONFIG_PARAMS.CLUSTERING_ENABLED)&&sie();try{Px&&await tie()}catch(n){console.error(n)}let t=eie();jse(),t.isWorker=e,await Zse(nie(rie.getConfigFilePath()),t,"hdb",!0,AA),await Xse(AA,t);let r=[];for(let[n]of AA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(aie,"loadRootComponents");Ux.exports.loadRootComponents=aie});var We=g((vSe,Ui)=>{"use strict";var{Worker:cie,MessageChannel:uie,parentPort:hs,isMainThread:IA,threadId:lie,workerData:Ks}=require("worker_threads"),{PACKAGE_ROOT:_ie}=P(),{join:xx,isAbsolute:die,extname:fie}=require("path"),{server:Gx}=(lr(),ie(xi)),{watch:Eie,readdir:hie}=require("fs/promises"),{totalmem:vx}=require("os"),Ul=P(),qx=Z(),Ws=$(),{randomBytes:mie}=require("crypto"),{_assignPackageExport:pie}=require("../index"),Sie=P(),Bx=1024*1024,Pi=[],Tn=[],Tie=50,wA=1e4,gie="restart",Fx="request_thread_info",kx="resource_report",Vx="thread_info",$x="added-port",Rie="ack",OA;pie("threads",Tn);Ui.exports={startWorker:bA,restartWorkers:DA,shutdownWorkers:Nie,workers:Pi,setMonitorListener:Uie,onMessageFromWorkers:Iie,onMessageByType:jx,broadcast:Cie,broadcastWithAcknowledgement:Lie,setChildListenerByType:yie,getWorkerIndex:Yx,getWorkerCount:Kx,getTicketKeys:Qx,setMainIsWorker:Oie,setTerminateTimeout:Aie,restartNumber:Ks?.restartNumber||1};Tn.onMessageByType=jx;Tn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Tn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var CA;function Aie(e){wA=e}a(Aie,"setTerminateTimeout");function Yx(){return Ks?Ks.workerIndex:CA?0:void 0}a(Yx,"getWorkerIndex");function Kx(){return Ks?Ks.workerCount:CA?1:void 0}a(Kx,"getWorkerCount");function Oie(e){CA=e}a(Oie,"setMainIsWorker");var Wx=1,VE;function Qx(){return VE||(VE=IA?mie(48):Ks.ticketKeys,VE)}a(Qx,"getTicketKeys");Object.defineProperty(Gx,"workerIndex",{get(){return Yx()}});Object.defineProperty(Gx,"workerCount",{get(){return Kx()}});var zx={[Fx](e,t){Mie(t)},[kx](e,t){Pie(t,e)}};function bA(e,t={}){let r=process.constrainedMemory?.()||vx();r=Math.min(r,vx(),2e4*Bx);let n=qx.get(Ul.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Bx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of Tn){let _=new uie;_.existingPort=u,i.push(_),o.push(_.port2)}fie(e)||(e+=".js");let c=new cie(die(e)?e:xx(_ie,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:Wx=t.threadCount,name:t.name,restartNumber:Ui.exports.restartNumber,ticketKeys:Qx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:$x,port:u,threadId:c.threadId},[u]);return YE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>bA(e,t),c.on("error",u=>{Ws.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Pi.splice(Pi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Tie?(t.unexpectedRestarts=c.unexpectedRestarts+1,bA(e,t)):Ws.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{zx[u.type]?.(u,c)}),Pi.push(c),Bie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(bA,"startWorker");var bie=[Ul.THREAD_TYPES.HTTP];async function DA(e=null,t=Math.max(Wx>3,1),r=!0){if(IA){if(r){let{loadRootComponents:o}=lA();await o()}Ui.exports.restartNumber++,t<1&&(t=t*Pi.length);let n=[],s=[];for(let o of Pi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ws.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ui.exports.restartNumber,type:Ul.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=bie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),wA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let E=a(f=>{f.type===Sie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ws.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",E))},"startListener");Ws.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=zu();r&&(e==="http"||!e)&&qx.get(Ul.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else hs.postMessage({type:gie,workerType:e})}a(DA,"restartWorkers");function yie(e,t){zx[e]=t}a(yie,"setChildListenerByType");function Nie(e){return DA(e,1/0,!1)}a(Nie,"shutdownWorkers");var Jx=[];function Iie(e){Jx.push(e)}a(Iie,"onMessageFromWorkers");var yA=new Map;function jx(e,t){let r=yA.get(e);r||yA.set(e,r=[]),r.push(t)}a(jx,"onMessageByType");var wie=10;async function Cie(e){let t=0;for(let r of Tn)try{r.postMessage(e),t++>wie&&(t=0,await new Promise(setImmediate))}catch(n){Ws.error("Unable to send message to worker",n)}}a(Cie,"broadcast");var $E=new Map,Die=1;function Lie(e){return new Promise(t=>{let r=0;for(let n of Tn)try{let s=Die++,i=a(()=>{$E.delete(s),--r===0&&t(),n!==hs&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,$E.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of $E)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ws.error("Unable to send message to worker",s)}r===0&&t()})}a(Lie,"broadcastWithAcknowledgement");function Mie(e){e.postMessage({type:Vx,workers:Xx()})}a(Mie,"sendThreadInfo");function Xx(){let e=Date.now();return Pi.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(Xx,"getChildWorkerInfo");function Pie(e,t){e.resources=t,e.resources.updated=Date.now()}a(Pie,"recordResourceReport");var NA;function Uie(e){NA=e}a(Uie,"setMonitorListener");var vie=1e3,Hx=!1;function Bie(){Hx||(Hx=!0,setInterval(()=>{for(let e of Pi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}NA&&NA()},vie).unref())}a(Bie,"startMonitoring");var Hie=1e3;if(hs){YE(hs);for(let e=0,t=Ks.addPorts.length;e<t;e++){let r=Ks.addPorts[e];r.threadId=Ks.addThreadIds[e],YE(r)}setInterval(()=>{let e=process.memoryUsage();hs.postMessage({type:kx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Hie).unref(),OA=a(()=>new Promise((e,t)=>{hs.on("message",r),hs.postMessage({type:Fx});function r(n){n.type===Vx&&(hs.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else OA=Xx;Ui.exports.getThreadInfo=OA;function YE(e,t){Tn.push(e),e.on("message",r=>{if(r.type===$x)r.port.threadId=r.threadId,YE(r.port);else if(r.type===Rie){let n=$E.get(r.id);n&&n()}else{for(let s of Jx)s(r,e);let n=yA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ws.error(i)}}}).on("close",()=>{Tn.splice(Tn.indexOf(e),1)}).on("exit",()=>{Tn.splice(Tn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(YE,"addPort");if(IA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await hie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(xx(s,o.name));try{for await(let{filename:o}of Eie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await DA(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");Ui.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else hs.on("message",async e=>{let{type:t}=e;t===Ul.ITC_EVENT_TYPES.SHUTDOWN&&(Ui.exports.restartNumber=e.restartNumber,hs.unref(),setTimeout(()=>{Ws.warn("Thread did not voluntarily terminate",lie),process.exit(0)},wA).unref())})});var PC={};Fe(PC,{AUDIT_STORE_OPTIONS:()=>Rf,createAuditEntry:()=>R_,openAuditStore:()=>zE,readAuditEntry:()=>vt,setAuditRetention:()=>Gie,transactionKeyEncoder:()=>aG});function zE(e){let t=e.auditStore=e.openDB(sG.AUDIT_STORE_NAME,Rf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=KE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-LA})){if((_[0]&15)===UA){let l=vt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=xie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,LA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,QE.getWorkerIndex)()===(0,QE.getWorkerCount)()-1&&s(KE),t}function Gie(e,t=KE){LA=e,KE=t}function R_(e,t,r,n,s,i,o){let c=cG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?nc.setFloat64(0,n):gn.set(mm),u=9),E(0),E(t),d(r),nc.setFloat64(u,e),u+=8,s?d(s):gn[u++]=0,gn[n?8:0]=c;let l=gn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(f){let h=u;u+=1,u=(0,sc.writeKey)(f,gn,u);let p=u-h-1;p>127?p>16383?(BA.error("Key or username was too large for audit entry",f),u=h+1,gn[h]=0):(gn.copyWithin(h+2,h+1,u),nc.setUint16(h,p|32768),u++):gn[h]=p}function E(f){f<128?gn[u++]=f:f<16384?(nc.setUint16(u,f|32768),u+=2):f<1056964608?(nc.setUint32(u,f|3221225472),u+=4):(gn[u]=255,nc.setUint32(u+1,f),u+=5)}}function vt(e){try{let t=e.dataView||(e.dataView=new vA(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:cG[n&7],tableId:i,get recordId(){return nG(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?nG(e,l,d):void 0},getValue(E,f,h){if(n&MA||n&PA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&PA&&h)return HA(E.getEntry(this.recordId),h,E)}}}catch(t){return BA.error("Reading audit entry error",t,e),{}}}function nG(e,t,r){let n=e.subarray(t,r);return(0,sc.readKey)(n,0,r-t)}var sc,WE,sG,iG,QE,oG,BA,gn,nc,aG,Rf,LA,xie,KE,MA,PA,Zx,UA,eG,tG,rG,cG,vA,ri=Re(()=>{sc=require("ordered-binary"),WE=B(Z()),sG=B(ft()),iG=B(P()),QE=B(We()),oG=B(z());Mc();BA=B($());JE();(0,WE.initSync)();gn=Buffer.alloc(1024),nc=new DataView(gn.buffer,gn.byteOffset,1024),aG={writeKey(e,t,r){return e===Lc?(t.set(Lc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,sc.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,sc.readKey)(e,t,r)}},Rf={encoding:"binary",keyEncoder:aG},LA=(0,oG.convertToMS)((0,WE.get)(iG.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,xie=1e3,KE=1e4;a(zE,"openAuditStore");a(Gie,"setAuditRetention");MA=16,PA=32,Zx=1,UA=2,eG=3,tG=4,rG=5,cG={put:Zx|MA,[Zx]:"put",delete:UA,[UA]:"delete",message:eG|MA,[eG]:"message",invalidate:tG,[tG]:"invalidate",patch:rG|PA,[rG]:"patch"};a(R_,"createAuditEntry");a(vt,"readAuditEntry");vA=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(nG,"readKeySafely")});var xA={};Fe(xA,{add:()=>jE,applyReverse:()=>uG,getRecordAtTime:()=>HA,rebuildUpdateBefore:()=>XE});function jE(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function XE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,jE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function uG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=qie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=lG}}function HA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=vt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":uG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===lG&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=vt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var qie,lG,JE=Re(()=>{ri();a(jE,"add");jE.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};qie={add:jE};a(XE,"rebuildUpdateBefore");a(uG,"applyReverse");lG={};a(HA,"getRecordAtTime")});function Zr(e){return e[Nt]||(e[Nt]=Object.create(null))}function nh(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 Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a number, attempt to assign ${d}`);Zr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be a number, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new Rn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Zr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be an object, attempt to assign ${l}`);Zr(this)[c]=l},"set")}_={get(){let l=this[Nt];if(l&&c in l){let E=l[c];if(E?.__op__){let f=this[de]?.[c];return E.update(f)}return E}let d=this[de]?.[c];if(d&&typeof d=="object"){let E=dG(d,o);if(E)return l||(l=this[Nt]=Object.create(null)),l[c]=E}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Nt];return u?.[o]!==void 0?u[o]:this[de]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Rn.ClientError("Can not add a property to a sealed table schema");Zr(this)[o]=c}),i("deleteProperty",function(o){Zr(this)[o]=void 0}),i("toJSON",function(){let o=this[Nt],c;for(let _ in o){c||(c=Object.assign({},this[de]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[de])),Object.assign(c,this)),c||this[de]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function dG(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=s}},nh(r,t)),new r(e)):new ZE(e);case Array:let n=new th(e.length);n[de]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=dG(o,t?.elements)),n[s]=o}return n;default:return e}}function pd(e){let t=e[Nt],r;for(let s in t){r||(r=Object.assign({},e[de]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=pd(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[de])),Object.assign(r,e)),r||e[de]}function Po(e,t=e[Nt]){let r;if(_G.call(e,de)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Po(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[de]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=xA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Po(s);r[n]=s}return r?Object.freeze(r):_G.call(e,de)?e[de]:e}function eh(e){let t=e[de];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[de]===s){if(eh(i))return!0}else return!0}}else{let r=e[Nt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[de]===i){if(eh(s))return!0}else return!0}else return!0}}return!1}var Rn,Nt,ZE,_G,Mo,th,rh,Sd=Re(()=>{Nn();Rn=B(ne());JE();Nt=Symbol("own-data");a(Zr,"getChanges");a(nh,"assignTrackedAccessors");a(dG,"trackObject");ZE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=t}};nh(ZE,{});a(pd,"collapseData");_G=Object.prototype.hasOwnProperty;a(Po,"deepFreeze");a(eh,"hasChanges");Mo=Symbol.for("has-array-changes"),th=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()}};th.prototype.constructor=Array;rh=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Fp={};Fe(Fp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>kn,RECORD_PROPERTY:()=>de,Resource:()=>$t,snake_case:()=>kie,transformForSelect:()=>ih});function kie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function fG(e,t){if(vl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(vl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new qA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){vl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function en(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[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[Le]??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 f of s){if(typeof f=="object"&&f)break;c.push(f)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,f)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)}else return Ze(o,()=>{let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)},d);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,u,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,l,o):f.allowUpdate(o.user,l,o):t.type==="create"?f.allowCreate(o.user,l,o):f.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new sh(o.user);return typeof l?.then=="function"?l.then(S=>e(f,u,o,S)):e(f,u,o,l)});if(!h)throw new sh(o.user)}return typeof l?.then=="function"?l.then(h=>e(f,u,o,h)):e(f,u,o,l)}a(E,"authorizeActionOnResource")}}function tn(e,t){let r=new mG.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 GA(e,t,r){let n=e[de];if(n){let s=e[Nt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function ih(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):GA(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(GA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(E=>E&&typeof E=="object"?c(E):E);let _={},l=i(GA(u,r,n)),d;for(let E of e){let f=l(E);f===void 0&&o&&(f=null),f?.then?(d||(d=[]),d.push(f.then(h=>_[E.name||E]=h))):_[E.name||E]=f}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=ih(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var EG,hG,mG,ye,Le,kn,de,Fie,$t,sh,vl,qA,Nn=Re(()=>{EG=require("crypto");yc();hG=require("../index"),mG=B(ne());Sd();no();eE();ye=Symbol.for("context"),Le=Symbol.for("primary-key"),kn=Symbol("is-collection"),de=Symbol("stored-record"),Fie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$t=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=en(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=ih(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=en(function(t,r,n,s){if(Array.isArray(s)&&t[kn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):tn(t,"put")},{hasContent:!0,type:"update"});static patch=en(function(t,r,n,s){return t.patch?t.patch(s,r):tn(t,"patch")},{hasContent:!0,type:"update"});static delete=en(function(t,r,n,s){return t.delete?t.delete(r):tn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,EG.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),n||(n={}),Ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):tn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=en(function(t,r,n,s){return t.invalidate?t.invalidate(r):tn(t,"delete")},{hasContent:!1,type:"update"});static post=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=en(function(t,r,n,s){return t.connect?t.connect(s,r):tn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=en(function(t,r,n,s){return t.subscribe?t.subscribe(r):tn(t,"subscribe")},{type:"read"});static publish=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):tn(t,"publish")},{hasContent:!0,type:"create"});static search=en(function(t,r,n,s){let i=t.search?t.search(r):tn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ih(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=en(function(t,r,n,s){return t.search?t.search(s,r):tn(t,"search")},{hasContent:!0,type:"read"});static copy=en(function(t,r,n,s){return t.copy?t.copy(s,r):tn(t,"copy")},{type:"create"});static move=en(function(t,r,n,s){return t.move?t.move(s,r):tn(t,"move")},{type:"delete"});post(t){if(this[kn])return this.constructor.create(this[Le],t,this[ye]);tn(this,"post")}static isCollection(t){return t?.[kn]}static coerceId(t){return t}static parseQuery(t){return Zf(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&&Fie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:fG(t,this),isCollection:vl}}let i=fG(t,this);return vl?{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(_=>_[Le]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],E=_.get(d);E?E.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[kn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Le]}getContext(){return this[ye]}};$t.prototype[ye]=null;(0,hG._assignPackageExport)("Resource",$t);a(kie,"snake_case");sh=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(fG,"pathToId");qA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(en,"transactional");a(tn,"missingMethod");a(GA,"selectFromObject");a(ih,"transformForSelect")});function TG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=SG,Vie(e.primaryStore,e.auditStore)):(c=pG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{gG(pG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Ia(t);let l=new kA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function gG(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=vt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,u,_=Ia(i.recordId),l=0;do{let d=o.get(_);if(d){for(let f of d)if(!(l>0&&!(f.includeDescendants&&!(f.onlyChildren&&l>1)))){if(f.startTime>=n){(0,FA.info)("omitting",c,f.startTime,n);continue}try{let h;f.supportsTransactions&&f.txnInProgress!==i.version&&(h=!0,f.txnInProgress||(r?r.push(f):r=[f]),f.txnInProgress=i.version),f.listener(c,i,n,h)}catch(h){console.error(h),(0,FA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Vie(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u=SG[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),gG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var FA,pG,SG,kA,RG=Re(()=>{FA=B($());yc();ju();ri();pG=Object.create(null),SG=Object.create(null);a(TG,"addSubscription");kA=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(gG,"notifyFromTransactionData");a(Vie,"listenToCommits")});var RR={};Fe(RR,{coerceType:()=>oh,makeTable:()=>uh,setServerUtilities:()=>Xie,updateResource:()=>ah});function uh(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=Tm(i,n,u),R=0,b,C,H={},v=Promise.resolve(),F,M,Q;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(F=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(M=K),K.expiresAt&&(Q=K),K.isPrimaryKey&&(H=K);let J,j=[],ae=[],ce=1,ge=2,Ge={},Ne={},ve=864e5,e_,t_,Js,uO=!1,yh,Nh,yq=i.getRange({start:!1,end:!1}).constructor,Nq=10,Iq=6;h&&dO();class Je extends $t{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=F;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),C=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(L=>{let N=this.sources.slice(0,-1);if(N=N.filter(U=>U[L]&&(!U[L].reliesOnPrototype||U.prototype[L])),N.length>0)if(N.length===1){let U=N[0];return(k,D,x)=>{if(k?.source!==U)return U[L](D,x,k)}}else return(U,k,D)=>{let x=[];for(let G of N){if(U?.source===G)break;x.push(G[L](k,D,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(L=>{if(y[L]&&(!y[L].reliesOnPrototype||y.prototype[L]))return(N,U,k)=>{if(!N?.source)return y[L](U,k,N)}},"getApplyToCanonicalSource");return Ge={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ne={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let L=!1,N=a(async(U,k)=>{let D=U.value,x=U.table?ct[c][U.table]:Je;if(c===$n.SYSTEM_SCHEMA_NAME&&(U.table===$n.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===$n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),U.id===void 0&&(U.id=D[x.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let G=await x.getResource(U.id,k,ic);switch(U.type){case"put":return G._writeUpdate(D,!0,ic);case"patch":return G._writeUpdate(D,!1,ic);case"delete":return G._writeDelete(ic);case"publish":return G._writePublish(D,ic);case"invalidate":return G.invalidate(ic);default:it.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let k=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,D=U&&k&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let x;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){it.error("Bad subscription event",G);continue}if(G.source=m,x)if(G.beginTxn)x.resolve();else{N(G,x);continue}if(G.type==="end_txn")continue;let me=Ze(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ue){throw ue.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ue}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ue of G.attributes)te.find(qe=>qe.name===ue.name)||(te.push(ue),Pe=!0);Pe&&(Et({table:s,database:c,attributes:te,origin:"cluster"}),kl.signalSchemaChange(new Vl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,N(G,G),new Promise(te=>{x.resolve=te})):N(G,G)});L&&(await me,kl.signalUserChange(new Vl.UserEventMsg(process.pid))),G.onCommit&&(me?.then?me.then(G.onCommit):G.onCommit())}catch(se){it.error("error in subscription handler",se)}}}catch(U){it.error(U)}})(),this}static getResource(m,A,w){let y=super.getResource(m,A,w);if(m!=null){lc(m);try{if(y.hasOwnProperty(de))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!w?.async||i.cache?.get(m),L=On(A),N=L.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Ih(m,A,{transaction:N},O,U=>{if(U?ah(y,U):y[de]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new rn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let k=wh(m,U,A,y);if(k)return L?.disregardReadTxn(),y[VA]=!0,YA(k,D=>(ah(y,D),y))}return y})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return y}ensureLoaded(){let m=wh(this[Le],this[Lr],this[ye]);if(m)return this[VA]=!0,YA(m,A=>{this[Lr]=A,this[de]=A.value,this[ql]=A.version})}static setTTLExpiration(m){if(typeof m=="number")E=m*1e3,f||(f=0);else if(m&&typeof m=="object")E=m.expiration*1e3,f=(m.eviction||0)*1e3,ve=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");ve=ve||(E+f)/4,Dh()}static enableAuditing(m=!0){h=m,m&&dO(),Je.audit=m}static coerceId(m){return m===""?null:oh(m,H)}static async dropTable(){if(delete ct[c][s],c===o){for(let m of S)l.remove(Je.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Je.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));kl.signalSchemaChange(new Vl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[kn])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let A=Je.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let w=n_(m);if(w?.read){if(w.isSuperUser)return!0;let y=w.attribute_permissions,O=A?.select;if(y?.length>0||uO&&O){if(A||(A={}),O){let L=y?.length>0&&$A(y,"read");A.select=O.map(N=>{let U=N.name||N;if(!L||L[U]){let k=Js[U]?.definition?.tableClass;if(k){if(N.name||(N={name:N}),!k.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=y.filter(L=>L.read&&!Js[L.attribute_name]).map(L=>L.attribute_name);return A}else return!0}}allowUpdate(m,A){let w=n_(m);if(w?.update){let y=w.attribute_permissions;if(y?.length>0){let O=$A(y,"update");for(let L in A)if(!O[L])return!1;for(let L of y){let N=L.attribute_name;!L.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[kn]){let w=n_(m);if(w?.insert){let y=w.attribute_permissions;if(y?.length>0){let O=$A(y,"insert");for(let L in A)if(!O[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return n_(m)?.delete}update(m,A){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&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[de]={},this[Nt]=m):(y=this[Nt],y&&(m=Object.assign(y,m)),this[Nt]=y=m)),this._writeUpdate(this[Nt],A),this}addTo(m,A){if(typeof A=="number"||typeof A=="bigint")this[Bl]===OG?this.set(m,(+this.getProperty(m)||0)+A):(this[Bl]||this.update(),this.set(m,new rh(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Lr]}invalidate(m){let A=this[ye],w=this[Le];lc(w),On(this[ye]).addWrite({key:w,store:i,invalidated:!0,entry:this[Lr],nodeName:this[ye]?.nodeName,before:Ge.invalidate?.bind(this,A,w),beforeIntermediate:Ne.invalidate?.bind(this,A,w),commit:(O,L)=>{if(L?.version>O)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(w,N,this[Lr],O,Hl,h,this[ye],0,"invalidate")}})}static evict(m,A,w){let y=this.Source,O;if(!((C||h)&&(!A||(O=i.getEntry(m),!O||!A)||O.version!==w))){if(C){if(i.hasLock(m,O.version))return;let L;for(let N in r)L||(L={}),L[N]=A[N];if(L)return T(m,L,O,w,xl,null,null,0,null,!0)}return i.ifVersion(m,w,()=>{r_(m,A,null)}),h?T(m,null,O,w,xl,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,CG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,w){let y=this[ye],O=On(y),L=this[Le];lc(L);let N=this[Lr];this[Bl]=A?OG:zie;let U={key:L,store:i,entry:N,nodeName:y?.nodeName,validate:k=>{m||(m=this[Nt]),A||m&&eh(this[Nt]===m?this:m)?y?.source||(O.checkOverloaded(),this.validate(m,!A),M&&(m[M.name]=M.type==="Date"?new Date(k):M.type==="String"?new Date(k).toISOString():k),A&&(t&&m[t]!==L&&(m[t]=L),F&&(N?.value?m[F.name]=N?.value[F.name]:m[F.name]=F.type==="Date"?new Date(k):F.type==="String"?new Date(k).toISOString():k),m=Po(m))):O.removeWrite(U)},before:A?Ge.put?()=>Ge.put(y,L,m):null:Ge.patch?()=>Ge.patch(y,L,m):Ge.put?()=>Ge.put(y,L,Po(this)):null,beforeIntermediate:A?Ne.put?()=>Ne.put(y,L,m):null:Ne.patch?()=>Ne.patch(y,L,m):Ne.put?()=>Ne.put(y,L,Po(this)):null,commit:(k,D,x)=>{if(x){if(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),this[Lr]=D,D?.value?.[de])throw new Error("Can not assign a record to a record, check for circular references");A||(this[de]=D?.value??null)}this[Nt]=void 0,this[ql]=k;let G=D?.value,se=m;if(this[Bl]=0,D?.version>=k)if(h){let ue=D.localTime,qe=D.version;for(;se&&(ue>k||qe>=k&&ue>0);){let re=u.get(ue);if(!re)break;let X=vt(re);if(qe=X.version,qe>k){if(X.type==="patch"){let pe=X.getValue(i);se=XE(se,pe)}else if(X.type==="put"||X.type==="delete")return}else if(qe===k)return;ue=X.previousLocalTime}}else{if(A)return;se=XE(se,G)}let me;if(A?me=se:(this[de]=G,me=A?se:Po(this,se)),this[de]=me,me?.[de])throw new Error("Can not assign a record to a record, check for circular references");let te;A||(te=m),r_(L,G,me);let Pe=A?"put":"patch";T(L,me,D,k,0,h,y,y.expiresAt||(E?E+Date.now():0),Pe,!1,te)}};O.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[kn]){for await(let A of this.search(m))(await Je.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[de]?this._writeDelete(m):!1}_writeDelete(m){let A=On(this[ye]),w=this[Le];lc(w);let y=this[ye];return A.addWrite({key:w,store:i,resource:this,nodeName:y?.nodeName,before:Ge.delete?.bind(this,y,w),beforeIntermediate:Ne.delete?.bind(this,y,w),commit:(O,L,N)=>{let U=L?.value;N&&(y&&L?.version>(y.lastModified||0)&&(y.lastModified=L.version),ah(this,L)),!(L?.version>O)&&(r_(this[Le],U),it.trace("Write delete entry",w,O),h||p?(T(w,null,this[Lr],O,0,h,this[ye],0,"delete"),h||Dh()):i.remove(this[Le]))}}),!0}search(m){let A=this[ye],w=On(A);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(y=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(y));let O,L={};function N(X,pe){let Be;switch(pe){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}let Yn=Be&&{},js;for(let Ke of X){if(Ke.conditions){Ke.conditions=N(Ke.conditions,Ke.operator);continue}let kt=Ke[0]??Ke.attribute,on=kt==null?H:qs(S,kt);if(on){if(Be){let Kn=xn(kt),Vt=Yn[Kn];Vt?(Vt.push(Ke),js=!0):Yn[Kn]=[Ke]}(on.type||Wg[Ke.comparator])&&(Ke[1]===void 0?Ke.value=k(Ke.value,on):Ke[1]=k(Ke[1],on))}else if(kt!=null)throw(0,rn.handleHDBError)(new Error,`${kt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(js)for(let Ke in Yn){let kt=Yn[Ke],on=kt.length;if(on>1)for(let Kn=0;Kn<on;Kn++){let Vt=kt[Kn];if(Vt.comparator==="ge"||Vt.comparator==="greater_than_equal")for(let Xs=0;Xs<on;Xs++){let qo=kt[Xs];(qo.comparator==="le"||qo.comparator==="less_than_equal")&&(Vt.comparator="between",Vt.value=[Vt.value,qo.value],X.splice(X.indexOf(qo),1))}if(Vt.comparator==="equals"||!Vt.comparator){for(let Xs=0;Xs<on;Xs++)if(Xs!==Kn){let qo=kt[Xs];X.splice(X.indexOf(qo),1)}break}}}return X}a(N,"prepareConditions");function U(X,pe){if(m.enforceExecutionOrder)return X;for(let Be of X)Be.conditions&&(Be.conditions=U(Be.conditions,Be.operator));return X.length>1&&pe!=="or"?(0,wG.sortBy)(X,Xf(Je)):X}a(U,"orderConditions");function k(X,pe){return Array.isArray(X)?X.map(Be=>oh(Be,pe)):oh(X,pe)}a(k,"coerceTypedValues");let D=m.operator;(y.length>0||D)&&(y=N(y,D));let x=typeof m.sort=="object"&&m.sort,G;if(x&&D!=="or"){let X=x.attribute;if(O=y.find(pe=>xn(pe.attribute)===xn(X)),!O){let pe=qs(S,X);if(!pe)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(pe.indexed)O={attribute:X,comparator:"sort"},y.push(O);else if(y.length===0&&!m.allowFullScan)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}O&&(O.descending=!!x.descending)}y=U(y,D),x&&(O&&y[0]===O?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&y.splice(y.indexOf(O),1),G=x));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:D,postOrdering:G,selectApplied:!!se};let me=w.useReadTxn(),te=Qg(y,D,Je,me,m,A,(X,pe)=>lO(X,se,A,me,pe),L),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ue=Je.transformEntryForSelect(se,A,me,L,Pe,!0),qe=Je.transformToOrderedSelect(te,se,G,me,A,ue);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),G&&(qe=re(qe)),qe.onDone=()=>{qe.onDone=null,w.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(se){let X=[];for(let pe of se)pe==="*"?X.push(...S.map(Be=>Be.name)):X.push(pe.name||pe);return X}return S.map(X=>X.name)},qe}static transformToOrderedSelect(m,A,w,y,O,L){let N=new yq;if(w){m=lO(m,A,y,O,null);let U;N.iterate=function(){let D,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=w.dbOrderedAttribute,me,te,Pe=!0;function ue(re){let X=re.next&&ue(re.next),pe=re.descending;return(Be,Yn)=>{let js=Ch(Be,re.attribute,y),Ke=Ch(Yn,re.attribute,y),kt=pe?(0,Bo.compareKeys)(Ke,js):(0,Bo.compareKeys)(js,Ke);return kt===0?X?.(Be,Yn)||0:kt}}a(ue,"createComparator");let qe=ue(w);return{async next(){let re;if(D)if(re=D.next(),re.done){if(G)return N.onDone&&N.onDone(),re}else return{value:await L.call(this,re.value)};U=[],me&&U.push(me);do if(re=await x.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let pe=Ch(X,se,y);if(Pe)Pe=!1,te=pe;else if(pe!==te){te=pe,me=X;break}}U.push(X)}while(!0);return w.isGrouped,U.sort(qe),D=U[Symbol.iterator](),re=D.next(),re.done?(N.onDone&&N.onDone(),re):{value:await L.call(this,re.value)}},return(){N.onDone&&N.onDone(),x.return()},throw(){N.onDone&&N.onDone(),x.throw()}}};let k=a(D=>{if(typeof A=="object"&&Array.isArray(D.attribute))for(let x=0;x<A.length;x++){let G=A[x],se;if(G.name===D.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=D.attribute.slice(1),se.descending=D.descending}else G===D.attribute[0]&&(A[x]=se={name:G,sort:{attribute:D.attribute.slice(1),descending:D.descending}})}D.next&&k(D.next)},"applySortingOnSelect");k(w)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(L);return N}static transformEntryForSelect(m,A,w,y,O,L){if(m&&(m===t||m?.length===1&&m[0]===t)){let D=a(x=>(A?.transaction?.stale&&(A.transaction.stale=!1),x?.key??x),"transform");return m===t?D:m.asArray?x=>[D(x)]:x=>({[t]:D(x)})}let N;O&&C&&!m?.every(D=>{let x;return typeof D=="object"?x=D.name:x=D,r[x]||x===t})&&(N=!0);let U,k=a(function(D){let x;if(A?.transaction?.stale&&(A.transaction.stale=!1),D!=null){if(yh=D,x=D.value||D.deref?.(),!x&&(D.key===void 0||D.deref)){if(D=Ih(D.key??D,A,{transaction:w,lazy:m?.length<4},this.isSync,G=>G),D?.then)return D.then(k.bind(this));x=D?.value}if(N&&(D.metadataFlags&(Hl|xl)||D.expiresAt&&D.expiresAt<Date.now())){let G=wh(D.key??D,D,A);if(G?.then)return G.then(k)}}if(x==null)return L?Uo.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Pe)=>{let ue;typeof te=="object"?ue=te.name:ue=te;let qe=Js?.[ue],re;if(qe){let X=y?.[ue];if(X)if(X.hasMappings){let Be=qe.from?x[qe.from]:xn(D.key);re=X.get(Be),re||(re=[])}else re=X.fromRecord?.(x);else re=qe(x,A,D);let pe=a(Be=>{if(Be&&typeof Be=="object"){let Yn=qe.definition?.tableClass||Je;U||(U={});let js=U[ue]||(U[ue]=Yn.transformEntryForSelect(ue===te?null:te.select||(Array.isArray(te)?te:null),A,w,X,O));if(Array.isArray(Be)){let Ke=[],kt=Yn.transformToOrderedSelect(Be,te.select,typeof te.sort=="object"&&te.sort,A,w,js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),on=a(Vt=>{for(;!Vt.done;){if(Vt?.then)return Vt.then(on);Ke.push(Vt.value),Vt=kt.next()}Pe(Ke,ue)},"nextValue"),Kn=on(kt.next());Kn&&(G||(G=[]),G.push(Kn));return}else if(Be=js.call(this,Be),Be?.then){G||(G=[]),G.push(Be.then(Ke=>Pe(Ke,ue)));return}}Pe(Be,ue)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(pe))):pe(re);return}else re=x[ue],re&&typeof re=="object"&&ue!==te&&(re=Je.transformEntryForSelect(te.select||te,A,w,null)({value:re}));Pe(re,ue)},"selectAttribute"),me;if(typeof m=="string")se(m,te=>{me=te});else if(Array.isArray(m))if(m.asArray)me=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=x:se(te,ue=>me[Pe]=ue)});else{me={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ue in x)me[ue]=x[ue];else se(Pe,(ue,qe)=>{ue===void 0&&te&&(ue=null),me[qe]=ue})}else throw new rn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>me):me}return x},"transform");return k}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||Et({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let A=!m.rawEvents,w=TG(Je,this[Le]??null,function(N,U,k,D){try{let x=U.getValue?.(i,A);if(!x&&U.type==="patch"&&A){let G=i.getEntry(N);G?.version===U.version?x=G.value:x=U.getValue?.(i,!0,k),U.type="put"}this.send({id:N,timestamp:k,value:x,version:U.version,type:U.type,beginTxn:D})}catch(x){it.error(x)}},m.startTime||0,m);this[kn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.supportsTransactions&&(w.supportsTransactions=!0);let y=this[Le],O=m.previousCount;O>1e3&&(O=1e3);let L=m.startTime;if(this[kn]){if(L){if(O)throw new rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:L,exclusiveStart:!0})){let k=vt(U);if(k.tableId!==n)continue;let D=k.recordId;if(y==null||NG(y,D)){let x=k.getValue(i,A,N);w.send({id:D,timestamp:N,value:x,version:k.version,type:k.type})}w.startTime=N}}else if(O){let N=[];for(let{key:U,value:k}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=vt(k);if(D.tableId!==n)continue;let x=D.recordId;if(y==null||NG(y,x)){let G=D.getValue(i,A,U);if(N.push({id:x,timestamp:U,value:G,version:D.version,type:D.type}),--O<=0)break}}catch(D){it.error("Error getting history entry",U,D)}for(let U=N.length;U>0;)w.send(N[--U]);N[0]&&(w.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:k,localTime:D}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&w.send({id:N,timestamp:D,value:U,version:k,type:"put"})}else{O&&!L&&(L=0);let N=this[Lr]?.localTime;if(N===Sm&&(i.cache?.delete(y),this[Lr]=i.getEntry(y),it.trace("re-retrieved record",N,this[Lr]?.localTime),N=this[Lr]?.localTime),it.trace("Subscription from",L,"from",y,N),L<N){let U=[],k=N;do{let D=u.get(k);if(D){m.omitCurrent=!0;let x=vt(D),G=x.getValue(i,A,k);A&&(x.type="put"),U.push({id:y,value:G,timestamp:k,...x}),k=x.previousLocalTime}else break;O&&O--}while(k>L&&O!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=N}!m.omitCurrent&&this.doesExist()&&w.send({id:y,timestamp:N,value:this[de],version:this[ql],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[de]||this[Bl])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let w=On(this[ye]),y=this[Le]||null;lc(y);let O=this[ye];w.addWrite({key:y,store:i,entry:this[Lr],nodeName:O?.nodeName,validate:()=>{O?.source||(w.checkOverloaded(),this.validate(m))},before:Ge.publish?.bind(this,O,y,m),beforeIntermediate:Ne.publish?.bind(this,O,y,m),commit:(L,N,U)=>{N===void 0&&p&&!h&&Dh(),T(y,N?.value??null,N,N?.version||L,0,!0,O,N?.expiresAt,"message",!1,m)}})}validate(m,A){let w,y=a((O,L,N)=>{if(L.type&&O!=null)if(A&&O.__op__&&(O=O.value),L.properties){typeof O!="object"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be an object${L.type?" ("+L.type+")":""}`);let U=L.properties;for(let k=0,D=U.length;k<D;k++){let x=U[k],G=y(O[x.name],x,N+"."+x.name);G&&(O[x.name]=G)}if(L.sealed&&O!=null&&typeof O=="object")for(let k in O)U.find(D=>D.name===k)||(w||(w=[])).push(`Property ${k} is not allowed within object in property ${N}`)}else switch(L.type){case"Int":(typeof O!="number"||O>>0!==O)&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(L.elements)for(let U=0,k=O.length;U<k;U++){let D=O[U],x=y(D,L.elements,N+"[*]");x&&(O[U]=x)}}else(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a Buffer or Uint8Array`);break}L.nullable===!1&&O==null&&(w||(w=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let O=0,L=S.length;O<L;O++){let N=S[O];if(!N.relationship&&(!A||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let O in m)S.find(L=>L.name===O)||(w||(w=[])).push(`Property ${O} is not allowed`);if(w)throw new rn.ClientError(w.join(". "))}getUpdatedTime(){return this[ql]}wasLoadedFromSource(){return C?!!this[VA]:void 0}static async addAttributes(m){let A=S.slice(0);for(let w of m){if(!w.name)throw new rn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new rn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(w)}return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static async removeAttributes(m){let A=S.filter(w=>!m.includes(w.name));return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,w=5e3,y=1e3,O;A>w&&!m?.exactCount&&(O=y);let L=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:O}))N!=null&&L++;if(O){let N=L;L=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))Pe!=null&&L++;let U=O*2,k=(L+N)/U,D=Math.pow((L-N+1)/O/2,2)+k*(1-k)/U,x=Math.max(Math.sqrt(D)*A,1),G=Math.round(k*A),se=Math.max(G-1.96*x,0),me=Math.min(G+1.96*x,A),te=Math.pow(10,Math.round(Math.log10(x)));return te>G&&(te=te/10),L=Math.round(G/te)*te,{recordCount:L,estimatedRange:[Math.round(se),Math.round(me)]}}return{recordCount:L}}static updatedAttributes(){Js=this.propertyResolvers={$id:(m,A,w)=>({value:w.key}),$updatedtime:(m,A,w)=>w.version,$record:(m,A,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),uO=!0,A.to)m.elements?.definition?(Js[m.name]=m.resolve=(w,y,O)=>{let L=w[A.from?A.from:t],N=m.elements.definition.tableClass;return O?xa({attribute:A.to,value:L},On(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:A.to,value:L}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let w=m.definition||m.elements?.definition;w?(Js[m.name]=m.resolve=(y,O,L)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let U,k=N.map(D=>{let x=L?w.tableClass.primaryStore.getEntry(D,{transaction:On(O).getReadTxn()}):w.tableClass.get(D,O);return x?.then&&(U=!0),x});return A.filterMissing?U?Promise.all(k).then(D=>D.filter(IG)):k.filter(IG):U?Promise.all(k):k}return L?w.tableClass.primaryStore.getEntry(N,{transaction:On(O).getReadTxn()}):w.tableClass.get(N,O)}},m.set=(y,O)=>{if(Array.isArray(O)){let L=O.map(N=>N[Le]||N[w.tableClass.primaryKey]);y[A.from]=L}else{let L=O[Le]||O[w.tableClass.primaryKey];y[A.from]=L}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}nh(this,this)}static async deleteHistory(m=0){let A;for(let{key:w,value:y}of u.getRange({start:0,end:m}))await Gl(),vt(y).tableId===n&&(A=u.remove(w));await A}static async*getHistory(m=0,A=1/0){for(let{key:w,value:y}of u.getRange({start:m,end:A})){await Gl();let O=vt(y);O.tableId===n&&(yield{id:O.recordId,localTime:w,version:O.version,type:O.type,value:O.getValue(i,!0,w),user:O.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return A;let y=w.localTime;if(!y)throw new Error("The entry does not have a local audit time");let O=0;do{await Gl();let L=u.get(y);if(L){let N=vt(L);A.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(O<1e3&&y);return A.reverse()}static cleanup(){J?.remove()}}Je.updatedAttributes();let wq=Je.prototype;return wq[Qie]=!0,E&&Je.setTTLExpiration(E/1e3),Q&&Cq(),Je;function r_(K,m,A){let w;for(let y in r){let O=r[y],L=O.isIndexing,N=A?.[y],U=m?.[y];if(N===U&&!L)continue;w=!0;let k=O.indexNulls,D=(0,Fl.getIndexedValues)(N,k),x=(0,Fl.getIndexedValues)(U,k);if(x?.length>0){let G=new Set(x);if(D=D?D.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],x=Array.from(G),(x.length>0||D.length>0)&&AG){let se=x.concat(D).map(me=>({key:me,value:K}));O.prefetch(se,yG)}for(let se=0,me=x.length;se<me;se++)O.remove(x[se],K)}else D?.length>0&&AG&&O.prefetch(D.map(G=>({key:G,value:K})),yG);if(D)for(let G=0,se=D.length;G<se;G++)O.put(D[G],K)}return w}a(r_,"updateIndices");function lc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>bG)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,Jie,0)>bG)throw new Error("Primary key size is too large: "+K.length);return!0}a(lc,"checkValidId");function Ih(K,m,A,w,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,K);let L=i.getEntry(K,A);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),y(L,K)},"whenPrefetched");return w?O():ce>0?(ce--,O()):new Promise((L,N)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),k()})):(j.push(K),ae.push(k),j.length>Iq&&(ce--,U()));function U(){if(j.length>0){let D=ae;i.prefetch(j,()=>{ce===-1?U():ce++;for(let x of D)x()}),j=[],ae=[],ge>2&&ge--}else ce=ge,ge<Nq&&ge++}a(U,"prefetch");function k(){try{L(O())}catch(D){N(D)}}a(k,"load")})}a(Ih,"loadLocalRecord");function n_(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return jie;let A=m[c],w,y=A?.tables;if(y)return y[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(n_,"getTablePermissions");function wh(K,m,A,w){if(C){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Hl|xl)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,Wr(!y,"cache-hit",s)),y){let O=_O(K,m,A).then(L=>(L?.value?.[de]&&it.error("Can not assign a record with a record property"),A&&(L?.version>(A.lastModified||0)&&(A.lastModified=L.version),A.lastRefreshed=Date.now()),L));if(A?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,K)){if(O.catch(L=>it.warn(L)),A?.onlyIfCached&&!w.doesExist())throw new rn.ServerError("Entry is not cached",504);return}else return O}}}a(wh,"ensureLoadedFromSource");function On(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new ro,m.lmdbDb=i,m;m=A}while(!0)}else return new hd}a(On,"txnForContext");function Ch(K,m,A){if(!K)return;yh=K;let w=K.value||K.deref?.()||(yh=i.getEntry(K.key))?.value;if(typeof m=="object"){let O=Js,L=w;for(let N=0,U=m.length;N<U;N++){let k=m[N],D=O?.[k];L=D&&L?D(L,A,!0)?.value:L?.[k],O=D?.definition?.tableClass?.propertyResolvers}return L}let y=Js[m];return y?y(w,A):w[m]}a(Ch,"getAttributeValue");function lO(K,m,A,w,y){let O=y?.length,L={transaction:w,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(k,D){let x=k?.value;if(!x)return Uo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](x,k))return Uo.SKIP;return D!==void 0&&(k.key=D),k}if(a(U,"processEntry"),O>0||!K.hasEntries){let k=K.map(D=>{if(N=null,typeof D=="object"&&D?.key!==void 0)return O>0?U(D):D;if(D==null)return Uo.SKIP;for(let x=0;x<O;x++){let se=y[x].idFilter;if(se){if(!se(D))return Uo.SKIP;N||(N=[]),N.push(x)}}return Ih(D,A,L,!1,U)});return Array.isArray(K)&&(k=k.filter(D=>D!==Uo.SKIP)),k.hasEntries=!0,k}return K}a(lO,"transformToEntries");async function _O(K,m,A){let w=m?.metadataFlags,y=m?.version,O,L;if(!i.attemptLock(K,y,()=>{clearTimeout(L);let D=i.getEntry(K);!D||!D.value||D.metadataFlags&(Hl|xl)?O(_O(K,i.getEntry(K),A)):O(D)}))return new Promise(D=>{O=D,L=setTimeout(()=>{i.unlock(K,y)},Wie)});let N=m?.value,U={requestContext:A,replacingRecord:N,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:A?.resourceCache},k=A?.responseHeaders;return new Promise((D,x)=>{let G;YA(Ze(U,async se=>{let me=performance.now(),te,Pe,ue;try{for(let pe of Je.sources)if(pe.get&&(!pe.get.reliesOnPrototype||pe.prototype.get)&&(U.source=pe,te=await pe.get(K,U),te))break;ue=w&Hl;let re=U.lastModified||ue&&y;Pe=ue||re>y||!N,re||(re=(0,Fl.getNextMonotonicTime)());let X=performance.now()-me;if(Sr(X,"cache-resolution",s),k&&mg(k,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=re,E&&!U.expiresAt&&(U.expiresAt=Date.now()+E),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==K&&(te[t]=K)}G=!0,D({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${s}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(D({version:y,value:N}),it.trace(re.message,"(returned stale record)")):x(re),U.transaction.abort();return}if(A?.noCacheStore||U.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==y)return;let pe=r_(K,N,te);te?(Ne.put?.(U,K,te),T(K,te,X,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ue)):(Ne.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Pe||null,U,0,"delete",!!ue):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&it.error("Error committing cache update",se)})})}a(_O,"getFromSource");function Dh(){if(ve!==e_&&(e_=ve,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(t_&&clearTimeout(t_),!ve)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/ve)*ve+K.getTime(),A=a(w=>{it.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),t_=setTimeout(()=>v=v.then(async()=>{if(A(Math.max(w+ve,Date.now())),i.rootStore.status!=="open"){clearTimeout(t_);return}let y=50,O=new Array(y),L=0;it.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:U,value:k,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;k===null&&!h&&D+Kie<Date.now()?G=i.remove(U,D):x&&x+f<Date.now()&&(G=Je.evict(U,k,D),N++),G&&(await O[L],O[L]=G.catch(se=>{it.error("Cleanup error",se)}),++L>=y&&(L=0)),await Gl()}it.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){it.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Dh,"scheduleCleanup");function dO(){J=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(dO,"addDeleteRemoval");function Cq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!Nh){Nh=!0;try{let K=Q.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${Q} must be indexed`);for(let A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let w of m.getValues(A)){let y=i.getEntry(w);y?.value?y.value[K]<Date.now()&&Je.evict(w,y.value,y.version):i.ifVersion(w,y?.version,()=>m.remove(A,w))}await Gl()}}catch(K){it.error("Error in evicting old records",K)}finally{Nh=!1}}},Yie).unref()}a(Cq,"runRecordExpirationEviction")}function $A(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 yG(){}function Xie(e){CG=e}function oh(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?isNaN(e)?e==="null"?null:(Zie.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,ch.autoCast)(e):e}function NG(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 YA(e,t,r){return e?.then?e.then(t,r):t(e)}function ah(e,t){e[Lr]=t,e[de]=t?.value??null,e[ql]=t?.version}function IG(e){return e!=null}function Vn(e){try{return JSON.stringify(e)}catch{return e}}var $n,Uo,Fl,wG,$l,rn,kl,Vl,it,Bo,vo,ch,$ie,CG,Yie,Kie,AG,Wie,ql,Qie,Lr,Bl,OG,zie,VA,ic,Hl,xl,Jie,bG,jie,TTe,Zie,Gl,EE=Re(()=>{$n=B(P()),Uo=require("lmdb"),Fl=B(vr()),wG=require("lodash");Nn();cS();$l=B(Z());RG();rn=B(ne()),kl=B(ys()),Vl=B(Mn());Ae();eE();it=B($());Sd();no();Bo=require("ordered-binary"),vo=B(We());ri();ch=B(z());Mc();Cs();JE();Xu();$ie=new Uint8Array(9);$ie[8]=192;Yie=6e4,Kie=864e5;$l.initSync();AG=$l.get($n.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Wie=1e4,ql=Symbol.for("version"),Qie=Symbol.for("incremental-update"),Lr=Symbol("entry"),Bl=Symbol("is-saving"),OG=1,zie=2,VA=Symbol("loaded-from-source"),ic={isNotification:!0,ensureLoaded:!1},Hl=1,xl=8,Jie=Buffer.allocUnsafeSlow(8192),bG=1978,jie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},TTe=(0,ch.convertToMS)($l.get($n.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(uh,"makeTable");a($A,"attributesAsObject");a(yG,"noop");a(Xie,"setServerUtilities");Zie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(oh,"coerceType");a(NG,"isDescendantId");Gl=a(()=>new Promise(setImmediate),"rest");a(YA,"when");a(ah,"updateResource");a(IG,"exists");a(Vn,"stringify")});var ke={};Fe(ke,{database:()=>ca,databases:()=>ct,dropDatabase:()=>fS,dropTableMeta:()=>soe,getDatabases:()=>mr,getDefaultCompression:()=>Af,getTables:()=>eoe,onUpdatedTable:()=>eA,readMetaDb:()=>Yl,resetDatabases:()=>$u,table:()=>Et,tables:()=>Br});function eoe(){return Eh||mr(),Br||{}}function mr(){if(Eh)return ct;Eh=!0,cc=new Map;let e=(0,St.getHdbBasePath)()&&(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),t=(0,St.get)(Ut.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,nn.existsSync)(e)?e:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,nn.existsSync)(e))for(let r of(0,nn.readdirSync)(e,{withFileTypes:!0})){let n=(0,ot.basename)(r.name,".mdb");r.isFile()&&(0,ot.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Yl((0,ot.join)(e,r.name),null,n)}if((0,nn.existsSync)((0,ac.getBaseSchemaPath)())){for(let r of(0,nn.readdirSync)((0,ac.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,ot.join)((0,ac.getBaseSchemaPath)(),r.name),s=(0,ot.join)((0,ac.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,nn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,ot.extname)(i.name).toLowerCase()===".mdb"){let o=(0,ot.join)(s,i.name);Yl((0,ot.join)(n,i.name),(0,ot.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,nn.existsSync)(s))for(let o of(0,nn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,ot.extname)(o.name).toLowerCase()===".mdb"&&Yl((0,ot.join)(s,o.name),(0,ot.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,ot.join)(c.path,(0,ot.basename)(o+".mdb"));(0,nn.existsSync)(u)&&Yl(u,o,r,null,!0)}}for(let r in ct){let n=cc.get(r);if(n){let s=ct[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete ct[r],r==="data"){for(let s in Br)delete Br[s];delete Br[hh]}}return cc=null,ct}}function $u(){Eh=!1;for(let[,e]of vi)e.needsDeletion=!0;mr();for(let[e,t]of vi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),vi.delete(e));return ct}function Yl(e,t,r=QA,n,s){let i=new KA.default(e,!1);try{let o=vi.get(e);o?o.needsDeletion=!1:(o=(0,_h.open)(i),vi.set(e,o));let c=new Ho.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(lh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,nn.existsSync)(n)&&(i.path=n,_=(0,_h.open)(i),_.isLegacy=!0):_=zE(o));let l=PG(r),d=l[hh],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[p,S]=f.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let T=E.get(p);T||E.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:p,primary:S}=h;if(!S){for(let j of p)if(j.is_hash_attribute||j.isPrimaryKey){S=j;break}if(!S){An.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[f],R={},b=[],C,H,v=typeof S.audit=="boolean"?S.audit:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),F=S.trackDeletes,M=S.expiration,Q=S.eviction,J=S.sealed;if(T)R=T.indices,b=T.attributes,T.schemaVersion++;else{C=S.tableId,C?C>=(u.get(oc)||0)&&u.putSync(oc,C+1):(S.tableId=C=u.get(oc),C||(C=1),u.putSync(oc,C+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 ae=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||MG;j.compression.threshold=ae}H=A_(o.openDB(S.key,j)),H.rootStore=o,H.tableId=C}for(let j of p){j.attribute=j.name;try{if(!j.is_hash_attribute&&(j.indexed||j.attribute&&!j.name)){if(!R[j.name]){let ce=new Ho.default(!j.is_hash_attribute,j.is_hash_attribute);R[j.name]=o.openDB(j.key,ce),R[j.name].indexNulls=j.indexNulls}let ae=b.find(ce=>ce.name===j.name);ae?b.splice(b.indexOf(ae),1,j):b.push(j)}}catch(ae){An.error("Error trying to update attribute",j,b,R,ae)}}if(!T){T=UG(l,f,uh({primaryStore:H,auditStore:_,audit:v,sealed:J,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:F,tableName:f,tableId:C,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let j of zA)j(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function PG(e){let t=ct[e];if(t||(e==="data"?t=ct[e]=Br:e==="system"?Object.defineProperty(ct,"system",{value:t=Object.create(null),configurable:!0}):t=ct[e]=Object.create(null)),cc&&!cc.has(e)){let r=new Set;t[hh]=r,cc.set(e,r)}return t}function UG(e,t,r){return e[t]=r,r}function ca({database:e,table:t}){e||(e=QA),mr();let r=PG(e),n=(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),s=(0,St.get)(Ut.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||((0,nn.existsSync)(n)?n:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME));let o=(0,ot.join)(n,(i?t:e)+".mdb"),c=vi.get(o);if(!c){let u=new KA.default(o,!1);c=(0,_h.open)(u),vi.set(o,c)}return c}async function fS(e){if(!ct[e])throw new Error("Schema does not exist");let t=ct[e],r;for(let n in t)r=t[n].primaryStore.rootStore,vi.delete(r.path),r.status==="open"&&(await r.close(),await Kl.remove(r.path));if(r||(r=ca({database:e,table:null}),r.status==="open"&&(await r.close(),await Kl.remove(r.path))),e==="data"){for(let n in Br)delete Br[n];delete Br[hh]}delete ct[e]}function Et({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=QA);let d=ca({database:t,table:e}),E=ct[t],f=E?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let R=new Ho.default(!1);for(let M of i)M.attribute&&!M.name?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let b,C;if(f){if(h=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=d.auditStore;M||(M=zE(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=Af(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let Q=new Ho.default(!1,!0);Q.compression=p.compression;let J=e+"/",j=A_(d.openDB(J,Q));j.rootStore=d,T=d.dbisDb=d.openDB(lh.INTERNAL_DBIS_NAME,R),j.tableId=T.get(oc),j.tableId||(j.tableId=1),T.putSync(oc,j.tableId+1),p.tableId=j.tableId,f=UG(E,e,uh({primaryStore:j,auditStore:M,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:j.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,b=!0,F(),T.put(J,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(lh.INTERNAL_DBIS_NAME,R)),f.dbisDB=T;let H=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[J,j]=M.toString().split("/");if(j===""&&(j=Q.name),j){if(J!==e)continue}else j=J;if(!i.find(ce=>ce.name===j)?.indexed&&Q.indexed&&!Q.isPrimaryKey){F(),b=!0,T.remove(M);let ce=f.indices[J];ce&&H.push(ce)}}let v=[];try{for(let M of i||[]){if(M.relationship)continue;let Q=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:Q,configurable:!0});let J=T.get(Q);if(M.isPrimaryKey){if(J=J||T.get(Q=e+"/")||{},o!==f.audit||c!==c||(+r||void 0)!==(+J.expiration||void 0)||(+n||void 0)!==(+J.eviction||void 0)){let ae=Object.assign({},J);typeof o=="boolean"&&(o&&f.enableAuditing(o),ae.audit=o),r&&(ae.expiration=+r),n&&(ae.eviction=+n),c!==void 0&&(ae.sealed=c),b=!0,F(),T.put(Q,ae)}continue}J?.attribute&&!J.name&&(J.indexed=!0);let j=!J||J.type!==M.type||J.indexed!==M.indexed||J.nullable!==M.nullable||JSON.stringify(J.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(J.elements)!==JSON.stringify(M.elements);if(M.indexed){let ae=new Ho.default(!0,!1),ce=d.openDB(Q,ae);(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Wl.workerData?.restartNumber)&&(b=!0,F(),J=T.get(Q),(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Wl.workerData?.restartNumber)&&(b=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=J?.lastIndexedKey||!1,M.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ce}),v.push(M))),T.put(Q,M)),J?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ce.indexNulls=M.indexNulls,S[M.name]=ce}else j&&(b=!0,F(),T.put(Q,M))}}finally{C&&C()}if(b&&(f.schemaVersion++,f.updatedAttributes()),An.trace(`${e} table loading, running index`),v.length>0||H.length>0?f.indexingOperation=noe(f,v,H):b&&dh.signalSchemaChange(new fh.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=l,b)for(let M of zA)M(f,l!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),f;function F(){C||d.transactionSync(()=>({then(M){C=M}}))}a(F,"startTxn")}async function noe(e,t,r){try{let n=e.schemaVersion;await dh.signalSchemaChange(new fh.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,p=(0,DG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>u--,E=>{u--,An.error(E)}),Wl.workerData&&Wl.workerData.restartNumber!==LG.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}u>toe?await s:u>roe&&await new Promise(E=>setImmediate(E))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await dh.signalSchemaChange(new fh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){An.error("Error in indexing",n)}}function soe({table:e,database:t}){let r=ca({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function eA(e){zA.push(e)}function Af(){let e=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||MG,n={startingOffset:32};return t&&(n.dictionary=Kl.readFileSync(t)),r&&(n.threshold=r),e&&n}var St,lh,_h,ot,nn,ac,Ho,KA,Ut,Kl,WA,DG,dh,fh,Wl,An,LG,QA,hh,MG,Br,ct,oc,zA,Eh,vi,cc,toe,roe,Ae=Re(()=>{St=B(Z()),lh=B(ft()),_h=require("lmdb"),ot=require("path"),nn=require("fs"),ac=B(je());EE();Ho=B(Pc()),KA=B(Uc()),Ut=B(P()),Kl=B(require("fs-extra")),WA=require("../index"),DG=B(vr()),dh=B(ys()),fh=B(Mn()),Wl=require("worker_threads"),An=B($()),LG=B(We());ri();Mc();QA="data",hh=Symbol("defined-tables"),MG=((0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,St.initSync)();Br=Object.create(null),ct=Object.create(null);(0,WA._assignPackageExport)("databases",ct);(0,WA._assignPackageExport)("tables",Br);oc=Symbol.for("next-table-id"),zA=[],vi=new Map;a(eoe,"getTables");a(mr,"getDatabases");a($u,"resetDatabases");a(Yl,"readMetaDb");a(PG,"ensureDB");a(UG,"setTable");a(ca,"database");a(fS,"dropDatabase");a(Et,"table");toe=1e3,roe=10;a(noe,"runIndexing");a(soe,"dropTableMeta");a(eA,"onUpdatedTable");a(Af,"getDefaultCompression")});var z=g((wTe,QG)=>{"use strict";var Bi=require("path"),GG=require("fs-extra"),Mr=$(),vG=require("fs-extra"),mh=require("os"),ioe=require("net"),ooe=require("recursive-iterator"),dt=P(),aoe=YO(),BG=require("papaparse"),ph=require("moment"),{inspect:coe}=require("util"),HG=require("is-number"),ITe=require("lodash"),uoe=require("minimist"),loe=require("https"),_oe=require("http"),{hdb_errors:Sh}=ne(),doe=/^((\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)))$/,qG=require("util").promisify(setTimeout),foe=100,Eoe=5,hoe="",moe=4,xG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};QG.exports={isEmpty:sn,isEmptyOrZeroLength:ms,arrayHasEmptyValues:Toe,arrayHasEmptyOrZeroLengthValues:goe,buildFolderPath:Roe,isBoolean:FG,errorizeMessage:poe,stripFileExtension:Ooe,autoCast:boe,autoCastJSON:kG,autoCastJSONDeep:jA,removeDir:yoe,compareVersions:Noe,isCompatibleDataVersion:Ioe,escapeRawValue:woe,unescapeValue:Coe,stringifyProps:Doe,timeoutPromise:Moe,isClusterOperation:Uoe,getClusterUser:Boe,checkGlobalSchemaTable:voe,getHomeDir:$G,getPropsFilePath:Loe,promisifyPapaParse:Hoe,removeBOM:YG,createEventPromise:xoe,checkProcessRunning:Goe,checkSchemaTableExist:qoe,checkSchemaExists:KG,checkTableExists:WG,getStartOfTomorrowInSeconds:Foe,getLimitKey:koe,isObject:Aoe,isNotEmptyAndHasValue:Soe,autoCasterIsNumberCheck:VG,backtickASTSchemaItems:Voe,isPortTaken:Poe,createForkArgs:$oe,autoCastBoolean:Yoe,async_set_timeout:qG,getTableHashAttribute:Koe,doesSchemaExist:Woe,doesTableExist:Qoe,stringifyObj:zoe,ms_to_time:Joe,changeExtension:joe,getEnvCliRootPath:XA,noBootFile:Xoe,httpRequest:Zoe,transformReq:eae,convertToMS:tae,PACKAGE_ROOT:dt.PACKAGE_ROOT};function poe(e){return e instanceof Error?e:new Error(e)}a(poe,"errorizeMessage");function sn(e){return e==null}a(sn,"isEmpty");function Soe(e){return!sn(e)&&(e||e===0||e===""||FG(e))}a(Soe,"isNotEmptyAndHasValue");function ms(e){return sn(e)||e.length===0||e.size===0}a(ms,"isEmptyOrZeroLength");function Toe(e){if(sn(e))return!0;for(let t=0;t<e.length;t++)if(sn(e[t]))return!0;return!1}a(Toe,"arrayHasEmptyValues");function goe(e){if(ms(e))return!0;for(let t=0;t<e.length;t++)if(ms(e[t]))return!0;return!1}a(goe,"arrayHasEmptyOrZeroLengthValues");function Roe(...e){try{return e.join(Bi.sep)}catch{console.error(e)}}a(Roe,"buildFolderPath");function FG(e){return sn(e)?!1:e===!0||e===!1}a(FG,"isBoolean");function Aoe(e){return sn(e)?!1:typeof e=="object"}a(Aoe,"isObject");function Ooe(e){return ms(e)?hoe:e.slice(0,-moe)}a(Ooe,"stripFileExtension");function boe(e){return sn(e)||e===""||typeof e!="string"?e:xG[e]!==void 0?xG[e]:VG(e)===!0?Number(e):doe.test(e)?new Date(e):e}a(boe,"autoCast");function kG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(kG,"autoCastJSON");function jA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=jA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=jA(r);n!==r&&(e[t]=n)}return e}else return kG(e)}a(jA,"autoCastJSONDeep");function VG(e){if(e.startsWith("0.")&&HG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&HG(e))}a(VG,"autoCasterIsNumberCheck");async function yoe(e){if(ms(e))throw new Error(`Directory path: ${e} does not exist`);try{await vG.emptyDir(e),await vG.remove(e)}catch(t){throw Mr.error(`Error removing files in ${e} -- ${t}`),t}}a(yoe,"removeDir");function Noe(e,t){if(ms(e)){Mr.info("Invalid current version sent as parameter.");return}if(ms(t)){Mr.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(Noe,"compareVersions");function Ioe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Ioe,"isCompatibleDataVersion");function woe(e){if(sn(e))return e;let t=String(e);return t==="."?dt.UNICODE_PERIOD:t===".."?dt.UNICODE_PERIOD+dt.UNICODE_PERIOD:t.replace(dt.FORWARD_SLASH_REGEX,dt.UNICODE_FORWARD_SLASH)}a(woe,"escapeRawValue");function Coe(e){if(sn(e))return e;let t=String(e);return t===dt.UNICODE_PERIOD?".":t===dt.UNICODE_PERIOD+dt.UNICODE_PERIOD?"..":String(e).replace(dt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Coe,"unescapeValue");function Doe(e,t){if(sn(e))return Mr.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+mh.EOL}!ms(n)&&n[0]===";"?r+=" "+n+s+mh.EOL:ms(n)||(r+=n+"="+s+mh.EOL)}catch{Mr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Doe,"stringifyProps");function $G(){let e;try{e=mh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a($G,"getHomeDir");function Loe(){let e=Bi.join($G(),dt.HDB_HOME_DIR_NAME,dt.BOOT_PROPS_FILE_NAME);return GG.existsSync(e)||(e=Bi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Loe,"getPropsFilePath");function Moe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Moe,"timeoutPromise");async function Poe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=ioe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Poe,"isPortTaken");function Uoe(e){try{return dt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Uoe,"isClusterOperation");function voe(e,t){let r=(Ae(),ie(ke)).getDatabases();if(!r[e])return Sh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return Sh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(voe,"checkGlobalSchemaTable");function Boe(e,t){if(sn(t)){Mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(sn(e)||ms(e)){Mr.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Mr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Boe,"getClusterUser");function Hoe(){BG.parsePromise=function(e,t,r){return new Promise(function(n,s){BG.parse(e,{header:!0,transformHeader:YG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Hoe,"promisifyPapaParse");function YG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(YG,"removeBOM");function xoe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Mr.info(`Got cluster status event response: ${coe(s)}`);try{i.cancel()}catch{Mr.error("Error trying to cancel timeout.")}n(s)})})}a(xoe,"createEventPromise");async function Goe(e){let t=!0,r=0;do await qG(foe*r++),(await aoe.findPs(e)).length>0&&(t=!1);while(t&&r<Eoe);if(t)throw new Error(`process ${e} was not started`)}a(Goe,"checkProcessRunning");function qoe(e,t){let r=KG(e);if(r)return r;let n=WG(e,t);if(n)return n}a(qoe,"checkSchemaTableExist");function KG(e){let{getDatabases:t}=(Ae(),ie(ke));if(!t()[e])return Sh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(KG,"checkSchemaExists");function WG(e,t){let{getDatabases:r}=(Ae(),ie(ke));if(!r()[e][t])return Sh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(WG,"checkTableExists");function Foe(){let e=ph().utc().add(1,dt.MOMENT_DAYS_TAG).startOf(dt.MOMENT_DAYS_TAG).unix(),t=ph().utc().unix();return e-t}a(Foe,"getStartOfTomorrowInSeconds");function koe(){return ph().utc().format("DD-MM-YYYY")}a(koe,"getLimitKey");function Voe(e){try{let t=new ooe(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){Mr.error("Got an error back ticking items."),Mr.error(t)}}a(Voe,"backtickASTSchemaItems");function $oe(e){return[e]}a($oe,"createForkArgs");function Yoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Yoe,"autoCastBoolean");function Koe(e,t){let{getDatabases:r}=(Ae(),ie(ke)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Koe,"getTableHashAttribute");function Woe(e){let{getDatabases:t}=(Ae(),ie(ke));return t()[e]!==void 0}a(Woe,"doesSchemaExist");function Qoe(e,t){let{getDatabases:r}=(Ae(),ie(ke));return r()[e]?.[t]!==void 0}a(Qoe,"doesTableExist");function zoe(e){try{return JSON.stringify(e)}catch{return e}}a(zoe,"stringifyObj");function Joe(e){let t=ph.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(Joe,"ms_to_time");function joe(e,t){let r=Bi.basename(e,Bi.extname(e));return Bi.join(Bi.dirname(e),r+t)}a(joe,"changeExtension");function XA(){if(process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=uoe(process.argv);if(e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(XA,"getEnvCliRootPath");var JA;function Xoe(){if(JA)return JA;let e=XA();if(XA()&&GG.pathExistsSync(Bi.join(e,dt.HDB_CONFIG_FILE)))return JA=!0,!0}a(Xoe,"noBootFile");function Zoe(e,t){let r;return e.protocol==="http:"?r=_oe:r=loe,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(Zoe,"httpRequest");function eae(e){if(!e.schema&&!e.database){e.schema=dt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(eae,"transformReq");function tae(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(tae,"convertToMS")});var Z=g((DTe,ZG)=>{"use strict";var ZA=require("fs-extra"),xo=require("path"),zG=require("os"),rae=require("properties-reader"),zl=$(),Ql=z(),le=P(),Th=Er(),nae="Error initializing environment manager",gh="BOOT_PROPS_FILE_PATH",JG=!1,sae={[le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Qs={};ZG.exports={BOOT_PROPS_FILE_PATH:gh,getHdbBasePath:iae,setHdbBasePath:oae,get:jG,initSync:cae,setProperty:Me,initTestEnvironment:lae,setCloneVar:uae};function iae(){return Qs[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(iae,"getHdbBasePath");function oae(e){Qs[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(oae,"setHdbBasePath");function jG(e){let t=Th.getConfigValue(e);return t===void 0?Qs[e]:t}a(jG,"get");function Me(e,t){sae[e]&&(Qs[e]=t),Th.updateConfigObject(e,t)}a(Me,"setProperty");function aae(){let e;try{e=Ql.getPropsFilePath(),ZA.accessSync(e,ZA.constants.F_OK|ZA.constants.R_OK),JG=!0;let t=rae(e);return Qs[le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(le.HDB_SETTINGS_NAMES.INSTALL_USER),Qs[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Qs[gh]=e,!0}catch{return zl.trace(`Environment manager found no properties file at ${e}`),!1}}a(aae,"doesPropFileExist");function cae(e=!1){try{(JG||aae()||Ql.noBootFile())&&!XG&&(Th.initConfig(e),Qs[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Th.getConfigValue(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){zl.error(nae),zl.error(t),console.error(t),process.exit(1)}}a(cae,"initSync");var XG=!1;function uae(e){XG=e}a(uae,"setCloneVar");function lae(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");Qs[gh]=xo.join(u,"hdb_boot_properties.file"),Me(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xo.join(u,"settings.test")),Me(le.HDB_SETTINGS_NAMES.INSTALL_USER,zG.userInfo()?zG.userInfo().username:void 0),Me(le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xo.join(u,"envDir","log")),Me(le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xo.join(u,"envDir")),Me(le.CONFIG_PARAMS.STORAGE_PATH,xo.join(u,"envDir")),s&&(Me(le.CONFIG_PARAMS.HTTP_SECUREPORT,jG(le.CONFIG_PARAMS.HTTP_PORT)),Me(le.CONFIG_PARAMS.HTTP_PORT,null)),Me(le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ql.isEmpty(i)?!1:i),Me(le.CONFIG_PARAMS.HTTP_CORS,Ql.isEmpty(i)?!1:i),Me(le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ql.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${gh}. Please check your boot props and settings files`;zl.fatal(r),zl.error(t)}}a(lae,"initTestEnvironment")});var sq=g((MTe,nq)=>{"use strict";var rq=require("joi"),{string:Jl,boolean:eq,array:_ae}=rq.types(),tq=P(),dae=Xe();nq.exports=fae;function fae(e){let t=rq.object({operation:Jl.valid(tq.OPERATIONS_ENUM.ADD_NODE,tq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Jl.required(),subscriptions:_ae.items({schema:Jl.required(),table:Jl.optional(),hash_attribute:Jl.optional(),subscribe:eq.required(),publish:eq.required()}).min(1).required()});return dae.validateBySchema(e,t)}a(fae,"updateRemoteSourceValidator")});var jl=g((UTe,iq)=>{"use strict";var eO=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};iq.exports=eO});var uq=g((BTe,cq)=>{"use strict";var Eae=sq(),zs=$(),tO=Ve(),hae=P(),rO=dn(),Go=ut(),oq=Au(),mae=dd(),{Node:pae,NodeSubscription:aq}=Si(),nO=jl(),sO=z(),Sae=Z(),{cloneDeep:Tae}=require("lodash"),{broadcast:gae}=We();cq.exports=Rae;async function Rae(e){try{let t=Eae(e);if(t)return zs.error(`Validation error in updateRemoteSource: ${t.message}`),new nO(tO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=Tae(await rO.getNodeRecord(n)),c=!sO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&zs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],E=d.schema,f=d.table;if(!sO.doesSchemaExist(E)){zs.trace(`updateRemoteSource creating schema: ${E}`);try{await oq.createSchema({operation:"create_schema",schema:E})}catch(h){zs.error(h)}}if(f&&!sO.doesTableExist(E,f)){let h=new mae(E,f,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),zs.trace(`updateRemoteSource creating table: ${f} in schema: ${E} with attributes: ${JSON.stringify(d.attributes)}`);try{await oq.createTable(h)}catch(p){zs.error(p)}}if(zs.trace(`Creating local stream for ${E}.${f}`),await Go.createLocalTableStream(E,f),c?(await Go.updateConsumerIterator(E,f,n,"stop"),await Go.updateRemoteConsumer(d,n),d.subscribe===!0&&await Go.updateConsumerIterator(E,f,n,"start")):(await Go.updateRemoteConsumer(d,n),d.subscribe===!0?await Go.updateConsumerIterator(E,f,n,"start"):await Go.updateConsumerIterator(E,f,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===E&&T.table===f){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new aq(E,f,d.publish,d.subscribe))}else i.push(new aq(E,f,d.publish,d.subscribe))}c||(o=new pae(n,i,void 0),zs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await rO.upsertNodeRecord(u),gae({type:"nats_update"}),new nO(tO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Sae.get(hae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await rO.getSystemInfo())}catch(t){zs.error(t);let r=t.message?t.message:t;return new nO(tO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Rae,"updateRemoteSource")});var fq=g((xTe,dq)=>{"use strict";var _q=require("joi"),{string:lq}=_q.types(),Aae=P(),Oae=Xe();dq.exports=bae;function bae(e){let t=_q.object({operation:lq.valid(Aae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:lq.required()});return Oae.validateBySchema(e,t)}a(bae,"removeRemoteSourceValidator")});var mq=g((qTe,hq)=>{"use strict";var yae=fq(),Rh=$(),Ah=Ve(),iO=P(),Nae=dn(),Iae=z(),Eq=ut(),wae=Z(),Oh=jl(),{NodeSubscription:Cae}=Si(),Dae=oa(),Lae=ai(),{broadcast:Mae}=We(),Pae=wae.get(iO.CONFIG_PARAMS.CLUSTERING_NODENAME);hq.exports=Uae;async function Uae(e){try{let t=yae(e);if(t)return Rh.error(`Validation error in removeRemoteSource: ${t.message}`),new Oh(Ah.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await Nae.getNodeRecord(r);if(Iae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return Rh.error(i),new Oh(Ah.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];Rh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Cae(c.schema,c.table,!1,!1);await Eq.updateConsumerIterator(c.schema,c.table,r,"stop"),await Eq.updateRemoteConsumer(u,r)}let s=new Dae(iO.SYSTEM_SCHEMA_NAME,iO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Lae.deleteRecord(s),Mae({type:"nats_update"}),new Oh(Ah.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Pae} successfully removed node '${r}'.`)}catch(t){Rh.error(t);let r=t.message?t.message:t;return new Oh(Ah.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Uae,"removeRemoteSource")});var gq=g((kTe,Tq)=>{"use strict";var bh=$(),Xl=P(),pq=Ve(),oO=Z(),vae=z(),Sq=jl(),Bae=dn(),Hae=Vd(),xae=qr();Tq.exports=Gae;async function Gae(e){try{bh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=vae.ms_to_time(t),n=new qae(oO.get(Xl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),oO.get(Xl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??oO.get(Xl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Bae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new Hae(Xl.SYSTEM_SCHEMA_NAME,Xl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await xae.update(i)}catch(s){bh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return bh.trace("getRemoteSourceConfig response:",n),new Sq(pq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){bh.error(t);let r=t.message?t.message:t;return new Sq(pq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Gae,"getRemoteSourceConfig");function qae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(qae,"ConfigResponseObject")});var bq=g(($Te,Oq)=>{"use strict";var Rq=Z();Rq.initSync();var Aq=ut(),Zl=$(),uc=P(),aO=Ve(),Fae=uq(),kae=mq(),Vae=gq(),$ae=jl(),{encode:Yae,decode:Kae}=require("msgpackr"),Wae=bs(),Qae=Os(),zae=require("util"),Jae=P(),{isMainThread:jae,parentPort:Xae}=require("worker_threads");We();var Zae=zae.promisify(Wae.setSchemaDataToGlobal),cO=Rq.get(uc.CONFIG_PARAMS.CLUSTERING_NODENAME);Oq.exports=ece;async function ece(){try{Zl.notify("Starting reply service."),await Zae();let e=await Aq.getConnection(),t=`${cO}.__request__`,r=e.subscribe(t,{queue:cO});await tce(r)}catch(e){Zl.error(e)}}a(ece,"initialize");async function tce(e){for await(let t of e){let r=Kae(t.data),n;switch(r.operation){case uc.OPERATIONS_ENUM.ADD_NODE:case uc.OPERATIONS_ENUM.UPDATE_NODE:n=await Fae(r);break;case uc.OPERATIONS_ENUM.REMOVE_NODE:n=await kae(r);break;case uc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Vae(r);break;case uc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await rce();break;default:let s=`node '${cO}' reply service received unrecognized request operation`;Zl.error(s),n=new $ae(aO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Zl.trace(n),t.respond(Yae(n))}}a(tce,"handleRequest");async function rce(){try{return{status:aO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Qae.describeAll()}}catch(e){return Zl.error(e),{status:aO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(rce,"getRemoteDescribeAll");jae||Xae.on("message",async e=>{let{type:t}=e;t===Jae.ITC_EVENT_TYPES.SHUTDOWN&&Aq.closeConnection()})});var nce=bq();(async()=>{try{await nce()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
31
|
+
`))}},25).unref()}o.close?.(()=>{if(qe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&Ll()==0)try{Zx(qe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,UE),o.cantCleanupProperly||Pt.warn("Had to forcefully exit the thread",UE),process.exit(0)},5e3).unref()})}if(aH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Pt.info("Could not close debugger",i)}}}).ref();let e=[];if(eH&&!qse)for(let t in Es){let r=Es[t];if(isNaN(t)&&Ll()==0){Cse(t)&&Zx(t),e.push(new Promise((i,o)=>{r.listen({path:t},()=>{i(),Pt.info("Domain socket listening on "+t)}).on("error",o)}));continue}let n=qe.get(_t.CONFIG_PARAMS.HTTP_THREADRANGE);if(n){let i=typeof n=="string"?n.split("-"):n,o=Ll();if(o<i[0]||o>i[1])continue}let s;try{s=eH(+t,"::")}catch(i){console.error(`Unable to bind to port ${t}`,i);continue}e.push(new Promise((i,o)=>{r.listen({fd:s},()=>{i(),Pt.trace("Listening on port "+t,UE)}).on("error",o)}))}Promise.all(e).then(()=>{Dl?.postMessage({type:_t.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(cH,"startServers");iA||cH();function cA(e,t,r){let n=e?.read?e:new Ose({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Es[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=Es[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Pt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(cA,"deliverSocket");var tH=new Map;function Vse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=tH.get(s),r){case"connection":i=cA(void 0,t),tH.set(s,i),i.write=(c,u,_)=>(Dl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Dl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Dl.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(Vse,"proxyRequest");function uA(e,t,r=!0){!+t&&t!==qe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(qe.get(_t.CONFIG_PARAMS.HTTP_PORT),10));let n=Es[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",rH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else Es[t]=e;e.on("unhandled",rH)}a(uA,"registerServer");function uH(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=[],qe.get(_t.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:qe.get(_t.CONFIG_PARAMS.HTTP_PORT),secure:qe.get(_t.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),qe.get(_t.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:qe.get(_t.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&qe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:qe.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(uH,"getPorts");function lA(e,t){for(let{port:r,secure:n}of uH(t))lH(r,n,t?.isOperationsServer),typeof e=="function"?oA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,uA(e,r,!1)),BE[r]=aA(oA,r),Fse=aA(kse,r)}a(lA,"httpServer");function lH(e,t,r){if(!Ys[e]){let n=r?"operationsApi_network":"http",s={noDelay:!0,keepAliveTimeout:qe.get(n+"_keepAliveTimeout"),headersTimeout:qe.get(n+"_headersTimeout"),requestTimeout:qe.get(n+"_timeout")},i=qe.get(n+"_mtls"),o=qe.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=qe.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:nH(),maxHeaderSize:qe.get(_t.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:_A(u)})}let c=Bse();Ys[e]=(t?Ise:yse)(s,async(u,_)=>{try{let d=performance.now(),E=new iH(u,_);r&&(E.isOperationsServer=!0);let f=await BE[e](E);if(!f){if(E._nodeResponse.statusCode)return;f=_H(E)}if(c?f.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):f.headers?.set?.("Server","HarperDB"),f.status===-1){for(let H of f.headers||[])_.setHeader(H[0],H[1]);return u.baseRequest=E,_.baseResponse=f,Ys[e].emit("unhandled",u,_)}let h=f.status||200,p=performance.now(),S=p-d,T=f.body,R;if(!f.handlesHeaders){let H=f.headers||new sH;T?T.length>=0&&(typeof T=="string"?H.set("Content-Length",Buffer.byteLength(T)):H.set("Content-Length",T.length),R=!0):(H.set("Content-Length","0"),R=!0);let U=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(U+=", miss"),Use(H,"Server-Timing",U,!0),_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),R&&_.end(T)}let N=E.handlerPath,I=E.method;if(Cl(S,"duration",N,I,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),vse(h<400,"success",N,I),!R)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let H=0;T.on("data",U=>{H+=U.length}),T.on("end",()=>{Cl(performance.now()-p,"transfer",N,I),Cl(H,"bytes-sent",N,I)})}else T?.then?T.then(H=>{_.end(H)},l):_.end(T)}catch(d){l(d)}function l(d){let E=d.headers;_.writeHead(d.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),_.end(d.toString()),d.statusCode?d.statusCode===500?Pt.warn(d):Pt.info(d):Pt.error(d)}a(l,"onError")}),i&&(Ys[e].mtlsConfig=i),t&&(Ys[e].on("secureConnection",u=>{u._parent.startTime&&Cl(performance.now()-u._parent.startTime,"tls-handshake",e),Cl(u.isSessionReused(),"tls-reused",e)}),Ys[e].isSecure=!0,s.SNICallback(null,(u,_)=>{try{Xa=_,_&&Ys[e].setSecureContext(_.options)}finally{Xa=null}})),uA(Ys[e],e)}return Ys[e]}a(lH,"getHTTPServer");function aA(e,t){let r=_H;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(aA,"makeCallbackChain");function _H(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new sH}}a(_H,"unhandled");function $se(e,t){lA(e,{requestOnly:!0,...t})}a($se,"onRequest");function Yse(e,t){let r;if(t.securePort){let n=Object.assign({},qe.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={noDelay:!0,rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:_A(n)};r=Mse(s,e),s.SNICallback(null,(i,o)=>{try{Xa=o,o&&r.setSecureContext(o.options)}finally{Xa=null}}),Es[t.securePort]=r}return t.port&&(r=bse({noDelay:!0},e),Es[t.port]=r),r}a(Yse,"onSocket");Object.defineProperty(Nse.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 Kse(e,t){let r;for(let{port:n,secure:s}of uH(t)){vE[n]||(vE[n]=new Dse({server:r=lH(n,s)}),vE[n].on("connection",async(c,u)=>{try{let _=new iH(u);_.isWebSocket=!0;let l=BE[n](_),d=u.headers["sec-websocket-protocol"]||"",E=nA[n];if(d){let f;for(let h=0;h<E.length;h++){let p=E[h];p.protocol===d&&(f=!0,p.listener(c,_,l))}if(f)return}for(let f=0;f<E.length;f++){let h=E[f];h.protocol||h.listener(c,_,l)}}catch(_){Pt.warn("Error handling WebSocket connection",_)}}),vE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=nA[n];o||(o=nA[n]=[]),o.push({listener:e,protocol:i}),BE[n]=aA(oA,n)}return r}a(Kse,"onWebSocket");function rH(e,t){t.writeHead(404),t.end(`Not found
|
|
32
|
+
`)}a(rH,"defaultNotFound");function sA(e){return e.startsWith("-----BEGIN")?e:wse(e)}a(sA,"readPEM");function _A(e){let t=[];for(let o=0;e[o];o++)t.push(e[o]);t.length||t.push(e);let r=new Map,n,s,i=!1;for(let o of t){let c=sA(o.privateKey),u=sA(o.certificate),_=o.certificateAuthority&&sA(o.certificateAuthority);if(!c||!u)throw new Error("Missing private key or certificate for secure server");let l={ciphers:o.ciphers,ca:_,ticketKeys:nH()},d=Lse(l);d.options=l,l.instantiatedContext=d,d.context.setCert(u),d.context.setKey(c,void 0),l.cert=u,l.key=c,d.certStart=u.slice(0,100).toString(),n||(n=d);let E=new xse(u);d.subject=E.subject;let f=o.hostname??o.host??o.hostnames??o.hosts??(E.subjectAltName?E.subjectAltName.split(",").map(h=>{let p=h.indexOf(":");return h.slice(p+1)}):[E.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(f)||(f=[f]);for(let h of f)h?(h[0]==="*"&&(i=!0,h=h.slice(1)),r.has(h)||r.set(h,d),!s&&h.match(/\d+\.\d+\.\d+\.\d+/)&&(s=d)):Pt.error("No hostname found for certificate at",o.certificate)}return(o,c)=>{let u=o;for(;;){let _=r.get(u);if(_)return Pt.debug("Found certificate for",o,_.certStart),c(null,_);if(i&&u){let l=u.indexOf(".",1);l<0?u="":u=u.slice(l)}else break}Pt.debug("No certificate found to match",o,"using the first certificate"),o?c(null,n):c(null,s)}}a(_A,"createSNICallback")});async function pH({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await fA.get(e,{returnNonexistent:!0});i=new mA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await fA.get(e);o&&o.delete()}i=new GE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Ml.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function EA(){return HE++,HE>65500&&(HE=1),HE}function hA(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=bi.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var EH,Mi,hH,mH,fH,fA,Ml,HE,GE,mA,SH=Re(()=>{Ae();Xu();EH=x(vr()),Mi=x($());no();hH=x(We()),mH=x(dH());lr();fH=100,fA=Et({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),Ml=Et({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,hH.getWorkerIndex)()===0&&(async()=>{await mH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Ml.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await at.getUser(r.user.username)),Ze(r,()=>{try{hA(r,t,r)}catch{(0,Mi.warn)("Failed to publish will",t)}Ml.delete(e.id,r)})}})();a(pH,"getSession");HE=1;a(EA,"getNextMessageId");GE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let E={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Mi.trace)("Resuming subscription from",s,"from",o);let f=bi.getMatch(_);if(!f){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let T=E.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,T.indexOf("+")===T.length-1)E.onlyChildren=!0,E.url="/"+T.slice(0,T.length-1);else{let R=T.split("/"),N;for(let U=0;U<R.length;U++)if(R[U].indexOf("+")>-1)if(R[U]==="+")N=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&N)throw new Error("Filters can not be combined");let I=!0;R[R.length-1]==="#"&&(R.length--,I=!1),N&&(n=a(U=>{let k=U.id;if(!Array.isArray(k)||I&&k.length!==R.length)return!1;for(let M=0;M<R.length;M++)if(R[M]!=="+"&&R[M]!==k[M])return!1;return!0},"filter"));let H=R.indexOf("+");E.url="/"+(H>-1?R.slice(0,H):R).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Ze(E,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let R=await p.subscribe(E,T);if(!R)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let N=(async()=>{for await(let I of R)try{let H;if(I.type&&I.type!=="put"&&I.type!=="delete"&&I.type!=="message"&&I.type!=="patch"||n&&!n(I))continue;r?(I.topic=s,H=this.needsAcknowledge(I)):(I.acknowledge?.(),H=EA());let U=I.id;if(Array.isArray(U)&&(U=Ia(U)),U==null&&(U=""),await this.listener(h+"/"+U,I.value,H,t)===!1)break;this.awaitingAcks?.size>fH?await new Promise(M=>setTimeout(M,this.awaitingAcks.size-fH)):await new Promise(setImmediate)}catch(H){(0,Mi.warn)(H)}})();return R});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=EA();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return hA(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Ze(r,async()=>{try{if(!t){let n=await Ml.get(this.sessionId);n?.doesExist()&&await hA(n,n.data,r)}}finally{await Ml.delete(this.sessionId)}}).catch(n=>{(0,Mi.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(hA,"publish");mA=class extends GE{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=EA(),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);if(!r)return;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,Mi.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,EH.getNextMonotonicTime)()),(0,Mi.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),fA.put(this.sessionRecord)}}});var SA={};Fe(SA,{bypassAuth:()=>Wse,start:()=>Qse});function Wse(){OH=!0}function Qse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new AH.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),jt.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=gH(_,h=>{_.send(h)},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",E),_.on("close",f),_.on("error",h=>{jt.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(o.events.emit("connection",_),jt.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let f=u.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{l=await e.getUser(f,null,null),(0,Za.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&FE.notify({username:l?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Za.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&FE.error({username:f,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else jt.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),jt.error(f)}else if(u.required)return jt.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&OH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,RH.getSuperUser)(),jt.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:E}=gH(_,f=>_.write(f),null,l,o);_.on("data",d),_.on("close",E),_.on("error",f=>{jt.info("Socket error",f)})},{port:t,securePort:s,mtls:u})),c}function gH(e,t,r,n,s){TH||(TH=!0,hu(d=>{qE>0&&d.push({metric:"mqtt-connections",connections:qE,byThread:!0})}));let i;qE++;let o,c={protocolVersion:4},u=(0,kE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){qE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!1,"connection","mqtt","disconnect"),jt.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;let E=d.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;Sr(d.length,"bytes-received",h,S(d),"mqtt");try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await at.getUser(d.username,d.password.toString(),r),(0,Za.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&FE.notify({username:n?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Za.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&FE.error({username:d.username,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let M=e.deserialize||(e.deserialize=bo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=pH({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return jt.error(M),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Wr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,J,j)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",M);let ae=M.indexOf("/",1),ce=ae>0?M.slice(0,ae):M;p({cmd:"publish",topic:M,payload:T(Q),messageId:J||Math.floor(Math.random()*1e8),qos:j.qos},ce);let de=e._socket??e;return de.writableNeedDrain?new Promise(Be=>de.once("drain",Be)):!de.closed}catch(ae){return jt.error(ae),o?.disconnect(),s.sessions.delete(o),!1}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let R=[];for(let M of d.subscriptions){let Q;try{Q=(await o.addSubscription(M,M.qos>=1)).qos||0}catch(J){s.events.emit("error",J,e,M,o),jt.error(J),Q=c.protocolVersion<5?128:J.statusCode===403?135:J.statusCode===404?143:128}R.push(Q)}await o.committed,p({cmd:"suback",granted:R,messageId:d.messageId});break;case"unsubscribe":{let M=[];for(let Q of d.unsubscriptions)M.push(o.removeSubscription(Q)?0:17);p({cmd:"unsuback",granted:M,messageId:d.messageId});break}case"pubrel":p({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let N=d.qos===2?"pubrec":"puback",I=e.deserialize||(e.deserialize=bo(r?.headers.get?.("content-type"))),U=(d.payload?.length||0)>0?I(d.payload):void 0,k;try{k=await o.publish(d,U)}catch(M){s.events.emit("error",M,e,d,o),jt.warn(M),d.qos>0&&p({cmd:N,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&p({cmd:N,messageId:d.messageId,reasonCode:k===!1?144:0},d.topic);break;case"pubrec":p({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":p({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!0,"connection","mqtt","disconnect"),jt.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(R){s.events.emit("error",R,e,d,o),jt.error(R),p({cmd:"disconnect"})}function p(R,N){let I=(0,kE.generate)(R,c);t(I),Sr(I.length,"bytes-sent",N,S(R),"mqtt")}a(p,"sendPacket");function S(R){return R.qos>0?R.cmd+",qos="+R.qos:R.cmd}a(S,"packetMethodName");function T(R){return go(R,r)}a(T,"serialize")}),u.on("error",d=>{jt.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:_,onClose:l}}var kE,RH,Za,Xt,pA,AH,FE,jt,OH,TH,qE,bH=Re(()=>{kE=require("mqtt-packet");SH();RH=x(_n());Ca();Cs();lr();Za=x(ee()),Xt=x(P()),pA=x($()),AH=require("events"),FE=(0,pA.loggerWithTag)("auth-event"),jt=(0,pA.loggerWithTag)("mqtt"),OH=(0,Za.get)(Xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Wse,"bypassAuth");a(Qse,"start");qE=0;a(gH,"onSocket")});var Hf={};Fe(Hf,{component_errors:()=>tc,loadComponent:()=>VE,loadComponentDirectories:()=>PH,setErrorReporter:()=>Xse});function PH(e,t){t&&(gA=t),e&&(RA=e);let r=[];if((0,tt.existsSync)(TA)){let s=(0,tt.readdirSync)(TA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,st.join)(TA,o);r.push(VE(c,gA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(VE(n,gA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{MH=!0})}function Xse(e){Pl=e}async function VE(e,t,r,n,s,i){let o=(0,tt.realpathSync)(e);if(!NH.has(o)){NH.set(o,!0),s&&(RA=s);try{let c;n&&(tc=new Map);let u=(0,st.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,tt.existsSync)(u)?c=n?(0,LH.getConfigObj)():(0,IH.parseDocument)((0,tt.readFileSync)(u,"utf8"),{simpleKeys:!0}).toJSON():c=AA;let _=(0,st.join)(e,"node_modules","harperdb");try{Lo.isMainThread&&(n||(0,tt.existsSync)(_)&&(0,tt.realpathSync)(nc.PACKAGE_ROOT)!==(0,tt.realpathSync)(_))&&((0,tt.rmSync)(_,{recursive:!0,force:!0}),(0,tt.existsSync)((0,st.join)(e,"node_modules"))||(0,tt.mkdirSync)((0,st.join)(e,"node_modules")),(0,tt.symlinkSync)(nc.PACKAGE_ROOT,_,"dir"))}catch(E){ec.default.error("Error symlinking harperdb module",E)}let l=[],d=n;for(let E in c){let f=c[E];if(tc.set(n?E:(0,st.basename)(e),!1),!f)continue;let h,p=f.package;try{if(p){let I=e,H;for(;!(0,tt.existsSync)(H=(0,st.join)(I,"node_modules",E));)if(I=(0,st.dirname)(I),I.length<(0,DH.getHdbBasePath)().length){H=null;break}if(H)h=await VE(H,t,r,!1),d=!0;else throw new Error(`Unable to find package ${E}:${p}`)}else h=jse[E];if(!h)continue;l.push(h);let S=a(I=>(I.origin=r,Et(I)),"ensureTable"),T=f.network||(f.port||f.securePort)&&f,R=T?.securePort||T?.https&&T.port,N=!T?.https&&T?.port;if(Lo.isMainThread&&(h=await h.startOnMainThread?.({server:at,ensureTable:S,port:N,securePort:R,resources:t,...f})||h,n&&T))for(let I of[N,R])try{if(+I&&!yH.includes(I)){let H=OA.get(nc.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);H&&ec.default.warn("Session affinity is not recommended and may cause memory leaks"),(H||!CE)&&(yH.push(I),Hx(I,H))}}catch(H){console.error("Error listening on socket",I,H,E)}if(t.isWorker&&(h=await h.start?.({server:at,ensureTable:S,port:N,securePort:R,resources:t,...f})||h),RA.set(h,!0),(h.handleFile||h.handleDirectory)&&f.files){if(f.files.includes(".."))throw(0,CH.handleHDBError)("Can not reference parent directories");let I=(0,st.join)(e,f.files).replace(/\\/g,"/"),H=I.indexOf("/*");if(H>-1&&f.files!==AA[E]?.files&&!(0,tt.existsSync)(I.slice(0,H)))throw new Error(`The path '${I.slice(0,H)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let U=(0,st.basename)(e),k=f.path||"/";k=k.startsWith("/")?k:k.startsWith("./")?"/"+U+k.slice(2):k==="."?"/"+U:"/"+U+"/"+k;let M,Q,J;if(f.root){let ae=f.root;ae.startsWith("/")&&(ae=ae.slice(1)),ae.endsWith("/")&&(ae=ae.slice(0,-1)),ae+="/",Q=(0,st.join)(e,ae)}else(J=I.indexOf("/*"))>-1&&(Q=I.slice(0,J+1),M=(0,st.relative)(e,Q));let j=!1;if(Lo.isMainThread&&h.setupDirectory&&(j=await h.setupDirectory?.(k,Q,t)),t.isWorker&&h.handleDirectory&&(j=await h.handleDirectory?.(k,Q,t)),j)continue;for(let ae of await(0,wH.default)(I,{onlyFiles:!1,objectMode:!0})){let{path:ce,dirent:de}=ae;d=!0;let Be=(0,st.relative)(e,ce).replace(/\\/g,"/");if(M)if(Be.startsWith(M))Be=Be.slice(M.length+1);else throw new Error(`The root path '${f.root}' does not reference a valid part of the file path '${Be}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let Ne=k+(k.endsWith("/")?"":"/")+Be;try{if(de.isFile()){let xe=await Jse(ce);Lo.isMainThread&&await h.setupFile?.(xe,Ne,ce,t),t.isWorker&&await h.handleFile?.(xe,Ne,ce,t)}else Lo.isMainThread&&await h.setupDirectory?.(Ne,ce,t),t.isWorker&&await h.handleDirectory?.(Ne,ce,t)}catch(xe){xe.message=`Could not load ${de.isFile()?"file":"directory"} '${ce}'${f.module?" using '"+f.module+"'":""} for application '${e}' due to: ${xe.message}`,Pl?.(xe),((0,rc.getWorkerIndex)()===0?console:ec.default).error(xe),t.set(f.path||"/",new Ul(xe)),tc.set(n?E:(0,st.basename)(e),xe.message)}}}}catch(S){S.message=`Could not load component '${E}' for application '${(0,st.basename)(e)}' due to: ${S.message}`,Pl?.(S),((0,rc.getWorkerIndex)()===0?console:ec.default).error(S),t.set(f.path||"/",new Ul(S),null,!0),tc.set(n?E:(0,st.basename)(e),S.message)}}if(Lo.isMainThread&&!MH&&i&&(0,rc.watchDir)(e,async()=>PH()),c.extensionModule)return await p_((0,st.join)(e,c.extensionModule));if(!d&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;Pl?.(new Error(E)),((0,rc.getWorkerIndex)()===0?console:ec.default).error(E),tc.set((0,st.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Pl?.(c),t.set("",new Ul(c))}}}var tt,st,Lo,IH,OA,nc,wH,rc,ec,CH,DH,zse,LH,Jse,TA,RA,MH,gA,tc,jse,AA,yH,NH,Pl,Ul,Gf=Re(()=>{tt=require("fs"),st=require("path"),Lo=require("worker_threads"),IH=require("yaml"),OA=x(ee()),nc=x(P());Ab();Nb();Ib();v0();Nx();Mx();wH=x(require("fast-glob")),rc=x(We()),ec=x($());jh();lr();CH=x(se());cn();Ae();Gx();DH=x(ee()),zse=x($x());Df();Xx();bH();LH=x(Er());DE();({readFile:Jse}=tt.promises),TA=OA.get(nc.CONFIG_PARAMS.COMPONENTSROOT),RA=new Map,tc=new Map;a(PH,"loadComponentDirectories");jse={REST:nE,rest:nE,graphqlSchema:Jh,jsResource:Zh,fastifyRoutes:qR,login:tm,static:FR,operationsApi:zse,customFunctions:{},http:{},clustering:tA,authentication:el,mqtt:SA},AA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(AA,"static",{value:{files:"web/**"}});yH=[],NH=new Map;a(Xse,"setErrorReporter");a(VE,"loadComponent");Ul=class extends $t{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var dA=g((BSe,vH)=>{var{isMainThread:UH}=require("worker_threads"),{getTables:Zse}=(Ae(),ie(ke)),{loadComponentDirectories:eie,loadComponent:tie}=(Gf(),ie(Hf)),{resetResources:rie}=(Xu(),ie($U)),nie=gg(),sie=Er(),{dirname:iie}=require("path"),{getConnection:oie}=ut(),aie=ee(),cie=P(),bA=new Map;async function uie(e=!1){!UH&&aie.get(cie.CONFIG_PARAMS.CLUSTERING_ENABLED)&&oie();try{UH&&await nie()}catch(n){console.error(n)}let t=rie();Zse(),t.isWorker=e,await tie(iie(sie.getConfigFilePath()),t,"hdb",!0,bA),await eie(bA,t);let r=[];for(let[n]of bA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(uie,"loadRootComponents");vH.exports.loadRootComponents=uie});var We=g((HSe,Ui)=>{"use strict";var{Worker:lie,MessageChannel:_ie,parentPort:hs,isMainThread:CA,threadId:die,workerData:Ks}=require("worker_threads"),{PACKAGE_ROOT:fie}=P(),{join:GH,isAbsolute:Eie,extname:hie}=require("path"),{server:qH}=(lr(),ie(Hi)),{watch:mie,readdir:pie}=require("fs/promises"),{totalmem:BH}=require("os"),vl=P(),FH=ee(),Ws=$(),{randomBytes:Sie}=require("crypto"),{_assignPackageExport:Tie}=require("../index"),gie=P(),xH=1024*1024,Pi=[],gn=[],Rie=50,DA=1e4,Aie="restart",kH="request_thread_info",VH="resource_report",$H="thread_info",YH="added-port",Oie="ack",yA;Tie("threads",gn);Ui.exports={startWorker:NA,restartWorkers:MA,shutdownWorkers:wie,workers:Pi,setMonitorListener:Bie,onMessageFromWorkers:Cie,onMessageByType:XH,broadcast:Lie,broadcastWithAcknowledgement:Pie,setChildListenerByType:Iie,getWorkerIndex:KH,getWorkerCount:WH,getTicketKeys:zH,setMainIsWorker:yie,setTerminateTimeout:bie,restartNumber:Ks?.restartNumber||1};gn.onMessageByType=XH;gn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=gn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var LA;function bie(e){DA=e}a(bie,"setTerminateTimeout");function KH(){return Ks?Ks.workerIndex:LA?0:void 0}a(KH,"getWorkerIndex");function WH(){return Ks?Ks.workerCount:LA?1:void 0}a(WH,"getWorkerCount");function yie(e){LA=e}a(yie,"setMainIsWorker");var QH=1,$E;function zH(){return $E||($E=CA?Sie(48):Ks.ticketKeys,$E)}a(zH,"getTicketKeys");Object.defineProperty(qH,"workerIndex",{get(){return KH()}});Object.defineProperty(qH,"workerCount",{get(){return WH()}});var JH={[kH](e,t){Uie(t)},[VH](e,t){vie(t,e)}};function NA(e,t={}){let r=process.constrainedMemory?.()||BH();r=Math.min(r,BH(),2e4*xH);let n=FH.get(vl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/xH/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of gn){let _=new _ie;_.existingPort=u,i.push(_),o.push(_.port2)}hie(e)||(e+=".js");let c=new lie(Eie(e)?e:GH(fie,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:QH=t.threadCount,name:t.name,restartNumber:Ui.exports.restartNumber,ticketKeys:zH()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:YH,port:u,threadId:c.threadId},[u]);return KE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>NA(e,t),c.on("error",u=>{Ws.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Pi.splice(Pi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Rie?(t.unexpectedRestarts=c.unexpectedRestarts+1,NA(e,t)):Ws.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{JH[u.type]?.(u,c)}),Pi.push(c),Hie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(NA,"startWorker");var Nie=[vl.THREAD_TYPES.HTTP];async function MA(e=null,t=Math.max(QH>3,1),r=!0){if(CA){if(r){let{loadRootComponents:o}=dA();await o()}Ui.exports.restartNumber++,t<1&&(t=t*Pi.length);let n=[],s=[];for(let o of Pi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ws.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ui.exports.restartNumber,type:vl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Nie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),DA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let E=a(f=>{f.type===gie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ws.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",E))},"startListener");Ws.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=Ju();r&&(e==="http"||!e)&&FH.get(vl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else hs.postMessage({type:Aie,workerType:e})}a(MA,"restartWorkers");function Iie(e,t){JH[e]=t}a(Iie,"setChildListenerByType");function wie(e){return MA(e,1/0,!1)}a(wie,"shutdownWorkers");var jH=[];function Cie(e){jH.push(e)}a(Cie,"onMessageFromWorkers");var IA=new Map;function XH(e,t){let r=IA.get(e);r||IA.set(e,r=[]),r.push(t)}a(XH,"onMessageByType");var Die=10;async function Lie(e){let t=0;for(let r of gn)try{r.postMessage(e),t++>Die&&(t=0,await new Promise(setImmediate))}catch(n){Ws.error("Unable to send message to worker",n)}}a(Lie,"broadcast");var YE=new Map,Mie=1;function Pie(e){return new Promise(t=>{let r=0;for(let n of gn)try{let s=Mie++,i=a(()=>{YE.delete(s),--r===0&&t(),n!==hs&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,YE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of YE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ws.error("Unable to send message to worker",s)}r===0&&t()})}a(Pie,"broadcastWithAcknowledgement");function Uie(e){e.postMessage({type:$H,workers:ZH()})}a(Uie,"sendThreadInfo");function ZH(){let e=Date.now();return Pi.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(ZH,"getChildWorkerInfo");function vie(e,t){e.resources=t,e.resources.updated=Date.now()}a(vie,"recordResourceReport");var wA;function Bie(e){wA=e}a(Bie,"setMonitorListener");var xie=1e3,HH=!1;function Hie(){HH||(HH=!0,setInterval(()=>{for(let e of Pi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}wA&&wA()},xie).unref())}a(Hie,"startMonitoring");var Gie=1e3;if(hs){KE(hs);for(let e=0,t=Ks.addPorts.length;e<t;e++){let r=Ks.addPorts[e];r.threadId=Ks.addThreadIds[e],KE(r)}setInterval(()=>{let e=process.memoryUsage();hs.postMessage({type:VH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Gie).unref(),yA=a(()=>new Promise((e,t)=>{hs.on("message",r),hs.postMessage({type:kH});function r(n){n.type===$H&&(hs.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else yA=ZH;Ui.exports.getThreadInfo=yA;function KE(e,t){gn.push(e),e.on("message",r=>{if(r.type===YH)r.port.threadId=r.threadId,KE(r.port);else if(r.type===Oie){let n=YE.get(r.id);n&&n()}else{for(let s of jH)s(r,e);let n=IA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ws.error(i)}}}).on("close",()=>{gn.splice(gn.indexOf(e),1)}).on("exit",()=>{gn.splice(gn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(KE,"addPort");if(CA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await pie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(GH(s,o.name));try{for await(let{filename:o}of mie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await MA(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");Ui.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else hs.on("message",async e=>{let{type:t}=e;t===vl.ITC_EVENT_TYPES.SHUTDOWN&&(Ui.exports.restartNumber=e.restartNumber,hs.unref(),setTimeout(()=>{Ws.warn("Thread did not voluntarily terminate",die),process.exit(0)},DA).unref())})});var UC={};Fe(UC,{AUDIT_STORE_OPTIONS:()=>Af,createAuditEntry:()=>A_,openAuditStore:()=>JE,readAuditEntry:()=>vt,setAuditRetention:()=>Fie,transactionKeyEncoder:()=>cG});function JE(e){let t=e.auditStore=e.openDB(iG.AUDIT_STORE_NAME,Af);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=WE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-PA})){if((_[0]&15)===BA){let l=vt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=qie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,PA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,zE.getWorkerIndex)()===(0,zE.getWorkerCount)()-1&&s(WE),t}function Fie(e,t=WE){PA=e,WE=t}function A_(e,t,r,n,s,i,o){let c=uG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?sc.setFloat64(0,n):Rn.set(pm),u=9),E(0),E(t),d(r),sc.setFloat64(u,e),u+=8,s?d(s):Rn[u++]=0,Rn[n?8:0]=c;let l=Rn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(f){let h=u;u+=1,u=(0,ic.writeKey)(f,Rn,u);let p=u-h-1;p>127?p>16383?(HA.error("Key or username was too large for audit entry",f),u=h+1,Rn[h]=0):(Rn.copyWithin(h+2,h+1,u),sc.setUint16(h,p|32768),u++):Rn[h]=p}function E(f){f<128?Rn[u++]=f:f<16384?(sc.setUint16(u,f|32768),u+=2):f<1056964608?(sc.setUint32(u,f|3221225472),u+=4):(Rn[u]=255,sc.setUint32(u+1,f),u+=5)}}function vt(e){try{let t=e.dataView||(e.dataView=new xA(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:uG[n&7],tableId:i,get recordId(){return sG(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?sG(e,l,d):void 0},getValue(E,f,h){if(n&UA||n&vA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&vA&&h)return GA(E.getEntry(this.recordId),h,E)}}}catch(t){return HA.error("Reading audit entry error",t,e),{}}}function sG(e,t,r){let n=e.subarray(t,r);return(0,ic.readKey)(n,0,r-t)}var ic,QE,iG,oG,zE,aG,HA,Rn,sc,cG,Af,PA,qie,WE,UA,vA,eG,BA,tG,rG,nG,uG,xA,ri=Re(()=>{ic=require("ordered-binary"),QE=x(ee()),iG=x(ft()),oG=x(P()),zE=x(We()),aG=x(z());Pc();HA=x($());jE();(0,QE.initSync)();Rn=Buffer.alloc(1024),sc=new DataView(Rn.buffer,Rn.byteOffset,1024),cG={writeKey(e,t,r){return e===Mc?(t.set(Mc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,ic.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,ic.readKey)(e,t,r)}},Af={encoding:"binary",keyEncoder:cG},PA=(0,aG.convertToMS)((0,QE.get)(oG.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,qie=1e3,WE=1e4;a(JE,"openAuditStore");a(Fie,"setAuditRetention");UA=16,vA=32,eG=1,BA=2,tG=3,rG=4,nG=5,uG={put:eG|UA,[eG]:"put",delete:BA,[BA]:"delete",message:tG|UA,[tG]:"message",invalidate:rG,[rG]:"invalidate",patch:nG|vA,[nG]:"patch"};a(A_,"createAuditEntry");a(vt,"readAuditEntry");xA=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(sG,"readKeySafely")});var qA={};Fe(qA,{add:()=>XE,applyReverse:()=>lG,getRecordAtTime:()=>GA,rebuildUpdateBefore:()=>ZE});function XE(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function ZE(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,XE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function lG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=kie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=_G}}function GA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=vt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":lG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===_G&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=vt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var kie,_G,jE=Re(()=>{ri();a(XE,"add");XE.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};kie={add:XE};a(ZE,"rebuildUpdateBefore");a(lG,"applyReverse");_G={};a(GA,"getRecordAtTime")});function Zr(e){return e[Nt]||(e[Nt]=Object.create(null))}function sh(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 An.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 An.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new An.ClientError(`${c} must be a number, attempt to assign ${d}`);Zr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new An.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new An.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new An.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 An.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 An.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 An.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 An.ClientError(`${c} must be an object, attempt to assign ${l}`);Zr(this)[c]=l},"set")}_={get(){let l=this[Nt];if(l&&c in l){let E=l[c];if(E?.__op__){let f=this[Ee]?.[c];return E.update(f)}return E}let d=this[Ee]?.[c];if(d&&typeof d=="object"){let E=fG(d,o);if(E)return l||(l=this[Nt]=Object.create(null)),l[c]=E}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Nt];return u?.[o]!==void 0?u[o]:this[Ee]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new An.ClientError("Can not add a property to a sealed table schema");Zr(this)[o]=c}),i("deleteProperty",function(o){Zr(this)[o]=void 0}),i("toJSON",function(){let o=this[Nt],c;for(let _ in o){c||(c=Object.assign({},this[Ee]));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[Ee])),Object.assign(c,this)),c||this[Ee]}),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 fG(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?.[Ee])throw new Error("Can not track an already tracked object, check for circular references");this[Ee]=s}},sh(r,t)),new r(e)):new eh(e);case Array:let n=new rh(e.length);n[Ee]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=fG(o,t?.elements)),n[s]=o}return n;default:return e}}function Sd(e){let t=e[Nt],r;for(let s in t){r||(r=Object.assign({},e[Ee]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=Sd(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[Ee])),Object.assign(r,e)),r||e[Ee]}function Po(e,t=e[Nt]){let r;if(dG.call(e,Ee)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Po(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[Ee]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=qA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Po(s);r[n]=s}return r?Object.freeze(r):dG.call(e,Ee)?e[Ee]:e}function th(e){let t=e[Ee];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?.[Ee]===s){if(th(i))return!0}else return!0}}else{let r=e[Nt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[Ee]===i){if(th(s))return!0}else return!0}else return!0}}return!1}var An,Nt,eh,dG,Mo,rh,nh,Td=Re(()=>{cn();An=x(se());jE();Nt=Symbol("own-data");a(Zr,"getChanges");a(sh,"assignTrackedAccessors");a(fG,"trackObject");eh=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[Ee])throw new Error("Can not track an already tracked object, check for circular references");this[Ee]=t}};sh(eh,{});a(Sd,"collapseData");dG=Object.prototype.hasOwnProperty;a(Po,"deepFreeze");a(th,"hasChanges");Mo=Symbol.for("has-array-changes"),rh=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()}};rh.prototype.constructor=Array;nh=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var kp={};Fe(kp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Me,IS_COLLECTION:()=>kn,MultiPartId:()=>Ga,RECORD_PROPERTY:()=>Ee,Resource:()=>$t,snake_case:()=>$ie,transformForSelect:()=>oh});function $ie(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(Bl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Bl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new Ga;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Bl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function en(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[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 f of s){if(typeof f=="object"&&f)break;c.push(f)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,f)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)}else return Ze(o,()=>{let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)},d);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,u,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,l,o):f.allowUpdate(o.user,l,o):t.type==="create"?f.allowCreate(o.user,l,o):f.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new ih(o.user);return typeof l?.then=="function"?l.then(S=>e(f,u,o,S)):e(f,u,o,l)});if(!h)throw new ih(o.user)}return typeof l?.then=="function"?l.then(h=>e(f,u,o,h)):e(f,u,o,l)}a(E,"authorizeActionOnResource")}}function tn(e,t){let r=new pG.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 FA(e,t,r){let n=e[Ee];if(n){let s=e[Nt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function oh(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):FA(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(FA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(E=>E&&typeof E=="object"?c(E):E);let _={},l=i(FA(u,r,n)),d;for(let E of e){let f=l(E);f===void 0&&o&&(f=null),f?.then?(d||(d=[]),d.push(f.then(h=>_[E.name||E]=h))):_[E.name||E]=f}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=oh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var hG,mG,pG,ye,Me,kn,Ee,Vie,$t,ih,Bl,Ga,cn=Re(()=>{hG=require("crypto");Nc();mG=require("../index"),pG=x(se());Td();no();tE();ye=Symbol.for("context"),Me=Symbol.for("primary-key"),kn=Symbol("is-collection"),Ee=Symbol("stored-record"),Vie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$t=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=en(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=oh(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=en(function(t,r,n,s){if(Array.isArray(s)&&t[kn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):tn(t,"put")},{hasContent:!0,type:"update"});static patch=en(function(t,r,n,s){return t.patch?t.patch(s,r):tn(t,"patch")},{hasContent:!0,type:"update"});static delete=en(function(t,r,n,s){return t.delete?t.delete(r):tn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,hG.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),n||(n={}),Ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):tn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=en(function(t,r,n,s){return t.invalidate?t.invalidate(r):tn(t,"delete")},{hasContent:!1,type:"update"});static post=en(function(t,r,n,s){return t[Me]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=en(function(t,r,n,s){return t.connect?t.connect(s,r):tn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=en(function(t,r,n,s){return t.subscribe?t.subscribe(r):tn(t,"subscribe")},{type:"read"});static publish=en(function(t,r,n,s){return t[Me]!=null&&t.update?.(),t.publish?t.publish(s,r):tn(t,"publish")},{hasContent:!0,type:"create"});static search=en(function(t,r,n,s){let i=t.search?t.search(r):tn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=oh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=en(function(t,r,n,s){return t.search?t.search(s,r):tn(t,"search")},{hasContent:!0,type:"read"});static copy=en(function(t,r,n,s){return t.copy?t.copy(s,r):tn(t,"copy")},{type:"create"});static move=en(function(t,r,n,s){return t.move?t.move(s,r):tn(t,"move")},{type:"delete"});post(t){if(this[kn])return this.constructor.create(this[Me],t,this[ye]);tn(this,"post")}static isCollection(t){return t?.[kn]}static coerceId(t){return t}static parseQuery(t){return eE(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&&Vie[o];if(c)r.requestedContentType=c;else if(n)n.property=o;else return{query:{property:o},id:EG(t,this),isCollection:Bl}}let i=EG(t,this);return Bl?{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],E=_.get(d);E?E.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[kn]=!0),s}subscribe(t){return new Nn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Nn}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]}};$t.prototype[ye]=null;(0,mG._assignPackageExport)("Resource",$t);a($ie,"snake_case");ih=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");Ga=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(en,"transactional");a(tn,"missingMethod");a(FA,"selectFromObject");a(oh,"transformForSelect")});function gG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=TG,Yie(e.primaryStore,e.auditStore)):(c=SG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{RG(SG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Ia(t);let l=new VA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function RG(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=vt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,u,_=Ia(i.recordId),l=0;do{let d=o.get(_);if(d){for(let f of d)if(!(l>0&&!(f.includeDescendants&&!(f.onlyChildren&&l>1)))){if(f.startTime>=n){(0,kA.info)("omitting",c,f.startTime,n);continue}try{let h;f.supportsTransactions&&f.txnInProgress!==i.version&&(h=!0,f.txnInProgress||(r?r.push(f):r=[f]),f.txnInProgress=i.version),f.listener(c,i,n,h)}catch(h){console.error(h),(0,kA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Yie(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u=TG[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),RG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var kA,SG,TG,VA,AG=Re(()=>{kA=x($());Nc();Xu();ri();SG=Object.create(null),TG=Object.create(null);a(gG,"addSubscription");VA=class extends Nn{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(RG,"notifyFromTransactionData");a(Yie,"listenToCommits")});var OR={};Fe(OR,{coerceType:()=>ah,makeTable:()=>lh,setServerUtilities:()=>eoe,updateResource:()=>ch});function lh(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=gm(i,n,u),R=0,N,I,H={},U=Promise.resolve(),k,M,Q;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(M=K),K.expiresAt&&(Q=K),K.isPrimaryKey&&(H=K);let J,j=[],ae=[],ce=1,de=2,Be={},Ne={},xe=864e5,t_,r_,Js,lO=!1,Nh,Ih,Iq=i.getRange({start:!1,end:!1}).constructor,wq=10,Cq=6;h&&fO();class Je extends $t{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),I=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let D=a(L=>{let b=this.sources.slice(0,-1);if(b=b.filter(v=>v[L]&&(!v[L].reliesOnPrototype||v.prototype[L])),b.length>0)if(b.length===1){let v=b[0];return(q,C,G)=>{if(q?.source!==v)return v[L](C,G,q)}}else return(v,q,C)=>{let G=[];for(let B of b){if(v?.source===B)break;G.push(B[L](q,C,v))}return Promise.all(G)}},"getApplyToIntermediateSource"),O=this.sources[this.sources.length-1],y=a(L=>{if(O[L]&&(!O[L].reliesOnPrototype||O.prototype[L]))return(b,v,q)=>{if(!b?.source)return O[L](v,q,b)}},"getApplyToCanonicalSource");return Be={put:y("put"),patch:y("patch"),delete:y("delete"),publish:y("publish")},Ne={put:D("put"),patch:D("patch"),delete:D("delete"),publish:D("publish"),invalidate:D("invalidate")},(async()=>{let L=!1,b=a(async(v,q)=>{let C=v.value,G=v.table?ct[c][v.table]:Je;if(c===$n.SYSTEM_SCHEMA_NAME&&(v.table===$n.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||v.table===$n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),v.id===void 0&&(v.id=C[G.primaryKey],v.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(v));v.source=m;let B=await G.getResource(v.id,q,oc);switch(v.type){case"put":return B._writeUpdate(C,!0,oc);case"patch":return B._writeUpdate(C,!1,oc);case"delete":return B._writeDelete(oc);case"publish":return B._writePublish(C,oc);case"invalidate":return B.invalidate(oc);default:it.error("Unknown operation",v.type,v.id)}},"writeUpdate");try{let v=m.subscribe;v&&p==null&&(p=!0);let q=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,C=v&&q&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let G;for await(let B of C)try{if(!(B.type==="transaction"?B.writes[0]:B)){it.error("Bad subscription event",B);continue}if(B.source=m,G)if(B.beginTxn)G.resolve();else{b(B,G);continue}if(B.type==="end_txn")continue;let le=Ze(B,()=>{if(B.type==="transaction"){let ne=[];for(let Ue of B.writes)try{ne.push(b(Ue,B))}catch(ue){throw ue.message+=" writing "+JSON.stringify(Ue)+" of event "+JSON.stringify(B),ue}return Promise.all(ne)}else if(B.type==="define_schema"){let ne=this.attributes.slice(0),Ue;for(let ue of B.attributes)ne.find(De=>De.name===ue.name)||(ne.push(ue),Ue=!0);Ue&&(Et({table:s,database:c,attributes:ne,origin:"cluster"}),Vl.signalSchemaChange(new $l.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return B.beginTxn?(G=B,b(B,B),new Promise(ne=>{G.resolve=ne})):b(B,B)});L&&(await le,Vl.signalUserChange(new $l.UserEventMsg(process.pid))),B.onCommit&&(le?.then?le.then(B.onCommit):B.onCommit())}catch(Z){it.error("error in subscription handler",Z)}}}catch(v){it.error(v)}})(),this}static getResource(m,A,D){let O=super.getResource(m,A,D);if(m!=null){_c(m);try{if(O.hasOwnProperty(Ee))return O;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let y=!D?.async||i.cache?.get(m),L=bn(A),b=L.getReadTxn();if(b?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return wh(m,A,{transaction:b},y,v=>{if(v?ch(O,v):O[Ee]=null,A.onlyIfCached&&A.noCacheStore){if(!O.doesExist())throw new rn.ServerError("Entry is not cached",504)}else if(D?.ensureLoaded){let q=Ch(m,v,A,O);if(q)return L?.disregardReadTxn(),O[$A]=!0,KA(q,C=>(ch(O,C),O))}return O})}catch(y){throw y.message.includes("Unable to serialize object")&&(y.message+=": "+JSON.stringify(m)),y}}return O}ensureLoaded(){let m=Ch(this[Me],this[Lr],this[ye]);if(m)return this[$A]=!0,KA(m,A=>{this[Lr]=A,this[Ee]=A.value,this[Fl]=A.version})}static setTTLExpiration(m){if(typeof m=="number")E=m*1e3,f||(f=0);else if(m&&typeof m=="object")E=m.expiration*1e3,f=(m.eviction||0)*1e3,xe=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");xe=xe||(E+f)/4,Lh()}static enableAuditing(m=!0){h=m,m&&fO(),Je.audit=m}static coerceId(m){return m===""?null:ah(m,H)}static async dropTable(){if(delete ct[c][s],c===o){for(let m of S)l.remove(Je.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Je.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Vl.signalSchemaChange(new $l.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[kn])return this.search(m);if(this[Me]===null){if(m?.conditions)return this.search(m);let A=Je.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let D=s_(m);if(D?.read){if(D.isSuperUser)return!0;let O=D.attribute_permissions,y=A?.select;if(O?.length>0||lO&&y){if(A||(A={}),y){let L=O?.length>0&&YA(O,"read");A.select=y.map(b=>{let v=b.name||b;if(!L||L[v]){let q=Js[v]?.definition?.tableClass;if(q){if(b.name||(b={name:b}),!q.prototype.allowRead.call(null,m,b))return!1;if(!b.select)return b.name}return b}}).filter(Boolean)}else A.select=O.filter(L=>L.read&&!Js[L.attribute_name]).map(L=>L.attribute_name);return A}else return!0}}allowUpdate(m,A){let D=s_(m);if(D?.update){let O=D.attribute_permissions;if(O?.length>0){let y=YA(O,"update");for(let L in A)if(!y[L])return!1;for(let L of O){let b=L.attribute_name;!L.update&&!(b in A)&&(A[b]=this.getProperty(b))}}return!0}}allowCreate(m,A){if(this[kn]){let D=s_(m);if(D?.insert){let O=D.attribute_permissions;if(O?.length>0){let y=YA(O,"insert");for(let L in A)if(!y[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return s_(m)?.delete}update(m,A){if(!bn(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let O;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[Ee]={},this[Nt]=m):(O=this[Nt],O&&(m=Object.assign(O,m)),this[Nt]=O=m)),this._writeUpdate(this[Nt],A),this}addTo(m,A){if(typeof A=="number"||typeof A=="bigint")this[xl]===bG?this.set(m,(+this.getProperty(m)||0)+A):(this[xl]||this.update(),this.set(m,new nh(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Lr]}invalidate(m){let A=this[ye],D=this[Me];_c(D),bn(this[ye]).addWrite({key:D,store:i,invalidated:!0,entry:this[Lr],nodeName:this[ye]?.nodeName,before:Be.invalidate?.bind(this,A,D),beforeIntermediate:Ne.invalidate?.bind(this,A,D),commit:(y,L)=>{if(L?.version>y)return;let b=null;for(let v in r)b||(b={}),b[v]=this.getProperty(v);T(D,b,this[Lr],y,Hl,h,this[ye],0,"invalidate")}})}static evict(m,A,D){let O=this.Source,y;if(!((I||h)&&(!A||(y=i.getEntry(m),!y||!A)||y.version!==D))){if(I){if(i.hasLock(m,y.version))return;let L;for(let b in r)L||(L={}),L[b]=A[b];if(L)return T(m,L,y,D,Gl,null,null,0,null,!0)}return i.ifVersion(m,D,()=>{n_(m,A,null)}),h?T(m,null,y,D,Gl,null,null,0,null,!0):i.remove(m,D)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,LG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,D){let O=this[ye],y=bn(O),L=this[Me];_c(L);let b=this[Lr];this[xl]=A?bG:jie;let v={key:L,store:i,entry:b,nodeName:O?.nodeName,validate:q=>{m||(m=this[Nt]),A||m&&th(this[Nt]===m?this:m)?O?.source||(y.checkOverloaded(),this.validate(m,!A),M&&(m[M.name]=M.type==="Date"?new Date(q):M.type==="String"?new Date(q).toISOString():q),A&&(t&&m[t]!==L&&(m[t]=L),k&&(b?.value?m[k.name]=b?.value[k.name]:m[k.name]=k.type==="Date"?new Date(q):k.type==="String"?new Date(q).toISOString():q),m=Po(m))):y.removeWrite(v)},before:A?Be.put?()=>Be.put(O,L,m):null:Be.patch?()=>Be.patch(O,L,m):Be.put?()=>Be.put(O,L,Po(this)):null,beforeIntermediate:A?Ne.put?()=>Ne.put(O,L,m):null:Ne.patch?()=>Ne.patch(O,L,m):Ne.put?()=>Ne.put(O,L,Po(this)):null,commit:(q,C,G)=>{if(G){if(O&&C?.version>(O.lastModified||0)&&(O.lastModified=C.version),this[Lr]=C,C?.value?.[Ee])throw new Error("Can not assign a record to a record, check for circular references");A||(this[Ee]=C?.value??null)}this[Nt]=void 0,this[Fl]=q;let B=C?.value,Z=m;if(this[xl]=0,C?.version>=q)if(h){let ue=C.localTime,De=C.version;for(;Z&&(ue>q||De>=q&&ue>0);){let re=u.get(ue);if(!re)break;let X=vt(re);if(De=X.version,De>q){if(X.type==="patch"){let Se=X.getValue(i);Z=ZE(Z,Se)}else if(X.type==="put"||X.type==="delete")return}else if(De===q)return;ue=X.previousLocalTime}}else{if(A)return;Z=ZE(Z,B)}let le;if(A?le=Z:(this[Ee]=B,le=A?Z:Po(this,Z)),this[Ee]=le,le?.[Ee])throw new Error("Can not assign a record to a record, check for circular references");let ne;A||(ne=m),n_(L,B,le);let Ue=A?"put":"patch";T(L,le,C,q,0,h,O,O.expiresAt||(E?E+Date.now():0),Ue,!1,ne)}};y.addWrite(v)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[kn]){for await(let A of this.search(m))(await Je.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[Ee]?this._writeDelete(m):!1}_writeDelete(m){let A=bn(this[ye]),D=this[Me];_c(D);let O=this[ye];return A.addWrite({key:D,store:i,resource:this,nodeName:O?.nodeName,before:Be.delete?.bind(this,O,D),beforeIntermediate:Ne.delete?.bind(this,O,D),commit:(y,L,b)=>{let v=L?.value;b&&(O&&L?.version>(O.lastModified||0)&&(O.lastModified=L.version),ch(this,L)),!(L?.version>y)&&(n_(this[Me],v),it.trace("Write delete entry",D,y),h||p?(T(D,null,this[Lr],y,0,h,this[ye],0,"delete"),h||Lh()):i.remove(this[Me]))}}),!0}search(m){let A=this[ye],D=bn(A);if(!m)throw new Error("No query provided");let O=m.conditions;O?O.length===void 0&&(O=O[Symbol.iterator]?Array.from(O):[O]):O=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Me]&&(O=[{attribute:null,comparator:"prefix",value:this[Me]}].concat(O));let y,L={};function b(X,Se){let He;switch(Se){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');He=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Se)}let Yn=He&&{},js;for(let Ke of X){if(Ke.conditions){Ke.conditions=b(Ke.conditions,Ke.operator);continue}let kt=Ke[0]??Ke.attribute,on=kt==null?H:qs(S,kt);if(on){if(He){let Kn=Hn(kt),Vt=Yn[Kn];Vt?(Vt.push(Ke),js=!0):Yn[Kn]=[Ke]}(on.type||zg[Ke.comparator])&&(Ke[1]===void 0?Ke.value=q(Ke.value,on):Ke[1]=q(Ke[1],on))}else if(kt!=null)throw(0,rn.handleHDBError)(new Error,`${kt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(js)for(let Ke in Yn){let kt=Yn[Ke],on=kt.length;if(on>1)for(let Kn=0;Kn<on;Kn++){let Vt=kt[Kn];if(Vt.comparator==="ge"||Vt.comparator==="greater_than_equal")for(let Xs=0;Xs<on;Xs++){let qo=kt[Xs];(qo.comparator==="le"||qo.comparator==="less_than_equal")&&(Vt.comparator="between",Vt.value=[Vt.value,qo.value],X.splice(X.indexOf(qo),1))}if(Vt.comparator==="equals"||!Vt.comparator){for(let Xs=0;Xs<on;Xs++)if(Xs!==Kn){let qo=kt[Xs];X.splice(X.indexOf(qo),1)}break}}}return X}a(b,"prepareConditions");function v(X,Se){if(m.enforceExecutionOrder)return X;for(let He of X)He.conditions&&(He.conditions=v(He.conditions,He.operator));return X.length>1&&Se!=="or"?(0,DG.sortBy)(X,Zf(Je)):X}a(v,"orderConditions");function q(X,Se){return Array.isArray(X)?X.map(He=>ah(He,Se)):ah(X,Se)}a(q,"coerceTypedValues");let C=m.operator;(O.length>0||C)&&(O=b(O,C));let G=typeof m.sort=="object"&&m.sort,B;if(G&&C!=="or"){let X=G.attribute;if(y=O.find(Se=>Hn(Se.attribute)===Hn(X)),!y){let Se=qs(S,X);if(!Se)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(Se.indexed)y={attribute:X,comparator:"sort"},O.push(y);else if(O.length===0&&!m.allowFullScan)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}y&&(y.descending=!!G.descending)}O=v(O,C),G&&(y&&O[0]===y?G.next&&(B={dbOrderedAttribute:G.attribute,attribute:G.next.attribute,descending:G.next.descending,next:G.next.next}):(y&&O.splice(O.indexOf(y),1),B=G));let Z=m.select;if(O.length===0&&(O=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:O,operator:C,postOrdering:B,selectApplied:!!Z};let le=D.useReadTxn(),ne=Jg(O,C,Je,le,m,A,(X,Se)=>_O(X,Z,A,le,Se),L),Ue=m.ensureLoaded!==!1;B||(ne=re(ne));let ue=Je.transformEntryForSelect(Z,A,le,L,Ue,!0),De=Je.transformToOrderedSelect(ne,Z,B,le,A,ue);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),B&&(De=re(De)),De.onDone=()=>{De.onDone=null,D.doneReadTxn()},De.selectApplied=!0,De.getColumns=()=>{if(Z){let X=[];for(let Se of Z)Se==="*"?X.push(...S.map(He=>He.name)):X.push(Se.name||Se);return X}return S.map(X=>X.name)},De}static transformToOrderedSelect(m,A,D,O,y,L){let b=new Iq;if(D){m=_O(m,A,O,y,null);let v;b.iterate=function(){let C,G=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),B,Z=D.dbOrderedAttribute,le,ne,Ue=!0;function ue(re){let X=re.next&&ue(re.next),Se=re.descending;return(He,Yn)=>{let js=Dh(He,re.attribute,O),Ke=Dh(Yn,re.attribute,O),kt=Se?(0,Bo.compareKeys)(Ke,js):(0,Bo.compareKeys)(js,Ke);return kt===0?X?.(He,Yn)||0:kt}}a(ue,"createComparator");let De=ue(D);return{async next(){let re;if(C)if(re=C.next(),re.done){if(B)return b.onDone&&b.onDone(),re}else return{value:await L.call(this,re.value)};v=[],le&&v.push(le);do if(re=await G.next(),re.done){if(B=!0,v.length)break;return b.onDone&&b.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),Z){let Se=Dh(X,Z,O);if(Ue)Ue=!1,ne=Se;else if(Se!==ne){ne=Se,le=X;break}}v.push(X)}while(!0);return D.isGrouped,v.sort(De),C=v[Symbol.iterator](),re=C.next(),re.done?(b.onDone&&b.onDone(),re):{value:await L.call(this,re.value)}},return(){b.onDone&&b.onDone(),G.return()},throw(){b.onDone&&b.onDone(),G.throw()}}};let q=a(C=>{if(typeof A=="object"&&Array.isArray(C.attribute))for(let G=0;G<A.length;G++){let B=A[G],Z;if(B.name===C.attribute[0]){for(Z=B.sort||(B.sort={});Z.next;)Z=Z.next;Z.attribute=C.attribute.slice(1),Z.descending=C.descending}else B===C.attribute[0]&&(A[G]=Z={name:B,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&q(C.next)},"applySortingOnSelect");q(D)}else b.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),b=b.map(L);return b}static transformEntryForSelect(m,A,D,O,y,L){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(G=>(A?.transaction?.stale&&(A.transaction.stale=!1),G?.key??G),"transform");return m===t?C:m.asArray?G=>[C(G)]:G=>({[t]:C(G)})}let b;y&&I&&!m?.every(C=>{let G;return typeof C=="object"?G=C.name:G=C,r[G]||G===t})&&(b=!0);let v,q=a(function(C){let G;if(A?.transaction?.stale&&(A.transaction.stale=!1),C!=null){if(Nh=C,G=C.value||C.deref?.(),!G&&(C.key===void 0||C.deref)){if(C=wh(C.key??C,A,{transaction:D,lazy:m?.length<4},this.isSync,B=>B),C?.then)return C.then(q.bind(this));G=C?.value}if(b&&(C.metadataFlags&(Hl|Gl)||C.expiresAt&&C.expiresAt<Date.now())){let B=Ch(C.key??C,C,A);if(B?.then)return B.then(q)}}if(G==null)return L?Uo.SKIP:G;if(m&&!(m[0]==="*"&&m.length===1)){let B,Z=a((ne,Ue)=>{let ue;typeof ne=="object"?ue=ne.name:ue=ne;let De=Js?.[ue],re;if(De){let X=O?.[ue];if(X)if(X.hasMappings){let He=De.from?G[De.from]:Hn(C.key);re=X.get(He),re||(re=[])}else re=X.fromRecord?.(G);else re=De(G,A,C);let Se=a(He=>{if(He&&typeof He=="object"){let Yn=De.definition?.tableClass||Je;v||(v={});let js=v[ue]||(v[ue]=Yn.transformEntryForSelect(ue===ne?null:ne.select||(Array.isArray(ne)?ne:null),A,D,X,y));if(Array.isArray(He)){let Ke=[],kt=Yn.transformToOrderedSelect(He,ne.select,typeof ne.sort=="object"&&ne.sort,A,D,js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),on=a(Vt=>{for(;!Vt.done;){if(Vt?.then)return Vt.then(on);Ke.push(Vt.value),Vt=kt.next()}Ue(Ke,ue)},"nextValue"),Kn=on(kt.next());Kn&&(B||(B=[]),B.push(Kn));return}else if(He=js.call(this,He),He?.then){B||(B=[]),B.push(He.then(Ke=>Ue(Ke,ue)));return}}Ue(He,ue)},"handleResolvedValue");re?.then?(B||(B=[]),B.push(re.then(Se))):Se(re);return}else re=G[ue],re&&typeof re=="object"&&ue!==ne&&(re=Je.transformEntryForSelect(ne.select||ne,A,D,null)({value:re}));Ue(re,ue)},"selectAttribute"),le;if(typeof m=="string")Z(m,ne=>{le=ne});else if(Array.isArray(m))if(m.asArray)le=[],m.forEach((ne,Ue)=>{ne==="*"?m[Ue]=G:Z(ne,ue=>le[Ue]=ue)});else{le={};let ne=m.forceNulls;for(let Ue of m)if(Ue==="*")for(let ue in G)le[ue]=G[ue];else Z(Ue,(ue,De)=>{ue===void 0&&ne&&(ue=null),le[De]=ue})}else throw new rn.ClientError("Invalid select"+m);return B?Promise.all(B).then(()=>le):le}return G},"transform");return q}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||Et({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let A=!m.rawEvents,D=[],O=gG(Je,this[Me]??null,function(L,b,v,q){try{let C=b.getValue?.(i,A);if(!C&&b.type==="patch"&&A){let B=i.getEntry(L);B?.version===b.version?C=B.value:C=b.getValue?.(i,!0,v),b.type="put"}let G={id:L,timestamp:v,value:C,version:b.version,type:b.type,beginTxn:q};D?D.push(G):this.send(G)}catch(C){it.error(C)}},m.startTime||0,m),y=(async()=>{this[kn]&&(O.includeDescendants=!0,m.onlyChildren&&(O.onlyChildren=!0)),m.supportsTransactions&&(O.supportsTransactions=!0);let L=this[Me],b=m.previousCount;b>1e3&&(b=1e3);let v=m.startTime;if(this[kn]){if(v){if(b)throw new rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:q,value:C}of u.getRange({start:v,exclusiveStart:!0})){let G=vt(C);if(G.tableId!==n)continue;let B=G.recordId;if(L==null||wG(L,B)){let Z=G.getValue(i,A,q);if(O.send({id:B,timestamp:q,value:Z,version:G.version,type:G.type}),O.queue?.length>NG&&await O.waitForDrain()===!1)return}O.startTime=q}}else if(b){let q=[];for(let{key:C,value:G}of u.getRange({start:"z",end:!1,reverse:!0}))try{let B=vt(G);if(B.tableId!==n)continue;let Z=B.recordId;if(L==null||wG(L,Z)){let le=B.getValue(i,A,C);if(q.push({id:Z,timestamp:C,value:le,version:B.version,type:B.type}),--b<=0)break}}catch(B){it.error("Error getting history entry",C,B)}for(let C=q.length;C>0;)O.send(q[--C]);q[0]&&(O.startTime=q[0].timestamp)}else if(!m.omitCurrent){for(let{key:q,value:C,version:G,localTime:B}of i.getRange({start:L??!1,end:L==null?void 0:[L,Bo.MAXIMUM_KEY],versions:!0}))if(C&&(O.send({id:q,timestamp:B,value:C,version:G,type:"put"}),O.queue?.length>NG&&await O.waitForDrain()===!1))return}}else{b&&!v&&(v=0);let q=this[Lr]?.localTime;if(q===Tm&&(i.cache?.delete(L),this[Lr]=i.getEntry(L),it.trace("re-retrieved record",q,this[Lr]?.localTime),q=this[Lr]?.localTime),it.trace("Subscription from",v,"from",L,q),v<q){let C=[],G=q;do{let B=u.get(G);if(B){m.omitCurrent=!0;let Z=vt(B),le=Z.getValue(i,A,G);A&&(Z.type="put"),C.push({id:L,value:le,timestamp:G,...Z}),G=Z.previousLocalTime}else break;b&&b--}while(G>v&&b!==0);for(let B=C.length;B>0;)O.send(C[--B]);O.startTime=q}!m.omitCurrent&&this.doesExist()&&O.send({id:L,timestamp:q,value:this[Ee],version:this[Fl],type:"put"})}for(let q of D)O.send(q);D=null})();return m.listener&&O.on("data",m.listener),O}doesExist(){return!!(this[Ee]||this[xl])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let D=bn(this[ye]),O=this[Me]||null;_c(O);let y=this[ye];D.addWrite({key:O,store:i,entry:this[Lr],nodeName:y?.nodeName,validate:()=>{y?.source||(D.checkOverloaded(),this.validate(m))},before:Be.publish?.bind(this,y,O,m),beforeIntermediate:Ne.publish?.bind(this,y,O,m),commit:(L,b,v)=>{b===void 0&&p&&!h&&Lh(),T(O,b?.value??null,b,b?.version||L,0,!0,y,b?.expiresAt,"message",!1,m)}})}validate(m,A){let D,O=a((y,L,b)=>{if(L.type&&y!=null)if(A&&y.__op__&&(y=y.value),L.properties){typeof y!="object"&&(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be an object${L.type?" ("+L.type+")":""}`);let v=L.properties;for(let q=0,C=v.length;q<C;q++){let G=v[q],B=O(y[G.name],G,b+"."+G.name);B&&(y[G.name]=B)}if(L.sealed&&y!=null&&typeof y=="object")for(let q in y)v.find(C=>C.name===q)||(D||(D=[])).push(`Property ${q} is not allowed within object in property ${b}`)}else switch(L.type){case"Int":(typeof y!="number"||y>>0!==y)&&(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof y!="number"||!(Math.floor(y)===y&&Math.abs(y)<=9007199254740992))&&(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof y!="number"&&(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a number`);break;case"ID":typeof y=="string"||y?.length>0&&y.every?.(v=>typeof v=="string")||(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a string, or an array of strings`);break;case"String":typeof y!="string"&&(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a string`);break;case"Boolean":typeof y!="boolean"&&(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a boolean`);break;case"Date":if(!(y instanceof Date)){if(typeof y=="string"||typeof y=="number")return new Date(y);(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a Date`)}break;case"BigInt":if(typeof y!="bigint"){if(typeof y=="string"||typeof y=="number")return BigInt(y);(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a bigint`)}break;case"Bytes":y instanceof Uint8Array||(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(y)){if(L.elements)for(let v=0,q=y.length;v<q;v++){let C=y[v],G=O(C,L.elements,b+"[*]");G&&(y[v]=G)}}else(D||(D=[])).push(`Value ${Vn(y)} in property ${b} must be a Buffer or Uint8Array`);break}L.nullable===!1&&y==null&&(D||(D=[])).push(`Property ${b} is required (and not does not allow null values)`)},"validateValue");for(let y=0,L=S.length;y<L;y++){let b=S[y];if(!b.relationship&&(!A||b.name in m)){let v=O(m[b.name],b,b.name);v&&(m[b.name]=v)}}if(d)for(let y in m)S.find(L=>L.name===y)||(D||(D=[])).push(`Property ${y} is not allowed`);if(D)throw new rn.ClientError(D.join(". "))}getUpdatedTime(){return this[Fl]}wasLoadedFromSource(){return I?!!this[$A]:void 0}static async addAttributes(m){let A=S.slice(0);for(let D of m){if(!D.name)throw new rn.ClientError("Attribute name is required");if(D.name.match(/[`/]/))throw new rn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(D)}return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static async removeAttributes(m){let A=S.filter(D=>!m.includes(D.name));return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,D=1e3/2,O=performance.now(),y=Math.floor(A/2),L=m?.exactCount,b=0,v=0,q;for(let{value:C}of i.getRange({start:!0,lazy:!0}))if(C!=null&&b++,v++,!L&&v<y&&performance.now()-O>D){q=v;break}if(q){let C=b;b=0;for(let{value:re}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:q}))re!=null&&b++;let G=q*2,B=(b+C)/G,Z=Math.pow((b-C+1)/q/2,2)+B*(1-B)/G,le=Math.max(Math.sqrt(Z)*A,1),ne=Math.round(B*A),Ue=Math.max(ne-1.96*le,b+C),ue=Math.min(ne+1.96*le,A),De=Math.pow(10,Math.round(Math.log10(le)));return De>ne&&(De=De/10),b=Math.round(ne/De)*De,{recordCount:b,estimatedRange:[Math.round(Ue),Math.round(ue)]}}return{recordCount:b}}static updatedAttributes(){Js=this.propertyResolvers={$id:(m,A,D)=>({value:D.key}),$updatedtime:(m,A,D)=>D.version,$record:(m,A,D)=>D?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),lO=!0,A.to)m.elements?.definition?(Js[m.name]=m.resolve=(D,O,y)=>{let L=D[A.from?A.from:t],b=m.elements.definition.tableClass;return y?Ha({attribute:A.to,value:L},bn(O).getReadTxn(),!1,b,!1).asArray:b.search([{attribute:A.to,value:L}],O).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let D=m.definition||m.elements?.definition;D?(Js[m.name]=m.resolve=(O,y,L)=>{let b=O[A.from];if(b!==void 0){if(m.elements){let v,q=b.map(C=>{let G=L?D.tableClass.primaryStore.getEntry(C,{transaction:bn(y).getReadTxn()}):D.tableClass.get(C,y);return G?.then&&(v=!0),G});return A.filterMissing?v?Promise.all(q).then(C=>C.filter(CG)):q.filter(CG):v?Promise.all(q):q}return L?D.tableClass.primaryStore.getEntry(b,{transaction:bn(y).getReadTxn()}):D.tableClass.get(b,y)}},m.set=(O,y)=>{if(Array.isArray(y)){let L=y.map(b=>b[Me]||b[D.tableClass.primaryKey]);O[A.from]=L}else{let L=y[Me]||y[D.tableClass.primaryKey];O[A.from]=L}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}sh(this,this)}static async deleteHistory(m=0){let A;for(let{key:D,value:O}of u.getRange({start:0,end:m}))await ql(),vt(O).tableId===n&&(A=u.remove(D));await A}static async*getHistory(m=0,A=1/0){for(let{key:D,value:O}of u.getRange({start:m,end:A})){await ql();let y=vt(O);y.tableId===n&&(yield{id:y.recordId,localTime:D,version:y.version,type:y.type,value:y.getValue(i,!0,D),user:y.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let D=i.getEntry(m);if(!D)return A;let O=D.localTime;if(!O)throw new Error("The entry does not have a local audit time");let y=0;do{await ql();let L=u.get(O);if(L){let b=vt(L);A.push({id:b.recordId,localTime:O,version:b.version,type:b.type,value:b.getValue(i,!0,O),user:b.user}),O=b.previousLocalTime}else break}while(y<1e3&&O);return A.reverse()}static cleanup(){J?.remove()}}Je.updatedAttributes();let Dq=Je.prototype;return Dq[Jie]=!0,E&&Je.setTTLExpiration(E/1e3),Q&&Lq(),Je;function n_(K,m,A){let D;for(let O in r){let y=r[O],L=y.isIndexing,b=A?.[O],v=m?.[O];if(b===v&&!L)continue;D=!0;let q=y.indexNulls,C=(0,kl.getIndexedValues)(b,q),G=(0,kl.getIndexedValues)(v,q);if(G?.length>0){let B=new Set(G);if(C=C?C.filter(Z=>{if(B.has(Z))B.delete(Z);else return!0}):[],G=Array.from(B),(G.length>0||C.length>0)&&OG){let Z=G.concat(C).map(le=>({key:le,value:K}));y.prefetch(Z,IG)}for(let Z=0,le=G.length;Z<le;Z++)y.remove(G[Z],K)}else C?.length>0&&OG&&y.prefetch(C.map(B=>({key:B,value:K})),IG);if(C)for(let B=0,Z=C.length;B<Z;B++)y.put(C[B],K)}return D}a(n_,"updateIndices");function _c(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>yG)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,Xie,0)>yG)throw new Error("Primary key size is too large: "+K.length);return!0}a(_c,"checkValidId");function wh(K,m,A,D,O){let y=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return O(null,K);let L=i.getEntry(K,A);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),O(L,K)},"whenPrefetched");return D?y():ce>0?(ce--,y()):new Promise((L,b)=>{ce===0?(ce--,i.prefetch([K],()=>{v(),q()})):(j.push(K),ae.push(q),j.length>Cq&&(ce--,v()));function v(){if(j.length>0){let C=ae;i.prefetch(j,()=>{ce===-1?v():ce++;for(let G of C)G()}),j=[],ae=[],de>2&&de--}else ce=de,de<wq&&de++}a(v,"prefetch");function q(){try{L(y())}catch(C){b(C)}}a(q,"load")})}a(wh,"loadLocalRecord");function s_(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return Zie;let A=m[c],D,O=A?.tables;if(O)return O[s];if(c==="data"&&(D=m[s])&&!D.tables)return D}a(s_,"getTablePermissions");function Ch(K,m,A,D){if(I){let O;if(A.noCache?O=!0:(m?(!m.value||m.metadataFlags&(Hl|Gl)||m.expiresAt&&m.expiresAt<Date.now())&&(O=!0):O=!0,Wr(!O,"cache-hit",s)),O){let y=dO(K,m,A).then(L=>(L?.value?.[Ee]&&it.error("Can not assign a record with a record property"),A&&(L?.version>(A.lastModified||0)&&(A.lastModified=L.version),A.lastRefreshed=Date.now()),L));if(A?.onlyIfCached||m?.value&&D?.allowStaleWhileRevalidate?.(m,K)){if(y.catch(L=>it.warn(L)),A?.onlyIfCached&&!D.doesExist())throw new rn.ServerError("Entry is not cached",504);return}else return y}}}a(Ch,"ensureLoadedFromSource");function bn(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new ro,m.lmdbDb=i,m;m=A}while(!0)}else return new md}a(bn,"txnForContext");function Dh(K,m,A){if(!K)return;Nh=K;let D=K.value||K.deref?.()||(Nh=i.getEntry(K.key))?.value;if(typeof m=="object"){let y=Js,L=D;for(let b=0,v=m.length;b<v;b++){let q=m[b],C=y?.[q];L=C&&L?C(L,A,!0)?.value:L?.[q],y=C?.definition?.tableClass?.propertyResolvers}return L}let O=Js[m];return O?O(D,A):D[m]}a(Dh,"getAttributeValue");function _O(K,m,A,D,O){let y=O?.length,L={transaction:D,lazy:y>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},b;function v(q,C){let G=q?.value;if(!G)return Uo.SKIP;for(let B=0;B<y;B++)if(!b?.includes(B)&&!O[B](G,q))return Uo.SKIP;return C!==void 0&&(q.key=C),q}if(a(v,"processEntry"),y>0||!K.hasEntries){let q=K.map(C=>{if(b=null,typeof C=="object"&&C?.key!==void 0)return y>0?v(C):C;if(C==null)return Uo.SKIP;for(let G=0;G<y;G++){let Z=O[G].idFilter;if(Z){if(!Z(C))return Uo.SKIP;b||(b=[]),b.push(G)}}return wh(C,A,L,!1,v)});return Array.isArray(K)&&(q=q.filter(C=>C!==Uo.SKIP)),q.hasEntries=!0,q}return K}a(_O,"transformToEntries");async function dO(K,m,A){let D=m?.metadataFlags,O=m?.version,y,L;if(!i.attemptLock(K,O,()=>{clearTimeout(L);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Hl|Gl)?y(dO(K,i.getEntry(K),A)):y(C)}))return new Promise(C=>{y=C,L=setTimeout(()=>{i.unlock(K,O)},zie)});let b=m?.value,v={requestContext:A,replacingRecord:b,replacingVersion:O,noCacheStore:!1,source:null,resourceCache:A?.resourceCache},q=A?.responseHeaders;return new Promise((C,G)=>{let B;KA(Ze(v,async Z=>{let le=performance.now(),ne,Ue,ue;try{for(let Se of Je.sources)if(Se.get&&(!Se.get.reliesOnPrototype||Se.prototype.get)&&(v.source=Se,ne=await Se.get(K,v),ne))break;ue=D&Hl;let re=v.lastModified||ue&&O;Ue=ue||re>O||!b,re||(re=(0,kl.getNextMonotonicTime)());let X=performance.now()-le;if(Sr(X,"cache-resolution",s),q&&pg(q,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),Z.timestamp=re,E&&!v.expiresAt&&(v.expiresAt=Date.now()+E),ne){if(typeof ne!="object")throw new Error("Only objects can be cached and stored in tables");typeof ne.toJSON=="function"&&(ne=ne.toJSON()),t&&ne[t]!==K&&(ne[t]=K)}B=!0,C({version:re,value:ne})}catch(re){re.message+=` while resolving record ${K} for ${s}`,b&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(C({version:O,value:b}),it.trace(re.message,"(returned stale record)")):G(re),v.transaction.abort();return}if(A?.noCacheStore||v.noCacheStore){v.transaction.abort();return}bn(v).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==O)return;let Se=n_(K,b,ne);ne?(Ne.put?.(v,K,ne),T(K,ne,X,re,0,h&&Ue||null,v,v.expiresAt,"put",!!ue)):(Ne.delete?.(v,K),h||p?T(K,null,X,re,0,h&&Ue||null,v,0,"delete",!!ue):i.remove(K,O))}})}),()=>{i.unlock(K,O)},Z=>{i.unlock(K,O),B&&it.error("Error committing cache update",Z)})})}a(dO,"getFromSource");function Lh(){if(xe!==t_&&(t_=xe,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(r_&&clearTimeout(r_),!xe)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())/xe)*xe+K.getTime(),A=a(D=>{it.trace(`Scheduled next cleanup scan at ${new Date(D)}ms`),r_=setTimeout(()=>U=U.then(async()=>{if(A(Math.max(D+xe,Date.now())),i.rootStore.status!=="open"){clearTimeout(r_);return}let O=50,y=new Array(O),L=0;it.trace(`Starting cleanup scan for ${s}`);try{let b=0;for(let{key:v,value:q,version:C,expiresAt:G}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let B;q===null&&!h&&C+Qie<Date.now()?B=i.remove(v,C):G&&G+f<Date.now()&&(B=Je.evict(v,q,C),b++),B&&(await y[L],y[L]=B.catch(Z=>{it.error("Cleanup error",Z)}),++L>=O&&(L=0)),await ql()}it.trace(`Finished cleanup scan for ${s}, evicted ${b} entries`)}catch(b){it.trace(`Error in cleanup scan for ${s}:`,b)}}),Math.min(D-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Lh,"scheduleCleanup");function fO(){J=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(fO,"addDeleteRemoval");function Lq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!Ih){Ih=!0;try{let K=Q.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${Q} must be indexed`);for(let A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let D of m.getValues(A)){let O=i.getEntry(D);O?.value?O.value[K]<Date.now()&&Je.evict(D,O.value,O.version):i.ifVersion(D,O?.version,()=>m.remove(A,D))}await ql()}}catch(K){it.error("Error in evicting old records",K)}finally{Ih=!1}}},Wie).unref()}a(Lq,"runRecordExpirationEviction")}function YA(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 IG(){}function eoe(e){LG=e}function ah(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;switch(r){case"Int":case"Long":return e==="null"?null:parseInt(e);case"Float":return e==="null"?null:parseFloat(e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":return isNaN(e)?e==="null"?null:(toe.test(e)||(e+="Z"),new Date(e)):new Date(+e);case void 0:case"Any":return(0,uh.autoCast)(e);default:return e}}function wG(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 ch(e,t){e[Lr]=t,e[Ee]=t?.value??null,e[Fl]=t?.version}function CG(e){return e!=null}function Vn(e){try{return JSON.stringify(e)}catch{return e}}var $n,Uo,kl,DG,Yl,rn,Vl,$l,it,Bo,vo,uh,Kie,LG,Wie,Qie,OG,zie,Fl,Jie,Lr,xl,bG,jie,$A,oc,Hl,Gl,Xie,yG,NG,Zie,ATe,toe,ql,hE=Re(()=>{$n=x(P()),Uo=require("lmdb"),kl=x(vr()),DG=require("lodash");cn();uS();Yl=x(ee());AG();rn=x(se()),Vl=x(ys()),$l=x(Mn());Ae();tE();it=x($());Td();no();Bo=require("ordered-binary"),vo=x(We());ri();uh=x(z());Pc();Cs();jE();Zu();Kie=new Uint8Array(9);Kie[8]=192;Wie=6e4,Qie=864e5;Yl.initSync();OG=Yl.get($n.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),zie=1e4,Fl=Symbol.for("version"),Jie=Symbol.for("incremental-update"),Lr=Symbol("entry"),xl=Symbol("is-saving"),bG=1,jie=2,$A=Symbol("loaded-from-source"),oc={isNotification:!0,ensureLoaded:!1},Hl=1,Gl=8,Xie=Buffer.allocUnsafeSlow(8192),yG=1978,NG=100,Zie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},ATe=(0,uh.convertToMS)(Yl.get($n.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(lh,"makeTable");a(YA,"attributesAsObject");a(IG,"noop");a(eoe,"setServerUtilities");toe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(ah,"coerceType");a(wG,"isDescendantId");ql=a(()=>new Promise(setImmediate),"rest");a(KA,"when");a(ch,"updateResource");a(CG,"exists");a(Vn,"stringify")});var ke={};Fe(ke,{database:()=>ca,databases:()=>ct,dropDatabase:()=>ES,dropTableMeta:()=>ooe,getDatabases:()=>mr,getDefaultCompression:()=>Of,getTables:()=>roe,onUpdatedTable:()=>rA,readMetaDb:()=>Kl,resetDatabases:()=>Yu,table:()=>Et,tables:()=>Br});function roe(){return hh||mr(),Br||{}}function mr(){if(hh)return ct;hh=!0,uc=new Map;let e=(0,St.getHdbBasePath)()&&(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),t=(0,St.get)(Ut.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,nn.existsSync)(e)?e:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,nn.existsSync)(e))for(let r of(0,nn.readdirSync)(e,{withFileTypes:!0})){let n=(0,ot.basename)(r.name,".mdb");r.isFile()&&(0,ot.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Kl((0,ot.join)(e,r.name),null,n)}if((0,nn.existsSync)((0,cc.getBaseSchemaPath)())){for(let r of(0,nn.readdirSync)((0,cc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,ot.join)((0,cc.getBaseSchemaPath)(),r.name),s=(0,ot.join)((0,cc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,nn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,ot.extname)(i.name).toLowerCase()===".mdb"){let o=(0,ot.join)(s,i.name);Kl((0,ot.join)(n,i.name),(0,ot.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,nn.existsSync)(s))for(let o of(0,nn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,ot.extname)(o.name).toLowerCase()===".mdb"&&Kl((0,ot.join)(s,o.name),(0,ot.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,ot.join)(c.path,(0,ot.basename)(o+".mdb"));(0,nn.existsSync)(u)&&Kl(u,o,r,null,!0)}}for(let r in ct){let n=uc.get(r);if(n){let s=ct[r];r.includes("delete")&&On.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(On.trace(`delete table class ${i}`),delete s[i])}else if(delete ct[r],r==="data"){for(let s in Br)delete Br[s];delete Br[mh]}}return uc=null,ct}}function Yu(){hh=!1;for(let[,e]of vi)e.needsDeletion=!0;mr();for(let[e,t]of vi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),vi.delete(e));return ct}function Kl(e,t,r=zA,n,s){let i=new WA.default(e,!1);try{let o=vi.get(e);o?o.needsDeletion=!1:(o=(0,dh.open)(i),vi.set(e,o));let c=new xo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(_h.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,nn.existsSync)(n)&&(i.path=n,_=(0,dh.open)(i),_.isLegacy=!0):_=JE(o));let l=vG(r),d=l[mh],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[p,S]=f.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let T=E.get(p);T||E.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:p,primary:S}=h;if(!S){for(let j of p)if(j.is_hash_attribute||j.isPrimaryKey){S=j;break}if(!S){On.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[f],R={},N=[],I,H,U=typeof S.audit=="boolean"?S.audit:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,M=S.expiration,Q=S.eviction,J=S.sealed;if(T)R=T.indices,N=T.attributes,T.schemaVersion++;else{I=S.tableId,I?I>=(u.get(ac)||0)&&u.putSync(ac,I+1):(S.tableId=I=u.get(ac),I||(I=1),u.putSync(ac,I+1),u.putSync(S.key,S));let j=new xo.default(!S.is_hash_attribute,S.is_hash_attribute);if(j.compression=S.compression,j.compression){let ae=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||UG;j.compression.threshold=ae}H=O_(o.openDB(S.key,j)),H.rootStore=o,H.tableId=I}for(let j of p){j.attribute=j.name;try{if(!j.is_hash_attribute&&(j.indexed||j.attribute&&!j.name)){if(!R[j.name]){let ce=new xo.default(!j.is_hash_attribute,j.is_hash_attribute);R[j.name]=o.openDB(j.key,ce),R[j.name].indexNulls=j.indexNulls}let ae=N.find(ce=>ce.name===j.name);ae?N.splice(N.indexOf(ae),1,j):N.push(j)}}catch(ae){On.error("Error trying to update attribute",j,N,R,ae)}}if(!T){T=BG(l,f,lh({primaryStore:H,auditStore:_,audit:U,sealed:J,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:k,tableName:f,tableId:I,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let j of JA)j(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function vG(e){let t=ct[e];if(t||(e==="data"?t=ct[e]=Br:e==="system"?Object.defineProperty(ct,"system",{value:t=Object.create(null),configurable:!0}):t=ct[e]=Object.create(null)),uc&&!uc.has(e)){let r=new Set;t[mh]=r,uc.set(e,r)}return t}function BG(e,t,r){return e[t]=r,r}function ca({database:e,table:t}){e||(e=zA),mr();let r=vG(e),n=(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),s=(0,St.get)(Ut.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||((0,nn.existsSync)(n)?n:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME));let o=(0,ot.join)(n,(i?t:e)+".mdb"),c=vi.get(o);if(!c){let u=new WA.default(o,!1);c=(0,dh.open)(u),vi.set(o,c)}return c}async function ES(e){if(!ct[e])throw new Error("Schema does not exist");let t=ct[e],r;for(let n in t)r=t[n].primaryStore.rootStore,vi.delete(r.path),r.status==="open"&&(await r.close(),await Wl.remove(r.path));if(r||(r=ca({database:e,table:null}),r.status==="open"&&(await r.close(),await Wl.remove(r.path))),e==="data"){for(let n in Br)delete Br[n];delete Br[mh]}delete ct[e]}function Et({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=zA);let d=ca({database:t,table:e}),E=ct[t],f=E?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let R=new xo.default(!1);for(let M of i)M.attribute&&!M.name?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let N,I;if(f){if(h=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=d.auditStore;M||(M=JE(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=Of(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),On.trace(`${e} table loading, opening primary store`);let Q=new xo.default(!1,!0);Q.compression=p.compression;let J=e+"/",j=O_(d.openDB(J,Q));j.rootStore=d,T=d.dbisDb=d.openDB(_h.INTERNAL_DBIS_NAME,R),j.tableId=T.get(ac),j.tableId||(j.tableId=1),T.putSync(ac,j.tableId+1),p.tableId=j.tableId,f=BG(E,e,lh({primaryStore:j,auditStore:M,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:j.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,N=!0,k(),T.put(J,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(_h.INTERNAL_DBIS_NAME,R)),f.dbisDB=T;let H=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[J,j]=M.toString().split("/");if(j===""&&(j=Q.name),j){if(J!==e)continue}else j=J;if(!i.find(ce=>ce.name===j)?.indexed&&Q.indexed&&!Q.isPrimaryKey){k(),N=!0,T.remove(M);let ce=f.indices[J];ce&&H.push(ce)}}let U=[];try{for(let M of i||[]){if(M.relationship)continue;let Q=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:Q,configurable:!0});let J=T.get(Q);if(M.isPrimaryKey){if(J=J||T.get(Q=e+"/")||{},o!==f.audit||c!==c||(+r||void 0)!==(+J.expiration||void 0)||(+n||void 0)!==(+J.eviction||void 0)){let ae=Object.assign({},J);typeof o=="boolean"&&(o&&f.enableAuditing(o),ae.audit=o),r&&(ae.expiration=+r),n&&(ae.eviction=+n),c!==void 0&&(ae.sealed=c),N=!0,k(),T.put(Q,ae)}continue}J?.attribute&&!J.name&&(J.indexed=!0);let j=!J||J.type!==M.type||J.indexed!==M.indexed||J.nullable!==M.nullable||JSON.stringify(J.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(J.elements)!==JSON.stringify(M.elements);if(M.indexed){let ae=new xo.default(!0,!1),ce=d.openDB(Q,ae);(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Ql.workerData?.restartNumber)&&(N=!0,k(),J=T.get(Q),(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Ql.workerData?.restartNumber)&&(N=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=J?.lastIndexedKey||!1,M.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ce}),U.push(M))),T.put(Q,M)),J?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ce.indexNulls=M.indexNulls,S[M.name]=ce}else j&&(N=!0,k(),T.put(Q,M))}}finally{I&&I()}if(N&&(f.schemaVersion++,f.updatedAttributes()),On.trace(`${e} table loading, running index`),U.length>0||H.length>0?f.indexingOperation=ioe(f,U,H):N&&fh.signalSchemaChange(new Eh.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=l,N)for(let M of JA)M(f,l!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),On.trace(`${e} table loaded`),f;function k(){I||d.transactionSync(()=>({then(M){I=M}}))}a(k,"startTxn")}async function ioe(e,t,r){try{let n=e.schemaVersion;await fh.signalSchemaChange(new Eh.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,p=(0,MG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>u--,E=>{u--,On.error(E)}),Ql.workerData&&Ql.workerData.restartNumber!==PG.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}u>noe?await s:u>soe&&await new Promise(E=>setImmediate(E))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await fh.signalSchemaChange(new Eh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){On.error("Error in indexing",n)}}function ooe({table:e,database:t}){let r=ca({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function rA(e){JA.push(e)}function Of(){let e=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||UG,n={startingOffset:32};return t&&(n.dictionary=Wl.readFileSync(t)),r&&(n.threshold=r),e&&n}var St,_h,dh,ot,nn,cc,xo,WA,Ut,Wl,QA,MG,fh,Eh,Ql,On,PG,zA,mh,UG,Br,ct,ac,JA,hh,vi,uc,noe,soe,Ae=Re(()=>{St=x(ee()),_h=x(ft()),dh=require("lmdb"),ot=require("path"),nn=require("fs"),cc=x(je());hE();xo=x(Uc()),WA=x(vc()),Ut=x(P()),Wl=x(require("fs-extra")),QA=require("../index"),MG=x(vr()),fh=x(ys()),Eh=x(Mn()),Ql=require("worker_threads"),On=x($()),PG=x(We());ri();Pc();zA="data",mh=Symbol("defined-tables"),UG=((0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,St.initSync)();Br=Object.create(null),ct=Object.create(null);(0,QA._assignPackageExport)("databases",ct);(0,QA._assignPackageExport)("tables",Br);ac=Symbol.for("next-table-id"),JA=[],vi=new Map;a(roe,"getTables");a(mr,"getDatabases");a(Yu,"resetDatabases");a(Kl,"readMetaDb");a(vG,"ensureDB");a(BG,"setTable");a(ca,"database");a(ES,"dropDatabase");a(Et,"table");noe=1e3,soe=10;a(ioe,"runIndexing");a(ooe,"dropTableMeta");a(rA,"onUpdatedTable");a(Of,"getDefaultCompression")});var z=g((LTe,JG)=>{"use strict";var Bi=require("path"),FG=require("fs-extra"),Mr=$(),xG=require("fs-extra"),ph=require("os"),aoe=require("net"),coe=require("recursive-iterator"),dt=P(),uoe=KO(),HG=require("papaparse"),Sh=require("moment"),{inspect:loe}=require("util"),GG=require("is-number"),DTe=require("lodash"),_oe=require("minimist"),doe=require("https"),foe=require("http"),{hdb_errors:Th}=se(),Eoe=/^((\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)))$/,kG=require("util").promisify(setTimeout),hoe=100,moe=5,poe="",Soe=4,qG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};JG.exports={isEmpty:sn,isEmptyOrZeroLength:ms,arrayHasEmptyValues:Roe,arrayHasEmptyOrZeroLengthValues:Aoe,buildFolderPath:Ooe,isBoolean:VG,errorizeMessage:Toe,stripFileExtension:yoe,autoCast:Noe,autoCastJSON:$G,autoCastJSONDeep:XA,removeDir:Ioe,compareVersions:woe,isCompatibleDataVersion:Coe,escapeRawValue:Doe,unescapeValue:Loe,stringifyProps:Moe,timeoutPromise:Uoe,isClusterOperation:Boe,getClusterUser:Hoe,checkGlobalSchemaTable:xoe,getHomeDir:KG,getPropsFilePath:Poe,promisifyPapaParse:Goe,removeBOM:WG,createEventPromise:qoe,checkProcessRunning:Foe,checkSchemaTableExist:koe,checkSchemaExists:QG,checkTableExists:zG,getStartOfTomorrowInSeconds:Voe,getLimitKey:$oe,isObject:boe,isNotEmptyAndHasValue:goe,autoCasterIsNumberCheck:YG,backtickASTSchemaItems:Yoe,isPortTaken:voe,createForkArgs:Koe,autoCastBoolean:Woe,async_set_timeout:kG,getTableHashAttribute:Qoe,doesSchemaExist:zoe,doesTableExist:Joe,stringifyObj:joe,ms_to_time:Xoe,changeExtension:Zoe,getEnvCliRootPath:ZA,noBootFile:eae,httpRequest:tae,transformReq:rae,convertToMS:nae,PACKAGE_ROOT:dt.PACKAGE_ROOT};function Toe(e){return e instanceof Error?e:new Error(e)}a(Toe,"errorizeMessage");function sn(e){return e==null}a(sn,"isEmpty");function goe(e){return!sn(e)&&(e||e===0||e===""||VG(e))}a(goe,"isNotEmptyAndHasValue");function ms(e){return sn(e)||e.length===0||e.size===0}a(ms,"isEmptyOrZeroLength");function Roe(e){if(sn(e))return!0;for(let t=0;t<e.length;t++)if(sn(e[t]))return!0;return!1}a(Roe,"arrayHasEmptyValues");function Aoe(e){if(ms(e))return!0;for(let t=0;t<e.length;t++)if(ms(e[t]))return!0;return!1}a(Aoe,"arrayHasEmptyOrZeroLengthValues");function Ooe(...e){try{return e.join(Bi.sep)}catch{console.error(e)}}a(Ooe,"buildFolderPath");function VG(e){return sn(e)?!1:e===!0||e===!1}a(VG,"isBoolean");function boe(e){return sn(e)?!1:typeof e=="object"}a(boe,"isObject");function yoe(e){return ms(e)?poe:e.slice(0,-Soe)}a(yoe,"stripFileExtension");function Noe(e){return sn(e)||e===""||typeof e!="string"?e:qG[e]!==void 0?qG[e]:YG(e)===!0?Number(e):Eoe.test(e)?new Date(e):e}a(Noe,"autoCast");function $G(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a($G,"autoCastJSON");function XA(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=XA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=XA(r);n!==r&&(e[t]=n)}return e}else return $G(e)}a(XA,"autoCastJSONDeep");function YG(e){if(e.startsWith("0.")&&GG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&GG(e))}a(YG,"autoCasterIsNumberCheck");async function Ioe(e){if(ms(e))throw new Error(`Directory path: ${e} does not exist`);try{await xG.emptyDir(e),await xG.remove(e)}catch(t){throw Mr.error(`Error removing files in ${e} -- ${t}`),t}}a(Ioe,"removeDir");function woe(e,t){if(ms(e)){Mr.info("Invalid current version sent as parameter.");return}if(ms(t)){Mr.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(woe,"compareVersions");function Coe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Coe,"isCompatibleDataVersion");function Doe(e){if(sn(e))return e;let t=String(e);return t==="."?dt.UNICODE_PERIOD:t===".."?dt.UNICODE_PERIOD+dt.UNICODE_PERIOD:t.replace(dt.FORWARD_SLASH_REGEX,dt.UNICODE_FORWARD_SLASH)}a(Doe,"escapeRawValue");function Loe(e){if(sn(e))return e;let t=String(e);return t===dt.UNICODE_PERIOD?".":t===dt.UNICODE_PERIOD+dt.UNICODE_PERIOD?"..":String(e).replace(dt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Loe,"unescapeValue");function Moe(e,t){if(sn(e))return Mr.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+ph.EOL}!ms(n)&&n[0]===";"?r+=" "+n+s+ph.EOL:ms(n)||(r+=n+"="+s+ph.EOL)}catch{Mr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Moe,"stringifyProps");function KG(){let e;try{e=ph.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(KG,"getHomeDir");function Poe(){let e=Bi.join(KG(),dt.HDB_HOME_DIR_NAME,dt.BOOT_PROPS_FILE_NAME);return FG.existsSync(e)||(e=Bi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Poe,"getPropsFilePath");function Uoe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Uoe,"timeoutPromise");async function voe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=aoe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(voe,"isPortTaken");function Boe(e){try{return dt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Boe,"isClusterOperation");function xoe(e,t){let r=(Ae(),ie(ke)).getDatabases();if(!r[e])return Th.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return Th.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(xoe,"checkGlobalSchemaTable");function Hoe(e,t){if(sn(t)){Mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(sn(e)||ms(e)){Mr.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Mr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Hoe,"getClusterUser");function Goe(){HG.parsePromise=function(e,t,r){return new Promise(function(n,s){HG.parse(e,{header:!0,transformHeader:WG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Goe,"promisifyPapaParse");function WG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(WG,"removeBOM");function qoe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Mr.info(`Got cluster status event response: ${loe(s)}`);try{i.cancel()}catch{Mr.error("Error trying to cancel timeout.")}n(s)})})}a(qoe,"createEventPromise");async function Foe(e){let t=!0,r=0;do await kG(hoe*r++),(await uoe.findPs(e)).length>0&&(t=!1);while(t&&r<moe);if(t)throw new Error(`process ${e} was not started`)}a(Foe,"checkProcessRunning");function koe(e,t){let r=QG(e);if(r)return r;let n=zG(e,t);if(n)return n}a(koe,"checkSchemaTableExist");function QG(e){let{getDatabases:t}=(Ae(),ie(ke));if(!t()[e])return Th.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(QG,"checkSchemaExists");function zG(e,t){let{getDatabases:r}=(Ae(),ie(ke));if(!r()[e][t])return Th.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(zG,"checkTableExists");function Voe(){let e=Sh().utc().add(1,dt.MOMENT_DAYS_TAG).startOf(dt.MOMENT_DAYS_TAG).unix(),t=Sh().utc().unix();return e-t}a(Voe,"getStartOfTomorrowInSeconds");function $oe(){return Sh().utc().format("DD-MM-YYYY")}a($oe,"getLimitKey");function Yoe(e){try{let t=new coe(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){Mr.error("Got an error back ticking items."),Mr.error(t)}}a(Yoe,"backtickASTSchemaItems");function Koe(e){return[e]}a(Koe,"createForkArgs");function Woe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Woe,"autoCastBoolean");function Qoe(e,t){let{getDatabases:r}=(Ae(),ie(ke)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Qoe,"getTableHashAttribute");function zoe(e){let{getDatabases:t}=(Ae(),ie(ke));return t()[e]!==void 0}a(zoe,"doesSchemaExist");function Joe(e,t){let{getDatabases:r}=(Ae(),ie(ke));return r()[e]?.[t]!==void 0}a(Joe,"doesTableExist");function joe(e){try{return JSON.stringify(e)}catch{return e}}a(joe,"stringifyObj");function Xoe(e){let t=Sh.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(Xoe,"ms_to_time");function Zoe(e,t){let r=Bi.basename(e,Bi.extname(e));return Bi.join(Bi.dirname(e),r+t)}a(Zoe,"changeExtension");function ZA(){if(process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=_oe(process.argv);if(e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(ZA,"getEnvCliRootPath");var jA;function eae(){if(jA)return jA;let e=ZA();if(ZA()&&FG.pathExistsSync(Bi.join(e,dt.HDB_CONFIG_FILE)))return jA=!0,!0}a(eae,"noBootFile");function tae(e,t){let r;return e.protocol==="http:"?r=foe:r=doe,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(tae,"httpRequest");function rae(e){if(!e.schema&&!e.database){e.schema=dt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(rae,"transformReq");function nae(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(nae,"convertToMS")});var ee=g((PTe,tq)=>{"use strict";var eO=require("fs-extra"),Ho=require("path"),jG=require("os"),sae=require("properties-reader"),Jl=$(),zl=z(),_e=P(),gh=Er(),iae="Error initializing environment manager",Rh="BOOT_PROPS_FILE_PATH",XG=!1,oae={[_e.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Qs={};tq.exports={BOOT_PROPS_FILE_PATH:Rh,getHdbBasePath:aae,setHdbBasePath:cae,get:ZG,initSync:lae,setProperty:Pe,initTestEnvironment:dae,setCloneVar:_ae};function aae(){return Qs[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(aae,"getHdbBasePath");function cae(e){Qs[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(cae,"setHdbBasePath");function ZG(e){let t=gh.getConfigValue(e);return t===void 0?Qs[e]:t}a(ZG,"get");function Pe(e,t){oae[e]&&(Qs[e]=t),gh.updateConfigObject(e,t)}a(Pe,"setProperty");function uae(){let e;try{e=zl.getPropsFilePath(),eO.accessSync(e,eO.constants.F_OK|eO.constants.R_OK),XG=!0;let t=sae(e);return Qs[_e.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(_e.HDB_SETTINGS_NAMES.INSTALL_USER),Qs[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Qs[Rh]=e,!0}catch{return Jl.trace(`Environment manager found no properties file at ${e}`),!1}}a(uae,"doesPropFileExist");function lae(e=!1){try{(XG||uae()||zl.noBootFile())&&!eq&&(gh.initConfig(e),Qs[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=gh.getConfigValue(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Jl.error(iae),Jl.error(t),console.error(t),process.exit(1)}}a(lae,"initSync");var eq=!1;function _ae(e){eq=e}a(_ae,"setCloneVar");function dae(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Ho.join(__dirname,"../../","unitTests");Qs[Rh]=Ho.join(u,"hdb_boot_properties.file"),Pe(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Ho.join(u,"settings.test")),Pe(_e.HDB_SETTINGS_NAMES.INSTALL_USER,jG.userInfo()?jG.userInfo().username:void 0),Pe(_e.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Pe(_e.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Ho.join(u,"envDir","log")),Pe(_e.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Pe(_e.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Pe(_e.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Pe(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Ho.join(u,"envDir")),Pe(_e.CONFIG_PARAMS.STORAGE_PATH,Ho.join(u,"envDir")),s&&(Pe(_e.CONFIG_PARAMS.HTTP_SECUREPORT,ZG(_e.CONFIG_PARAMS.HTTP_PORT)),Pe(_e.CONFIG_PARAMS.HTTP_PORT,null)),Pe(_e.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Pe(_e.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Pe(_e.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,zl.isEmpty(i)?!1:i),Pe(_e.CONFIG_PARAMS.HTTP_CORS,zl.isEmpty(i)?!1:i),Pe(_e.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Pe(_e.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Pe(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Pe(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Pe(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Ho.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Pe(_e.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,zl.isEmpty(c)?!1:c),o&&(Pe("CORS_ACCESSLIST",o),Pe(_e.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Pe(_e.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Pe(_e.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Pe(_e.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Pe(_e.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Pe(_e.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Pe(_e.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Rh}. Please check your boot props and settings files`;Jl.fatal(r),Jl.error(t)}}a(dae,"initTestEnvironment")});var oq=g((vTe,iq)=>{"use strict";var sq=require("joi"),{string:jl,boolean:rq,array:fae}=sq.types(),nq=P(),Eae=Xe();iq.exports=hae;function hae(e){let t=sq.object({operation:jl.valid(nq.OPERATIONS_ENUM.ADD_NODE,nq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:jl.required(),subscriptions:fae.items({schema:jl.required(),table:jl.optional(),hash_attribute:jl.optional(),subscribe:rq.required(),publish:rq.required()}).min(1).required()});return Eae.validateBySchema(e,t)}a(hae,"updateRemoteSourceValidator")});var Xl=g((xTe,aq)=>{"use strict";var tO=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};aq.exports=tO});var _q=g((GTe,lq)=>{"use strict";var mae=oq(),zs=$(),rO=Ve(),pae=P(),nO=fn(),Go=ut(),cq=Ou(),Sae=fd(),{Node:Tae,NodeSubscription:uq}=Si(),sO=Xl(),iO=z(),gae=ee(),{cloneDeep:Rae}=require("lodash"),{broadcast:Aae}=We();lq.exports=Oae;async function Oae(e){try{let t=mae(e);if(t)return zs.error(`Validation error in updateRemoteSource: ${t.message}`),new sO(rO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=Rae(await nO.getNodeRecord(n)),c=!iO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&zs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],E=d.schema,f=d.table;if(!iO.doesSchemaExist(E)){zs.trace(`updateRemoteSource creating schema: ${E}`);try{await cq.createSchema({operation:"create_schema",schema:E})}catch(h){zs.error(h)}}if(f&&!iO.doesTableExist(E,f)){let h=new Sae(E,f,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),zs.trace(`updateRemoteSource creating table: ${f} in schema: ${E} with attributes: ${JSON.stringify(d.attributes)}`);try{await cq.createTable(h)}catch(p){zs.error(p)}}if(zs.trace(`Creating local stream for ${E}.${f}`),await Go.createLocalTableStream(E,f),c?(await Go.updateConsumerIterator(E,f,n,"stop"),await Go.updateRemoteConsumer(d,n),d.subscribe===!0&&await Go.updateConsumerIterator(E,f,n,"start")):(await Go.updateRemoteConsumer(d,n),d.subscribe===!0?await Go.updateConsumerIterator(E,f,n,"start"):await Go.updateConsumerIterator(E,f,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===E&&T.table===f){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new uq(E,f,d.publish,d.subscribe))}else i.push(new uq(E,f,d.publish,d.subscribe))}c||(o=new Tae(n,i,void 0),zs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await nO.upsertNodeRecord(u),Aae({type:"nats_update"}),new sO(rO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${gae.get(pae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await nO.getSystemInfo())}catch(t){zs.error(t);let r=t.message?t.message:t;return new sO(rO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Oae,"updateRemoteSource")});var hq=g((FTe,Eq)=>{"use strict";var fq=require("joi"),{string:dq}=fq.types(),bae=P(),yae=Xe();Eq.exports=Nae;function Nae(e){let t=fq.object({operation:dq.valid(bae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:dq.required()});return yae.validateBySchema(e,t)}a(Nae,"removeRemoteSourceValidator")});var Sq=g((VTe,pq)=>{"use strict";var Iae=hq(),Ah=$(),Oh=Ve(),oO=P(),wae=fn(),Cae=z(),mq=ut(),Dae=ee(),bh=Xl(),{NodeSubscription:Lae}=Si(),Mae=oa(),Pae=ai(),{broadcast:Uae}=We(),vae=Dae.get(oO.CONFIG_PARAMS.CLUSTERING_NODENAME);pq.exports=Bae;async function Bae(e){try{let t=Iae(e);if(t)return Ah.error(`Validation error in removeRemoteSource: ${t.message}`),new bh(Oh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await wae.getNodeRecord(r);if(Cae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return Ah.error(i),new bh(Oh.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];Ah.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Lae(c.schema,c.table,!1,!1);await mq.updateConsumerIterator(c.schema,c.table,r,"stop"),await mq.updateRemoteConsumer(u,r)}let s=new Mae(oO.SYSTEM_SCHEMA_NAME,oO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Pae.deleteRecord(s),Uae({type:"nats_update"}),new bh(Oh.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${vae} successfully removed node '${r}'.`)}catch(t){Ah.error(t);let r=t.message?t.message:t;return new bh(Oh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Bae,"removeRemoteSource")});var Aq=g((YTe,Rq)=>{"use strict";var yh=$(),Zl=P(),Tq=Ve(),aO=ee(),xae=z(),gq=Xl(),Hae=fn(),Gae=$d(),qae=qr();Rq.exports=Fae;async function Fae(e){try{yh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=xae.ms_to_time(t),n=new kae(aO.get(Zl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),aO.get(Zl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??aO.get(Zl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Hae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new Gae(Zl.SYSTEM_SCHEMA_NAME,Zl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await qae.update(i)}catch(s){yh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return yh.trace("getRemoteSourceConfig response:",n),new gq(Tq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){yh.error(t);let r=t.message?t.message:t;return new gq(Tq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Fae,"getRemoteSourceConfig");function kae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(kae,"ConfigResponseObject")});var Nq=g((WTe,yq)=>{"use strict";var Oq=ee();Oq.initSync();var bq=ut(),e_=$(),lc=P(),cO=Ve(),Vae=_q(),$ae=Sq(),Yae=Aq(),Kae=Xl(),{encode:Wae,decode:Qae}=require("msgpackr"),zae=bs(),Jae=Os(),jae=require("util"),Xae=P(),{isMainThread:Zae,parentPort:ece}=require("worker_threads");We();var tce=jae.promisify(zae.setSchemaDataToGlobal),uO=Oq.get(lc.CONFIG_PARAMS.CLUSTERING_NODENAME);yq.exports=rce;async function rce(){try{e_.notify("Starting reply service."),await tce();let e=await bq.getConnection(),t=`${uO}.__request__`,r=e.subscribe(t,{queue:uO});await nce(r)}catch(e){e_.error(e)}}a(rce,"initialize");async function nce(e){for await(let t of e){let r=Qae(t.data),n;switch(r.operation){case lc.OPERATIONS_ENUM.ADD_NODE:case lc.OPERATIONS_ENUM.UPDATE_NODE:n=await Vae(r);break;case lc.OPERATIONS_ENUM.REMOVE_NODE:n=await $ae(r);break;case lc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Yae(r);break;case lc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await sce();break;default:let s=`node '${uO}' reply service received unrecognized request operation`;e_.error(s),n=new Kae(cO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}e_.trace(n),t.respond(Wae(n))}}a(nce,"handleRequest");async function sce(){try{return{status:cO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Jae.describeAll()}}catch(e){return e_.error(e),{status:cO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(sce,"getRemoteDescribeAll");Zae||ece.on("message",async e=>{let{type:t}=e;t===Xae.ITC_EVENT_TYPES.SHUTDOWN&&bq.closeConnection()})});var ice=Nq();(async()=>{try{await ice()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|