harperdb 4.7.0-beta.6 → 4.7.0-beta.7

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.
@@ -1,4 +1,4 @@
1
- "use strict";var a6=Object.create;var hm=Object.defineProperty;var c6=Object.getOwnPropertyDescriptor;var l6=Object.getOwnPropertyNames;var u6=Object.getPrototypeOf,d6=Object.prototype.hasOwnProperty;var a=(e,t)=>hm(e,"name",{value:t,configurable:!0});var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var M=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ye=(e,t)=>{for(var r in t)hm(e,r,{get:t[r],enumerable:!0})},NM=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of l6(t))!d6.call(e,s)&&s!==r&&hm(e,s,{get:()=>t[s],enumerable:!(n=c6(t,s))||n.enumerable});return e};var b=(e,t,r)=>(r=e!=null?a6(u6(e)):{},NM(t||!e||!e.__esModule?hm(r,"default",{value:e,enumerable:!0}):r,e)),v=e=>NM(hm({},"__esModule",{value:!0}),e);var yt=M((GNe,PM)=>{var{join:f6,dirname:CM}=require("node:path"),{existsSync:m6,readFileSync:p6}=require("node:fs");function h6(){let t=__dirname,r,n=0;for(;!m6(r=f6(t,"package.json"));)if(t===(t=CM(t))||n++>10)throw new Error("Could not find package root");return r}a(h6,"findPackageJson");var OM=h6(),E6=JSON.parse(p6(OM,"utf8")),_6=CM(OM);PM.exports={packageJson:E6,PACKAGE_ROOT:_6}});var z={};ye(z,{AUTH_AUDIT_STATUS:()=>ai,AUTH_AUDIT_TYPES:()=>Fa,BOOT_PROPS_FILE_NAME:()=>H6,BOOT_PROP_PARAMS:()=>vM,CLUSTERING_FLAG:()=>Fb,CLUSTERING_PROCESSES:()=>N6,CLUSTER_MESSAGE_TYPE_ENUM:()=>Bb,CLUSTER_OPERATIONS:()=>r5,CONFIG_PARAMS:()=>F,CONFIG_PARAM_MAP:()=>MM,DATABASES_DIR_NAME:()=>jc,DATABASES_PARAM_CONFIG:()=>o5,DEFAULT_DATABASE_NAME:()=>O6,ESCAPED_FORWARD_SLASH_REGEX:()=>F6,FORWARD_SLASH_REGEX:()=>x6,FUNC_VAL:()=>_5,GEO_CONVERSION_ENUM:()=>s5,HDB_COMPONENT_CONFIG_FILE:()=>T6,HDB_CONFIG_FILE:()=>g6,HDB_DEFAULT_CONFIG_FILE:()=>S6,HDB_FILE_PERMISSIONS:()=>q6,HDB_HOME_DIR_NAME:()=>k6,HDB_PID_FILE:()=>C6,HDB_PROCESS_SERVICES:()=>w6,HDB_PROC_NAME:()=>y6,HDB_RESTART_SCRIPT:()=>R6,HDB_ROOT_DIR_NAME:()=>vb,HDB_SETTINGS_NAMES:()=>gm,HDB_SUPPORT_ADDRESS:()=>DM,INFO_TABLE_HASH_ATTRIBUTE:()=>z6,INSERT_MAX_CHARACTER_SIZE:()=>Y6,INSTALL_PROMPTS:()=>K6,ITC_EVENT_TYPES:()=>f_,JOB_STATUS_ENUM:()=>X6,JOB_TYPE_ENUM:()=>a5,JWT_ENUM:()=>Sm,LAUNCH_SERVICE_SCRIPTS:()=>L6,LEGACY_CONFIG_PARAMS:()=>i5,LEGACY_DATABASES_DIR_NAME:()=>l_,LICENSE_FILE_NAME:()=>J6,LICENSE_KEY_DIR_NAME:()=>xb,LICENSE_VALUES:()=>c5,LOG_LEVELS:()=>Em,LOG_NAMES:()=>P6,METADATA_PROPERTY:()=>d5,NODE_ERROR_CODES:()=>u5,OPERATIONS_ENUM:()=>V,PERMS_CRUD_ENUM:()=>h5,PERMS_UPDATE_RELEASE_TIMESTAMP:()=>p5,PRE_4_0_0_VERSION:()=>g5,PROCESS_DESCRIPTORS:()=>I6,PROCESS_NAME_ENV_PROP:()=>V6,RAM_ALLOCATION_ENUM:()=>l5,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:()=>d_,REG_KEY_FILE_NAME:()=>Q6,RESTART_TIMEOUT_MS:()=>G6,ROLE_TYPES_ENUM:()=>D6,S3_BUCKET_AUTH_KEYS:()=>e5,SEARCH_NOT_FOUND_MESSAGE:()=>M6,SEARCH_WILDCARDS:()=>E5,SERVICE_ACTIONS_ENUM:()=>n5,SUPPORT_HELP_MSG:()=>v6,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:()=>j6,SYSTEM_SCHEMA_NAME:()=>_m,SYSTEM_TABLE_NAMES:()=>Du,THREAD_TYPES:()=>Hb,TIME_STAMP_NAMES:()=>m5,TIME_STAMP_NAMES_ENUM:()=>f5,TRANSACTIONS_DIR_NAME:()=>$6,UNICODE_FORWARD_SLASH:()=>B6,UNICODE_PERIOD:()=>U6,UPGRADE_JSON_FIELD_NAMES_ENUM:()=>W6,VALID_S3_FILE_TYPES:()=>Z6,VALID_SQL_OPS_ENUM:()=>t5,VALUE_SEARCH_COMPARATORS:()=>u_,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:()=>kb});var a_,c_,g6,S6,vb,T6,y6,R6,LM,Db,Mb,Ub,b6,A6,I6,w6,N6,C6,O6,P6,Em,L6,D6,DM,v6,M6,U6,x6,B6,F6,_m,k6,xb,H6,G6,q6,jc,l_,$6,V6,vM,K6,Y6,W6,Du,z6,j6,Q6,J6,X6,V,Z6,e5,t5,r5,n5,s5,gm,i5,F,MM,o5,a5,Bb,c5,l5,u5,d5,Fb,UM,xM,f5,m5,p5,u_,kb,h5,E5,_5,d_,Sm,f_,Hb,g5,ai,Fa,H=se(()=>{a_=require("node:path"),c_=b(yt()),g6="harperdb-config.yaml",S6="defaultConfig.yaml",vb="hdb",T6="config.yaml",y6="harperdb.js",R6="restartHdb.js",LM="HarperDB",Db="Custom Functions",Mb="Clustering Hub",Ub="Clustering Leaf",b6="Clustering Ingest Service",A6="Clustering Reply Service",I6={HDB:LM,CLUSTERING_HUB:Mb,CLUSTERING_LEAF:Ub,CLUSTERING_INGEST_SERVICE:b6,CLUSTERING_REPLY_SERVICE:A6,CUSTOM_FUNCTIONS:Db,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"},w6={harperdb:LM,"clustering hub":Mb,"clustering leaf":Ub,"custom functions":Db,custom_functions:Db,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers",http:"http"},N6={CLUSTERING_HUB_PROC_DESCRIPTOR:Mb,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ub},C6="hdb.pid",O6="data",P6={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Em={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},L6={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:(0,a_.join)(c_.PACKAGE_ROOT,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:(0,a_.join)(c_.PACKAGE_ROOT,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:(0,a_.join)(c_.PACKAGE_ROOT,"launchServiceScripts/launchUpdateNodes4-0-0.js")},D6={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},DM="support@harperdb.io",v6=`For support, please submit a request at https://harperdbhelp.zendesk.com/hc/en-us/requests/new or contact ${DM}`,M6="None of the specified records were found.",U6="U+002E",x6=/\//g,B6="U+002F",F6=/U\+002F/g,_m="system",k6=".harperdb",xb="keys",H6="hdb_boot_properties.file",G6=6e4,q6=448,jc="database",l_="schema",$6="transactions",V6="PROCESS_NAME",vM={SETTINGS_PATH_KEY:"settings_path"},K6={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",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",DEFAULTS_MODE:"DEFAULTS_MODE",REPLICATION_HOSTNAME:"REPLICATION_HOSTNAME",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},Y6=250,W6={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},Du={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"},z6="info_id",j6={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"},Q6="060493.ks",J6=".license",X6={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},V={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",DESCRIBE_METRIC:"describe_metric",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_REGISTRATION_INFO:"registration_info",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",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",CLEANUP_ORPHAN_BLOBS:"cleanup_orphan_blobs",SIGN_CERTIFICATE:"sign_certificate",CREATE_CSR:"create_csr",LIST_CERTIFICATES:"list_certificates",ADD_CERTIFICATES:"add_certificate",REMOVE_CERTIFICATE:"remove_certificate",ADD_NODE_BACK:"add_node_back",REMOVE_NODE_BACK:"remove_node_back",ADD_SSH_KEY:"add_ssh_key",UPDATE_SSH_KEY:"update_ssh_key",DELETE_SSH_KEY:"delete_ssh_key",LIST_SSH_KEYS:"list_ssh_keys",SET_SSH_KNOWN_HOSTS:"set_ssh_known_hosts",GET_SSH_KNOWN_HOSTS:"get_ssh_known_hosts",GET_KEY:"get_key",GET_ANALYTICS:"get_analytics",LIST_METRICS:"list_metrics",GET_STATUS:"get_status",SET_STATUS:"set_status",CLEAR_STATUS:"clear_status",INSTALL_USAGE_LICENSE:"install_usage_license",GET_USAGE_LICENSES:"get_usage_licenses"},Z6={CSV:".csv",JSON:".json"},e5={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},t5={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},r5={[V.INSERT]:V.INSERT,[V.UPDATE]:V.UPDATE,[V.UPSERT]:V.UPSERT,[V.DELETE]:V.DELETE},n5={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},s5={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},gm={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"},i5={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"},F={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",ANALYTICS_REPLICATE:"analytics_replicate",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_COOKIE_DOMAINS:"authentication_cookie_domains",AUTHENTICATION_COOKIE_EXPIRES:"authentication_cookie_expires",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",AUTHENTICATION_HASHFUNCTION:"authentication_hashFunction",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_CORSACCESSCONTROLALLOWHEADERS:"http_corsAccessControlAllowHeaders",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_MAXPARAMLENGTH:"http_maxParamLength",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_MTLS_CERTIFICATEVERIFICATION:"http_mtls_certificateVerification",HTTP_MTLS_CERTIFICATEVERIFICATION_FAILUREMODE:"http_mtls_certificateVerification_failureMode",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL:"http_mtls_certificateVerification_crl",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_TIMEOUT:"http_mtls_certificateVerification_crl_timeout",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_CACHETTL:"http_mtls_certificateVerification_crl_cacheTtl",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_FAILUREMODE:"http_mtls_certificateVerification_crl_failureMode",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_GRACEPERIOD:"http_mtls_certificateVerification_crl_gracePeriod",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP:"http_mtls_certificateVerification_ocsp",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_TIMEOUT:"http_mtls_certificateVerification_ocsp_timeout",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_CACHETTL:"http_mtls_certificateVerification_ocsp_cacheTtl",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_ERRORCACHETTL:"http_mtls_certificateVerification_ocsp_errorCacheTtl",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_FAILUREMODE:"http_mtls_certificateVerification_ocsp_failureMode",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",HTTP_REQUESTQUEUELIMIT:"http_requestQueueLimit",HTTP_HTTP2:"http_http2",LICENSE_MODE:"license_mode",LICENSE_REGION:"license_region",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_CONSOLE:"logging_console",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_EXTERNAL_LEVEL:"logging_external_level",LOGGING_EXTERNAL_TAG:"logging_external_tag",LOGGING_EXTERNAL_PATH:"logging_external_path",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_ROTATION_RETENTION:"logging_rotation_retention",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_NETWORK_HTTP2:"operationsApi_network_http2",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",OPERATIONSAPI_SYSINFO_NETWORK:"operationsApi_sysInfo_network",OPERATIONSAPI_SYSINFO_DISK:"operationsApi_sysInfo_disk",REPLICATION:"replication",REPLICATION_HOSTNAME:"replication_hostname",REPLICATION_URL:"replication_url",REPLICATION_PORT:"replication_port",REPLICATION_SECUREPORT:"replication_securePort",REPLICATION_ROUTES:"replication_routes",REPLICATION_DATABASES:"replication_databases",REPLICATION_ENABLEROOTCAS:"replication_enableRootCAs",REPLICATION_MTLS_CERTIFICATEVERIFICATION:"replication_mtls_certificateVerification",REPLICATION_MTLS_CERTIFICATEVERIFICATION_FAILUREMODE:"replication_mtls_certificateVerification_failureMode",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL:"replication_mtls_certificateVerification_crl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_TIMEOUT:"replication_mtls_certificateVerification_crl_timeout",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_CACHETTL:"replication_mtls_certificateVerification_crl_cacheTtl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_FAILUREMODE:"replication_mtls_certificateVerification_crl_failureMode",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_GRACEPERIOD:"replication_mtls_certificateVerification_crl_gracePeriod",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP:"replication_mtls_certificateVerification_ocsp",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_TIMEOUT:"replication_mtls_certificateVerification_ocsp_timeout",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_CACHETTL:"replication_mtls_certificateVerification_ocsp_cacheTtl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_ERRORCACHETTL:"replication_mtls_certificateVerification_ocsp_errorCacheTtl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_FAILUREMODE:"replication_mtls_certificateVerification_ocsp_failureMode",REPLICATION_SHARD:"replication_shard",REPLICATION_BLOBTIMEOUT:"replication_blobTimeout",REPLICATION_FAILOVER:"replication_failOver",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_BLOBPATHS:"storage_blobPaths",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",STORAGE_RECLAMATION_THRESHOLD:"storage_reclamation_threshold",STORAGE_RECLAMATION_INTERVAL:"storage_reclamation_interval",STORAGE_RECLAMATION_EVICTIONFACTOR:"storage_reclamation_evictionFactor",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"},MM={settings_path:vM.SETTINGS_PATH_KEY,hdb_root_key:F.ROOTPATH,hdb_root:F.ROOTPATH,rootpath:F.ROOTPATH,server_port_key:F.OPERATIONSAPI_NETWORK_PORT,server_port:F.OPERATIONSAPI_NETWORK_PORT,cert_key:F.TLS_CERTIFICATE,certificate:F.TLS_CERTIFICATE,private_key_key:F.TLS_PRIVATEKEY,private_key:F.TLS_PRIVATEKEY,http_secure_enabled_key:F.OPERATIONSAPI_NETWORK_HTTPS,https_on:F.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:F.OPERATIONSAPI_NETWORK_CORS,cors_on:F.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:F.LOGGING_LEVEL,log_level:F.LOGGING_LEVEL,log_path_key:F.LOGGING_ROOT,log_path:F.LOGGING_ROOT,clustering_node_name_key:F.CLUSTERING_NODENAME,node_name:F.CLUSTERING_NODENAME,clustering_enabled_key:F.CLUSTERING_ENABLED,clustering:F.CLUSTERING_ENABLED,max_http_threads:F.THREADS_COUNT,max_hdb_processes:F.THREADS_COUNT,server_timeout_key:F.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:F.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:F.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:F.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:F.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:F.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:F.LOGGING_AUDITLOG,disable_transaction_log:F.LOGGING_AUDITLOG,operation_token_timeout_key:F.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:F.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:F.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:F.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:F.HTTP_PORT,custom_functions_port:F.HTTP_PORT,custom_functions_directory_key:F.COMPONENTSROOT,custom_functions_directory:F.COMPONENTSROOT,max_custom_function_processes:F.THREADS_COUNT,logging_console:F.LOGGING_CONSOLE,log_to_file:F.LOGGING_FILE,log_to_stdstreams:F.LOGGING_STDSTREAMS,local_studio_on:F.LOCALSTUDIO_ENABLED,clustering_port:F.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:F.CLUSTERING_USER,customfunctions_network_port:F.HTTP_PORT,customfunctions_tls_certificate:F.TLS_CERTIFICATE,customfunctions_network_cors:F.HTTP_CORS,customfunctions_network_corsaccesslist:F.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:F.HTTP_HEADERSTIMEOUT,customfunctions_network_https:F.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:F.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:F.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:F.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:F.HTTP_TIMEOUT,customfunctions_tls:F.TLS,http_threads:F.THREADS_COUNT,threads:F.THREADS_COUNT,threads_count:F.THREADS_COUNT,customfunctions_processes:F.THREADS_COUNT,customfunctions_root:F.COMPONENTSROOT,operationsapi_root:F.ROOTPATH};for(let e in F){let t=F[e];MM[t.toLowerCase()]=t}o5={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},a5={csv_file_load:"csv_file_load",csv_data_load:V.CSV_DATA_LOAD,csv_url_load:V.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"},Bb={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"},c5={VERSION_DEFAULT:"2.2.0"},l5={DEVELOPMENT:8192,DEFAULT:512},u5={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},d5=Symbol("metadata"),Fb="__clustering__",UM="__createdtime__",xM="__updatedtime__",f5={CREATED_TIME:UM,UPDATED_TIME:xM},m5=[UM,xM],p5=15984864e5,u_={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},kb={"<":"LESS","<=":"LESS_OR_EQ",">":"GREATER",">=":"GREATER_OR_EQ","...":"BETWEEN"},h5={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},E5=["*","%"],_5="func_val",d_={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Sm={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},f_={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",COMPONENT_STATUS_REQUEST:"component_status_request",COMPONENT_STATUS_RESPONSE:"component_status_response"},Hb={HTTP:"http"},g5="3.x.x",ai={SUCCESS:"success",FAILURE:"failure"},Fa={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"}});var Qc=M(($Ne,kM)=>{"use strict";var BM=require("minimist");kM.exports=S5;function S5(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=FM(process.env),n=FM(BM(process.argv))):(r=process.env,n=BM(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(S5,"assignCMDENVVariables");function FM(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(FM,"objKeysToLowerCase")});var ci=M(ts=>{"use strict";global.Resource=ts.Resource=void 0;global.tables=ts.tables={};global.databases=ts.databases={};global.getUser=ts.getUser=void 0;global.authenticateUser=ts.authenticateUser=void 0;global.server=ts.server={};global.contentTypes=ts.contentTypes=null;global.threads=ts.threads=[];global.logger={};global.RequestTarget=ts.RequestTarget=void 0;global.operation=ts.operation=void 0;ts._assignPackageExport=(e,t)=>{global[e]=ts[e]=t}});var Gb=M((YNe,HM)=>{if(__filename.endsWith("dev.js")&&!process.env.HARPER_SKIP_COMPILE){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n,basename:s}=require("node:path"),{existsSync:i,statSync:o,readFileSync:c,writeFileSync:l,unlinkSync:u}=require("node:fs"),{isMainThread:d}=require("node:worker_threads"),{spawnSync:f,spawn:m}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:p}=yt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],E="ts-build";if(d){let S=!1,y=!1;if(y=i(n(p,E))){let N=new Set;e.sync(h.map(I=>`${I}/**/*.ts`),{cwd:p}).forEach(I=>{let $=0,ee=0;try{N.add(I),$=o(n(p,I)).mtimeMs-5e3,ee=o(n(p,E,I.replace(/.ts$/,".js"))).mtimeMs}catch{}$>ee&&(S=!0)}),e.sync(h.map(I=>`${I}/**/*.js`),{cwd:n(p,E)}).forEach(I=>{if(!N.has(I.replace(/.js$/,".ts")))try{u(n(p,E,I))}catch{}})}else S=!0;if(S){console.log("Compiling TypeScript...");let N=f("npx",["tsc"],{cwd:p});if(N.stdout?.length&&console.log(N.stdout.toString()),N.stderr?.length&&console.log(N.stderr.toString()),y){let I=n(t(),"harperdb-tsc.pid"),$=!1;if(i(I))try{process.kill(+c(I,"utf8"),0),$=!0}catch{}if(!$){console.log("Starting background TypeScript compilation...");let ee=m("npx",["tsc","--watch"],{detached:!0,cwd:p,stdio:"ignore"});ee.on("error",G=>{console.error("Error trying to compile TypeScript",G)}),ee.pid&&l(I,String(ee.pid),"utf-8"),ee.unref()}}}}let g=HM.constructor,R=g._findPath;g._findPath=function(S,y,N){if(S.startsWith(".")&&!N&&y.length===1&&y[0].startsWith(p)&&!y[0].includes("node_modules")){let I=r(p,y[0]),$;I.startsWith(E)?$=n(p,r(E,I)):$=n(p,E,I),(S.endsWith(".js")||S.endsWith(".ts"))&&(S=S.slice(0,-3));let ee=n($,S),G=ee+".js";if(i(G))return G;if(s(ee).includes(".")&&i(ee))return ee}return R(S,y,N)}}});var Tm={};ye(Tm,{server:()=>Be});var GM,Be,Hr=se(()=>{GM=b(ci()),Be={};(0,GM._assignPackageExport)("server",Be)});var Yt=M((WNe,$M)=>{"use strict";var T5="__dbis__",y5="__txns__",R5="__environment_name__",b5="__dbi_defintion__",A5={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"},I5=["__createdtime__","__updatedtime__"],w5="\uFFFF",qM={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},N5=Object.values(qM);$M.exports={AUDIT_STORE_NAME:y5,INTERNAL_DBIS_NAME:T5,DBI_DEFINITION_NAME:b5,SEARCH_TYPES:A5,TIMESTAMP_NAMES:I5,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:R5,TRANSACTIONS_DBI_NAMES_ENUM:qM,TRANSACTIONS_DBIS:N5,OVERFLOW_MARKER:w5}});var Jr=M((zNe,XM)=>{"use strict";var VM=(H(),v(z)),KM=Yt(),YM={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},WM=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),zM={500:WM("There was an error processing your request."),400:"Invalid request"},C5=zM[YM.INTERNAL_SERVER_ERROR],O5={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},P5={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},L5={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),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:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},D5={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:"value is required",SEARCH_VALUE_TOO_LARGE:"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 ${KM.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${KM.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"},v5={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${VM.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),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 ${VM.INSERT_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"},jM={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"},M5={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:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_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:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},U5={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_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:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),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:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},x5={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},B5={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},F5={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},QM={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},JM={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:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},k5={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.",BAD_SSH_KEY_NAME:"SSH key name can only contain alphanumeric, dash and underscore characters"},H5={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},G5={...jM,...L5,...O5,...M5,...U5,...x5,...B5,...F5,...v5,...QM,...JM,...k5,...H5,...P5};XM.exports={CHECK_LOGS_WRAPPER:WM,HDB_ERROR_MSGS:G5,DEFAULT_ERROR_MSGS:zM,DEFAULT_ERROR_RESP:C5,HTTP_STATUS_CODES:YM,LMDB_ERRORS_ENUM:D5,AUTHENTICATION_ERROR_MSGS:jM,VALIDATION_ERROR_MSGS:QM,ITC_ERRORS:JM}});var oe=M(Ae=>{"use strict";var ka=require("path"),nU=require("fs-extra"),vn=J(),ZM=require("fs-extra"),m_=require("os"),q5=require("net"),$5=require("recursive-iterator"),Ir=(H(),v(z)),{PACKAGE_ROOT:V5}=yt(),eU=require("papaparse"),p_=require("moment"),{inspect:K5}=require("util"),tU=require("is-number"),Y5=require("minimist"),W5=require("https"),z5=require("http"),j5=/^((\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)))$/,Q5=require("util").promisify(setTimeout),J5="",X5=4,rU={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Ae.isEmpty=rs;Ae.isEmptyOrZeroLength=qi;Ae.arrayHasEmptyValues=t8;Ae.arrayHasEmptyOrZeroLengthValues=r8;Ae.buildFolderPath=n8;Ae.isBoolean=sU;Ae.errorizeMessage=Z5;Ae.stripFileExtension=i8;Ae.autoCast=o8;Ae.autoCastJSON=iU;Ae.autoCastJSONDeep=$b;Ae.removeDir=a8;Ae.compareVersions=c8;Ae.isCompatibleDataVersion=l8;Ae.escapeRawValue=u8;Ae.unescapeValue=d8;Ae.stringifyProps=f8;Ae.timeoutPromise=p8;Ae.isClusterOperation=E8;Ae.getClusterUser=g8;Ae.checkGlobalSchemaTable=_8;Ae.getHomeDir=aU;Ae.getPropsFilePath=m8;Ae.promisifyPapaParse=S8;Ae.removeBOM=cU;Ae.createEventPromise=T8;Ae.checkSchemaTableExist=y8;Ae.checkSchemaExists=lU;Ae.checkTableExists=uU;Ae.getStartOfTomorrowInSeconds=R8;Ae.getLimitKey=b8;Ae.isObject=s8;Ae.isNotEmptyAndHasValue=e8;Ae.autoCasterIsNumberCheck=oU;Ae.backtickASTSchemaItems=A8;Ae.isPortTaken=h8;Ae.createForkArgs=I8;Ae.autoCastBoolean=w8;Ae.asyncSetTimeout=Q5;Ae.getTableHashAttribute=N8;Ae.doesSchemaExist=C8;Ae.doesTableExist=O8;Ae.stringifyObj=P8;Ae.ms_to_time=L8;Ae.changeExtension=D8;Ae.getEnvCliRootPath=Vb;Ae.noBootFile=v8;Ae.httpRequest=M8;Ae.transformReq=U8;Ae.convertToMS=x8;Ae.PACKAGE_ROOT=V5;function Z5(e){return e instanceof Error?e:new Error(e)}a(Z5,"errorizeMessage");function rs(e){return e==null}a(rs,"isEmpty");function e8(e){return!rs(e)&&(e||e===0||e===""||sU(e))}a(e8,"isNotEmptyAndHasValue");function qi(e){return rs(e)||e.length===0||e.size===0}a(qi,"isEmptyOrZeroLength");function t8(e){if(rs(e))return!0;for(let t=0;t<e.length;t++)if(rs(e[t]))return!0;return!1}a(t8,"arrayHasEmptyValues");function r8(e){if(qi(e))return!0;for(let t=0;t<e.length;t++)if(qi(e[t]))return!0;return!1}a(r8,"arrayHasEmptyOrZeroLengthValues");function n8(...e){try{return e.join(ka.sep)}catch{console.error(e)}}a(n8,"buildFolderPath");function sU(e){return rs(e)?!1:e===!0||e===!1}a(sU,"isBoolean");function s8(e){return rs(e)?!1:typeof e=="object"}a(s8,"isObject");function i8(e){return qi(e)?J5:e.slice(0,-X5)}a(i8,"stripFileExtension");function o8(e){return rs(e)||e===""||typeof e!="string"?e:rU[e]!==void 0?rU[e]:oU(e)===!0?Number(e):j5.test(e)?new Date(e):e}a(o8,"autoCast");function iU(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(iU,"autoCastJSON");function $b(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=$b(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=$b(r);n!==r&&(e[t]=n)}return e}else return iU(e)}a($b,"autoCastJSONDeep");function oU(e){if(e.startsWith("0.")&&tU(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&tU(e))}a(oU,"autoCasterIsNumberCheck");async function a8(e){if(qi(e))throw new Error(`Directory path: ${e} does not exist`);try{await ZM.emptyDir(e),await ZM.remove(e)}catch(t){throw vn.error(`Error removing files in ${e} -- ${t}`),t}}a(a8,"removeDir");function c8(e,t){if(qi(e)){vn.info("Invalid current version sent as parameter.");return}if(qi(t)){vn.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("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(c8,"compareVersions");function l8(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(l8,"isCompatibleDataVersion");function u8(e){if(rs(e))return e;let t=String(e);return t==="."?Ir.UNICODE_PERIOD:t===".."?Ir.UNICODE_PERIOD+Ir.UNICODE_PERIOD:t.replace(Ir.FORWARD_SLASH_REGEX,Ir.UNICODE_FORWARD_SLASH)}a(u8,"escapeRawValue");function d8(e){if(rs(e))return e;let t=String(e);return t===Ir.UNICODE_PERIOD?".":t===Ir.UNICODE_PERIOD+Ir.UNICODE_PERIOD?"..":String(e).replace(Ir.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(d8,"unescapeValue");function f8(e,t){if(rs(e))return vn.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+m_.EOL}!qi(n)&&n[0]===";"?r+=" "+n+s+m_.EOL:qi(n)||(r+=n+"="+s+m_.EOL)}catch{vn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(f8,"stringifyProps");function aU(){let e;try{e=m_.homedir()}catch{e=process.env.HOME}return e}a(aU,"getHomeDir");function m8(){let e=ka.join(aU(),Ir.HDB_HOME_DIR_NAME,Ir.BOOT_PROPS_FILE_NAME);return nU.existsSync(e)||(e=ka.join(__dirname,"../","hdb_boot_properties.file")),e}a(m8,"getPropsFilePath");function p8(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(p8,"timeoutPromise");async function h8(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=q5.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(h8,"isPortTaken");function E8(e){try{return Ir.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){vn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(E8,"isClusterOperation");function _8(e,t){let r=(we(),v(ft)).getDatabases();if(!r[e])return h_.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return h_.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(_8,"checkGlobalSchemaTable");function g8(e,t){if(rs(t)){vn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(rs(e)||qi(e)){vn.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){vn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){vn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(g8,"getClusterUser");function S8(){eU.parsePromise=function(e,t,r){return new Promise(function(n,s){eU.parse(e,{header:!0,transformHeader:cU,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(S8,"promisifyPapaParse");function cU(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(cU,"removeBOM");function T8(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;vn.info(`Got cluster status event response: ${K5(s)}`);try{i.cancel()}catch{vn.error("Error trying to cancel timeout.")}n(s)})})}a(T8,"createEventPromise");function y8(e,t){let r=lU(e);if(r)return r;let n=uU(e,t);if(n)return n}a(y8,"checkSchemaTableExist");function lU(e){let{getDatabases:t}=(we(),v(ft));if(!t()[e])return h_.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(lU,"checkSchemaExists");function uU(e,t){let{getDatabases:r}=(we(),v(ft));if(!r()[e][t])return h_.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(uU,"checkTableExists");function R8(){let e=p_().utc().add(1,"d").startOf("d").unix(),t=p_().utc().unix();return e-t}a(R8,"getStartOfTomorrowInSeconds");function b8(){return p_().utc().format("DD-MM-YYYY")}a(b8,"getLimitKey");function A8(e){try{let t=new $5(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){vn.error("Got an error back ticking items."),vn.error(t)}}a(A8,"backtickASTSchemaItems");function I8(e){return[e]}a(I8,"createForkArgs");function w8(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(w8,"autoCastBoolean");function N8(e,t){let{getDatabases:r}=(we(),v(ft)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(N8,"getTableHashAttribute");function C8(e){let{getDatabases:t}=(we(),v(ft));return t()[e]!==void 0}a(C8,"doesSchemaExist");function O8(e,t){let{getDatabases:r}=(we(),v(ft));return r()[e]?.[t]!==void 0}a(O8,"doesTableExist");function P8(e){try{return JSON.stringify(e)}catch{return e}}a(P8,"stringifyObj");function L8(e){let t=p_.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(L8,"ms_to_time");function D8(e,t){let r=ka.basename(e,ka.extname(e));return ka.join(ka.dirname(e),r+t)}a(D8,"changeExtension");function Vb(){if(process.env[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Y5(process.argv);if(e[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(Vb,"getEnvCliRootPath");var qb;function v8(){if(qb)return qb;let e=Vb();if(Vb()&&nU.pathExistsSync(ka.join(e,Ir.HDB_CONFIG_FILE)))return qb=!0,!0}a(v8,"noBootFile");function M8(e,t){let r;return e.protocol==="http:"?r=z5:r=W5,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(M8,"httpRequest");function U8(e){if(!e.schema&&!e.database){e.schema=Ir.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(U8,"transformReq");function x8(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(x8,"convertToMS");var h_=Jr()});var Rt=M((XNe,_U)=>{"use strict";var Im=(H(),v(z)),B8=oe(),Mn=me(),wm=require("path"),F8=require("minimist"),dU=require("fs-extra"),fU=require("lodash");Mn.initSync();var{CONFIG_PARAMS:Ha,DATABASES_PARAM_CONFIG:ym,SYSTEM_SCHEMA_NAME:E_}=Im,Rm,bm,Am;function mU(){if(Rm!==void 0)return Rm;if(Mn.getHdbBasePath()!==void 0)return Rm=Mn.get(Ha.STORAGE_PATH)||wm.join(Mn.getHdbBasePath(),Im.DATABASES_DIR_NAME),Rm}a(mU,"getBaseSchemaPath");function pU(){if(bm!==void 0)return bm;if(Mn.getHdbBasePath()!==void 0)return bm=EU(E_),bm}a(pU,"getSystemSchemaPath");function hU(){if(Am!==void 0)return Am;if(Mn.getHdbBasePath()!==void 0)return Am=Mn.get(Im.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||wm.join(Mn.getHdbBasePath(),Im.TRANSACTIONS_DIR_NAME),Am}a(hU,"getTransactionAuditStoreBasePath");function k8(e,t){let r=Mn.get(Ha.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||wm.join(hU(),e.toString())}a(k8,"getTransactionAuditStorePath");function EU(e,t){e=e.toString(),t=t&&t.toString();let r=Mn.get(Im.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||wm.join(mU(),e)}a(EU,"getSchemaPath");function H8(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,F8(process.argv));let n=r[Ha.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!B8.isObject(n))throw o;i=n}for(let o of i){let c=o[E_];if(!c)continue;let l=Mn.get(Ha.DATABASES);l=l??{};let u=c?.tables?.[t]?.[ym.PATH];if(u)return fU.set(l,[E_,ym.TABLES,t,ym.PATH],u),Mn.setProperty(Ha.DATABASES,l),u;let d=c?.[ym.PATH];if(d)return fU.set(l,[E_,ym.PATH],d),Mn.setProperty(Ha.DATABASES,l),d}}let s=r[Ha.STORAGE_PATH.toUpperCase()];if(s){if(!dU.pathExistsSync(s))throw new Error(s+" does not exist");let i=wm.join(s,e);return dU.mkdirsSync(i),Mn.setProperty(Ha.STORAGE_PATH,s),i}return pU()}a(H8,"initSystemSchemaPaths");function G8(){Rm=void 0,bm=void 0,Am=void 0}a(G8,"resetPaths");_U.exports={getBaseSchemaPath:mU,getSystemSchemaPath:pU,getTransactionAuditStorePath:k8,getTransactionAuditStoreBasePath:hU,getSchemaPath:EU,initSystemSchemaPaths:H8,resetPaths:G8}});var Un=M((rCe,RU)=>{"use strict";var q8=Jr().LMDB_ERRORS_ENUM,eCe=require("lmdb"),$8=Yt(),tCe=require("buffer").Buffer,{OVERFLOW_MARKER:gU,MAX_SEARCH_KEY_LENGTH:__}=$8,SU=["number","string","symbol","boolean","bigint"];function V8(e){if(e=e?.primaryStore||e,!e)throw new Error(q8.ENV_REQUIRED)}a(V8,"validateEnv");function K8(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(K8,"stringifyData");function Y8(e){return e instanceof Date?e.valueOf():e}a(Y8,"convertKeyValueToWrite");function W8(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(SU.includes(typeof e))return e.length>__?[e.slice(0,__)+gU]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(SU.includes(typeof i))i.length>__?r.push(i.slice(0,__)+gU):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(W8,"getIndexedValues");var g_=0,TU=0;function yU(){TU=Date.now()-performance.now()}a(yU,"adjustStartTime");yU();var z8=6e4;setInterval(yU,z8).unref();function j8(){let e=performance.now()+TU;return e>g_?(g_=e,e):(g_+=488e-6,g_)}a(j8,"getNextMonotonicTime");RU.exports={validateEnv:V8,stringifyData:K8,convertKeyValueToWrite:Y8,getNextMonotonicTime:j8,getIndexedValues:W8}});var Nm=M((sCe,bU)=>{"use strict";var Q8=(H(),v(z)).OPERATIONS_ENUM,Kb=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=Q8.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};bU.exports=Kb});var _e=M((oCe,wU)=>{"use strict";var vu=Jr(),J8=(H(),v(z)),S_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,AU),this.statusCode=n||vu.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(vu.DEFAULT_ERROR_MSGS[n]?vu.DEFAULT_ERROR_MSGS[n]:vu.DEFAULT_ERROR_MSGS[vu.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&&J()[s](i)}},Yb=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}},Wb=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function AU(e,t,r,n=J8.LOG_LEVELS.ERROR,s=null,i=!1){if(IU(e))return e;let o=new S_(e,t,r,n,s);return i&&delete o.stack,o}a(AU,"handleHDBError");function Mu(e){this.message=e}a(Mu,"Violation");Mu.prototype=Object.create(Error.prototype);Mu.prototype.constructor=Mu;Mu.prototype.toString=function(){return`${this.constructor.name}: ${this.message}`};var zb=class extends Mu{static{a(this,"AccessViolation")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};function IU(e){return e.__proto__.constructor.name===S_.name}a(IU,"isHDBError");wU.exports={isHDBError:IU,handleHDBError:AU,ClientError:Yb,ServerError:Wb,AccessViolation:zb,Violation:Mu,hdbErrors:vu}});var Cm=M((lCe,PU)=>{"use strict";var cCe=Nm(),T_=(H(),v(z)),jb=oe(),NU=J(),X8=require("uuid"),{handleHDBError:y_,hdbErrors:Z8}=_e(),{HDB_ERROR_MSGS:R_,HTTP_STATUS_CODES:b_}=Z8;PU.exports=CU;function CU(e,t,r){for(let s=0;s<t.length;s++)OU(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];eZ(i,r,e.operation)}}a(CU,"processRows");CU.validateAttribute=OU;function OU(e){if(Buffer.byteLength(String(e))>T_.INSERT_MAX_CHARACTER_SIZE)throw y_(new Error,R_.ATTR_NAME_LENGTH_ERR(e),b_.BAD_REQUEST,void 0,void 0,!0);if(jb.isEmptyOrZeroLength(e)||jb.isEmpty(e.trim()))throw y_(new Error,R_.ATTR_NAME_NULLISH_ERR,b_.BAD_REQUEST,void 0,void 0,!0)}a(OU,"validateAttribute");function eZ(e,t,r){if(!e.hasOwnProperty(t)||jb.isEmptyOrZeroLength(e[t])){if(r===T_.OPERATIONS_ENUM.INSERT||r===T_.OPERATIONS_ENUM.UPSERT){e[t]=X8.v4();return}throw NU.error("Update transaction aborted due to record with no hash value:",e),y_(new Error,R_.RECORD_MISSING_HASH_ERR,b_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>T_.INSERT_MAX_CHARACTER_SIZE)throw NU.error(e),y_(new Error,R_.HASH_VAL_LENGTH_ERR,b_.BAD_REQUEST,void 0,void 0,!0)}a(eZ,"validateHash")});function BU(e){Jb=e}function sZ(){nZ=setInterval(function(){for(let e of Qb)if(e.stale){let t=e.getContext()?.url;MU.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},rZ).unref()}var Xb,vU,MU,UU,xU,LU,Qb,tZ,Do,Om,DU,Jb,vo,A_,rZ,nZ,Pm=se(()=>{Xb=b(Un()),vU=b(_e()),MU=b(J()),UU=b(me());H();xU=b(oe()),LU=100,Qb=new Set,tZ=(0,xU.convertToMS)(UU.get(F.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,Do={CLOSED:0,OPEN:1,LINGERING:2};a(BU,"replicationConfirmation");vo=class e{static{a(this,"DatabaseTransaction")}#e;writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=Do.OPEN;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===Do.OPEN)return this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),Qb.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Qb.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Om&&!this.overloadChecked&&performance.now()-DU>tZ)throw new vU.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===Do.CLOSED)throw new Error("Can not use a transaction that is no longer open");if(this.open===Do.LINGERING){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||(0,Xb.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let f=this.validated;this.validated=this.writes.length;for(let p=f;p<this.validated;p++)this.writes[p]?.validate?.(this.timestamp);let m;for(let p=f;p<this.validated;p++){let h=this.writes[p];h&&(h.before||h.beforeIntermediate)&&(m=!0)}if(m)return(async()=>{try{for(let p=0;p<2;p++){let h;for(let E=f;E<this.validated;E++){let g=this.writes[E];if(!g)continue;let R=g[p===0?"before":"beforeIntermediate"];if(R){let S=R();h?h.push?h.push(S):h=[h,S]:h=S}}h&&await(h.push?Promise.all(h):h)}}catch(p){throw this.abort(),p}return this.commit(t)})()}catch(f){throw this.abort(),f}n||this.doneReadTxn(),this.open=t?.doneWriting?Do.LINGERING:Do.OPEN;let s,i=[],o=0;this.writes=this.writes.filter(f=>f);let c=a(f=>{f.commit(r,f.entry,n)},"doWrite"),l=a(()=>{let f=this.writes[o++];if(f)if(f.key){(n>0||!f.entry)&&(f.entry=f.store.getEntry(f.key));let m=f.store.ifVersion(f.key,f.entry?.version??null,l);s=s||m}else l();else for(let m of this.writes)c(m)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<LU>>n?l():s=this.writes[0].store.transaction(()=>{for(let f of this.writes)f.entry=f.store.getEntry(f.key),c(f);return!0})),s)return Om||(Om=s,DU=performance.now(),Om.then(()=>{Om=null})),s.then(f=>{if(f){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let m=this.writes[0].store.rootStore.databaseName,p=this.writes[this.writes.length-1];Jb&&p&&i.push(Jb(m,p.store.getEntry(p.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+LU/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let d={txnTime:r};if(this.next){let f=this.next?.commit(t);if(f?.then)return f?.then(m=>({txnTime:r,next:m}));d.next=f}return d}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=Do.CLOSED,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},A_=class extends vo{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Xb.getNextMonotonicTime)())}getReadTxn(){}},rZ=3e4;a(sZ,"startMonitoringTxns");sZ()});var FU,ns,Zb,Uu=se(()=>{FU=require("events"),ns=class extends FU.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new Zb;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)}},Zb=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}}}});function bt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===Do.OPEN&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new vo;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(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 l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var kU,Ga=se(()=>{kU=b(ci());Pm();a(bt,"transaction");(0,kU._assignPackageExport)("transaction",bt);bt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};bt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var tA={};ye(tA,{add:()=>I_,applyReverse:()=>HU,getRecordAtTime:()=>eA,rebuildUpdateBefore:()=>w_});function I_(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 w_(e,t,r){let n=null;for(let s in e)if(s in t){let i=t[s];if(i?.__op__){let o=e[s];if(o?.__op__)if(o.__op__===i.__op__)n||(n={}),n[s]=o;else throw new Error("Can not merge updates with different operations");else n||(n={}),n[s]=o,I_(n,s,i)}else r&&(n||(n={}),n[s]=i)}else n||(n={}),n[s]=e[s];return n}function HU(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=iZ[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=GU}}function eA(e,t,r){let n=r.rootStore.auditStore,s={...e.value},i=e.localTime;for(;i>t;){let l=n.get(i),u=At(l);switch(u.type){case"put":s=u.getValue(r);break;case"patch":HU(s,u.getValue(r));break;case"delete":s=null}i=u.previousLocalTime}let o={},c=0;for(let l in s)s[l]===GU&&(o[l]=!0,c++);for(;c>0&&i>0;){let l=n.get(i),u=At(l),d;switch(u.type){case"put":d=u.getValue(r);break;case"patch":d=u.getValue(r);break}for(let f in d)o[f]&&(s[f]=d[f],o[f]=!1,c--);i=u.previousLocalTime}if(c>0)for(let l in o)s[l]=null;return s}var iZ,GU,N_=se(()=>{$i();a(I_,"add");I_.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)};iZ={add:I_};a(w_,"rebuildUpdateBefore");a(HU,"applyReverse");GU={};a(eA,"getRecordAtTime")});var wr=M(O_=>{var C_=J();for(let e of["trace","debug","info","warn","error","fatal","notify"])C_.logsAtLevel(e)&&(O_[e]=C_[e]);O_.loggerWithTag=e=>C_.loggerWithTag(e,!0);O_.setLogLevel=C_.setLogLevel});var zU={};ye(zU,{parse:()=>sA,streamAsJSON:()=>Dm,stringify:()=>Jc});function Dm(e){return new rA({value:e})}function qU(e){return console.error(e),JSON.stringify(Lm(e))}function $U(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Jc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===YU)return WU(e);if(t.resolution)return t.resolution.then(()=>Jc(e));throw t}}function WU(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+=WU(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Jc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function sA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),cZ.test(e)?oZ.parse(e):JSON.parse(e)):null}var VU,nA,KU,oZ,aZ,YU,Lm,rA,cZ,iA=se(()=>{VU=require("stream"),nA=b(J()),KU=b(require("json-bigint-fixes")),oZ=(0,KU.default)({useNativeBigInt:!0}),aZ=1e4,YU={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw YU};({errorToString:Lm}=nA);a(Dm,"streamAsJSON");rA=class extends VU.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(;;){try{o=i.next(),o.then&&(yield o.then(c=>(o=c,""),c=>(nA.warn("Error serializing in stream",c),o={done:!1,value:{error:Lm(c)}},i={next:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:Lm(c)}},i={next:a(()=>({done:!0}),"next")}}if(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),qU)}catch(s){yield qU(s)}else yield Jc(t)}else yield Jc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);$U(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(Lm(t)),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>aZ?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 $U(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(Lm(r)),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(qU,"handleError");a($U,"when");a(Jc,"stringify");a(WU,"jsStringify");cZ=/[[,:]\s*-?\d{16,}/;a(sA,"parse")});var sx={};ye(sx,{asyncSerialization:()=>uA,contentTypes:()=>lA,findBestSerializer:()=>L_,getDeserializer:()=>Bo,hasAsyncSerialization:()=>dA,registerContentHandlers:()=>Um,serialize:()=>xm,serializeMessage:()=>xo,toCsvStream:()=>P_});function lZ(e){try{return e?.[0]===123?cA(e):e}catch{return e}}function Um(e){e.register(uZ,{serializers:[{regex:/^application\/json$/,serializer:Dm},{regex:/^application\/cbor$/,serializer:a(function(t){return new Xc.EncoderStream(Mm).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Zc.Readable.from((0,Vi.encodeIter)(t,Mm)):(0,Vi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),P_(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Vi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Xc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function L_(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 l of c){let[u,...d]=l.split(/\s*;\s*/),f=1,m={q:1};for(let h of d){let E=h.indexOf("=");m[h.substring(0,E)]=h.substring(E+1)}f=+m.q;let p=hn.get(u);if(p){let h=(p.q||1)*f;h>s&&(n=p,i=p.type||u,s=h,o=m)}}if(!n){if(r)throw new JU.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(hn.keys()).join(", "),406);n=hn.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function xm(e,t,r){let n=QU&&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||e instanceof Ms)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=L_(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&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),aA.default.warn?.(`Error serializing error ${t?.url||t}: ${l}`),l)),e.getColumns=c}let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Uo.createBrotliCompress)({params:{[Uo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Uo.constants.BROTLI_MODE_TEXT:Uo.constants.BROTLI_MODE_GENERIC,[Uo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>QU?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Uo.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function xo(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Mo=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=L_(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=vm(e);return Mo?.length>0?(Mo.length===1?Mo[0]:Promise.all(Mo)).then(()=>xo(e,t,!0)):n}finally{Mo=void 0}}function uA(e){if(Mo)Mo.push(e);else throw new Error("Unable to serialize asynchronously")}function dA(){return!!Mo}function dZ(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 mZ(e){return fZ.includes(e)}function pZ(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function Bo(e="",t=!1){let r=pZ(e),n=r.type&&hn.get(r.type)?.deserialize||hZ(r);return t?s=>dZ(s).then(n):n}function hZ(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!mZ(e.parameters.charset)&&aA.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return cA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function EZ(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)}}}}}function P_(e,t){let r=Zc.default.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 ex.Transform(n,s);return r.pipe(i)}var Vi,Xc,Uo,JU,Zc,XU,oA,ZU,aA,ex,tx,rx,vm,cA,Mm,hn,lA,jU,nx,uZ,QU,Mo,fZ,Fo=se(()=>{iA();Vi=require("msgpackr"),Xc=require("cbor-x"),Uo=require("zlib"),JU=b(_e()),Zc=b(require("stream"));Hr();XU=b(ci()),oA=b(me());H();ZU=b(require("yaml")),aA=b(wr());ss();ex=require("json2csv"),tx=b(require("fastify-plugin")),rx=oA.default.get(F.SERIALIZATION_BIGINT)!==!1,vm=rx?Jc:JSON.stringify,cA=rx?sA:JSON.parse,Mm={useRecords:!1,useToJSON:!0},hn=new Map,lA=hn;Be.contentTypes=lA;(0,XU._assignPackageExport)("contentTypes",lA);hn.set("application/json",{serializeStream:Dm,serialize:vm,deserialize(e){return cA(e)},q:.8});jU=new Xc.Encoder(Mm);hn.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Xc.EncoderStream(Mm).end(e)},serialize:jU.encode,deserialize:jU.decode,q:1});hn.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Zc.Readable.from((0,Vi.encodeIter)(e,Mm)):(0,Vi.pack)(e)},serialize:Vi.pack,deserialize:Vi.unpack,q:.9});hn.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),P_(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]),P_(e,e?.getColumns?.())},q:.1});hn.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return Zc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});hn.set("text/yaml",{serialize(e){return ZU.stringify(e,{aliasDuplicateObjects:!1})},q:.7});hn.set("text/event-stream",{serializeStream:a(function(e){return Zc.Readable.from(EZ(e,this.serialize))},"serializeStream"),serialize:a(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+`
1
+ "use strict";var a6=Object.create;var hm=Object.defineProperty;var c6=Object.getOwnPropertyDescriptor;var l6=Object.getOwnPropertyNames;var u6=Object.getPrototypeOf,d6=Object.prototype.hasOwnProperty;var a=(e,t)=>hm(e,"name",{value:t,configurable:!0});var se=(e,t)=>()=>(e&&(t=e(e=0)),t);var M=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ye=(e,t)=>{for(var r in t)hm(e,r,{get:t[r],enumerable:!0})},NM=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of l6(t))!d6.call(e,s)&&s!==r&&hm(e,s,{get:()=>t[s],enumerable:!(n=c6(t,s))||n.enumerable});return e};var b=(e,t,r)=>(r=e!=null?a6(u6(e)):{},NM(t||!e||!e.__esModule?hm(r,"default",{value:e,enumerable:!0}):r,e)),v=e=>NM(hm({},"__esModule",{value:!0}),e);var yt=M((GNe,PM)=>{var{join:f6,dirname:CM}=require("node:path"),{existsSync:m6,readFileSync:p6}=require("node:fs");function h6(){let t=__dirname,r,n=0;for(;!m6(r=f6(t,"package.json"));)if(t===(t=CM(t))||n++>10)throw new Error("Could not find package root");return r}a(h6,"findPackageJson");var OM=h6(),E6=JSON.parse(p6(OM,"utf8")),_6=CM(OM);PM.exports={packageJson:E6,PACKAGE_ROOT:_6}});var z={};ye(z,{AUTH_AUDIT_STATUS:()=>ai,AUTH_AUDIT_TYPES:()=>Fa,BOOT_PROPS_FILE_NAME:()=>H6,BOOT_PROP_PARAMS:()=>vM,CLUSTERING_FLAG:()=>Fb,CLUSTERING_PROCESSES:()=>N6,CLUSTER_MESSAGE_TYPE_ENUM:()=>Bb,CLUSTER_OPERATIONS:()=>r5,CONFIG_PARAMS:()=>F,CONFIG_PARAM_MAP:()=>MM,DATABASES_DIR_NAME:()=>jc,DATABASES_PARAM_CONFIG:()=>o5,DEFAULT_DATABASE_NAME:()=>O6,ESCAPED_FORWARD_SLASH_REGEX:()=>F6,FORWARD_SLASH_REGEX:()=>x6,FUNC_VAL:()=>_5,GEO_CONVERSION_ENUM:()=>s5,HDB_COMPONENT_CONFIG_FILE:()=>T6,HDB_CONFIG_FILE:()=>g6,HDB_DEFAULT_CONFIG_FILE:()=>S6,HDB_FILE_PERMISSIONS:()=>q6,HDB_HOME_DIR_NAME:()=>k6,HDB_PID_FILE:()=>C6,HDB_PROCESS_SERVICES:()=>w6,HDB_PROC_NAME:()=>y6,HDB_RESTART_SCRIPT:()=>R6,HDB_ROOT_DIR_NAME:()=>vb,HDB_SETTINGS_NAMES:()=>gm,HDB_SUPPORT_ADDRESS:()=>DM,INFO_TABLE_HASH_ATTRIBUTE:()=>z6,INSERT_MAX_CHARACTER_SIZE:()=>Y6,INSTALL_PROMPTS:()=>K6,ITC_EVENT_TYPES:()=>f_,JOB_STATUS_ENUM:()=>X6,JOB_TYPE_ENUM:()=>a5,JWT_ENUM:()=>Sm,LAUNCH_SERVICE_SCRIPTS:()=>L6,LEGACY_CONFIG_PARAMS:()=>i5,LEGACY_DATABASES_DIR_NAME:()=>l_,LICENSE_FILE_NAME:()=>J6,LICENSE_KEY_DIR_NAME:()=>xb,LICENSE_VALUES:()=>c5,LOG_LEVELS:()=>Em,LOG_NAMES:()=>P6,METADATA_PROPERTY:()=>d5,NODE_ERROR_CODES:()=>u5,OPERATIONS_ENUM:()=>V,PERMS_CRUD_ENUM:()=>h5,PERMS_UPDATE_RELEASE_TIMESTAMP:()=>p5,PRE_4_0_0_VERSION:()=>g5,PROCESS_DESCRIPTORS:()=>I6,PROCESS_NAME_ENV_PROP:()=>V6,RAM_ALLOCATION_ENUM:()=>l5,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:()=>d_,REG_KEY_FILE_NAME:()=>Q6,RESTART_TIMEOUT_MS:()=>G6,ROLE_TYPES_ENUM:()=>D6,S3_BUCKET_AUTH_KEYS:()=>e5,SEARCH_NOT_FOUND_MESSAGE:()=>M6,SEARCH_WILDCARDS:()=>E5,SERVICE_ACTIONS_ENUM:()=>n5,SUPPORT_HELP_MSG:()=>v6,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:()=>j6,SYSTEM_SCHEMA_NAME:()=>_m,SYSTEM_TABLE_NAMES:()=>Du,THREAD_TYPES:()=>Hb,TIME_STAMP_NAMES:()=>m5,TIME_STAMP_NAMES_ENUM:()=>f5,TRANSACTIONS_DIR_NAME:()=>$6,UNICODE_FORWARD_SLASH:()=>B6,UNICODE_PERIOD:()=>U6,UPGRADE_JSON_FIELD_NAMES_ENUM:()=>W6,VALID_S3_FILE_TYPES:()=>Z6,VALID_SQL_OPS_ENUM:()=>t5,VALUE_SEARCH_COMPARATORS:()=>u_,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:()=>kb});var a_,c_,g6,S6,vb,T6,y6,R6,LM,Db,Mb,Ub,b6,A6,I6,w6,N6,C6,O6,P6,Em,L6,D6,DM,v6,M6,U6,x6,B6,F6,_m,k6,xb,H6,G6,q6,jc,l_,$6,V6,vM,K6,Y6,W6,Du,z6,j6,Q6,J6,X6,V,Z6,e5,t5,r5,n5,s5,gm,i5,F,MM,o5,a5,Bb,c5,l5,u5,d5,Fb,UM,xM,f5,m5,p5,u_,kb,h5,E5,_5,d_,Sm,f_,Hb,g5,ai,Fa,H=se(()=>{a_=require("node:path"),c_=b(yt()),g6="harperdb-config.yaml",S6="defaultConfig.yaml",vb="hdb",T6="config.yaml",y6="harperdb.js",R6="restartHdb.js",LM="HarperDB",Db="Custom Functions",Mb="Clustering Hub",Ub="Clustering Leaf",b6="Clustering Ingest Service",A6="Clustering Reply Service",I6={HDB:LM,CLUSTERING_HUB:Mb,CLUSTERING_LEAF:Ub,CLUSTERING_INGEST_SERVICE:b6,CLUSTERING_REPLY_SERVICE:A6,CUSTOM_FUNCTIONS:Db,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"},w6={harperdb:LM,"clustering hub":Mb,"clustering leaf":Ub,"custom functions":Db,custom_functions:Db,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers",http:"http"},N6={CLUSTERING_HUB_PROC_DESCRIPTOR:Mb,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ub},C6="hdb.pid",O6="data",P6={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Em={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},L6={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:(0,a_.join)(c_.PACKAGE_ROOT,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:(0,a_.join)(c_.PACKAGE_ROOT,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:(0,a_.join)(c_.PACKAGE_ROOT,"launchServiceScripts/launchUpdateNodes4-0-0.js")},D6={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},DM="support@harperdb.io",v6=`For support, please submit a request at https://harperdbhelp.zendesk.com/hc/en-us/requests/new or contact ${DM}`,M6="None of the specified records were found.",U6="U+002E",x6=/\//g,B6="U+002F",F6=/U\+002F/g,_m="system",k6=".harperdb",xb="keys",H6="hdb_boot_properties.file",G6=6e4,q6=448,jc="database",l_="schema",$6="transactions",V6="PROCESS_NAME",vM={SETTINGS_PATH_KEY:"settings_path"},K6={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",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",DEFAULTS_MODE:"DEFAULTS_MODE",REPLICATION_HOSTNAME:"REPLICATION_HOSTNAME",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},Y6=250,W6={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},Du={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"},z6="info_id",j6={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"},Q6="060493.ks",J6=".license",X6={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},V={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",DESCRIBE_METRIC:"describe_metric",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_REGISTRATION_INFO:"registration_info",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",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",CLEANUP_ORPHAN_BLOBS:"cleanup_orphan_blobs",SIGN_CERTIFICATE:"sign_certificate",CREATE_CSR:"create_csr",LIST_CERTIFICATES:"list_certificates",ADD_CERTIFICATES:"add_certificate",REMOVE_CERTIFICATE:"remove_certificate",ADD_NODE_BACK:"add_node_back",REMOVE_NODE_BACK:"remove_node_back",ADD_SSH_KEY:"add_ssh_key",UPDATE_SSH_KEY:"update_ssh_key",DELETE_SSH_KEY:"delete_ssh_key",LIST_SSH_KEYS:"list_ssh_keys",SET_SSH_KNOWN_HOSTS:"set_ssh_known_hosts",GET_SSH_KNOWN_HOSTS:"get_ssh_known_hosts",GET_KEY:"get_key",GET_ANALYTICS:"get_analytics",LIST_METRICS:"list_metrics",GET_STATUS:"get_status",SET_STATUS:"set_status",CLEAR_STATUS:"clear_status",INSTALL_USAGE_LICENSE:"install_usage_license",GET_USAGE_LICENSES:"get_usage_licenses"},Z6={CSV:".csv",JSON:".json"},e5={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},t5={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},r5={[V.INSERT]:V.INSERT,[V.UPDATE]:V.UPDATE,[V.UPSERT]:V.UPSERT,[V.DELETE]:V.DELETE},n5={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},s5={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},gm={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"},i5={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"},F={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",ANALYTICS_REPLICATE:"analytics_replicate",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_COOKIE_DOMAINS:"authentication_cookie_domains",AUTHENTICATION_COOKIE_EXPIRES:"authentication_cookie_expires",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",AUTHENTICATION_HASHFUNCTION:"authentication_hashFunction",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_CORSACCESSCONTROLALLOWHEADERS:"http_corsAccessControlAllowHeaders",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_MAXPARAMLENGTH:"http_maxParamLength",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_MTLS_CERTIFICATEVERIFICATION:"http_mtls_certificateVerification",HTTP_MTLS_CERTIFICATEVERIFICATION_FAILUREMODE:"http_mtls_certificateVerification_failureMode",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL:"http_mtls_certificateVerification_crl",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_TIMEOUT:"http_mtls_certificateVerification_crl_timeout",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_CACHETTL:"http_mtls_certificateVerification_crl_cacheTtl",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_FAILUREMODE:"http_mtls_certificateVerification_crl_failureMode",HTTP_MTLS_CERTIFICATEVERIFICATION_CRL_GRACEPERIOD:"http_mtls_certificateVerification_crl_gracePeriod",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP:"http_mtls_certificateVerification_ocsp",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_TIMEOUT:"http_mtls_certificateVerification_ocsp_timeout",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_CACHETTL:"http_mtls_certificateVerification_ocsp_cacheTtl",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_ERRORCACHETTL:"http_mtls_certificateVerification_ocsp_errorCacheTtl",HTTP_MTLS_CERTIFICATEVERIFICATION_OCSP_FAILUREMODE:"http_mtls_certificateVerification_ocsp_failureMode",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",HTTP_REQUESTQUEUELIMIT:"http_requestQueueLimit",HTTP_HTTP2:"http_http2",LICENSE_MODE:"license_mode",LICENSE_REGION:"license_region",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_CONSOLE:"logging_console",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_EXTERNAL_LEVEL:"logging_external_level",LOGGING_EXTERNAL_TAG:"logging_external_tag",LOGGING_EXTERNAL_PATH:"logging_external_path",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_ROTATION_RETENTION:"logging_rotation_retention",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_NETWORK_HTTP2:"operationsApi_network_http2",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",OPERATIONSAPI_SYSINFO_NETWORK:"operationsApi_sysInfo_network",OPERATIONSAPI_SYSINFO_DISK:"operationsApi_sysInfo_disk",REPLICATION:"replication",REPLICATION_HOSTNAME:"replication_hostname",REPLICATION_URL:"replication_url",REPLICATION_PORT:"replication_port",REPLICATION_SECUREPORT:"replication_securePort",REPLICATION_ROUTES:"replication_routes",REPLICATION_DATABASES:"replication_databases",REPLICATION_ENABLEROOTCAS:"replication_enableRootCAs",REPLICATION_MTLS_CERTIFICATEVERIFICATION:"replication_mtls_certificateVerification",REPLICATION_MTLS_CERTIFICATEVERIFICATION_FAILUREMODE:"replication_mtls_certificateVerification_failureMode",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL:"replication_mtls_certificateVerification_crl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_TIMEOUT:"replication_mtls_certificateVerification_crl_timeout",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_CACHETTL:"replication_mtls_certificateVerification_crl_cacheTtl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_FAILUREMODE:"replication_mtls_certificateVerification_crl_failureMode",REPLICATION_MTLS_CERTIFICATEVERIFICATION_CRL_GRACEPERIOD:"replication_mtls_certificateVerification_crl_gracePeriod",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP:"replication_mtls_certificateVerification_ocsp",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_TIMEOUT:"replication_mtls_certificateVerification_ocsp_timeout",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_CACHETTL:"replication_mtls_certificateVerification_ocsp_cacheTtl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_ERRORCACHETTL:"replication_mtls_certificateVerification_ocsp_errorCacheTtl",REPLICATION_MTLS_CERTIFICATEVERIFICATION_OCSP_FAILUREMODE:"replication_mtls_certificateVerification_ocsp_failureMode",REPLICATION_SHARD:"replication_shard",REPLICATION_BLOBTIMEOUT:"replication_blobTimeout",REPLICATION_FAILOVER:"replication_failOver",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_BLOBPATHS:"storage_blobPaths",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",STORAGE_RECLAMATION_THRESHOLD:"storage_reclamation_threshold",STORAGE_RECLAMATION_INTERVAL:"storage_reclamation_interval",STORAGE_RECLAMATION_EVICTIONFACTOR:"storage_reclamation_evictionFactor",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"},MM={settings_path:vM.SETTINGS_PATH_KEY,hdb_root_key:F.ROOTPATH,hdb_root:F.ROOTPATH,rootpath:F.ROOTPATH,server_port_key:F.OPERATIONSAPI_NETWORK_PORT,server_port:F.OPERATIONSAPI_NETWORK_PORT,cert_key:F.TLS_CERTIFICATE,certificate:F.TLS_CERTIFICATE,private_key_key:F.TLS_PRIVATEKEY,private_key:F.TLS_PRIVATEKEY,http_secure_enabled_key:F.OPERATIONSAPI_NETWORK_HTTPS,https_on:F.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:F.OPERATIONSAPI_NETWORK_CORS,cors_on:F.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:F.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:F.LOGGING_LEVEL,log_level:F.LOGGING_LEVEL,log_path_key:F.LOGGING_ROOT,log_path:F.LOGGING_ROOT,clustering_node_name_key:F.CLUSTERING_NODENAME,node_name:F.CLUSTERING_NODENAME,clustering_enabled_key:F.CLUSTERING_ENABLED,clustering:F.CLUSTERING_ENABLED,max_http_threads:F.THREADS_COUNT,max_hdb_processes:F.THREADS_COUNT,server_timeout_key:F.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:F.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:F.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:F.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:F.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:F.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:F.LOGGING_AUDITLOG,disable_transaction_log:F.LOGGING_AUDITLOG,operation_token_timeout_key:F.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:F.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:F.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:F.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:F.HTTP_PORT,custom_functions_port:F.HTTP_PORT,custom_functions_directory_key:F.COMPONENTSROOT,custom_functions_directory:F.COMPONENTSROOT,max_custom_function_processes:F.THREADS_COUNT,logging_console:F.LOGGING_CONSOLE,log_to_file:F.LOGGING_FILE,log_to_stdstreams:F.LOGGING_STDSTREAMS,local_studio_on:F.LOCALSTUDIO_ENABLED,clustering_port:F.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:F.CLUSTERING_USER,customfunctions_network_port:F.HTTP_PORT,customfunctions_tls_certificate:F.TLS_CERTIFICATE,customfunctions_network_cors:F.HTTP_CORS,customfunctions_network_corsaccesslist:F.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:F.HTTP_HEADERSTIMEOUT,customfunctions_network_https:F.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:F.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:F.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:F.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:F.HTTP_TIMEOUT,customfunctions_tls:F.TLS,http_threads:F.THREADS_COUNT,threads:F.THREADS_COUNT,threads_count:F.THREADS_COUNT,customfunctions_processes:F.THREADS_COUNT,customfunctions_root:F.COMPONENTSROOT,operationsapi_root:F.ROOTPATH};for(let e in F){let t=F[e];MM[t.toLowerCase()]=t}o5={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},a5={csv_file_load:"csv_file_load",csv_data_load:V.CSV_DATA_LOAD,csv_url_load:V.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"},Bb={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"},c5={VERSION_DEFAULT:"2.2.0"},l5={DEVELOPMENT:8192,DEFAULT:512},u5={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},d5=Symbol("metadata"),Fb="__clustering__",UM="__createdtime__",xM="__updatedtime__",f5={CREATED_TIME:UM,UPDATED_TIME:xM},m5=[UM,xM],p5=15984864e5,u_={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},kb={"<":"LESS","<=":"LESS_OR_EQ",">":"GREATER",">=":"GREATER_OR_EQ","...":"BETWEEN"},h5={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},E5=["*","%"],_5="func_val",d_={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Sm={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},f_={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",COMPONENT_STATUS_REQUEST:"component_status_request",COMPONENT_STATUS_RESPONSE:"component_status_response"},Hb={HTTP:"http"},g5="3.x.x",ai={SUCCESS:"success",FAILURE:"failure"},Fa={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"}});var Qc=M(($Ne,kM)=>{"use strict";var BM=require("minimist");kM.exports=S5;function S5(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=FM(process.env),n=FM(BM(process.argv))):(r=process.env,n=BM(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(S5,"assignCMDENVVariables");function FM(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(FM,"objKeysToLowerCase")});var ci=M(ts=>{"use strict";global.Resource=ts.Resource=void 0;global.tables=ts.tables={};global.databases=ts.databases={};global.getUser=ts.getUser=void 0;global.authenticateUser=ts.authenticateUser=void 0;global.server=ts.server={};global.contentTypes=ts.contentTypes=null;global.threads=ts.threads=[];global.logger={};global.RequestTarget=ts.RequestTarget=void 0;global.operation=ts.operation=void 0;ts._assignPackageExport=(e,t)=>{global[e]=ts[e]=t}});var Gb=M((YNe,HM)=>{if(__filename.endsWith("dev.js")&&!process.env.HARPER_SKIP_COMPILE){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n,basename:s}=require("node:path"),{existsSync:i,statSync:o,readFileSync:c,writeFileSync:l,unlinkSync:u}=require("node:fs"),{isMainThread:d}=require("node:worker_threads"),{spawnSync:f,spawn:m}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:p}=yt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],E="ts-build";if(d){let S=!1,y=!1;if(y=i(n(p,E))){let N=new Set;e.sync(h.map(I=>`${I}/**/*.ts`),{cwd:p}).forEach(I=>{let $=0,ee=0;try{N.add(I),$=o(n(p,I)).mtimeMs-5e3,ee=o(n(p,E,I.replace(/.ts$/,".js"))).mtimeMs}catch{}$>ee&&(S=!0)}),e.sync(h.map(I=>`${I}/**/*.js`),{cwd:n(p,E)}).forEach(I=>{if(!N.has(I.replace(/.js$/,".ts")))try{u(n(p,E,I))}catch{}})}else S=!0;if(S){console.log("Compiling TypeScript...");let N=f("npx",["tsc"],{cwd:p});if(N.stdout?.length&&console.log(N.stdout.toString()),N.stderr?.length&&console.log(N.stderr.toString()),y){let I=n(t(),"harperdb-tsc.pid"),$=!1;if(i(I))try{process.kill(+c(I,"utf8"),0),$=!0}catch{}if(!$){console.log("Starting background TypeScript compilation...");let ee=m("npx",["tsc","--watch"],{detached:!0,cwd:p,stdio:"ignore"});ee.on("error",G=>{console.error("Error trying to compile TypeScript",G)}),ee.pid&&l(I,String(ee.pid),"utf-8"),ee.unref()}}}}let g=HM.constructor,R=g._findPath;g._findPath=function(S,y,N){if(S.startsWith(".")&&!N&&y.length===1&&y[0].startsWith(p)&&!y[0].includes("node_modules")){let I=r(p,y[0]),$;I.startsWith(E)?$=n(p,r(E,I)):$=n(p,E,I),(S.endsWith(".js")||S.endsWith(".ts"))&&(S=S.slice(0,-3));let ee=n($,S),G=ee+".js";if(i(G))return G;if(s(ee).includes(".")&&i(ee))return ee}return R(S,y,N)}}});var Tm={};ye(Tm,{server:()=>Be});var GM,Be,Hr=se(()=>{GM=b(ci()),Be={};(0,GM._assignPackageExport)("server",Be)});var Yt=M((WNe,$M)=>{"use strict";var T5="__dbis__",y5="__txns__",R5="__environment_name__",b5="__dbi_defintion__",A5={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"},I5=["__createdtime__","__updatedtime__"],w5="\uFFFF",qM={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},N5=Object.values(qM);$M.exports={AUDIT_STORE_NAME:y5,INTERNAL_DBIS_NAME:T5,DBI_DEFINITION_NAME:b5,SEARCH_TYPES:A5,TIMESTAMP_NAMES:I5,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:R5,TRANSACTIONS_DBI_NAMES_ENUM:qM,TRANSACTIONS_DBIS:N5,OVERFLOW_MARKER:w5}});var Jr=M((zNe,XM)=>{"use strict";var VM=(H(),v(z)),KM=Yt(),YM={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},WM=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),zM={500:WM("There was an error processing your request."),400:"Invalid request"},C5=zM[YM.INTERNAL_SERVER_ERROR],O5={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},P5={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},L5={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),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:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},D5={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:"value is required",SEARCH_VALUE_TOO_LARGE:"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 ${KM.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${KM.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"},v5={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${VM.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),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 ${VM.INSERT_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"},jM={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"},M5={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:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_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:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},U5={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_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:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),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:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},x5={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},B5={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},F5={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},QM={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},JM={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:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},k5={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.",BAD_SSH_KEY_NAME:"SSH key name can only contain alphanumeric, dash and underscore characters"},H5={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},G5={...jM,...L5,...O5,...M5,...U5,...x5,...B5,...F5,...v5,...QM,...JM,...k5,...H5,...P5};XM.exports={CHECK_LOGS_WRAPPER:WM,HDB_ERROR_MSGS:G5,DEFAULT_ERROR_MSGS:zM,DEFAULT_ERROR_RESP:C5,HTTP_STATUS_CODES:YM,LMDB_ERRORS_ENUM:D5,AUTHENTICATION_ERROR_MSGS:jM,VALIDATION_ERROR_MSGS:QM,ITC_ERRORS:JM}});var oe=M(Ae=>{"use strict";var ka=require("path"),nU=require("fs-extra"),vn=J(),ZM=require("fs-extra"),m_=require("os"),q5=require("net"),$5=require("recursive-iterator"),Ir=(H(),v(z)),{PACKAGE_ROOT:V5}=yt(),eU=require("papaparse"),p_=require("moment"),{inspect:K5}=require("util"),tU=require("is-number"),Y5=require("minimist"),W5=require("https"),z5=require("http"),j5=/^((\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)))$/,Q5=require("util").promisify(setTimeout),J5="",X5=4,rU={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Ae.isEmpty=rs;Ae.isEmptyOrZeroLength=qi;Ae.arrayHasEmptyValues=t8;Ae.arrayHasEmptyOrZeroLengthValues=r8;Ae.buildFolderPath=n8;Ae.isBoolean=sU;Ae.errorizeMessage=Z5;Ae.stripFileExtension=i8;Ae.autoCast=o8;Ae.autoCastJSON=iU;Ae.autoCastJSONDeep=$b;Ae.removeDir=a8;Ae.compareVersions=c8;Ae.isCompatibleDataVersion=l8;Ae.escapeRawValue=u8;Ae.unescapeValue=d8;Ae.stringifyProps=f8;Ae.timeoutPromise=p8;Ae.isClusterOperation=E8;Ae.getClusterUser=g8;Ae.checkGlobalSchemaTable=_8;Ae.getHomeDir=aU;Ae.getPropsFilePath=m8;Ae.promisifyPapaParse=S8;Ae.removeBOM=cU;Ae.createEventPromise=T8;Ae.checkSchemaTableExist=y8;Ae.checkSchemaExists=lU;Ae.checkTableExists=uU;Ae.getStartOfTomorrowInSeconds=R8;Ae.getLimitKey=b8;Ae.isObject=s8;Ae.isNotEmptyAndHasValue=e8;Ae.autoCasterIsNumberCheck=oU;Ae.backtickASTSchemaItems=A8;Ae.isPortTaken=h8;Ae.createForkArgs=I8;Ae.autoCastBoolean=w8;Ae.asyncSetTimeout=Q5;Ae.getTableHashAttribute=N8;Ae.doesSchemaExist=C8;Ae.doesTableExist=O8;Ae.stringifyObj=P8;Ae.ms_to_time=L8;Ae.changeExtension=D8;Ae.getEnvCliRootPath=Vb;Ae.noBootFile=v8;Ae.httpRequest=M8;Ae.transformReq=U8;Ae.convertToMS=x8;Ae.PACKAGE_ROOT=V5;function Z5(e){return e instanceof Error?e:new Error(e)}a(Z5,"errorizeMessage");function rs(e){return e==null}a(rs,"isEmpty");function e8(e){return!rs(e)&&(e||e===0||e===""||sU(e))}a(e8,"isNotEmptyAndHasValue");function qi(e){return rs(e)||e.length===0||e.size===0}a(qi,"isEmptyOrZeroLength");function t8(e){if(rs(e))return!0;for(let t=0;t<e.length;t++)if(rs(e[t]))return!0;return!1}a(t8,"arrayHasEmptyValues");function r8(e){if(qi(e))return!0;for(let t=0;t<e.length;t++)if(qi(e[t]))return!0;return!1}a(r8,"arrayHasEmptyOrZeroLengthValues");function n8(...e){try{return e.join(ka.sep)}catch{console.error(e)}}a(n8,"buildFolderPath");function sU(e){return rs(e)?!1:e===!0||e===!1}a(sU,"isBoolean");function s8(e){return rs(e)?!1:typeof e=="object"}a(s8,"isObject");function i8(e){return qi(e)?J5:e.slice(0,-X5)}a(i8,"stripFileExtension");function o8(e){return rs(e)||e===""||typeof e!="string"?e:rU[e]!==void 0?rU[e]:oU(e)===!0?Number(e):j5.test(e)?new Date(e):e}a(o8,"autoCast");function iU(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(iU,"autoCastJSON");function $b(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=$b(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=$b(r);n!==r&&(e[t]=n)}return e}else return iU(e)}a($b,"autoCastJSONDeep");function oU(e){if(e.startsWith("0.")&&tU(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&tU(e))}a(oU,"autoCasterIsNumberCheck");async function a8(e){if(qi(e))throw new Error(`Directory path: ${e} does not exist`);try{await ZM.emptyDir(e),await ZM.remove(e)}catch(t){throw vn.error(`Error removing files in ${e} -- ${t}`),t}}a(a8,"removeDir");function c8(e,t){if(qi(e)){vn.info("Invalid current version sent as parameter.");return}if(qi(t)){vn.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("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(c8,"compareVersions");function l8(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(l8,"isCompatibleDataVersion");function u8(e){if(rs(e))return e;let t=String(e);return t==="."?Ir.UNICODE_PERIOD:t===".."?Ir.UNICODE_PERIOD+Ir.UNICODE_PERIOD:t.replace(Ir.FORWARD_SLASH_REGEX,Ir.UNICODE_FORWARD_SLASH)}a(u8,"escapeRawValue");function d8(e){if(rs(e))return e;let t=String(e);return t===Ir.UNICODE_PERIOD?".":t===Ir.UNICODE_PERIOD+Ir.UNICODE_PERIOD?"..":String(e).replace(Ir.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(d8,"unescapeValue");function f8(e,t){if(rs(e))return vn.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+m_.EOL}!qi(n)&&n[0]===";"?r+=" "+n+s+m_.EOL:qi(n)||(r+=n+"="+s+m_.EOL)}catch{vn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(f8,"stringifyProps");function aU(){let e;try{e=m_.homedir()}catch{e=process.env.HOME}return e}a(aU,"getHomeDir");function m8(){let e=ka.join(aU(),Ir.HDB_HOME_DIR_NAME,Ir.BOOT_PROPS_FILE_NAME);return nU.existsSync(e)||(e=ka.join(__dirname,"../","hdb_boot_properties.file")),e}a(m8,"getPropsFilePath");function p8(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(p8,"timeoutPromise");async function h8(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=q5.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(h8,"isPortTaken");function E8(e){try{return Ir.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){vn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(E8,"isClusterOperation");function _8(e,t){let r=(we(),v(ft)).getDatabases();if(!r[e])return h_.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return h_.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(_8,"checkGlobalSchemaTable");function g8(e,t){if(rs(t)){vn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(rs(e)||qi(e)){vn.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){vn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){vn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(g8,"getClusterUser");function S8(){eU.parsePromise=function(e,t,r){return new Promise(function(n,s){eU.parse(e,{header:!0,transformHeader:cU,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(S8,"promisifyPapaParse");function cU(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(cU,"removeBOM");function T8(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;vn.info(`Got cluster status event response: ${K5(s)}`);try{i.cancel()}catch{vn.error("Error trying to cancel timeout.")}n(s)})})}a(T8,"createEventPromise");function y8(e,t){let r=lU(e);if(r)return r;let n=uU(e,t);if(n)return n}a(y8,"checkSchemaTableExist");function lU(e){let{getDatabases:t}=(we(),v(ft));if(!t()[e])return h_.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(lU,"checkSchemaExists");function uU(e,t){let{getDatabases:r}=(we(),v(ft));if(!r()[e][t])return h_.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(uU,"checkTableExists");function R8(){let e=p_().utc().add(1,"d").startOf("d").unix(),t=p_().utc().unix();return e-t}a(R8,"getStartOfTomorrowInSeconds");function b8(){return p_().utc().format("DD-MM-YYYY")}a(b8,"getLimitKey");function A8(e){try{let t=new $5(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){vn.error("Got an error back ticking items."),vn.error(t)}}a(A8,"backtickASTSchemaItems");function I8(e){return[e]}a(I8,"createForkArgs");function w8(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(w8,"autoCastBoolean");function N8(e,t){let{getDatabases:r}=(we(),v(ft)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(N8,"getTableHashAttribute");function C8(e){let{getDatabases:t}=(we(),v(ft));return t()[e]!==void 0}a(C8,"doesSchemaExist");function O8(e,t){let{getDatabases:r}=(we(),v(ft));return r()[e]?.[t]!==void 0}a(O8,"doesTableExist");function P8(e){try{return JSON.stringify(e)}catch{return e}}a(P8,"stringifyObj");function L8(e){let t=p_.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(L8,"ms_to_time");function D8(e,t){let r=ka.basename(e,ka.extname(e));return ka.join(ka.dirname(e),r+t)}a(D8,"changeExtension");function Vb(){if(process.env[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Y5(process.argv);if(e[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ir.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(Vb,"getEnvCliRootPath");var qb;function v8(){if(qb)return qb;let e=Vb();if(Vb()&&nU.pathExistsSync(ka.join(e,Ir.HDB_CONFIG_FILE)))return qb=!0,!0}a(v8,"noBootFile");function M8(e,t){let r;return e.protocol==="http:"?r=z5:r=W5,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(M8,"httpRequest");function U8(e){if(!e.schema&&!e.database){e.schema=Ir.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(U8,"transformReq");function x8(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(x8,"convertToMS");var h_=Jr()});var Rt=M((XNe,_U)=>{"use strict";var Im=(H(),v(z)),B8=oe(),Mn=me(),wm=require("path"),F8=require("minimist"),dU=require("fs-extra"),fU=require("lodash");Mn.initSync();var{CONFIG_PARAMS:Ha,DATABASES_PARAM_CONFIG:ym,SYSTEM_SCHEMA_NAME:E_}=Im,Rm,bm,Am;function mU(){if(Rm!==void 0)return Rm;if(Mn.getHdbBasePath()!==void 0)return Rm=Mn.get(Ha.STORAGE_PATH)||wm.join(Mn.getHdbBasePath(),Im.DATABASES_DIR_NAME),Rm}a(mU,"getBaseSchemaPath");function pU(){if(bm!==void 0)return bm;if(Mn.getHdbBasePath()!==void 0)return bm=EU(E_),bm}a(pU,"getSystemSchemaPath");function hU(){if(Am!==void 0)return Am;if(Mn.getHdbBasePath()!==void 0)return Am=Mn.get(Im.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||wm.join(Mn.getHdbBasePath(),Im.TRANSACTIONS_DIR_NAME),Am}a(hU,"getTransactionAuditStoreBasePath");function k8(e,t){let r=Mn.get(Ha.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||wm.join(hU(),e.toString())}a(k8,"getTransactionAuditStorePath");function EU(e,t){e=e.toString(),t=t&&t.toString();let r=Mn.get(Im.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||wm.join(mU(),e)}a(EU,"getSchemaPath");function H8(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,F8(process.argv));let n=r[Ha.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!B8.isObject(n))throw o;i=n}for(let o of i){let c=o[E_];if(!c)continue;let l=Mn.get(Ha.DATABASES);l=l??{};let u=c?.tables?.[t]?.[ym.PATH];if(u)return fU.set(l,[E_,ym.TABLES,t,ym.PATH],u),Mn.setProperty(Ha.DATABASES,l),u;let d=c?.[ym.PATH];if(d)return fU.set(l,[E_,ym.PATH],d),Mn.setProperty(Ha.DATABASES,l),d}}let s=r[Ha.STORAGE_PATH.toUpperCase()];if(s){if(!dU.pathExistsSync(s))throw new Error(s+" does not exist");let i=wm.join(s,e);return dU.mkdirsSync(i),Mn.setProperty(Ha.STORAGE_PATH,s),i}return pU()}a(H8,"initSystemSchemaPaths");function G8(){Rm=void 0,bm=void 0,Am=void 0}a(G8,"resetPaths");_U.exports={getBaseSchemaPath:mU,getSystemSchemaPath:pU,getTransactionAuditStorePath:k8,getTransactionAuditStoreBasePath:hU,getSchemaPath:EU,initSystemSchemaPaths:H8,resetPaths:G8}});var Un=M((rCe,RU)=>{"use strict";var q8=Jr().LMDB_ERRORS_ENUM,eCe=require("lmdb"),$8=Yt(),tCe=require("buffer").Buffer,{OVERFLOW_MARKER:gU,MAX_SEARCH_KEY_LENGTH:__}=$8,SU=["number","string","symbol","boolean","bigint"];function V8(e){if(e=e?.primaryStore||e,!e)throw new Error(q8.ENV_REQUIRED)}a(V8,"validateEnv");function K8(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(K8,"stringifyData");function Y8(e){return e instanceof Date?e.valueOf():e}a(Y8,"convertKeyValueToWrite");function W8(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(SU.includes(typeof e))return e.length>__?[e.slice(0,__)+gU]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(SU.includes(typeof i))i.length>__?r.push(i.slice(0,__)+gU):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(W8,"getIndexedValues");var g_=0,TU=0;function yU(){TU=Date.now()-performance.now()}a(yU,"adjustStartTime");yU();var z8=6e4;setInterval(yU,z8).unref();function j8(){let e=performance.now()+TU;return e>g_?(g_=e,e):(g_+=488e-6,g_)}a(j8,"getNextMonotonicTime");RU.exports={validateEnv:V8,stringifyData:K8,convertKeyValueToWrite:Y8,getNextMonotonicTime:j8,getIndexedValues:W8}});var Nm=M((sCe,bU)=>{"use strict";var Q8=(H(),v(z)).OPERATIONS_ENUM,Kb=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=Q8.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};bU.exports=Kb});var _e=M((oCe,wU)=>{"use strict";var vu=Jr(),J8=(H(),v(z)),S_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),J().warn(`An HDB Error was created: ${this.stack}`),Error.captureStackTrace(this,AU),this.statusCode=n||vu.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(vu.DEFAULT_ERROR_MSGS[n]?vu.DEFAULT_ERROR_MSGS[n]:vu.DEFAULT_ERROR_MSGS[vu.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&&J()[s](i)}},Yb=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}},Wb=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function AU(e,t,r,n=J8.LOG_LEVELS.ERROR,s=null,i=!1){if(IU(e))return e;let o=new S_(e,t,r,n,s);return i&&delete o.stack,o}a(AU,"handleHDBError");function Mu(e){this.message=e}a(Mu,"Violation");Mu.prototype=Object.create(Error.prototype);Mu.prototype.constructor=Mu;Mu.prototype.toString=function(){return`${this.constructor.name}: ${this.message}`};var zb=class extends Mu{static{a(this,"AccessViolation")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};function IU(e){return e.__proto__.constructor.name===S_.name}a(IU,"isHDBError");wU.exports={isHDBError:IU,handleHDBError:AU,ClientError:Yb,ServerError:Wb,AccessViolation:zb,Violation:Mu,hdbErrors:vu}});var Cm=M((lCe,PU)=>{"use strict";var cCe=Nm(),T_=(H(),v(z)),jb=oe(),NU=J(),X8=require("uuid"),{handleHDBError:y_,hdbErrors:Z8}=_e(),{HDB_ERROR_MSGS:R_,HTTP_STATUS_CODES:b_}=Z8;PU.exports=CU;function CU(e,t,r){for(let s=0;s<t.length;s++)OU(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];eZ(i,r,e.operation)}}a(CU,"processRows");CU.validateAttribute=OU;function OU(e){if(Buffer.byteLength(String(e))>T_.INSERT_MAX_CHARACTER_SIZE)throw y_(new Error,R_.ATTR_NAME_LENGTH_ERR(e),b_.BAD_REQUEST,void 0,void 0,!0);if(jb.isEmptyOrZeroLength(e)||jb.isEmpty(e.trim()))throw y_(new Error,R_.ATTR_NAME_NULLISH_ERR,b_.BAD_REQUEST,void 0,void 0,!0)}a(OU,"validateAttribute");function eZ(e,t,r){if(!e.hasOwnProperty(t)||jb.isEmptyOrZeroLength(e[t])){if(r===T_.OPERATIONS_ENUM.INSERT||r===T_.OPERATIONS_ENUM.UPSERT){e[t]=X8.v4();return}throw NU.error("Update transaction aborted due to record with no hash value:",e),y_(new Error,R_.RECORD_MISSING_HASH_ERR,b_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>T_.INSERT_MAX_CHARACTER_SIZE)throw NU.error(e),y_(new Error,R_.HASH_VAL_LENGTH_ERR,b_.BAD_REQUEST,void 0,void 0,!0)}a(eZ,"validateHash")});function BU(e){Jb=e}function sZ(){nZ=setInterval(function(){for(let e of Qb)if(e.stale){let t=e.getContext()?.url;MU.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},rZ).unref()}var Xb,vU,MU,UU,xU,LU,Qb,tZ,Do,Om,DU,Jb,vo,A_,rZ,nZ,Pm=se(()=>{Xb=b(Un()),vU=b(_e()),MU=b(J()),UU=b(me());H();xU=b(oe()),LU=100,Qb=new Set,tZ=(0,xU.convertToMS)(UU.get(F.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,Do={CLOSED:0,OPEN:1,LINGERING:2};a(BU,"replicationConfirmation");vo=class e{static{a(this,"DatabaseTransaction")}#e;writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=Do.OPEN;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===Do.OPEN)return this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),Qb.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Qb.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Om&&!this.overloadChecked&&performance.now()-DU>tZ)throw new vU.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===Do.CLOSED)throw new Error("Can not use a transaction that is no longer open");if(this.open===Do.LINGERING){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||(0,Xb.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let f=this.validated;this.validated=this.writes.length;for(let p=f;p<this.validated;p++)this.writes[p]?.validate?.(this.timestamp);let m;for(let p=f;p<this.validated;p++){let h=this.writes[p];h&&(h.before||h.beforeIntermediate)&&(m=!0)}if(m)return(async()=>{try{for(let p=0;p<2;p++){let h;for(let E=f;E<this.validated;E++){let g=this.writes[E];if(!g)continue;let R=g[p===0?"before":"beforeIntermediate"];if(R){let S=R();h?h.push?h.push(S):h=[h,S]:h=S}}h&&await(h.push?Promise.all(h):h)}}catch(p){throw this.abort(),p}return this.commit(t)})()}catch(f){throw this.abort(),f}n||this.doneReadTxn(),this.open=t?.doneWriting?Do.LINGERING:Do.OPEN;let s,i=[],o=0;this.writes=this.writes.filter(f=>f);let c=a(f=>{f.commit(r,f.entry,n)},"doWrite"),l=a(()=>{let f=this.writes[o++];if(f)if(f.key){(n>0||!f.entry)&&(f.entry=f.store.getEntry(f.key));let m=f.store.ifVersion(f.key,f.entry?.version??null,l);s=s||m}else l();else for(let m of this.writes)c(m)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<LU>>n?l():s=this.writes[0].store.transaction(()=>{for(let f of this.writes)f.entry=f.store.getEntry(f.key),c(f);return!0})),s)return Om||(Om=s,DU=performance.now(),Om.then(()=>{Om=null})),s.then(f=>{if(f){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let m=this.writes[0].store.rootStore.databaseName,p=this.writes[this.writes.length-1];Jb&&p&&i.push(Jb(m,p.store.getEntry(p.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+LU/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let d={txnTime:r};if(this.next){let f=this.next?.commit(t);if(f?.then)return f?.then(m=>({txnTime:r,next:m}));d.next=f}return d}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=Do.CLOSED,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},A_=class extends vo{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Xb.getNextMonotonicTime)())}getReadTxn(){}},rZ=3e4;a(sZ,"startMonitoringTxns");sZ()});var FU,ns,Zb,Uu=se(()=>{FU=require("events"),ns=class extends FU.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new Zb;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)}},Zb=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}}}});function bt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===Do.OPEN&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new vo;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(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 l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var kU,Ga=se(()=>{kU=b(ci());Pm();a(bt,"transaction");(0,kU._assignPackageExport)("transaction",bt);bt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};bt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var tA={};ye(tA,{add:()=>I_,applyReverse:()=>HU,getRecordAtTime:()=>eA,rebuildUpdateBefore:()=>w_});function I_(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 w_(e,t,r){let n=null;for(let s in e)if(s in t){let i=t[s];if(i?.__op__){let o=e[s];if(o?.__op__)if(o.__op__===i.__op__)n||(n={}),n[s]=o;else throw new Error("Can not merge updates with different operations");else n||(n={}),n[s]=o,I_(n,s,i)}else r&&(n||(n={}),n[s]=i)}else n||(n={}),n[s]=e[s];return n}function HU(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=iZ[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=GU}}function eA(e,t,r){let n=r.rootStore.auditStore,s={...e.value},i=e.localTime;for(;i>t;){let l=n.get(i),u=At(l);switch(u.type){case"put":s=u.getValue(r);break;case"patch":HU(s,u.getValue(r));break;case"delete":s=null}i=u.previousLocalTime}let o={},c=0;for(let l in s)s[l]===GU&&(o[l]=!0,c++);for(;c>0&&i>0;){let l=n.get(i),u=At(l),d;switch(u.type){case"put":d=u.getValue(r);break;case"patch":d=u.getValue(r);break}for(let f in d)o[f]&&(s[f]=d[f],o[f]=!1,c--);i=u.previousLocalTime}if(c>0)for(let l in o)s[l]=null;return s}var iZ,GU,N_=se(()=>{$i();a(I_,"add");I_.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)};iZ={add:I_};a(w_,"rebuildUpdateBefore");a(HU,"applyReverse");GU={};a(eA,"getRecordAtTime")});var wr=M(O_=>{var C_=J();for(let e of["trace","debug","info","warn","error","fatal","notify"])C_.logsAtLevel(e)&&(O_[e]=C_[e]);O_.loggerWithTag=e=>C_.loggerWithTag(e,!0);O_.setLogLevel=C_.setLogLevel});var zU={};ye(zU,{parse:()=>sA,streamAsJSON:()=>Dm,stringify:()=>Jc});function Dm(e){return new rA({value:e})}function qU(e){return console.error(e),JSON.stringify(Lm(e))}function $U(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Jc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===YU)return WU(e);if(t.resolution)return t.resolution.then(()=>Jc(e));throw t}}function WU(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+=WU(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Jc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function sA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),cZ.test(e)?oZ.parse(e):JSON.parse(e)):null}var VU,nA,KU,oZ,aZ,YU,Lm,rA,cZ,iA=se(()=>{VU=require("stream"),nA=b(J()),KU=b(require("json-bigint-fixes")),oZ=(0,KU.default)({useNativeBigInt:!0}),aZ=1e4,YU={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw YU};({errorToString:Lm}=nA);a(Dm,"streamAsJSON");rA=class extends VU.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(;;){try{o=i.next(),o.then&&(yield o.then(c=>(o=c,""),c=>(nA.warn("Error serializing in stream",c),o={done:!1,value:{error:Lm(c)}},i={next:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:Lm(c)}},i={next:a(()=>({done:!0}),"next")}}if(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),qU)}catch(s){yield qU(s)}else yield Jc(t)}else yield Jc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);$U(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(Lm(t)),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>aZ?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 $U(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(Lm(r)),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(qU,"handleError");a($U,"when");a(Jc,"stringify");a(WU,"jsStringify");cZ=/[[,:]\s*-?\d{16,}/;a(sA,"parse")});var sx={};ye(sx,{asyncSerialization:()=>uA,contentTypes:()=>lA,findBestSerializer:()=>L_,getDeserializer:()=>Bo,hasAsyncSerialization:()=>dA,registerContentHandlers:()=>Um,serialize:()=>xm,serializeMessage:()=>xo,toCsvStream:()=>P_});function lZ(e){try{return e?.[0]===123?cA(e):e}catch{return e}}function Um(e){e.register(uZ,{serializers:[{regex:/^application\/json$/,serializer:Dm},{regex:/^application\/cbor$/,serializer:a(function(t){return new Xc.EncoderStream(Mm).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Zc.Readable.from((0,Vi.encodeIter)(t,Mm)):(0,Vi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),P_(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Vi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Xc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function L_(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 l of c){let[u,...d]=l.split(/\s*;\s*/),f=1,m={q:1};for(let h of d){let E=h.indexOf("=");m[h.substring(0,E)]=h.substring(E+1)}f=+m.q;let p=hn.get(u);if(p){let h=(p.q||1)*f;h>s&&(n=p,i=p.type||u,s=h,o=m)}}if(!n){if(r)throw new JU.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(hn.keys()).join(", "),406);n=hn.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function xm(e,t,r){let n=QU&&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||e instanceof Ms)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=L_(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&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),aA.default.warn?.(`Error serializing error ${t?.url||t}: ${l}`),l)),e.getColumns=c}let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Uo.createBrotliCompress)({params:{[Uo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Uo.constants.BROTLI_MODE_TEXT:Uo.constants.BROTLI_MODE_GENERIC,[Uo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>QU?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Uo.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function xo(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Mo=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=L_(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=vm(e);return Mo?.length>0?(Mo.length===1?Mo[0]:Promise.all(Mo)).then(()=>xo(e,t,!0)):n}finally{Mo=void 0}}function uA(e){if(Mo)Mo.push(e);else throw new Error("Unable to serialize asynchronously")}function dA(){return!!Mo}function dZ(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 mZ(e){return fZ.includes(e)}function pZ(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function Bo(e="",t=!1){let r=pZ(e),n=r.type&&hn.get(r.type)?.deserialize||hZ(r);return t?s=>dZ(s).then(n):n}function hZ(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!mZ(e.parameters.charset)&&aA.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return cA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function EZ(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)}}}}}function P_(e,t){let r=Zc.default.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 ex.Transform(n,s);return r.pipe(i)}var Vi,Xc,Uo,JU,Zc,XU,oA,ZU,aA,ex,tx,rx,vm,cA,Mm,hn,lA,jU,nx,uZ,QU,Mo,fZ,Fo=se(()=>{iA();Vi=require("msgpackr"),Xc=require("cbor-x"),Uo=require("zlib"),JU=b(_e()),Zc=b(require("stream"));Hr();XU=b(ci()),oA=b(me());H();ZU=b(require("yaml")),aA=b(wr());ss();ex=require("json2csv"),tx=b(require("fastify-plugin")),rx=oA.default.get(F.SERIALIZATION_BIGINT)!==!1,vm=rx?Jc:JSON.stringify,cA=rx?sA:JSON.parse,Mm={useRecords:!1,useToJSON:!0},hn=new Map,lA=hn;Be.contentTypes=lA;(0,XU._assignPackageExport)("contentTypes",lA);hn.set("application/json",{serializeStream:Dm,serialize:vm,deserialize(e){return cA(e)},q:.8});jU=new Xc.Encoder(Mm);hn.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Xc.EncoderStream(Mm).end(e)},serialize:jU.encode,deserialize:jU.decode,q:1});hn.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Zc.Readable.from((0,Vi.encodeIter)(e,Mm)):(0,Vi.pack)(e)},serialize:Vi.pack,deserialize:Vi.unpack,q:.9});hn.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),P_(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]),P_(e,e?.getColumns?.())},q:.1});hn.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return Zc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});hn.set("text/yaml",{serialize(e){return ZU.stringify(e,{aliasDuplicateObjects:!1})},q:.7});hn.set("text/event-stream",{serializeStream:a(function(e){return Zc.Readable.from(EZ(e,this.serialize))},"serializeStream"),serialize:a(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+`
2
2
  `),e.data){let r=e.data;typeof r=="object"&&(r=vm(r)),t+="data: "+r+`
3
3
  `}return e.id&&(t+="id: "+e.id+`
4
4
  `),e.retry&&(t+="retry: "+e.retry+`
@@ -12,7 +12,7 @@
12
12
  `),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
13
13
  `)},jie="certificate.pem",Qie="privateKey.pem",Jie="caCertificate.pem",Xie="natsCertificate.pem",Zie="natsCaCertificate.pem",Ot={DEFAULT:"default","DEFAULT-CA":"default-ca",SERVER:"server",CA:"ca","OPERATIONS-API":"operations-api","OPERATIONS-CA":"operations-ca"},eoe={tls_certificate:Ot.SERVER,tlsCertificateAuthority:Ot.CA,customFunctions_tls_certificate:Ot.SERVER,customFunctionsTlsCertificateAuthority:Ot.CA,operationsApi_tls_certificate:Ot["OPERATIONS-API"],operationsApiTlsCertificateAuthority:Ot["OPERATIONS-CA"]},toe={[Ot.SERVER]:2,[Ot.DEFAULT]:1},roe={[Ot["OPERATIONS-API"]]:3,[Ot.SERVER]:2,[Ot.DEFAULT]:1},noe={[Ot["OPERATIONS-API"]]:3,[Ot.SERVER]:2,[Ot.DEFAULT]:1},soe={[Ot["OPERATIONS-CA"]]:3,[Ot.CA]:2,[Ot["DEFAULT-CA"]]:1},ioe={[Ot["OPERATIONS-CA"]]:3,[Ot.CA]:2,[Ot["DEFAULT-CA"]]:1},ooe={[Ot.CA]:2,[Ot["DEFAULT-CA"]]:1};Sn.CERTIFICATE_PEM_NAME=jie;Sn.PRIVATEKEY_PEM_NAME=Qie;Sn.CA_PEM_NAME=Jie;Sn.CERT_NAME=Ot;Sn.CERT_CONFIG_NAME_MAP=eoe;Sn.CERT_PREFERENCE_APP=toe;Sn.CERT_PREFERENCE_OPS=roe;Sn.CERT_PREFERENCE_REP=noe;Sn.CA_CERT_PREFERENCE_REP=soe;Sn.CA_CERT_PREFERENCE_OPS=ioe;Sn.CA_CERT_PREFERENCE_APP=ooe;Sn.CERTIFICATE_VALUES=zie;Sn.NATS_CERTIFICATE_PEM_NAME=Xie;Sn.NATS_CA_PEM_NAME=Zie});var Ww=M((Eve,nG)=>{"use strict";var tG=require("fs-extra"),Se=require("joi"),aoe=require("os"),{boolean:We,string:_t,number:dr,array:tc}=Se.types(),{totalmem:XH}=require("os"),Ol=require("path"),coe=J(),Yw=oe(),hve=Kw(),ZH=(H(),v(z)),loe=mt(),eG="log",uoe="components",doe="Invalid logging.rotation.maxSize unit. Available units are G, M or K",foe="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",moe="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",poe="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",hoe="rootPath config parameter is undefined",Yn=Se.alternatives([dr.min(0),_t]).optional().empty(null),Wg=Se.alternatives([tc.items(_t,{host:_t.required(),port:Yn},{hostname:_t.required(),port:Yn}).empty(null),tc.items(_t)]),so,rG=!1;nG.exports={configValidator:Eoe,routesValidator:Roe,routeConstraints:Wg};function Eoe(e,t=!1){if(rG=t,so=e.rootPath,Yw.isEmpty(so))throw hoe;let r=We.optional(),n=dr.min(0).max(1e3).empty(null).default(yoe),s=_t.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Cp),i=_t.optional().empty(null),o=_t.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=Se.string().empty(null).default(Cp),l=Se.custom(goe).empty(null).default(Cp),u=e.clustering?.enabled,d=Se.object({certificate:i,certificateAuthority:i,privateKey:i}),f;return u===!0?f=Se.object({enabled:r,hubServer:Se.object({cluster:Se.object({name:Se.required().empty(null),network:Se.object({port:Yn,routes:Wg}).required()}).required(),leafNodes:Se.object({network:Se.object({port:Yn}).required()}).required(),network:Se.object({port:Yn}).required()}).required(),leafServer:Se.object({network:Se.object({port:Yn,routes:Wg}).required(),streams:Se.object({maxAge:dr.min(120).allow(null).optional(),maxBytes:dr.min(1).allow(null).optional(),maxMsgs:dr.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:Se.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:We.optional(),databaseLevel:We.optional(),tls:Se.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:We.required(),verify:We.optional()}),user:_t.optional().empty(null)}).optional():f=Se.object({enabled:r,tls:Se.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:We.optional()})}).optional(),Se.object({authentication:Se.alternatives(Se.object({authorizeLocal:We,cacheTTL:dr.required(),cookie:Se.object({domains:tc.items(_t).optional(),expires:_t.optional()}),enableSessions:We,hashFunction:_t.valid("md5","sha256","argon2id").optional().empty(null)}),We).optional(),analytics:Se.object({aggregatePeriod:dr,replicate:We.optional()}),replication:Se.object({hostname:Se.alternatives(_t,dr).optional().empty(null),url:_t.optional().empty(null),port:Yn,securePort:Yn,routes:tc.optional().empty(null),databases:Se.alternatives(_t,tc),enableRootCAs:We.optional(),copyTablesToCatchUp:We.optional()}).optional(),componentsRoot:s.optional(),clustering:f,localStudio:Se.object({enabled:r}).required(),logging:Se.object({auditAuthEvents:Se.object({logFailed:We,logSuccessful:We}),file:We.required(),level:Se.valid("notify","fatal","error","warn","info","debug","trace"),rotation:Se.object({enabled:We.optional(),compress:We.optional(),interval:_t.custom(Toe).optional().empty(null),maxSize:_t.custom(Soe).optional().empty(null),path:_t.optional().empty(null).default(Cp)}).required(),root:s,stdStreams:We.required(),auditLog:We.required()}).required(),operationsApi:Se.object({network:Se.object({cors:We.optional(),corsAccessList:tc.optional(),headersTimeout:dr.min(1).optional(),keepAliveTimeout:dr.min(1).optional(),port:Yn,domainSocket:Se.optional().empty("hdb/operations-server").default(Cp),securePort:Yn,timeout:dr.min(1).optional()}).optional(),tls:Se.alternatives([Se.array().items(d),d])}).required(),rootPath:_t.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:Se.object({network:Se.object({port:Yn,securePort:Yn,mtls:Se.alternatives([We.optional(),Se.object({user:_t.optional(),certificateAuthority:i,required:We.optional()})])}).required(),webSocket:We.optional(),requireAuthentication:We.optional()}),http:Se.object({compressionThreshold:dr.optional(),cors:We.optional(),corsAccessList:tc.optional(),headersTimeout:dr.min(1).optional(),port:Yn,securePort:Yn,maxHeaderSize:dr.optional(),mtls:Se.alternatives([We.optional(),Se.object({user:_t.optional(),certificateAuthority:i,required:We.optional()})]),threadRange:Se.alternatives([tc.optional(),_t.optional()])}).required(),threads:Se.alternatives(n.optional(),Se.object({count:n.optional(),debug:Se.alternatives(We.optional(),Se.object({startingPort:dr.min(1).optional(),host:_t.optional(),waitForDebugger:We.optional()})),maxHeapMemory:dr.min(0).optional()})),storage:Se.object({writeAsync:We.required(),overlappingSync:We.optional(),caching:We.optional(),compression:Se.alternatives([We.optional(),Se.object({dictionary:_t.optional(),threshold:dr.optional()})]),compactOnStart:We.optional(),compactOnStartKeepBackup:We.optional(),noReadAhead:We.optional(),path:l,prefetchWrites:We.optional(),maxFreeSpaceToLoad:dr.optional(),maxFreeSpaceToRetain:dr.optional()}).required(),ignoreScripts:We.optional(),tls:Se.alternatives([Se.array().items(d),d])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Eoe,"configValidator");function _oe(e){return rG||tG.existsSync(e)?null:`Specified path ${e} does not exist.`}a(_oe,"doesPathExist");function goe(e,t){Se.assert(e,_t.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=_oe(e);if(r)return t.message(r)}a(goe,"validatePath");function Soe(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(doe);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(moe):e}a(Soe,"validateRotationMaxSize");function Toe(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(foe);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(poe):e}a(Toe,"validateRotationInterval");function yoe(e,t){let r=t.state.path.join("."),n=aoe.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||XH();return i=Math.round(Math.min(i,XH())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),coe.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(yoe,"setDefaultThreads");function Cp(e,t){let r=t.state.path.join(".");if(!Yw.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(Yw.isEmpty(so))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Ol.join(so,uoe);case"logging.root":return Ol.join(so,eG);case"clustering.leafServer.streams.path":return Ol.join(so,"clustering","leaf");case"storage.path":let n=Ol.join(so,ZH.LEGACY_DATABASES_DIR_NAME);return tG.existsSync(n)?n:Ol.join(so,ZH.DATABASES_DIR_NAME);case"logging.rotation.path":return Ol.join(so,eG);case"operationsApi.network.domainSocket":return r==null?null:Ol.join(so,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Cp,"setDefaultRoot");function Roe(e){let t=Se.object({routes:Wg});return loe.validateBySchema({routes:e},t)}a(Roe,"routesValidator")});var gt=M(nr=>{"use strict";var Hs=(H(),v(z)),Cr=oe(),fr=J(),{configValidator:boe,routesValidator:sG}=Ww(),Tn=require("fs-extra"),oG=require("yaml"),hs=require("path"),Aoe=require("is-number"),aG=require("properties-reader"),Ioe=require("lodash"),{handleHDBError:woe}=_e(),{HTTP_STATUS_CODES:Noe,HDB_ERROR_MSGS:pd}=Jr(),{server:Coe}=(Hr(),v(Tm)),{PACKAGE_ROOT:cG}=yt(),{DATABASES_PARAM_CONFIG:Op,CONFIG_PARAMS:ps,CONFIG_PARAM_MAP:Ei}=Hs,Ooe="Unable to get config value because config is uninitialized",Poe="Config successfully initialized",Loe="Error backing up config file",Doe="Empty parameter sent to getConfigValue",lG=hs.join(cG,"config","yaml",Hs.HDB_DEFAULT_CONFIG_FILE),voe=hs.join(cG,"config","yaml","defaultNatsConfig.yaml"),Moe="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",iG={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"},zg,Ft,jg;nr.createConfigFile=Uoe;nr.getDefaultConfig=xoe;nr.getConfigValue=dG;nr.initConfig=Qg;nr.flattenConfig=hd;nr.updateConfigValue=fG;nr.updateConfigObject=Foe;nr.getConfiguration=Goe;nr.setConfiguration=qoe;nr.readConfigFile=Jw;nr.getClusteringRoutes=$oe;nr.initOldConfig=mG;nr.getConfigFromFile=Voe;nr.getConfigFilePath=Pl;nr.addConfig=Koe;nr.deleteConfigFromFile=Yoe;nr.getConfigObj=Woe;nr.resolvePath=zw;nr.getFlatConfigObj=zoe;function zw(e){if(e?.startsWith("~/"))return hs.join(Cr.getHomeDir(),e.slice(1));let t=me();try{return hs.resolve(t.getHdbBasePath(),e)}catch(r){return console.error("Unable to resolve path",e,r),e}}a(zw,"resolvePath");function Uoe(e,t=!1){let r=rc(lG);if(e.clustering_enabled||e.CLUSTERING_ENABLED||e.clustering){let c=oG.parseDocument(Tn.readFileSync(voe,"utf8"),{simpleKeys:!0});r.addIn(["clustering"],c.toJSON().clustering)}zg=hd(r.toJSON());let n;for(let c in e){let l=Ei[c.toLowerCase()];if(l===ps.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(u=>({[u]:e[c][u]}));continue}if(!l&&(c.endsWith("_package")||c.endsWith("_port"))&&(l=c),l!==void 0){let u=l.split("_"),d=jw(l,e[c]);l==="rootPath"&&d?.endsWith("/")&&(d=d.slice(0,-1));try{u.length>1&&typeof r.getIn(u.slice(0,-1))=="boolean"&&r.deleteIn(u.slice(0,-1)),r.setIn([...u],d)}catch(f){fr.error(f)}}}n&&uG(r,n),Qw(r,t);let s=r.toJSON();Ft=hd(s);let i=r.getIn(["rootPath"]),o=hs.join(i,Hs.HDB_CONFIG_FILE);if(Tn.createFileSync(o),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);Tn.writeFileSync(o,String(r)),fr.trace(`Config file written to ${o}`)}a(Uoe,"createConfigFile");function uG(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Cr.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Op.TABLES))for(let i in n[s][Op.TABLES])for(let o in n[s][Op.TABLES][i]){let c=n[s][Op.TABLES][i][o],l=[ps.DATABASES,s,Op.TABLES,i,o];e.hasIn(l)?e.setIn(l,c):e.addIn(l,c)}else for(let i in n[s]){let o=n[s][i],c=[ps.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){fr.error("Error parsing schemas CLI/env config arguments",n)}}a(uG,"setSchemasConfig");function xoe(e){if(zg===void 0){let r=rc(lG);zg=hd(r.toJSON())}let t=Ei[e.toLowerCase()];if(t!==void 0)return zg[t.toLowerCase()]}a(xoe,"getDefaultConfig");function dG(e){if(e==null){fr.info(Doe);return}if(Ft===void 0){fr.trace(Ooe);return}let t=Ei[e.toLowerCase()];if(t!==void 0)return Ft[t.toLowerCase()]}a(dG,"getConfigValue");function Pl(e=Cr.getPropsFilePath()){let t=Cr.getEnvCliRootPath();if(t)return zw(hs.join(t,Hs.HDB_CONFIG_FILE));let r=aG(e);return zw(r.get(Hs.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}a(Pl,"getConfigFilePath");function Qg(e=!1){if(Ft===void 0||e){let t;if(!Cr.noBootFile()){t=Cr.getPropsFilePath();try{Tn.accessSync(t,Tn.constants.F_OK|Tn.constants.R_OK)}catch(i){throw fr.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Pl(t),n;if(r.includes("config/settings.js"))try{mG(r);return}catch(i){if(i.code!==Hs.NODE_ERROR_CODES.ENOENT)throw i}try{n=rc(r)}catch(i){if(i.code===Hs.NODE_ERROR_CODES.ENOENT){fr.trace(`HarperDB config file not found at ${r}.
14
14
  This can occur during early stages of install where the config file has not yet been created`);return}else throw fr.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Boe(n,r),Qw(n);let s=n.toJSON();if(Coe.config=s,Ft=hd(s),Ft.logging_rotation_rotate)for(let i in iG)Ft[i]&&fr.error(`Config ${iG[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);fr.trace(Poe)}}a(Qg,"initConfig");function Boe(e,t){let r=e.getIn(["rootPath"]),n=!1;if(e.hasIn(["storage","path"])||(e.setIn(["storage","path"],hs.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],hs.join(r,"log")),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,replicate:!1}),n=!0),n){if(fr.trace("Updating config file with missing config params"),e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${e.errors}`);Tn.writeFileSync(t,String(e))}}a(Boe,"checkForUpdatedConfig");function Qw(e,t=!1){let r=e.toJSON();if(r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads),r.http?.port&&r.http?.port===r.http?.securePort)throw pd.CONFIG_VALIDATION("http.port and http.securePort cannot be the same value");if(r.operationsApi?.network?.port&&r.operationsApi?.network?.port===r.operationsApi?.network?.securePort)throw pd.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=boe(r,t);if(n.error)throw pd.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(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket),r?.clustering?.enabled&&e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path)}a(Qw,"validateConfig");function Foe(e,t){Ft===void 0&&(Ft={});let r=Ei[e.toLowerCase()];if(r===void 0){fr.trace(`Unable to update config object because config param '${e}' does not exist`);return}Ft[r.toLowerCase()]=t}a(Foe,"updateConfigObject");function fG(e,t,r=void 0,n=!1,s=!1,i=!1){Ft===void 0&&Qg();let o=dG(Ei.hdb_root),c=hs.join(o,Hs.HDB_CONFIG_FILE),l=rc(c),u;if(r&&Ft){let m=!1;for(let p in r)if(r[p]!=Ft[p.toLowerCase()]){m=!0;break}if(!m){fr.trace("No changes detected in config parameters, skipping update");return}}if(r===void 0&&e.toLowerCase()===ps.DATABASES)u=t;else if(r===void 0){let m;if(i)m=e;else if(m=Ei[e.toLowerCase()],m===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let p=m.split("_"),h=jw(m,t);l.setIn([...p],h)}else for(let m in r){let p=Ei[m.toLowerCase()];if(p===ps.HTTP_SECUREPORT&&r[m]===Ft[ps.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),p===ps.OPERATIONSAPI_NETWORK_SECUREPORT&&r[m]===Ft[ps.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),p===ps.DATABASES){u=r[m];continue}if(p?.startsWith("threads_")){let h=l.getIn(["threads"]);h>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],h))}if(!p&&(m.endsWith("_package")||m.endsWith("_port"))&&(p=m),p!==void 0){let h=p.split("_"),E=Hs.LEGACY_CONFIG_PARAMS[m.toUpperCase()];E&&E.startsWith("customFunctions")&&l.hasIn(E.split("_"))&&(p=E,h=E.split("_"));let g=jw(p,r[m]);p==="rootPath"&&g?.endsWith("/")&&(g=g.slice(0,-1));try{h.length>1&&typeof l.getIn(h.slice(0,-1))=="boolean"&&l.deleteIn(h.slice(0,-1)),l.setIn([...h],g)}catch(R){fr.error(R)}}}u&&uG(l,u),Qw(l);let d=l.getIn(["rootPath"]),f=hs.join(d,Hs.HDB_CONFIG_FILE);if(n===!0&&koe(c,d),l.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${l.errors}`);Tn.writeFileSync(f,String(l)),s&&(Ft=hd(l.toJSON())),fr.trace(`Config parameter: ${e} updated with value: ${t}`)}a(fG,"updateConfigValue");function koe(e,t){try{let r=hs.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${Hs.HDB_CONFIG_FILE}.bak`);Tn.copySync(e,r),fr.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){fr.error(Loe),fr.error(r)}}a(koe,"backupConfigFile");var Hoe=["databases"];function hd(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network={...e.http,...e.operationsApi.network}),e?.operationsApi&&(e.operationsApi.tls={...e.tls,...e.operationsApi.tls}),jg=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])&&!Hoe.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!ps[l.toUpperCase()]&&Ei[l]&&(s[Ei[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(hd,"flattenConfig");function jw(e,t){if(e===ps.CLUSTERING_NODENAME||e===ps.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(Aoe(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Cr.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 Cr.autoCast(t)}a(jw,"castConfigValue");function Goe(){let e=Cr.getPropsFilePath(),t=Pl(e);return rc(t).toJSON()}a(Goe,"getConfiguration");async function qoe(e){let{operation:t,hdb_user:r,hdbAuthHeader:n,...s}=e;try{return fG(void 0,void 0,s,!0),Moe}catch(i){throw typeof i=="string"||i instanceof String?woe(i,i,Noe.BAD_REQUEST,void 0,void 0,!0):i}}a(qoe,"setConfiguration");function Jw(){let e=Cr.getPropsFilePath();try{Tn.accessSync(e,Tn.constants.F_OK|Tn.constants.R_OK)}catch(n){if(!Cr.noBootFile())throw fr.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Pl(e);return rc(t).toJSON()}a(Jw,"readConfigFile");function rc(e){return oG.parseDocument(Tn.readFileSync(e,"utf8"),{simpleKeys:!0})}a(rc,"parseYamlDoc");function $oe(){let e=Jw(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Cr.isEmptyOrZeroLength(t)?[]:t;let r=sG(t);if(r)throw pd.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Cr.isEmptyOrZeroLength(n)?[]:n;let s=sG(n);if(s)throw pd.CONFIG_VALIDATION(s.message);if(!Cr.isEmptyOrZeroLength(n)&&!Cr.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Cr.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw pd.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a($oe,"getClusteringRoutes");function mG(e){let t=aG(e);Ft={};for(let r in Ei){let n=t.get(r.toUpperCase());if(Cr.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ei[r].toLowerCase();s===ps.LOGGING_ROOT?Ft[s]=hs.dirname(n):Ft[s]=n}return Ft}a(mG,"initOldConfig");function Voe(e){let t=Jw();return Ioe.get(t,e.replaceAll("_","."))}a(Voe,"getConfigFromFile");async function Koe(e,t){let r=rc(Pl());if(r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);await Tn.writeFile(Pl(),String(r))}a(Koe,"addConfig");function Yoe(e){let t=Pl(Cr.getPropsFilePath()),r=rc(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=hs.join(n,Hs.HDB_CONFIG_FILE);Tn.writeFileSync(s,String(r))}a(Yoe,"deleteConfigFromFile");function Woe(){return jg||(Qg(),jg)}a(Woe,"getConfigObj");function zoe(){return Ft||Qg(),Ft}a(zoe,"getFlatConfigObj")});var Es=M((Tve,Vr)=>{"use strict";var EG="username is required",_G="nothing to update, must supply active, role or password to update",gG="password cannot be an empty string",SG="If role is specified, it cannot be empty.",TG="active must be true or false";Vr.exports.addUser=nae;Vr.exports.alterUser=sae;Vr.exports.dropUser=oae;Vr.exports.getSuperUser=dae;Vr.exports.userInfo=aae;Vr.exports.listUsers=Zg;Vr.exports.listUsersExternal=cae;Vr.exports.setUsersWithRolesCache=Ll;Vr.exports.findAndValidateUser=iN;Vr.exports.getClusterUser=fae;Vr.exports.getUsersWithRolesCache=uae;Vr.exports.USERNAME_REQUIRED=EG;Vr.exports.ALTERUSER_NOTHING_TO_UPDATE=_G;Vr.exports.EMPTY_PASSWORD=gG;Vr.exports.EMPTY_ROLE=SG;Vr.exports.ACTIVE_BOOLEAN=TG;var yG=Vn(),joe=Nl(),Pp=(Dw(),v(Lw)),RG=EH(),Lp=gn(),tN=Wo(),io=oe(),bG=require("validate.js"),rN=J(),{promisify:Qoe}=require("util"),nN=no(),Zw=(H(),v(z)),pG=Ct(),Joe=gt(),Xoe=me(),Zoe=Xi(),{hdbErrors:eae,ClientError:_i}=_e(),{HTTP_STATUS_CODES:Jo,AUTHENTICATION_ERROR_MSGS:Xw,HDB_ERROR_MSGS:Ed}=eae,{UserEventMsg:sN}=ls(),eN=require("lodash"),{server:Xg}=(Hr(),v(Tm)),tae=J();Xg.getUser=(e,t)=>iN(e,t,t!=null);Xg.authenticateUser=(e,t)=>iN(e,t);var AG={username:!0,active:!0,role:!0,password:!0},hG=new Map,rae=Qoe(joe.delete),Jg=Xoe.get(Zw.CONFIG_PARAMS.AUTHENTICATION_HASHFUNCTION)??Pp.HASH_FUNCTION.SHA256,oo;async function nae(e){let t=bG.cleanAttributes(e,AG),r=RG.addUserValidation(t);if(r)throw new _i(r.message);let n=await Lp.searchByValue({schema:"system",table:"hdb_role",attribute:"role",value:t.role,get_attributes:["id","permission","role"]});if(!n||n.length<1)throw new _i(Ed.ROLE_NAME_NOT_FOUND(t.role),Jo.NOT_FOUND);if(n.length>1)throw new _i(Ed.DUP_ROLES_FOUND(t.role),Jo.CONFLICT);n[0].permission.cluster_user===!0&&(t.hash=nN.encrypt(t.password)),t.password=await Pp.hash(t.password,Jg),t.hash_function=Jg,t.role=n[0].id;let s=await yG.insert({operation:"insert",schema:"system",table:"hdb_user",records:[t]});if(rN.debug(s),await Ll(),s.skipped_hashes.length===1)throw new _i(Ed.USER_ALREADY_EXISTS(t.username),Jo.CONFLICT);return tN.signalUserChange(new sN(process.pid)),`${t.username} successfully added`}a(nae,"addUser");async function sae(e){let t=bG.cleanAttributes(e,AG);if(io.isEmptyOrZeroLength(t.username))throw new Error(EG);if(io.isEmptyOrZeroLength(t.password)&&io.isEmptyOrZeroLength(t.role)&&io.isEmptyOrZeroLength(t.active))throw new Error(_G);if(!io.isEmpty(t.password)&&io.isEmptyOrZeroLength(t.password.trim()))throw new Error(gG);if(!io.isEmpty(t.active)&&!io.isBoolean(t.active))throw new Error(TG);if(!io.isEmpty(t.password)&&!io.isEmptyOrZeroLength(t.password.trim())&&(iae(t.username)&&(t.hash=nN.encrypt(t.password)),t.password=await Pp.hash(t.password,Jg),t.hash_function=Jg),t.role==="")throw new Error(SG);if(t.role){let n=await Lp.searchByValue({schema:"system",table:"hdb_role",attribute:"role",value:t.role,get_attributes:["*"]});if(!n||n.length===0)throw new _i(Ed.ALTER_USER_ROLE_NOT_FOUND(t.role),Jo.NOT_FOUND);if(n.length>1)throw new _i(Ed.DUP_ROLES_FOUND(t.role),Jo.CONFLICT);t.role=n[0].id}let r=await yG.update({operation:"update",schema:"system",table:"hdb_user",records:[t]});return await Ll(),tN.signalUserChange(new sN(process.pid)),r}a(sae,"alterUser");function iae(e){let t=!1,r=oo.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(iae,"isClusterUser");async function oae(e){let t=RG.dropUserValidation(e);if(t)throw new _i(t.message);if(oo.get(e.username)===void 0)throw new _i(Ed.USER_NOT_EXIST(e.username),Jo.NOT_FOUND);let r=await rae({table:"hdb_user",schema:"system",hash_values:[e.username]});return rN.debug(r),await Ll(),tN.signalUserChange(new sN(process.pid)),`${e.username} successfully deleted`}a(oae,"dropUser");async function aae(e){let t={};if(!e||!e.hdb_user)return"There was no user info in the body";t=eN.cloneDeep(e.hdb_user);let r=await Lp.searchByHash({schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]});return t.role=r[0],delete t.password,delete t.refresh_token,delete t.hash,delete t.hash_function,t}a(aae,"userInfo");async function cae(){let e=await Zg();return e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token,delete t.hash_function}),[...e.values()]}a(cae,"listUsersExternal");async function Zg(){let e=await Lp.searchByValue({schema:"system",table:"hdb_role",value:"*",attribute:"role",get_attributes:["*"]}),t={};for(let s of e)t[s.id]=eN.cloneDeep(s);if(Object.keys(t).length===0)return null;let r=await Lp.searchByValue({schema:"system",table:"hdb_user",value:"*",attribute:"username",get_attributes:["*"]}),n=new Map;for(let s of r)s=eN.cloneDeep(s),s.role=t[s.role],lae(s.role),n.set(s.username,s);return n}a(Zg,"listUsers");function lae(e){if(!e){rN.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(Zoe)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}a(lae,"appendSystemTablesToRole");async function Ll(e=void 0){e?oo=e:oo=await Zg()}a(Ll,"setUsersWithRolesCache");async function uae(){return oo||await Ll(),oo}a(uae,"getUsersWithRolesCache");async function iN(e,t,r=!0){oo||await Ll();let n=oo.get(e);if(!n){if(!r)return{username:e};throw new _i(Xw.GENERIC_AUTH_FAIL,Jo.UNAUTHORIZED)}if(n&&!n.active)throw new _i(Xw.USER_INACTIVE,Jo.UNAUTHORIZED);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(hG.get(t)===n.password)return s;{let i=Pp.validate(n.password,t,n.hash_function||Pp.HASH_FUNCTION.MD5);if(i?.then&&(i=await i),i===!0)hG.set(t,n.password);else throw new _i(Xw.GENERIC_AUTH_FAIL,Jo.UNAUTHORIZED)}}return s}a(iN,"findAndValidateUser");async function dae(){oo||await Ll();for(let[,e]of oo)if(e.role.role==="super_user")return e}a(dae,"getSuperUser");async function fae(){let e=await Zg(),t=Joe.getConfigFromFile(Zw.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!(r==null||r?.role?.role!==Zw.ROLE_TYPES_ENUM.CLUSTER_USER))return r.decrypt_hash=nN.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+pG.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+pG.SERVER_SUFFIX.ADMIN,r}a(fae,"getClusterUser");var IG=[];Xg.invalidateUser=function(e){for(let t of IG)try{t(e)}catch(r){tae.error("Error invalidating user",r)}};Xg.onInvalidatedUser=function(e){IG.push(e)}});var Ne,_d=se(()=>{Ne={HEALTHY:"healthy",WARNING:"warning",ERROR:"error",UNKNOWN:"unknown",LOADING:"loading"}});var gd,oN=se(()=>{_d();gd=class{static{a(this,"ComponentStatus")}lastChecked;status;message;error;constructor(t,r,n){this.lastChecked=new Date,this.status=t,this.message=r,this.error=n}updateStatus(t,r){this.status=t,this.message=r,this.lastChecked=new Date,t!==Ne.ERROR&&(this.error=void 0)}markHealthy(t){this.updateStatus(Ne.HEALTHY,t||"Component is healthy")}markError(t,r){this.status=Ne.ERROR,this.error=t,this.message=r||(typeof t=="string"?t:t.message),this.lastChecked=new Date}markWarning(t){this.updateStatus(Ne.WARNING,t)}markLoading(t){this.updateStatus(Ne.LOADING,t||"Component is loading")}isHealthy(){return this.status===Ne.HEALTHY}hasError(){return this.status===Ne.ERROR}isLoading(){return this.status===Ne.LOADING}hasWarning(){return this.status===Ne.WARNING}getSummary(){let t=this.status.toUpperCase(),r=this.message?`: ${this.message}`:"";return`${t}${r}`}}});var Dl,nc,aN,Sd,cN,Td,lN,eS=se(()=>{Dl=b(Jr()),nc=class extends Error{static{a(this,"ComponentStatusError")}statusCode;timestamp;constructor(t,r=Dl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR){super(t),this.name="ComponentStatusError",this.statusCode=r,this.timestamp=new Date,Error.captureStackTrace(this,this.constructor)}},aN=class extends nc{static{a(this,"CrossThreadTimeoutError")}requestId;timeoutMs;collectedCount;constructor(t,r,n){super(`Component status collection timeout after ${r}ms. Collected ${n} responses for request ${t}.`,Dl.HTTP_STATUS_CODES.GATEWAY_TIMEOUT),this.name="CrossThreadTimeoutError",this.requestId=t,this.timeoutMs=r,this.collectedCount=n}},Sd=class extends nc{static{a(this,"ITCError")}operation;cause;constructor(t,r){super(`Inter-thread communication failed during ${t}: ${r?.message||"Unknown error"}`,Dl.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE),this.name="ITCError",this.operation=t,this.cause=r}},cN=class extends nc{static{a(this,"AggregationError")}componentCount;cause;constructor(t,r){super(`Failed to aggregate status for ${t} components: ${r?.message||"Unknown error"}`,Dl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="AggregationError",this.componentCount=t,this.cause=r}},Td=class extends nc{static{a(this,"ComponentStatusOperationError")}componentName;operation;constructor(t,r,n){super(`Component '${t}' ${r} failed: ${n}`,Dl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="ComponentStatusOperationError",this.componentName=t,this.operation=r}},lN=class extends nc{static{a(this,"CrossThreadCollectionError")}result;constructor(t){let r=t.success?`Partial collection success: ${t.collectedFromThreads} threads responded`+(t.timedOutThreads.length>0?`, ${t.timedOutThreads.length} timed out`:""):`Collection failed: ${t.errors.map(n=>n.message).join(", ")}`;super(r,Dl.HTTP_STATUS_CODES.OK),this.name="CrossThreadCollectionError",this.result=t}getDiagnostics(){let t=[`Cross-thread collection ${this.result.success?"partially succeeded":"failed"}`,`Threads responded: ${this.result.collectedFromThreads}`];return this.result.expectedThreads&&t.push(`Expected threads: ${this.result.expectedThreads}`),this.result.timedOutThreads.length>0&&t.push(`Timed out threads: ${this.result.timedOutThreads.join(", ")}`),this.result.errors.length>0&&(t.push("Errors:"),this.result.errors.forEach((r,n)=>{t.push(` ${n+1}. ${r.name}: ${r.message}`)})),t.join(`
15
- `)}}});var wG,vl,NG,sc,Dp,yd,mae,tS,uN=se(()=>{wG=b(ls()),vl=b(st());H();NG=b(wr());_d();eS();sc=(0,NG.loggerWithTag)("componentStatus.crossThread"),Dp=class{static{a(this,"CrossThreadStatusCollector")}awaitingResponses=new Map;responseCheckers=new Map;nextRequestId=1;listenerAttached=!1;timeout;cleanupTimer=null;constructor(t=5e3){this.timeout=t}attachListener(){this.listenerAttached||((0,vl.onMessageByType)(f_.COMPONENT_STATUS_RESPONSE,({message:t})=>{let r=t.isMainThread?"main":`worker-${t.workerIndex}`;sc.trace?.("Received component status response from %s, with requestId: %d",r,t.requestId);let n=this.awaitingResponses.get(t.requestId);if(n){n.push({workerIndex:t.workerIndex,isMainThread:t.isMainThread||!1,statuses:t.statuses||[]});let s=this.responseCheckers.get(t.requestId);s&&s()}}),this.listenerAttached=!0)}scheduleCleanup(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.awaitingResponses.size>0&&(this.cleanupTimer=setTimeout(()=>{this.awaitingResponses.size>0&&(sc.debug?.(`Cleaning up ${this.awaitingResponses.size} stale pending requests`),this.awaitingResponses.clear()),this.cleanupTimer=null},3e4))}async collect(t){try{this.attachListener(),this.scheduleCleanup();let r=this.nextRequestId++,n=[];this.awaitingResponses.set(r,n);let o=((0,vl.getWorkerCount)()||1)+1-1,l=await new Promise((p,h)=>{let E=!1,g=a(()=>{let y=this.awaitingResponses.get(r);y&&y.length>=o&&!E&&(E=!0,S(),sc.trace?.(`Collected all ${y.length} expected responses for request ${r}`),p(y))},"checkComplete"),R=setTimeout(()=>{if(!E){E=!0;let y=this.awaitingResponses.get(r)||[];this.awaitingResponses.delete(r),sc.debug?.(`Collection timeout for request ${r}: collected ${y.length}/${o} responses`),p(y)}},this.timeout),S=a(()=>{this.awaitingResponses.delete(r),clearTimeout(R)},"cleanup");this.responseCheckers.set(r,g),(0,wG.sendItcEvent)({type:f_.COMPONENT_STATUS_REQUEST,message:{requestId:r}}).then(()=>{g()}).catch(y=>{E=!0,S(),this.responseCheckers.delete(r),h(new Sd("sendItcEvent",y))})});this.responseCheckers.delete(r);let u=new Map,d=t.getAllStatuses(),f=(0,vl.getWorkerIndex)(),m=f===void 0?"main":`worker-${f}`;for(let[p,h]of d)u.set(`${p}@${m}`,{...h,workerIndex:f});for(let p of l)for(let[h,E]of p.statuses){let g=p.isMainThread?"main":`worker-${p.workerIndex}`;u.set(`${h}@${g}`,{...E,workerIndex:p.workerIndex})}return sc.debug?.(`Collected component status from ${l.length+1} threads (including local)`),u}catch(r){return r instanceof Sd?sc.error?.(`ITC failure during component status collection: ${r.message}`):sc.warn?.("Failed to collect component status from all threads:",r),sc.debug?.(`Collection failed for request. Error: ${r instanceof Error?r.message:"Unknown error"}`),this.getLocalStatusOnly(t)}}getLocalStatusOnly(t){let r=t.getAllStatuses(),n=new Map,s=(0,vl.getWorkerIndex)(),i=s===void 0?"main":`worker-${s}`;for(let[o,c]of r)n.set(`${o}@${i}`,{...c,workerIndex:s});return n}cleanup(){this.awaitingResponses.clear(),this.responseCheckers.clear(),this.cleanupTimer&&(clearTimeout(this.cleanupTimer),this.cleanupTimer=null)}},yd=class{static{a(this,"StatusAggregator")}static aggregate(t){let r=new Map,n=new Map;for(let[s,i]of t){let o=s.indexOf("@"),c=o!==-1?s.substring(0,o):s,l=n.get(c);l||(l=[],n.set(c,l)),l.push([s,i])}for(let[s,i]of n){let o=this.aggregateComponentGroup(s,i);r.set(s,o)}return r}static aggregateComponentGroup(t,r){let n={workers:{}},s=0,i,o,c=new Map,l=new Map;for(let[m,p]of r){let h=m.lastIndexOf("@"),E=h!==-1?m.substring(h+1):"",g=p.lastChecked instanceof Date?p.lastChecked.getTime():new Date(p.lastChecked).getTime();if(E==="main")n.main=g;else if(E&&E.startsWith("worker-")){let R=parseInt(E.substring(7));isNaN(R)||(n.workers[R]=g)}c.set(p.status,(c.get(p.status)||0)+1),p.status!==Ne.HEALTHY&&p.message&&(!i||g>s)&&(s=g,i=p.message),p.error&&!o&&(o=p.error)}let u=this.determineOverallStatus(c);if(Array.from(c.keys()).length>1)for(let[m,p]of r)p.status!==u&&l.set(m,{workerIndex:p.workerIndex!==void 0?p.workerIndex:-1,status:p.status,message:p.message,error:p.error});let f={componentName:t,status:u,lastChecked:n,latestMessage:i,error:o};return l.size>0&&(f.abnormalities=l),f}static determineOverallStatus(t){let r=[Ne.ERROR,Ne.WARNING,Ne.LOADING,Ne.UNKNOWN,Ne.HEALTHY];for(let n of r)if(t.has(n)&&t.get(n)>0)return n;return Ne.UNKNOWN}},mae=parseInt(process.env.COMPONENT_STATUS_TIMEOUT||"5000"),tS=new Dp(mae)});var ic,rS=se(()=>{oN();_d();uN();eS();ic=class e{static{a(this,"ComponentStatusRegistry")}statusMap=new Map;reset(){this.statusMap=new Map}setStatus(t,r,n,s){if(!t||typeof t!="string")throw new Td(String(t),"setStatus","Component name must be a non-empty string");if(!Object.values(Ne).includes(r))throw new Td(t,"setStatus",`Invalid status level: ${r}. Must be one of: ${Object.values(Ne).join(", ")}`);this.statusMap.set(t,new gd(r,n,s))}getStatus(t){return this.statusMap.get(t)}getAllStatuses(){return this.statusMap}reportHealthy(t,r){this.setStatus(t,Ne.HEALTHY,r)}reportError(t,r,n){this.setStatus(t,Ne.ERROR,n,r)}reportWarning(t,r){this.setStatus(t,Ne.WARNING,r)}initializeLoading(t,r){this.setStatus(t,Ne.LOADING,r||"Component is loading")}markLoaded(t,r){this.setStatus(t,Ne.HEALTHY,r||"Component loaded successfully")}markFailed(t,r,n){this.setStatus(t,Ne.ERROR,n,r)}getComponentsByStatus(t){let r=[];for(let[n,s]of this.statusMap)s.status===t&&r.push({name:n,status:s});return r}getStatusSummary(){let t={[Ne.HEALTHY]:0,[Ne.ERROR]:0,[Ne.WARNING]:0,[Ne.LOADING]:0,[Ne.UNKNOWN]:0};for(let r of this.statusMap.values())t[r.status]++;return t}static async getAggregatedFromAllThreads(t){let r=await tS.collect(t);return yd.aggregate(r)}async getAggregatedStatusFor(t,r){r||(r=await e.getAggregatedFromAllThreads(this));let n=[],s=t+".",i=r.get(t);i&&n.push({key:t,...i});for(let[f,m]of r)f.startsWith(s)&&n.push({key:f,...m});if(n.length===0)return{status:Ne.UNKNOWN,message:"The component has not been loaded yet (may need a restart)",lastChecked:{workers:{}}};let o=n.some(f=>f.status===Ne.ERROR),c=n.some(f=>f.status===Ne.LOADING),l=o?Ne.ERROR:c?Ne.LOADING:Ne.HEALTHY,u="All components loaded successfully",d={};if(o||c){u=n.filter(m=>m.status===Ne.ERROR||m.status===Ne.LOADING).map(m=>`${m.key}: ${m.latestMessage||m.status}`).join("; ");for(let m of n)m.status!==Ne.HEALTHY&&(d[m.key]={status:m.status,message:m.latestMessage})}return{status:l,message:u,...Object.keys(d).length>0&&{details:d},lastChecked:n[0]?.lastChecked||{workers:{}}}}}});var mr,nS=se(()=>{rS();mr=new ic});function OG(e){let t=CG.get(e);return t||(t=new dN(e),CG.set(e,t)),t}function PG(){mr.reset()}var dN,CG,ao,LG,DG=se(()=>{nS();_d();dN=class{static{a(this,"ComponentStatusBuilder")}componentName;constructor(t){this.componentName=t}healthy(t){return mr.setStatus(this.componentName,Ne.HEALTHY,t),this}warning(t){return mr.setStatus(this.componentName,Ne.WARNING,t),this}error(t,r){return mr.setStatus(this.componentName,Ne.ERROR,t,r),this}loading(t){return mr.setStatus(this.componentName,Ne.LOADING,t||"Loading..."),this}unknown(t){return mr.setStatus(this.componentName,Ne.UNKNOWN,t),this}get(){return mr.getStatus(this.componentName)}},CG=new Map;a(OG,"statusForComponent");ao={loading(e,t){mr.initializeLoading(e,t)},loaded(e,t){mr.markLoaded(e,t)},failed(e,t,r){mr.markFailed(e,t,r)}};a(PG,"reset");LG=Ne});var vp={};ye(vp,{AggregationError:()=>cN,COMPONENT_STATUS_LEVELS:()=>Ne,ComponentStatus:()=>gd,ComponentStatusError:()=>nc,ComponentStatusOperationError:()=>Td,ComponentStatusRegistry:()=>ic,CrossThreadCollectionError:()=>lN,CrossThreadStatusCollector:()=>Dp,CrossThreadTimeoutError:()=>aN,ITCError:()=>Sd,StatusAggregator:()=>yd,componentStatusRegistry:()=>mr,crossThreadCollector:()=>tS,query:()=>pae});var pae,vG=se(()=>{nS();rS();oN();rS();uN();nS();eS();_d();pae={get(e){return mr.getStatus(e)},all(){return mr.getAllStatuses()},byStatus(e){return mr.getComponentsByStatus(e)},summary(){return mr.getStatusSummary()},async allThreads(){return ic.getAggregatedFromAllThreads(mr)}}});var fN={};ye(fN,{STATUS:()=>LG,internal:()=>vp,lifecycle:()=>ao,reset:()=>PG,statusForComponent:()=>OG});var Mp=se(()=>{DG();vG()});var xp=M((eMe,xG)=>{"use strict";var _s=J(),yn=(H(),v(z)),hae=tB(),Eae=Es(),{validateEvent:mN}=ls(),Up=fs(),_ae=require("process"),{resetDatabases:gae}=(we(),v(ft)),Sae={[yn.ITC_EVENT_TYPES.SCHEMA]:Tae,[yn.ITC_EVENT_TYPES.USER]:UG,[yn.ITC_EVENT_TYPES.COMPONENT_STATUS_REQUEST]:Rae};async function Tae(e){let t=mN(e);if(t){_s.error(t);return}_s.trace("ITC schemaHandler received schema event:",e),await hae(e.message),await yae(e.message)}a(Tae,"schemaHandler");async function yae(e){try{Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=gae();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){_s.error(t)}}a(yae,"syncSchemaMetadata");var MG=[];async function UG(e){try{try{Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){_s.warn(r)}let t=mN(e);if(t){_s.error(t);return}_s.trace(`ITC userHandler ${yn.HDB_ITC_CLIENT_PREFIX}${_ae.pid} received user event:`,e),await Eae.setUsersWithRolesCache();for(let r of MG)r()}catch(t){_s.error(t)}}a(UG,"userHandler");UG.addListener=function(e){MG.push(e)};async function Rae(e){try{let t=mN(e);if(t){_s.error(t);return}_s.trace("ITC componentStatusRequestHandler received request:",e);let{internal:r}=(Mp(),v(fN)),{getWorkerIndex:n}=st(),{sendItcEvent:s}=ls(),i=r.componentStatusRegistry.getAllStatuses(),o=Array.from(i.entries()),c=n(),l=c===void 0,u=e.message.originator,d={type:yn.ITC_EVENT_TYPES.COMPONENT_STATUS_RESPONSE,message:{requestId:e.message.requestId,statuses:o,workerIndex:c,isMainThread:l}};u!==void 0&&threads.sendToThread(u,d)?_s.trace(`Sent component status response directly to thread ${u}`):(u===void 0?_s.debug("No originator threadId, falling back to broadcast"):_s.warn(`Failed to send direct response to thread ${u}, falling back to broadcast`),await s(d))}catch(t){_s.error("Error handling component status request:",t)}}a(Rae,"componentStatusRequestHandler");xG.exports=Sae});var ls=M((oMe,FG)=>{"use strict";var rMe=J(),pN=oe(),bae=(H(),v(z)),{ITC_ERRORS:Bp}=Jr(),{parentPort:nMe,threadId:Aae,isMainThread:Iae,workerData:sMe}=require("worker_threads"),{onMessageFromWorkers:wae,broadcast:iMe,broadcastWithAcknowledgement:Nae}=st();FG.exports={sendItcEvent:Cae,validateEvent:BG,SchemaEventMsg:Oae,UserEventMsg:Pae};var sS;wae(async(e,t)=>{sS=sS||xp(),BG(e),sS[e.type]&&await sS[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function Cae(e){return!Iae&&e.message&&(e.message.originator=Aae),Nae(e)}a(Cae,"sendItcEvent");function BG(e){if(typeof e!="object")return Bp.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||pN.isEmpty(e.type))return Bp.MISSING_TYPE;if(!e.hasOwnProperty("message")||pN.isEmpty(e.message))return Bp.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||pN.isEmpty(e.message.originator))return Bp.MISSING_ORIGIN;if(bae.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Bp.INVALID_EVENT(e.type)}a(BG,"validateEvent");function Oae(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(Oae,"SchemaEventMsg");function Pae(e){this.originator=e}a(Pae,"UserEventMsg")});var Wo=M((lMe,qG)=>{"use strict";var kG=(H(),v(z)),cMe=oe(),iS=J(),HG=B0(),Rd,{sendItcEvent:GG}=ls();function Lae(e){try{iS.debug("signalSchemaChange called with message:",e),Rd=Rd||xp();let t=new HG(kG.ITC_EVENT_TYPES.SCHEMA,e);return Rd.schema(t),GG(t)}catch(t){iS.error(t)}}a(Lae,"signalSchemaChange");function Dae(e){try{iS.trace("signalUserChange called with message:",e),Rd=Rd||xp();let t=new HG(kG.ITC_EVENT_TYPES.USER,e);return Rd.user(t),GG(t)}catch(t){iS.error(t)}}a(Dae,"signalUserChange");qG.exports={signalSchemaChange:Lae,signalUserChange:Dae}});function Fp(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}function $G(e,t){(typeof e.set!="function"||typeof e.has!="function")&&(e=new Gs(e));for(let[r,n]of t)e.has(r)?r.toLowerCase()==="set-cookie"&&e.append?.(r,n,!0):e.set(r,n);return e}var Gs,kp=se(()=>{Gs=class extends Map{static{a(this,"Headers")}constructor(t){if(t)if(t[Symbol.iterator])super(t);else{super();for(let r in t)this.set(r,t[r])}else super()}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(Fp,"appendHeader");a($G,"mergeHeaders")});function oS(e,t,r=Mae){let n;return function(...i){return n?n.length*hN>r?t(...i):new Promise((o,c)=>{n.push({args:i,fn(){try{let l=e(...i);o(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,o){setImmediate(()=>{let c=performance.now();hN=(hN*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var YG,vae,Mae,VG,Uae,EN,KG,hN,_N=se(()=>{YG=b(wr()),vae=3e3,Mae=2e4,VG=0,Uae=3e4,EN=3e3,KG=performance.now()+EN,hN=0;a(oS,"throttle");setInterval(()=>{let e=performance.now();e-KG-EN>vae&&VG+Uae<e&&(YG.default.warn?.("JavaScript execution has taken too long and is not allowing proper event queue cycling, consider using 'await new Promise(setImmediate)' in code that will execute for a long duration"),VG=e),KG=e},EN).unref()});var nq={};ye(nq,{EVICTED:()=>dl,INVALIDATED:()=>Fn,coerceType:()=>cS,makeTable:()=>uS});function uS(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:p}=e,{expirationMS:h,evictionMS:E,audit:g,trackDeletes:R}=e;E??=0;let{attributes:S}=e;S||(S=[]);let y=WA(i,n,l),N,I,$={},ee=Promise.resolve(),G,k,j;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(G=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(k=K),K.expiresAt&&(j=K),K.isPrimaryKey&&($=K);let Y,ce=[],de=[],te=1,ge=2,be={},Ye={},qe=864e5,Ar=0,er,Qr,xr,wu=!1,Kc,Ut,ii,Ma=Ul.get(F.REPLICATION_DATABASES);if(Array.isArray(Ma)){for(let K of Ma)if(K.name===c&&K.replicateTo>=0){ii=K.replicateTo;break}}let ZE=i.getRange({start:!1,end:!1}).constructor,cm=10,e_=6;g&&mm(),Hm(i.env.path,K=>{if(I)return xa(K)});class lm extends yl{static{a(this,"Updatable")}getUpdatedTime(){return Ya.get(this.getRecord())?.version}getExpiresAt(){return Ya.get(this.getRecord())?.expiresAt}addTo(_,T){if(typeof T=="number"||typeof T=="bigint")this.set(_,new Sp(T));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(_,T){return this.addTo(_,-T)}}class ve extends lr{#e;#t;#r;#n;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=S;static replicate=p;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=G;static updatedTimeProperty=k;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return h}static dbisDB=d;static schemaDefined=u;static sourcedFrom(_,T){if(T&&(this.sourceOptions=T,(T.expiration||T.eviction||T.scanInterval)&&this.setTTLExpiration(T)),T?.intermediateSource)_.intermediateSource=!0,this.sources.unshift(_);else{if(this.sources.some(D=>!D.intermediateSource)){if(this.sources.some(D=>D.name===_.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(_)}I=I||_.get&&(!_.get.reliesOnPrototype||_.prototype.get),N=N||_.load;let C=a(D=>{let A=this.sources;if(A=A.filter(U=>U.intermediateSource&&U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),A.length>0)if(A.length===1){let U=A[0];return(w,L,q)=>{if(w?.source!==U)return U[D](L,q,w)}}else return(U,w,L)=>{let q=[];for(let W of A){if(U?.source===W)break;q.push(W[D](w,L,U))}return Promise.all(q)}},"getApplyToIntermediateSource"),P=this.sources[this.sources.length-1];P.intermediateSource&&(P={});let O=a(D=>{if(P[D]&&(!P[D].reliesOnPrototype||P.prototype[D]))return(A,U,w)=>{if(!A?.source)return P[D](U,w,A)}},"getApplyToCanonicalSource");be={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ye={put:C("put"),patch:C("patch"),delete:C("delete"),publish:C("publish"),invalidate:C("invalidate")};let x=P.shouldRevalidateEvents;return(async()=>{let D=!1,A,U=a(async(w,L)=>{let q=w.value,W=w.table?Me[c][w.table]:ve;if(c===_m&&(w.table===Du.ROLE_TABLE_NAME||w.table===Du.USER_TABLE_NAME)&&(D=!0),w.id===void 0&&(w.id=q[W.primaryKey],w.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(w));w.source=_;let Q={residencyId:Yc(w.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:w.nodeId,async:!0},B=w.id,Ee=await W.getResource(B,L,Q);switch(w.finished&&await w.finished,w.type){case"put":return x?Ee._writeInvalidate(B,q,Q):Ee._writeUpdate(B,q,!0,Q);case"patch":return x?Ee._writeInvalidate(B,q,Q):Ee._writeUpdate(B,q,!1,Q);case"delete":return Ee._writeDelete(B,Q);case"publish":case"message":return Ee._writePublish(B,q,Q);case"invalidate":return Ee._writeInvalidate(B,q,Q);case"relocate":return Ee._writeRelocate(B,Q);default:ke.default.error?.("Unknown operation",w.type,w.id)}},"writeUpdate");try{let w=_.subscribe;w&&R==null&&(R=!0);let L={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},q=_.subscribeOnThisThread?_.subscribeOnThisThread((0,Ml.getWorkerIndex)(),L):(0,Ml.getWorkerIndex)()===0,W=w&&q&&await _.subscribe?.(L);if(W){let Q;for await(let B of W)try{if(!(B.type==="transaction"?B.writes[0]:B)){ke.default.error?.("Bad subscription event",B);continue}if(B.source=_,B.type==="end_txn"){Q?.resolve();let pe;if(B.localTime&&A!==B.localTime&&B.remoteNodeIds?.length>0&&(pe=a(()=>{let re=[Symbol.for("seq"),B.remoteNodeIds[0]],ie=d.get(re),Oe=ie?.nodes;Oe||(Oe=[]);for(let ae of B.remoteNodeIds.slice(1)){let xe=Oe.find(Ce=>Ce.id===ae);Oe=Oe.filter(Ce=>Ce.id!==ae||Ce===xe),xe||(xe={id:ae,seqId:0},Oe.push(xe)),xe.seqId=Math.max(ie?.seqId??1,B.localTime),ae===Q?.nodeId&&(xe.lastTxnTime=B.timestamp)}let le=Math.max(ie?.seqId??1,B.localTime);ke.default.trace?.("Received txn",c,le,new Date(le),B.localTime,new Date(B.localTime),B.remoteNodeIds),d.put(re,{seqId:le,nodes:Oe})},"updateRecordedSequenceId"),A=B.localTime),B.onCommit){let re=Q?Q.committed.then(B.onCommit):B.onCommit();pe&&(re?.then?re.then(pe):pe())}else pe&&pe();continue}if(Q)if(B.beginTxn)Q.resolve();else{Q.writePromises.push(U(B,Q));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let fe=bt(B,()=>{if(B.type==="transaction"){let pe=[];for(let re of B.writes)try{pe.push(U(re,B))}catch(ie){throw ie.message+=" writing "+JSON.stringify(re)+" of event "+JSON.stringify(B),ie}return Promise.all(pe)}else if(B.type==="define_schema"){let pe=this.attributes.slice(0),re=!1;for(let ie of B.attributes)pe.find(Oe=>Oe.name===ie.name)||(pe.push(ie),re=!0);re&&(Xe({table:s,database:c,attributes:pe,origin:"cluster"}),Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,V.CREATE_TABLE,c,s)))}else return B.beginTxn?(Q=B,Q.writePromises=[U(B,B)],new Promise(pe=>{Q.resolve=()=>pe(Promise.all(Q.writePromises))})):U(B,B)});Q&&(Q.committed=fe),D&&fe&&!fe?.waitingForUserChange&&(fe.then(()=>Gp.signalUserChange(new qp.UserEventMsg(process.pid))),fe.waitingForUserChange=!0),B.onCommit&&(fe?fe.then(B.onCommit):B.onCommit())}catch(Ee){ke.default.error?.("error in subscription handler",Ee)}}}catch(w){ke.default.error?.(w)}})(),this}static get isCaching(){return I}static get shouldRevalidateEvents(){return this.prototype.get!==ve.prototype.get}static getResource(_,T,C){let P=super.getResource(_,T,C);if(this.loadAsInstance===!1&&(T._freezeRecords=!0),_!=null&&this.loadAsInstance!==!1){Hi(_);try{if(P.getRecord?.())return P;if(typeof _=="object"&&_&&!Array.isArray(_))throw new Error(`Invalid id ${JSON.stringify(_)}`);let O=!C?.async||i.cache?.get?.(_),x=Br(T),D=x.getReadTxn();if(D?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Lo(_,T,{transaction:D,ensureLoaded:C?.ensureLoaded},O,A=>{if(A?ve._updateResource(P,A):P.#e=null,T.onlyIfCached){if(!P.doesExist())throw new ut.ServerError("Entry is not cached",504)}else if(C?.ensureLoaded){let U=pn(_,A,T,P);if(U)return x?.disregardReadTxn(),P.#i=!0,T.loadedFromSource=!0,qs(U,w=>(ve._updateResource(P,w),P))}return P})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(_)),O}}return P}static _updateResource(_,T){_.#n=T,_.#e=T?.value??null,_.#r=T?.version}ensureLoaded(){let _=pn(this.getId(),this.#n,this.getContext());if(_)return this.#i=!0,this.getContext().loadedFromSource=!0,qs(_,T=>{this.#n=T,this.#e=T.value,this.#r=T.version})}static getNewId(){let _=$?.type;if(_==="String"||_==="ID")return super.getNewId();if(!Ut){let O=i.getEntry(Symbol.for("id_allocation")),x=O?.value,D;if(x&&x.nodeName===server.hostname&&(!Wae(i)||x.pid===process.pid)){let A=x.start,U=x.end;D=A;for(let w of i.getKeys({start:U,end:A,limit:1,reverse:!0}))D=w}else x=P(O?.version??null),D=x.start;Ut=new BigInt64Array([BigInt(D)+1n]),Ut=new BigInt64Array(i.getUserSharedBuffer("id",Ut.buffer)),Ut.maxSafeId=x.end}let T=Number(Atomics.add(Ut,0,1n)),C=_==="Int"?512:1048576;if(T+C>=Ut.maxSafeId){let O=a(x=>{Ut.maxSafeId=T+(_==="Int"?1023:4194303);let D=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,A=x?void 0:i.useReadTransaction(),U=Number(Ut[0]);for(let q of i.getKeys({start:U+1,end:D,limit:1,transaction:A}))D=q;A?.done();let{value:w,version:L}=i.getEntry(Symbol.for("id_allocation"));if(Ut.maxSafeId<D){if(w.end>Ut.maxSafeId-100)return;ke.default.info?.("New id allocation",T,Ut.maxSafeId,L),i.put(Symbol.for("id_allocation"),{start:w.start,end:Ut.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),L)}else{ke.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Ut.maxSafeId}, but id of ${D} detected`);let q=P(L);q.alreadyUpdated||Atomics.store(Ut,0,BigInt(q.start+1)),Ut.maxSafeId=q.end}},"updateEnd");T+C===Ut.maxSafeId?setImmediate(O):T+100>=Ut.maxSafeId&&(ke.default.warn?.(`Synchronous id allocation required on table ${s}${_=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>O(!0)))}return T;function P(O){let x=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=x/4,A,U,w=!1,L,q;do{L=Math.floor(Math.random()*x),q={start:L,end:L+(_==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},A=0;for(let W of i.getKeys({start:L,limit:1,reverse:!0}))A=W;U=x;for(let W of i.getKeys({start:L+1,end:x,limit:1}))U=W;D*=.875,D<1e3&&!w&&(w=!0,ke.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${_==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,L,A,U,D))}while(!(D<U-L&&(D<L-A||A===0)));return i.transactionSync(()=>{let W=i.getEntry(Symbol.for("id_allocation"));return(W?.version??null)==O?(ke.default.info?.("Allocated new id range",q),i.put(Symbol.for("id_allocation"),q,Date.now()),q):(ke.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...W.value})})}}static setTTLExpiration(_){if(typeof _=="number")h=_*1e3,E||(E=0);else if(_&&typeof _=="object")h=_.expiration*1e3,E=(_.eviction||0)*1e3,qe=_.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(h<0)throw new Error("Expiration can not be negative");qe=qe||(h+E)/4,xa()}static getResidencyRecord(_){return d.get([Symbol.for("residency_by_id"),_])}static setResidency(_){ve.getResidency=_&&((T,C)=>{try{return _(T,C)}catch(P){throw P.message+=` in residency function for table ${s}`,P}})}static setResidencyById(_){ve.getResidencyById=_&&(T=>{try{return _(T)}catch(C){throw C.message+=` in residency function for table ${s}`,C}})}static getResidency(_,T){if(ve.getResidencyById)return ve.getResidencyById(_[t]);let C=ii;if(T.replicateTo!=null){if(Array.isArray(T.replicateTo))return T.replicateTo.includes(server.hostname)?T.replicateTo:[server.hostname,...T.replicateTo];T.replicateTo>=0&&(C=T.replicateTo)}if(C>=0&&server.nodes){let P=[server.hostname];if(T.previousResidency)P.push(...T.previousResidency.slice(0,C));else{let O=server.nodes.map(A=>A.name),x=Math.floor(O.length*Math.random());P.push(...O.slice(x,x+C));let D=x+C-O.length;D>0&&P.push(...O.slice(0,D))}return P}}static enableAuditing(){g||(g=!0,mm(),ve.audit=!0)}static coerceId(_){return _===""?null:cS(_,$)}static async dropTable(){delete Me[c][s];for(let _ of i.getRange({versions:!0,snapshot:!1,lazy:!0}))_.metadataFlags&Zr&&_.value&&$a(_.value);if(c===o){for(let _ of S)d.remove(ve.tableName+"/"+_.name),r[_.name]?.drop();d.remove(ve.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),SN.default.unlinkSync(i.env.path);Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,V.DROP_TABLE,c,s))}get(_){let T=this.constructor;if(typeof _=="string"&&T.loadAsInstance!==!1)return this.getProperty(_);if(um(_))return this.search(_);if(_&&_.id===void 0&&!_.toString()){let C={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:S,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?ve.getRecordCount().then(P=>(C.recordCount=P.recordCount,C.estimatedRecordRange=P.estimatedRange,C)):C}if(_!==void 0&&T.loadAsInstance===!1){let C=this.getContext(),P=Br(C),O=P.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let x=Ds(_);Hi(x);let D=!0;return _.checkPermission&&(D=this.allowRead(C.user,_)),qs(qs(D,A=>{if(!A)throw new ut.AccessViolation(C.user);let U=!0;return Lo(x,C,{transaction:O,ensureLoaded:U},!1,w=>{if(C.onlyIfCached){if(!w?.value)throw new ut.ServerError("Entry is not cached",504)}else if(U){let L=pn(x,w,C);if(L)return P?.disregardReadTxn(),C.loadedFromSource=!0,L.then(q=>q?.value)}return w?.value})}),A=>{let U=_?.select;return U&&A!=null?Zu(U,this.constructor)(A):A})}if(_?.property)return this.getProperty(_.property);if(this.doesExist()||_?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(_,T){let C=Dn(_,T);if(C?.read){if(C.isSuperUser)return!0;let P=C.attribute_permissions,O=T?.select;if(P?.length>0||wu&&O){if(T||(T={}),O){let x=Array.isArray(O)?O:[O],D=P?.length>0&&gN(P,"read");T.select=x.map(A=>{let U=A.name||A;if(!D||D[U]){let w=xr[U]?.definition?.tableClass;if(w){if(A.name||(A={name:A}),!A.checkPermission&&T.checkPermission&&(A.checkPermission=T.checkPermission),!w.prototype.allowRead.call(null,_,A))return!1;if(!A.select)return A.name}return A}}).filter(Boolean)}else T.select=P.filter(x=>x.read&&!xr[x.attribute_name]).map(x=>x.attribute_name);return T}else return!0}}allowUpdate(_,T,C){let P=Dn(_,C);if(P?.update){let O=P.attribute_permissions;if(O?.length>0){let x=gN(O,"update");for(let D in T)if(!x[D])return!1;for(let D of O){let A=D.attribute_name;!D.update&&!(A in T)&&(T[A]=this.getProperty(A))}}return Ua(this.getContext())}}allowCreate(_,T,C){if(this.isCollection){let P=Dn(_,C);if(P?.insert){let O=P.attribute_permissions;if(O?.length>0){let x=gN(O,"insert");for(let D in T)if(!x[D])return!1;return Ua(this.getContext())}else return Ua(this.getContext())}}else return this.allowUpdate(_,{})}allowDelete(_,T){return Dn(_,T)?.delete&&Ua(this.getContext())}update(_,T){let C,P=typeof T=="boolean"||T===void 0&&(_==null||typeof _=="object"&&!(_ instanceof URLSearchParams)),O=!1;P?(O=T,T=_,C=this.getId()):C=Ds(_);let x=this.getContext();if(!Br(x))throw new Error("Can not update a table resource outside of a transaction");if(T===!1)return this;if(typeof T=="object"&&T)if(O)Object.isFrozen(T)&&(T={...T}),this.#e={},this.#t=T;else if(P){let A=this.#t;A&&(T=Object.assign(A,T)),this.#t=T}else{let A=!0;if(_==null)throw new TypeError("Can not put a record without a target");return _.checkPermission&&(A=this.allowUpdate(x.user,T,_)),qs(A,U=>{if(!U)throw new ut.AccessViolation(x.user);return qs(i.get(Ds(_)),w=>{let L=new lm(w);return L._setChanges(T),this._writeUpdate(C,L.getChanges(),!1),L})})}return this._writeUpdate(C,this.#t,O),this}addTo(_,T){if(typeof T=="number"||typeof T=="bigint")this.#s===zG?this.set(_,(+this.getProperty(_)||0)+T):(this.#s||this.update(),this.set(_,new Sp(T)));else throw new Error("Can not add a non-numeric value")}subtractFrom(_,T){if(typeof T=="number")return this.addTo(_,-T);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#n}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(_){this.#t=_}setRecord(_){this.#e=_}invalidate(_){let T=!0,C=this.getContext();return _?.checkPermission&&(T=this.allowDelete(C.user,_,C)),qs(T,P=>{if(!P)throw new ut.AccessViolation(C.user);this._writeInvalidate(_?Ds(_):this.getId())})}_writeInvalidate(_,T,C){let P=this.getContext();Hi(_),Br(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:be.invalidate?.bind(this,P,_),beforeIntermediate:Pu(T,Ye.invalidate?.bind(this,P,_)),commit:a((x,D)=>{if(!(Fr(x,D,C?.nodeId)<=0)){T??=null;for(let A in r)T||(T={}),T[A]===void 0&&(T[A]=this.getProperty(A));ke.default.trace?.(`Invalidating entry in ${s} id: ${_}, timestamp: ${new Date(x).toISOString()}`),y(_,T,D,x,Fn,g,{user:P?.user,residencyId:C?.residencyId,nodeId:C?.nodeId,tableToTrack:s},"invalidate")}},"commit")})}_writeRelocate(_,T){let C=this.getContext();Hi(_),Br(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:be.relocate?.bind(this,C,_),beforeIntermediate:Ye.relocate?.bind(this,C,_),commit:a((O,x)=>{if(Fr(O,x,T?.nodeId)<=0)return;let D=ve.getResidencyRecord(T.residencyId),A=0,U=null,w=x?.value;if(D&&!D.includes(server.hostname)){for(let L in r)U||(U={}),U[L]=w[L];A=Fn}else U=w;ke.default.trace?.(`Relocating entry id: ${_}, timestamp: ${new Date(O).toISOString()}`),y(_,U,x,O,A,g,{user:C.user,residencyId:T.residencyId,nodeId:T.nodeId,expiresAt:T.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(_,T){let C={previousResidency:this.getResidencyRecord(_.residencyId),isRelocation:!0},P=Ba(this.getResidency(T.value,C)),O;if(P){if(!P.includes(server.hostname))return!1;O=Yc(P)}let x=0;ke.default.debug?.("Performing a relocate of an entry",_.key,T.value,P);let D=y(_.key,T.value,_,_.version,x,!0,{residencyId:O,expiresAt:T.expiresAt},"relocate",!1,null);return!0}static evict(_,T,C){let P=this.Source,O;if(!((I||g)&&(!T||(O=i.getEntry(_),!O||!T)||O.version!==C))){if(I){if(i.hasLock(_,O.version))return;let x;for(let D in r)x||(x={}),x[D]=T[D];if(x)return y(_,x,O,C,dl,null,null,null,!0)}return i.ifVersion(_,C,()=>{Nu(_,T,null)}),ul(i,O??i.getEntry(_),C)}}lock(){throw new Error("Not yet implemented")}static operation(_,T){return _.table||=s,_.schema||=c,global.operation(_,T)}put(_,T){if(T===void 0||T instanceof URLSearchParams)this.update(_,!0);else{let C=!0;if(_==null)throw new TypeError("Can not put a record without a target");let P=this.getContext();return _.checkPermission&&(C=this.allowUpdate(P.user,T,_)),qs(C,O=>{if(!O)throw new ut.AccessViolation(P.user);if(Array.isArray(T))for(let x of T){let D=x[t];this._writeUpdate(D,x,!0)}else{let x=Ds(_);this._writeUpdate(x,T,!0)}})}}create(_,T){let C=!0,P=this.getContext();if(!T&&!(_ instanceof URLSearchParams)&&(T=_,_=void 0),!T||typeof T!="object"||Array.isArray(T))throw new TypeError("Can not create a record without an object");return _?.checkPermission&&(C=this.allowCreate(P.user,T,_)),qs(C,O=>{if(!O)throw new ut.AccessViolation(P.user);let x=Ds(_)??T[t];if(x===void 0)x=this.constructor.getNewId();else if(i.get(x))throw new ut.ClientError("Record already exists",409);return this._writeUpdate(x,T,!0),T})}patch(_,T){if(T===void 0||T instanceof URLSearchParams)this.update(_,!1);else{let C=this.update(_,T);if(C?.then)return C.then(()=>{})}}_writeUpdate(_,T,C,P){let O=this.getContext(),x=Br(O);Hi(_);let D=this.#n??i.getEntry(_);this.#s=C?zG:$ae;let A=a(w=>C?w.put?()=>w.put(O,_,T):null:w.patch?()=>w.patch(O,_,T):w.put?()=>w.put(O,_,Rl(this)):null,"writeToSources"),U={key:_,store:i,entry:D,nodeName:O?.nodeName,validate:a(w=>{T||(T=this.#t),C||T&&Ug(this.#t===T?this:T)?O?.source||(x.checkOverloaded(),this.validate(T,!C),k&&(T[k.name]=k.type==="Date"?new Date(w):k.type==="String"?new Date(w).toISOString():w),C&&(t&&T[t]!==_&&(T[t]=_),G&&(D?.value?T[G.name]=D?.value[G.name]:T[G.name]=G.type==="Date"?new Date(w):G.type==="String"?new Date(w).toISOString():w),T=Rl(T))):x.removeWrite(U)},"validate"),before:A(be),beforeIntermediate:Pu(T,A(Ye)),commit:a((w,L,q)=>{if(q){if(O&&L?.version>(O.lastModified||0)&&(O.lastModified=L.version),this.#n=L,L?.value&&L.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");C||(this.#e=L?.value??null)}this.#t=void 0,this.#r=w;let W=L?.value,Q;this.#s=0;let B=!1,Ee=Fr(w,L,P?.nodeId),fe;if(Ee<=0){if(g){let le=L.localTime,ae=L.version;ke.default.trace?.("Applying CRDT update to record with id: ",_,"txn time",new Date(w),"applying later update from:",new Date(ae),"local recorded time",new Date(le));let xe=[];for(;le>w||ae>=w&&le>0;){let Ce=l.get(le);if(!Ce)break;let Le=At(Ce);if(ae=Le.version,ae>=w){if(ae===w){if(Ee=Fr(w,{version:ae,localTime:le},P?.nodeId),Ee===0)return;if(Ee>0){le=Le.previousLocalTime;continue}}if(Le.type==="patch")xe.push(Le),fe=T;else if(Le.type==="put"||Le.type==="delete")return}le=Le.previousLocalTime}le||ke.default.debug?.("No further audit history, applying incremental updates based on available history",_,"existing version preserved",L),xe.sort((Ce,Le)=>Ce.version-Le.version);for(let Ce of xe){let Le=Ce.getValue(i);if(ke.default.debug?.("Rebuilding update with future patch:",new Date(Ce.version),Le,Ce),Q=w_(Q??T,Le,C),!Q)return}}else{if(C)return;Q=w_(Q??T,W,C),ke.default.debug?.("Rebuilding update without audit:",Q)}ke.default.trace?.("Rebuilt record to save:",Q," is full update:",C)}let pe;if(C&&!Q?pe=T:this.constructor.loadAsInstance===!1?pe=Rl(W,Q??T):(this.#e=W,pe=Rl(this,Q??T)),this.#e=pe,pe&&pe.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let re;if(P?.residencyId!=null)re=P.residencyId;else{D?.residencyId&&(O.previousResidency=ve.getResidencyRecord(D.residencyId));let le=Ba(ve.getResidency(pe,O));if(le&&!le.includes(server.hostname))if(fe??=pe,B=!0,ve.getResidencyById)pe=void 0;else{pe=null;for(let ae in r)pe||(pe={}),pe[ae]=fe[ae]}re=Yc(le)}C||(fe=T);let ie=O?.expiresAt??(h?h+Date.now():-1);ke.default.trace?.(`Saving record with id: ${_}, timestamp: ${new Date(w).toISOString()}${ie?", expires at: "+new Date(ie).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(pe).slice(0,100)}catch{return""}})()),Nu(_,W,pe);let Oe=C?"put":"patch";y(_,pe,L,w,B?Fn:0,g,{omitLocalRecord:B,user:O?.user,residencyId:re,expiresAt:ie,nodeId:P?.nodeId,originatingOperation:O?.originatingOperation,tableToTrack:c==="system"?null:s},Oe,!1,fe),O.expiresAt&&xa()},"commit")};x.addWrite(U)}async delete(_){if(um(_)){_.select=["$id"];for await(let T of this.search(_))this._writeDelete(T.$id);return!0}if(_){let T=!0,C=this.getContext();return _.checkPermission&&(T=this.allowDelete(C.user,_,C)),qs(T,P=>{if(!P)throw new ut.AccessViolation(C.user);let O=Ds(_);return this._writeDelete(O),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(_,T){let C=Br(this.getContext());Hi(_);let P=this.getContext();return C.addWrite({key:_,store:i,entry:this.#n,nodeName:P?.nodeName,before:be.delete?.bind(this,P,_),beforeIntermediate:Ye.delete?.bind(this,P,_),commit:a((O,x,D)=>{let A=x?.value;D&&(P&&x?.version>(P.lastModified||0)&&(P.lastModified=x.version),ve._updateResource(this,x)),!(Fr(O,x,T?.nodeId)<=0)&&(Nu(this.getId(),A),ke.default.trace?.(`Deleting record with id: ${_}, txn timestamp: ${new Date(O).toISOString()}`),g||R?(y(_,null,x,O,0,g,{user:P?.user,nodeId:T?.nodeId,tableToTrack:s},"delete"),g||xa()):ul(i,x))},"commit")}),!0}search(_){let T=this.getContext(),C=Br(T);if(!_)throw new Error("No query provided");if(_.parseError)throw _.parseError;if(_.checkPermission&&!this.allowRead(T.user,_))throw new ut.AccessViolation(T.user);T&&(T.lastModified=kae);let P=_.conditions;P?P.length===void 0&&(P=P[Symbol.iterator]?Array.from(P):[P]):P=Array.isArray(_)?_:_[Symbol.iterator]?Array.from(_):[];let O=_.id??this.getId();O&&(P=[{attribute:null,comparator:Array.isArray(O)?"prefix":"starts_with",value:O}].concat(P));let x,D={};function A(ie,Oe){let le;switch(Oe){case"and":case void 0:if(ie.length<1)throw new Error('An "and" operator requires at least one condition');le=!0;break;case"or":if(ie.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Oe)}for(let ae of ie){if(ae.conditions){ae.conditions=A(ae.conditions,ae.operator);continue}let xe=ae[0]??ae.attribute,Ce=xe==null?$:zi(S,xe);if(Ce)(Ce.type||jA[ae.comparator])&&(ae[1]===void 0?ae.value=w(ae.value,Ce):ae[1]=w(ae[1],Ce));else if(xe!=null&&!_.allowConditionsOnDynamicAttributes)throw(0,ut.handleHDBError)(new Error,`${xe} is not a defined attribute`,404);if(ae.chainedConditions)if(ae.chainedConditions.length===1&&(!ae.operator||ae.operator=="and")){let Le=ae.chainedConditions[0],De,pt;if(Le.comparator==="gt"||Le.comparator==="greater_than"||Le.comparator==="ge"||Le.comparator==="greater_than_equal"?(De=ae,pt=Le):(De=Le,pt=ae),De.comparator!=="lt"&&De.comparator!=="less_than"&&De.comparator!=="le"&&De.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let wt=pt.comparator==="ge"||pt.comparator==="greater_than_equal",xt=De.comparator==="le"||De.comparator==="less_than_equal";ae.comparator=(wt?"ge":"gt")+(xt?"le":"lt"),ae.value=[pt.value,De.value]}else throw new Error("Multiple chained conditions are not currently supported")}return ie}a(A,"prepareConditions");function U(ie,Oe){if(_.enforceExecutionOrder)return ie;for(let le of ie)le.conditions&&(le.conditions=U(le.conditions,le.operator));return ie.length>1&&Oe!=="or"?xae(ie,ug(ve)):ie}a(U,"orderConditions");function w(ie,Oe){return Array.isArray(ie)?ie.map(le=>cS(le,Oe)):cS(ie,Oe)}a(w,"coerceTypedValues");let L=_.operator;(P.length>0||L)&&(P=A(P,L));let q=typeof _.sort=="object"&&_.sort,W;if(q&&L!=="or"){let ie=q.attribute;if(ie==null)throw new ut.ClientError("Sort requires an attribute");if(x=P.find(Oe=>Qu(Oe.attribute)===Qu(ie)),!x){let Oe=zi(S,ie);if(!Oe)throw(0,ut.handleHDBError)(new Error,`${Array.isArray(ie)?ie.join("."):ie} is not a defined attribute`,404);if(Oe.indexed)x={...q,comparator:"sort"},P.push(x);else if(P.length===0&&!_.allowFullScan)throw(0,ut.handleHDBError)(new Error,`${Array.isArray(ie)?ie.join("."):ie} is not indexed and not combined with any other conditions`,404)}x&&(x.descending=!!q.descending)}P=U(P,L),q&&(x&&P[0]===x?q.next&&(W={dbOrderedAttribute:q.attribute,attribute:q.next.attribute,descending:q.next.descending,next:q.next.next}):(x&&P.splice(P.indexOf(x),1),W=q));let Q=_.select;if(P.length===0&&(P=[{attribute:t,comparator:"greater_than",value:!0}]),_.explain)return{conditions:P,operator:L,postOrdering:W,selectApplied:!!Q};let B=C.useReadTxn(),Ee=QA(P,L,ve,B,_,T,(ie,Oe)=>fm(ie,Q,T,B,Oe),D),fe=_.ensureLoaded!==!1,pe=ve.transformEntryForSelect(Q,T,B,D,fe,!0),re=ve.transformToOrderedSelect(Ee,Q,W,T,B,pe);return(_.offset||_.limit!==void 0)&&(re=re.slice(_.offset,_.limit!==void 0?(_.offset||0)+_.limit:void 0)),re.onDone=()=>{re.onDone=null,C.doneReadTxn()},re.selectApplied=!0,re.getColumns=()=>{if(Q){let ie=[];for(let Oe of Q)Oe==="*"?ie.push(...S.map(le=>le.name)):ie.push(Oe.name||Oe);return ie}return S.filter(ie=>!ie.computed&&!ie.relationship).map(ie=>ie.name)},re}static transformToOrderedSelect(_,T,C,P,O,x){let D=new ZE;if(C){_=fm(_,T,P,O,null);let A;D.iterate=function(){let w,L=_[Symbol.asyncIterator]?_[Symbol.asyncIterator]():_[Symbol.iterator](),q,W=C.dbOrderedAttribute,Q,B,Ee=!0;function fe(re){let ie=re.next&&fe(re.next),Oe=re.descending;return P.sort=re,(le,ae)=>{let xe=Cu(le,re.attribute,P),Ce=Cu(ae,re.attribute,P),Le=Oe?(0,xl.compareKeys)(Ce,xe):(0,xl.compareKeys)(xe,Ce);return Le===0?ie?.(le,ae)||0:Le}}a(fe,"createComparator");let pe=fe(C);return{async next(){let re;if(w)if(re=w.next(),re.done){if(q)return D.onDone&&D.onDone(),re}else return{value:await x.call(this,re.value)};A=[],Q&&A.push(Q);do if(re=await L.next(),re.done){if(q=!0,A.length)break;return D.onDone&&D.onDone(),re}else{let ie=re.value;if(ie?.then&&(ie=await ie),W){let Oe=Cu(ie,W,P);if(Ee)Ee=!1,B=Oe;else if(Oe!==B){B=Oe,Q=ie;break}}A.push(ie)}while(!0);return C.isGrouped,A.sort(pe),w=A[Symbol.iterator](),re=w.next(),re.done?(D.onDone&&D.onDone(),re):{value:await x.call(this,re.value)}},return(){return D.onDone&&D.onDone(),L.return()},throw(){return D.onDone&&D.onDone(),L.throw()}}};let U=a(w=>{if(typeof T=="object"&&Array.isArray(w.attribute))for(let L=0;L<T.length;L++){let q=T[L],W;if(q.name===w.attribute[0]){for(W=q.sort||(q.sort={});W.next;)W=W.next;W.attribute=w.attribute.slice(1),W.descending=w.descending}else q===w.attribute[0]&&(T[L]=W={name:q,sort:{attribute:w.attribute.slice(1),descending:w.descending}})}w.next&&U(w.next)},"applySortingOnSelect");U(C)}else D.iterate=(_[Symbol.asyncIterator]||_[Symbol.iterator]).bind(_),D=D.map(function(A){try{let U=x.call(this,A);return typeof U?.catch=="function"?U.catch(w=>{throw w.partialObject={[t]:A.key},w}):U}catch(U){throw U.partialObject={[t]:A.key},U}});return D}static transformEntryForSelect(_,T,C,P,O,x){let D;O&&I&&!(typeof _=="string"?[_]:_)?.every(w=>{let L;return typeof w=="object"?L=w.name:L=w,r[L]||L===t})&&(D=!0);let A,U=a(function(w){let L;if(T?.transaction?.stale&&(T.transaction.stale=!1),w!=null){if(L=w.deref?w.deref():w.value,!L&&(w.key===void 0||w.deref)||w.metadataFlags&Fn){if(w.metadataFlags&Fn&&T.replicateFrom===!1&&x&&w.residencyId)return ac.SKIP;if(w=Lo(w.key??w,T,{transaction:C,lazy:_?.length<4,ensureLoaded:O},this?.isSync,q=>q),w?.then)return w.then(U.bind(this));L=w?.value}if(D&&w?.metadataFlags&(Fn|dl)||w?.expiresAt!=null&&w?.expiresAt<Date.now()){if(T.onlyIfCached)return{[t]:w.key,message:"This entry has expired"};let q=pn(w.key??w,w,T);if(q?.then)return q.then(U)}}if(L==null)return x?ac.SKIP:L;if(_&&!(_[0]==="*"&&_.length===1)){let q,W=a((B,Ee)=>{let fe;typeof B=="object"?fe=B.name:fe=B;let pe=xr?.[fe],re;if(pe){let ie=P?.[fe];if(ie)if(ie.hasMappings){let le=pe.from?L[pe.from]:Qu(w.key);re=ie.get(le),re||(re=[])}else re=ie.fromRecord?.(L);else re=pe(L,T,w,!0);let Oe=a(le=>{if(pe.directReturn)return Ee(le,fe);if(le&&typeof le=="object"){let ae=pe.definition?.tableClass||ve;A||(A={});let xe=A[fe]||(A[fe]=ae.transformEntryForSelect(fe===B?null:B.select||(Array.isArray(B)?B:null),T,C,ie,O));if(Array.isArray(le)){let Ce=[],Le=ae.transformToOrderedSelect(le,B.select,typeof B.sort=="object"&&B.sort,T,C,xe)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),De=a(wt=>{for(;!wt.done;){if(wt?.then)return wt.then(De);Ce.push(wt.value),wt=Le.next()}Ee(Ce,fe)},"nextValue"),pt=De(Le.next());pt&&(q||(q=[]),q.push(pt));return}else if(le=xe.call(this,le),le?.then){q||(q=[]),q.push(le.then(Ce=>Ee(Ce,fe)));return}}Ee(le,fe)},"handleResolvedValue");re?.then?(q||(q=[]),q.push(re.then(Oe))):Oe(re);return}else re=L[fe],re&&typeof re=="object"&&fe!==B&&(re=ve.transformEntryForSelect(B.select||B,T,C,null)({value:re}));Ee(re,fe)},"selectAttribute"),Q;if(typeof _=="string")W(_,B=>{Q=B});else if(Array.isArray(_))if(_.asArray)Q=[],_.forEach((B,Ee)=>{B==="*"?_[Ee]=L:W(B,fe=>Q[Ee]=fe)});else{Q={};let B=_.forceNulls;for(let Ee of _)if(Ee==="*")for(let fe in L)Q[fe]=L[fe];else W(Ee,(fe,pe)=>{fe===void 0&&B&&(fe=null),Q[pe]=fe})}else throw new ut.ClientError("Invalid select"+_);return q?Promise.all(q).then(()=>Q):Q}return L},"transform");return U}async subscribe(_){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||Xe({table:s,database:c,schemaDefined:u,attributes:S,audit:!0}),_||(_={});let T=!_.rawEvents,C=[],P=nI(ve,this.getId()??null,function(D,A,U,w){try{let L=A.getValue?.(i,T),q=A.type;if(!L&&q==="patch"&&T){let Q=i.getEntry(D);Q?.version===A.version?L=Q.value:L=A.getValue?.(i,!0,U),q="put"}let W={id:D,localTime:U,value:L,version:A.version,type:q,beginTxn:w};C?C.push(W):(c!=="system"&&Ve(A.size??1,"db-message",s,null),this.send(W))}catch(L){ke.default.error?.(L)}},_.startTime||0,_),O=(async()=>{this.isCollection&&(P.includeDescendants=!0,_.onlyChildren&&(P.onlyChildren=!0)),_.supportsTransactions&&(P.supportsTransactions=!0);let D=this.getId(),A=_.previousCount;A>1e3&&(A=1e3);let U=_.startTime;if(this.isCollection){if(U){if(A)throw new ut.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:w,value:L}of l.getRange({start:U,exclusiveStart:!0,snapshot:!1})){let q=At(L);if(q.tableId!==n)continue;let W=q.recordId;if(D==null||XG(D,W)){let Q=q.getValue(i,T,w);if(x({id:W,localTime:w,value:Q,version:q.version,type:q.type,size:q.size}),P.queue?.length>QG&&await P.waitForDrain()===!1)return}P.startTime=w}}else if(A){let w=[];for(let{key:L,value:q}of l.getRange({start:"z",end:!1,reverse:!0}))try{let W=At(q);if(W.tableId!==n)continue;let Q=W.recordId;if(D==null||XG(D,Q)){let B=W.getValue(i,T,L);if(w.push({id:Q,localTime:L,value:B,version:W.version,type:W.type}),--A<=0)break}}catch(W){ke.default.error("Error getting history entry",L,W)}for(let L=w.length;L>0;)x(w[--L]);w[0]&&(P.startTime=w[0].localTime)}else if(!_.omitCurrent){for(let{key:w,value:L,version:q,localTime:W,size:Q}of i.getRange({start:D??!1,end:D==null?void 0:[D,xl.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(L&&(x({id:w,localTime:W,value:L,version:q,type:"put",size:Q}),P.queue?.length>QG&&await P.waitForDrain()===!1))return}}else{A&&!U&&(U=0);let w=this.#n?.localTime;if(w===YA&&(i.cache?.delete(D),this.#n=i.getEntry(D),ke.default.trace?.("re-retrieved record",w,this.#n?.localTime),w=this.#n?.localTime),ke.default.trace?.("Subscription from",U,"from",D,w),U<w){let L=[],q=w;do{let W=l.get(q);if(W){_.omitCurrent=!0;let Q=At(W),B=Q.getValue(i,T,q);T&&(Q.type="put"),L.push({id:D,value:B,localTime:q,...Q}),q=Q.previousLocalTime}else break;A&&A--}while(q>U&&A!==0);for(let W=L.length;W>0;)x(L[--W]);P.startTime=w}!_.omitCurrent&&this.doesExist()&&x({id:D,localTime:w,value:this.#e,version:this.#r,type:"put"})}for(let w of C)x(w);C=null})();function x(D){c!=="system"&&Ve(D.size??1,"db-message",s,null),P.send(D)}return a(x,"send"),_.listener&&P.on("data",_.listener),P}static subscribeOnThisThread(_,T){return _===0||T?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(_,T,C){if(T===void 0||T instanceof URLSearchParams)this._writePublish(this.getId(),_,T);else{let P=!0,O=this.getContext();return _.checkPermission&&(P=this.allowCreate(O.user,_,O)),qs(P,x=>{if(!x)throw new ut.AccessViolation(O.user);let D=Ds(_);this._writePublish(D,T,C)})}}_writePublish(_,T,C){let P=Br(this.getContext());_??=null,_!==null&&Hi(_);let O=this.getContext();P.addWrite({key:_,store:i,entry:this.#n,nodeName:O?.nodeName,validate:a(()=>{O?.source||(P.checkOverloaded(),this.validate(T))},"validate"),before:be.publish?.bind(this,O,_,T),beforeIntermediate:Pu(T,Ye.publish?.bind(this,O,_,T)),commit:a((x,D,A)=>{D===void 0&&R&&!g&&xa(),ke.default.trace?.(`Publishing message to id: ${_}, timestamp: ${new Date(x).toISOString()}`),y(_,D?.value??null,D,D?.version||x,0,!0,{user:O?.user,residencyId:C?.residencyId,expiresAt:O?.expiresAt,nodeId:C?.nodeId,tableToTrack:s},"message",!1,T)},"commit")})}validate(_,T){let C,P=a((O,x,D)=>{if(x.type&&O!=null)if(T&&O.__op__&&(O=O.value),x.properties){typeof O!="object"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an object${x.type?" ("+x.type+")":""}`);let A=x.properties;for(let U=0,w=A.length;U<w;U++){let L=A[U];if(L.relationship||L.computed){_.hasOwnProperty(L.name)&&(C||(C=[])).push(`Computed property ${D}.${L.name} may not be directly assigned a value`);continue}let q=P(O[L.name],L,D+"."+L.name);q&&(O[L.name]=q)}if(x.sealed&&O!=null&&typeof O=="object")for(let U in O)A.find(w=>w.name===U)||(C||(C=[])).push(`Property ${U} is not allowed within object in property ${D}`)}else switch(x.type){case"Int":(typeof O!="number"||O>>0!==O)&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(A=>typeof A=="string")||(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a string`);break;case"Boolean":typeof O!="boolean"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a bigint`)}break;case"Bytes":if(!(O instanceof Uint8Array)){if(typeof O=="string")return Buffer.from(O);(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(O instanceof Ms)){if(typeof O=="string"&&(O=Buffer.from(O)),O instanceof Buffer)return createBlob(O,{type:"text/plain"});(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a Blob`)}break;case"array":if(Array.isArray(O)){if(x.elements)for(let A=0,U=O.length;A<U;A++){let w=O[A],L=P(w,x.elements,D+"[*]");L&&(O[A]=L)}}else(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an Array`);break}x.nullable===!1&&O==null&&(C||(C=[])).push(`Property ${D} is required (and not does not allow null values)`)},"validateValue");for(let O=0,x=S.length;O<x;O++){let D=S[O];if(D.relationship||D.computed){Object.hasOwn(_,D.name)&&(C||(C=[])).push(`Computed property ${D.name} may not be directly assigned a value`);continue}if(!T||D.name in _){let A=P(_[D.name],D,D.name);A!==void 0&&(_[D.name]=A)}}if(f)for(let O in _)S.find(x=>x.name===O)||(C||(C=[])).push(`Property ${O} is not allowed`);if(C)throw new ut.ClientError(C.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return I?!!this.#i:void 0}static async addAttributes(_){let T=S.slice(0);for(let C of _){if(!C.name)throw new ut.ClientError("Attribute name is required");if(C.name.match(/[`/]/))throw new ut.ClientError("Attribute names cannot include backticks or forward slashes");Bae(C.name),T.push(C)}return Xe({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static async removeAttributes(_){let T=S.filter(C=>!_.includes(C.name));return Xe({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static getSize(){let _=i.getStats();return(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getAuditSize(){let _=l?.getStats();return _&&(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getStorageStats(){let _=i.env.path,T=SN.default.statfsSync?.(_)??{};return{available:T.bavail*T.bsize,free:T.bfree*T.bsize,size:T.blocks*T.bsize}}static async getRecordCount(_){let T=i.getStats().entryCount,C=1e3/2,P=performance.now(),O=Math.floor(T/2),x=_?.exactCount,D=0,A=0,U;for(let{value:w}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(w!=null&&D++,A++,await oc(),!x&&A<O&&performance.now()-P>C){U=A;break}if(U){let w=D;D=0;for(let{value:re}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:U,snapshot:!1}))re!=null&&D++,await oc();let L=U*2,q=(D+w)/L,W=Math.pow((D-w+1)/U/2,2)+q*(1-q)/L,Q=Math.max(Math.sqrt(W)*T,1),B=Math.round(q*T),Ee=Math.max(B-1.96*Q,D+w),fe=Math.min(B+1.96*Q,T),pe=Math.pow(10,Math.round(Math.log10(Q)));return pe>B&&(pe=pe/10),D=Math.round(B/pe)*pe,{recordCount:D,estimatedRange:[Math.round(Ee),Math.round(fe)]}}return{recordCount:D}}static updatedAttributes(){xr=this.propertyResolvers={$id:a((_,T,C)=>({value:C.key}),"$id"),$updatedtime:a((_,T,C)=>C.version,"$updatedtime"),$updatedTime:a((_,T,C)=>C.version,"$updatedTime"),$expiresAt:a((_,T,C)=>C.expiresAt,"$expiresAt"),$record:a((_,T,C)=>C?{value:_}:_,"$record"),$distance:a((_,T,C)=>C&&(C.distance??T?.vectorDistances?.get(C)),"$distance")};for(let _ of this.attributes){_.isPrimaryKey&&($=_),_.resolve=null;let T=_.relationship,C=_.computed;if(T)if(_.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),C&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),wu=!0,T.to)_.elements?.definition?(xr[_.name]=_.resolve=(P,O,x,D)=>{let A=P[T.from?T.from:t],U=_.elements.definition.tableClass;return D?ju({attribute:T.to,value:A},Br(O).getReadTxn(),!1,U,!1).map(w=>w&&w.key!==void 0?w:U.primaryStore.getEntry(w,{transaction:Br(O).getReadTxn()})).asArray:U.search([{attribute:T.to,value:A}],O).asArray},_.set=()=>{},_.resolve.definition=_.elements.definition,_.resolve.to=T.to,T.from&&(_.resolve.from=T.from)):console.error(`The one-to-many/many-to-many relationship property "${_.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(T.from){let P=_.definition||_.elements?.definition;P?(xr[_.name]=_.resolve=(O,x,D,A)=>{let U=O[T.from];if(U===void 0)return;if(_.elements){let L,q=U?.map(W=>{let Q=P.tableClass.primaryStore[A?"getEntry":"get"](W,{transaction:Br(x).getReadTxn()});return Q?.then&&(L=!0),ve.loadAsInstance===!1&&Object.freeze(A?Q?.value:Q),Q});return T.filterMissing?L?Promise.all(q).then(W=>W.filter(ZG)):q.filter(ZG):L?Promise.all(q):q}let w=P.tableClass.primaryStore[A?"getEntry":"get"](U,{transaction:Br(x).getReadTxn()});return ve.loadAsInstance===!1&&Object.freeze(A?w?.value:w),w},_.set=(O,x)=>{if(Array.isArray(x)){let D=x.map(A=>A.getId?.()||A[P.tableClass.primaryKey]);O[T.from]=D}else{let D=x.getId?.()||x[P.tableClass.primaryKey];O[T.from]=D}},_.resolve.definition=_.definition||_.elements?.definition,_.resolve.from=T.from):console.error(`The relationship property "${_.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${_.name}" in table "${s}" must use either "from" or "to" arguments`);else if(C)typeof C.from=="function"&&this.setComputedAttribute(_.name,C.from),xr[_.name]=_.resolve=(P,O,x)=>{let D=typeof C.from=="string"?P[C.from]:P,A=this.userResolvers[_.name];if(A)return A(D,O,x);ke.default.warn(`Computed attribute "${_.name}" does not have a function assigned to it. Please use setComputedAttribute('${_.name}', resolver) to assign a resolver function.`),this.userResolvers[_.name]=()=>{}},_.resolve.directReturn=!0;else if(r[_.name]?.customIndex?.propertyResolver){let P=r[_.name].customIndex;xr[_.name]=(O,x,D)=>{let A=O[_.name];return P.propertyResolver(A,x,D)},xr[_.name].directReturn=!0}}Tp(this,this),Tp(lm,this,!0);for(let _ of S){let T=_.name;_.resolve&&(Object.defineProperty(i.encoder.structPrototype,T,{get(){return _.resolve(this,Xu.getStore())},set(C){return _.set(this,C)},configurable:!0,enumerable:_.enumerable}),_.enumerable&&!i.encoder.structPrototype.toJSON&&Object.defineProperty(i.encoder.structPrototype,"toJSON",{configurable:!0,value(){let C={};for(let P in this)C[P]=this[P];return C}}))}}static setComputedAttribute(_,T){let C=zi(S,_);if(!C){console.error(`The attribute "${_}" does not exist in the table "${s}"`);return}if(!C.computed){console.error(`The attribute "${_}" is not defined as computed in the table "${s}"`);return}this.userResolvers[_]=T}static async deleteHistory(_=0,T=!1){let C;for(let{key:P,value:O}of l.getRange({start:0,end:_}))await oc(),At(O).tableId===n&&(C=z_(l,P,O));if(T)for(let P of i.getRange({start:0,versions:!0})){let{key:O,value:x,localTime:D}=P;await oc(),x===null&&D<_&&(C=ul(i,P))}await C}static async*getHistory(_=0,T=1/0){for(let{key:C,value:P}of l.getRange({start:_||1,end:T})){await oc();let O=At(P);O.tableId===n&&(yield{id:O.recordId,localTime:C,version:O.version,type:O.type,value:O.getValue(i,!0,C),user:O.user,operation:O.originatingOperation})}}static async getHistoryOfRecord(_){let T=[];if(_==null)throw new Error("An id is required");let C=i.getEntry(_);if(!C)return T;let P=C.localTime;if(!P)throw new Error("The entry does not have a local audit time");let O=0;do{await oc();let x=l.get(P);if(x){let D=At(x);T.push({id:D.recordId,localTime:P,version:D.version,type:D.type,value:D.getValue(i,!0,P),user:D.user}),P=D.previousLocalTime}else break}while(O<1e3&&P);return T.reverse()}static cleanup(){Y?.remove()}}let t_=oS(async(K,_,T)=>{for(let C of ve.sources)if(C.get&&(!C.get.reliesOnPrototype||C.prototype.get)){if(C.available?.(T)===!1)continue;_.source=C;let P=await C.get(K,_);if(P)return P}},()=>{throw new ut.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});ve.updatedAttributes();let wb=ve.prototype;return h&&ve.setTTLExpiration(h/1e3),j&&r_(),ve;function Nu(K,_,T){let C;for(let P in r){let O=r[P],x=O.isIndexing,D=xr[P],A=T&&(D?D(T):T[P]),U=_&&(D?D(_):_[P]);if(A===U&&!x)continue;if(O.customIndex){O.customIndex.index(K,A,U);continue}C=!0;let w=O.indexNulls,L=(0,Hp.getIndexedValues)(A,w),q=(0,Hp.getIndexedValues)(U,w);if(q?.length>0){let W=new Set(q);if(L=L?L.filter(Q=>{if(W.has(Q))W.delete(Q);else return!0}):[],q=Array.from(W),(q.length>0||L.length>0)&&WG){let Q=q.concat(L).map(B=>({key:B,value:K}));O.prefetch(Q,JG)}for(let Q=0,B=q.length;Q<B;Q++)O.remove(q[Q],K)}else L?.length>0&&WG&&O.prefetch(L.map(W=>({key:W,value:K})),JG);if(L)for(let W=0,Q=L.length;W<Q;W++)O.put(L[W],K)}return C}a(Nu,"updateIndices");function Hi(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>jG)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");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,xl.writeKey)(K,Vae,0)>jG)throw new Error("Primary key size is too large: "+K.length);return!0}a(Hi,"checkValidId");function Ds(K){return typeof K=="object"&&K?K.id:K}a(Ds,"requestTargetToId");function um(K){return typeof K=="object"&&K&&K.isCollection}a(um,"isSearchTarget");function dm(K){}a(dm,"isRequestTarget");function Lo(K,_,T,C,P){if(ve.getResidencyById&&T.ensureLoaded&&_?.replicateFrom!==!1){let x=Ba(ve.getResidencyById(K));if(x&&!x.includes(server.hostname)&&N)return N({key:K,residency:x}).then(P)}let O=a(()=>{if(_?.transaction?.stale&&(_.transaction.stale=!1),T.transaction?.isDone)return P(null,K);let x=i.getEntry(K,T);return(c!=="system"||s==="hdb_analytics")&&(rq.default.trace?.("Recording db-read action for",`${c}.${s}`),Ve(x?.size??1,"db-read",s,null)),_?._freezeRecords&&Object.freeze(x?.value),x?.residencyId&&x.metadataFlags&Fn&&N&&T.ensureLoaded&&_?.replicateFrom!==!1?N(x).then(D=>P(D,K),D=>(ke.default.error?.("Error loading remote record",K,x,T,D),P(null,K))):(x&&_&&(x?.version>(_.lastModified||0)&&(_.lastModified=x.version),x?.localTime&&!_.lastRefreshed&&(_.lastRefreshed=x.localTime)),P(x,K))},"whenPrefetched");return C?O():te>0?(te--,O()):new Promise((x,D)=>{te===0?(te--,i.prefetch([K],()=>{A(),U()})):(ce.push(K),de.push(U),ce.length>e_&&(te--,A()));function A(){if(ce.length>0){let w=de;i.prefetch(ce,()=>{te===-1?A():te++;for(let L of w)L()}),ce=[],de=[],ge>2&&ge--}else te=ge,ge<cm&&ge++}a(A,"prefetch");function U(){try{x(O())}catch(w){D(w)}}a(U,"load")})}a(Lo,"loadLocalRecord");function Dn(K,_){let T=_?.checkPermission;if(typeof T!="object"){if(!K?.role)return;T=K.role.permission}if(T.super_user)return Kae;let C=T[c],P,O=C?.tables;if(O)return O[s];if(c==="data"&&(P=T[s])&&!P.tables)return P}a(Dn,"getTablePermissions");function pn(K,_,T,C){if(I){let P=!1;if(T.noCache?P=!0:(_?(!_.value||_.metadataFlags&(Fn|dl)||_.expiresAt!=null&&_.expiresAt<Date.now())&&(P=!0):P=!0,tn(!P,"cache-hit",s)),P){let O=Ou(K,_,T).then(x=>(x?.value&&x?.value.getRecord?.()&&ke.default.error?.("Can not assign a record that is already a resource"),T&&(x?.version>(T.lastModified||0)&&(T.lastModified=x.version),T.lastRefreshed=Date.now()),x));if(T?.onlyIfCached||_?.value&&C?.allowStaleWhileRevalidate?.(_,K)){if(O.catch(x=>ke.default.warn?.(x)),T?.onlyIfCached&&!C.doesExist())throw new ut.ServerError("Entry is not cached",504);return}else return O}}else if(_?.value&&_.expiresAt!=null&&_.expiresAt<Date.now())return ve.evict(_.key,_.value,_.version),_.value=null,{then(P){return P(_)}}}a(pn,"ensureLoadedFromSource");function Br(K){let _=K?.transaction;if(_){if(!_.lmdbDb)return _.lmdbDb=i,_;do{if(_.lmdbDb?.path===i.path)return _;let T=_.next;if(!T)return _=_.next=new vo,_.lmdbDb=i,_;_=T}while(!0)}else return new A_}a(Br,"txnForContext");function Cu(K,_,T){if(!K)return;let C=(K.deref?K.deref():K.value)??i.getEntry(K.key)?.value;if(typeof _=="object"){let O=xr,x=C;for(let D=0,A=_.length;D<A;D++){let U=_[D],w=O?.[U];x=w&&x?w(x,T,K):x?.[U],K=null,O=w?.definition?.tableClass?.propertyResolvers}return x}let P=xr[_];return P?P(C,T,K):C[_]}a(Cu,"getAttributeValue");function fm(K,_,T,C,P){let O=P?.length,x={transaction:C,lazy:O>0||typeof _=="string"||_?.length<4,alwaysPrefetch:!0},D;function A(U,w){let L=U?.value;if(!L)return ac.SKIP;for(let q=0;q<O;q++)if(!D?.includes(q)&&!P[q](L,U))return ac.SKIP;return w!==void 0&&(U.key=w),U}if(a(A,"processEntry"),O>0||!K.hasEntries){let U=K.map(w=>{if(D=null,typeof w=="object"&&w?.key!==void 0)return O>0?A(w):w;if(w==null)return ac.SKIP;for(let L=0;L<O;L++){let W=P[L].idFilter;if(W){if(!W(w))return ac.SKIP;D||(D=[]),D.push(L)}}return Lo(w,T,x,!1,A)});return Array.isArray(K)&&(U=U.filter(w=>w!==ac.SKIP)),U.hasEntries=!0,U}return K}a(fm,"transformToEntries");function Fr(K,_,T=server.replication?.getThisNodeId(l)){if(K<=_?.version){if(_?.version===K&&T!==void 0){let C=server.replication?.exportIdMapping(l),P=_.localTime,O=P&&l.get(P);if(O){let x,D,A=At(O);for(let U in C)C[U]===T&&(x=U),C[U]===A.nodeId&&(D=U);if(x>D)return 1;if(x===D)return 0}}return-1}return 1}a(Fr,"precedesExistingVersion");async function Ou(K,_,T){let C=_?.metadataFlags,P=_?.version,O,x;if(!i.attemptLock(K,P,()=>{clearTimeout(x);let w=i.getEntry(K);!w||!w.value||w.metadataFlags&(Fn|dl)?O(Ou(K,i.getEntry(K),T)):O(w)}))return new Promise(w=>{O=w,x=setTimeout(()=>{i.unlock(K,P)},qae)});let D=_?.value,A={requestContext:T,replacingRecord:D,replacingEntry:_,replacingVersion:P,noCacheStore:!1,source:null,resourceCache:T?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},U=T?.responseHeaders;return new Promise((w,L)=>{let q;qs(bt(A,async W=>{let Q=performance.now(),B,Ee,fe;try{B=await t_(K,A,_),fe=C&Fn;let re=A.lastModified||fe&&P;Ee=fe||re>P||!D,re||(re=(0,Hp.getNextMonotonicTime)());let ie=performance.now()-Q;if(Ve(ie,"cache-resolution",s,null,"success"),U&&Fp(U,"Server-Timing",`cache-resolve;dur=${ie.toFixed(2)}`,!0),W.timestamp=re,h&&A.expiresAt==null&&(A.expiresAt=Date.now()+h),B){if(typeof B!="object")throw new Error("Only objects can be cached and stored in tables");if(B.status>0&&B.headers)if(B.status>=300)if(B.status===304)B=D,re=P;else throw new ut.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==K&&(B[t]=K)}q=!0,w({key:K,version:re,value:B})}catch(re){re.message+=` while resolving record ${K} for ${s}`,D&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!T?.mustRevalidate||T?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(w({key:K,version:P,value:D}),ke.default.trace?.(re.message,"(returned stale record)")):L(re);let ie=performance.now()-Q;Ve(ie,"cache-resolution",s,null,"fail"),U&&Fp(U,"Server-Timing",`cache-resolve;dur=${ie.toFixed(2)}`,!0),A.transaction.abort();return}if(T?.noCacheStore||A.noCacheStore){A.transaction.abort();return}Br(A).addWrite({key:K,store:i,entry:_,nodeName:"source",before:Pu(B),commit:a((re,ie)=>{if(ie?.version!==P)return;let Oe=Nu(K,D,B);if(B){Ye.put?.(A,K,B),ie&&(T.previousResidency=ve.getResidencyRecord(ie.residencyId));let le,ae=!1,xe,Ce=Ba(ve.getResidency(B,T));if(Ce){if(!Ce.includes(server.hostname))if(le=B,ae=!0,ve.getResidencyById)B=void 0;else{B=null;for(let Le in r)B||(B={}),B[Le]=le[Le]}xe=Yc(Ce)}ke.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),y(K,B,ie,re,ae?Fn:0,g&&(Ee||ae)||null,{user:A?.user,expiresAt:A.expiresAt,residencyId:xe,tableToTrack:s},"put",!!fe,le)}else ie&&(Ye.delete?.(A,K),ke.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),g||R?y(K,null,ie,re,0,g&&Ee||null,{user:A?.user,tableToTrack:s},"delete",!!fe):ul(i,ie,P))},"commit")})}),()=>{i.unlock(K,P)},W=>{i.unlock(K,P),q&&ke.default.error?.("Error committing cache update",W)})})}a(Ou,"getFromSource");function Ua(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new ut.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new ut.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Ua,"checkContextPermissions");function xa(K){let _=!1;if(K&&(K-Ar>1&&(_=!0),Ar=K),!(qe===er&&!_)&&(er=qe,(0,Ml.getWorkerIndex)()===(0,Ml.getWorkerCount)()-1))return Qr&&clearTimeout(Qr),qe?new Promise(T=>{let C=new Date;C.setMonth(0),C.setDate(1),C.setHours(0),C.setMinutes(0),C.setSeconds(0);let P=qe/(1+Ar),O=_?Date.now():Math.ceil((Date.now()-C.getTime())/P)*P+C.getTime(),x=a(D=>{ke.default.trace?.(`Scheduled next cleanup scan at ${new Date(D)}`),Qr=setTimeout(()=>ee=ee.then(async()=>{if(x(Math.max(D+qe,Date.now())),i.rootStore.status!=="open"){clearTimeout(Qr);return}let A=50,U=new Array(A),w=0,L=Math.pow(Ar,8)*(Ul.get(F.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),q=E/Math.pow(Math.max(Ar,1),4);ke.default.debug?.(`Starting cleanup scan for ${s}, evict threshold ${L}, adjusted eviction ${q}ms`);function W(Q,B,Ee,fe){let pe=Q+q-Date.now();if(pe<0)return!0;if(Ar){let re=i.lastSize;return Ee&Zr&&el(fe,ie=>{ie.size&&(re+=ie.size)}),ke.default.trace?.(`shouldEvict adjusted ${pe} ${re}, ${pe*(Q-B)/re} < ${L}`),pe*(Q-B)/re<L}return!1}a(W,"shouldEvict");try{let Q=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:Ee,value:fe,version:pe,expiresAt:re,metadataFlags:ie}=B,Oe;fe===null&&!g&&pe+Gae<Date.now()?Oe=ul(i,B,pe):re!=null&&W(re,pe,ie,fe)&&(Oe=ve.evict(Ee,fe,pe),Q++),Oe&&(await U[w],U[w]=Oe.catch(le=>{ke.default.error?.("Cleanup error",le)}),++w>=A&&(w=0)),await oc()}ke.default.debug?.(`Finished cleanup scan for ${s}, evicted ${Q} entries`)}catch(Q){ke.default.warn?.(`Error in cleanup scan for ${s}:`,Q)}T(void 0),Ar=0}),Math.min(D-Date.now(),2147483647)).unref()},"startNextTimer");x(O)}):void 0}a(xa,"scheduleCleanup");function mm(){Y=l?.addDeleteRemovalCallback(n,i,(K,_)=>{i.remove(K,_)})}a(mm,"addDeleteRemoval");function r_(){(0,Ml.getWorkerIndex)()===0&&setInterval(async()=>{if(!Kc){Kc=!0;try{let K=j.name,_=r[K];if(!_)throw new Error(`expiresAt attribute ${j} must be indexed`);for(let T of _.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let C of _.getValues(T)){let P=i.getEntry(C);P?.value?P.value[K]<Date.now()&&ve.evict(C,P.value,P.version):i.ifVersion(C,P?.version,()=>_.remove(T,C))}await oc()}}catch(K){ke.default.error?.("Error in evicting old records",K)}finally{Kc=!1}}},Hae).unref()}a(r_,"runRecordExpirationEviction");function Ba(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let _=server.shards?.get?.(K);if(_)return ke.default.trace?.(`Shard ${K} mapped to ${_.map(T=>T.name).join(", ")}`),_.map(T=>T.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(Ba,"residencyFromFunction");function Yc(K){if(K){let _=K.join(","),T=d.get([Symbol.for("residency_by_set"),_]);return T||(d.put([Symbol.for("residency_by_set"),_],T=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),T],K),T)}}a(Yc,"getResidencyId");function Pu(K,_){let T=_A(K,i.rootStore);if(T){let C=_;return C?async()=>{await C(),await T}:()=>T}return _}a(Pu,"preCommitBlobsForRecordBefore")}function gN(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 JG(){}function cS(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return aS(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return aS(+e);case"Float":return e==="null"?null:aS(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;Yae.test(e)||(e+="Z");let n=new Date(e);return aS(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,lS.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function aS(e){if(isNaN(e))throw new SyntaxError;return e}function XG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);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 qs(e,t,r){return e?.then?e.then(t,r):t(e)}function ZG(e){return e!=null}function $s(e){try{return JSON.stringify(e)}catch{return e}}function Wae(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var ac,Hp,eq,tq,Ul,ut,Gp,qp,ke,xl,Ml,lS,SN,rq,xae,Bae,Fae,kae,Hae,Gae,WG,qae,zG,$ae,Fn,dl,Vae,jG,QG,Kae,LMe,Yae,oc,mg=se(()=>{H();ac=require("lmdb"),Hp=b(Un()),eq=b(require("lodash")),tq=b(Cm());Vo();Pm();Ul=b(me());sI();ut=b(_e()),Gp=b(Wo()),qp=b(ls());we();fg();ke=b(wr());fw();Ga();xl=require("ordered-binary"),Ml=b(st());$i();lS=b(oe());al();is();N_();kp();SN=b(require("node:fs"));ss();V_();rq=b(J());_N();({sortBy:xae}=eq.default),{validateAttribute:Bae}=tq.default,Fae=new Uint8Array(9);Fae[8]=192;kae=1/0,Hae=6e4,Gae=864e5;Ul.initSync();WG=Ul.get(F.STORAGE_PREFETCHWRITES),qae=1e4,zG=1,$ae=2,Fn=1,dl=8,Vae=Buffer.allocUnsafeSlow(8192),jG=1978,QG=100,Kae={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},LMe=(0,lS.convertToMS)(Ul.get(F.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(uS,"makeTable");a(gN,"attributesAsObject");a(JG,"noop");Yae=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(cS,"coerceType");a(aS,"rejectNaN");a(XG,"isDescendantId");oc=a(()=>new Promise(setImmediate),"rest");a(qs,"when");a(ZG,"exists");a($s,"stringify");a(Wae,"hasOtherProcesses")});function dS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Euclidean distance comparison requires an array");let r=0,n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let i=e[s]||0,o=t[s]||0,c=i-o;r+=c*c}return r}function fS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Cosine distance comparison requires an array");let r=0,n=0,s=0,i=Math.max(e.length,t.length);for(let o=0;o<i;o++){let c=e[o]||0,l=t[o]||0;r+=c*l,n+=c*c,s+=l*l}return n=Math.sqrt(n),s=Math.sqrt(s),1-r/(n*s||1)}var sq=se(()=>{a(dS,"euclideanDistance");a(fS,"cosineDistance")});var iq,oq,Ad,co,bd,zae,jae,mS,aq=se(()=>{sq();iq=require("msgpackr"),oq=b(wr()),Ad=b(_e()),co=(0,oq.loggerWithTag)("HNSW"),bd=Symbol.for("entryPoint"),zae=Symbol.for("key"),jae=10,mS=class{static{a(this,"HierarchicalNavigableSmallWorld")}static useObjectStore=!0;indexStore;M=16;efConstruction=100;efConstructionSearch=50;mL=1/Math.log(this.M);optimizeRouting=.5;nodesVisitedCount=0;idIncrementer;distance;constructor(t,r){this.indexStore=t,t&&(this.indexStore.encoder.useFloat32=iq.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?dS:fS,r&&(r.M!==void 0&&(this.M=r.M,this.mL=1/Math.log(this.M)),r.efConstruction!==void 0&&(this.efConstruction=this.efConstructionSearch=r.efConstruction),r.efConstructionSearch!==void 0&&(this.efConstructionSearch=r.efConstructionSearch),r.mL!==void 0&&(this.mL=r.mL),r.optimizeRouting!==void 0&&(this.optimizeRouting=r.optimizeRouting))}index(t,r,n){let s=typeof t=="number"?[zae,t]:t,i=this.indexStore.get(s);if(!i){if(!r)return;if(!this.idIncrementer){let f=0;for(let m of this.indexStore.getKeys({reverse:!0,limit:1,start:1/0,end:0}))typeof m=="number"&&(f=m);this.idIncrementer=new BigInt64Array([BigInt(f)+1n]),this.idIncrementer=new BigInt64Array(this.indexStore.getUserSharedBuffer("next-id",this.idIncrementer.buffer))}i=Number(Atomics.add(this.idIncrementer,0,1n)),this.indexStore.put(s,i)}let o=new Map,c,l=this.indexStore.get(bd);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f===void 0){let E=Math.floor(-Math.log(Math.random())*this.mL),g={vector:r,level:E,primaryKey:t};for(let R=0;R<=E;R++)g[R]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);co.debug?.("setting entry point to",i),this.indexStore.put(bd,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),jae),p=f.level;if(m>=p){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);co.debug?.("setting entry point to",i),this.indexStore.put(bd,i)}for(;p>m;){let E=this.searchLayer(r,l,f,this.efConstruction,p);E.length>0&&(l=E[0].id,f=E[0].node),p--}let h=new Array(m+1);for(let E=0;E<=m;E++)h[E]=[];for(let E=Math.min(m,p);E>=0;E--){let g=this.searchLayer(r,l,f,this.efConstruction,E);g=g.slice(0,this.M<<1),g.length===0&&E===0&&co.info?.("should not have zero connections for",l);let R=h[E];for(let S=0;S<g.length;S++){let{id:y,distance:N,node:I}=g[S];if(y===i)continue;let $=[];if(this.optimizeRouting){let k=!1,j=I[E],Y=1+this.optimizeRouting*(1+.5*S/this.M);for(let ce=0;ce<j.length;ce++){let{id:de,distance:te}=j[ce],ge=1+this.optimizeRouting*(1+.5*ce/this.M);for(let be=0;be<R.length;be++){let{id:Ye,distance:qe}=R[be];if(Ye===de){N*Y>qe+te?k=!0:te*ge>N+qe&&($.push({fromId:Ye,toId:y}),$.push({fromId:y,toId:Ye}));break}}if(k)break}if(k)continue}else if(S>=(E>0?this.M:this.M<<1))continue;R.push({id:y,distance:N});for(let{fromId:k,toId:j}of $){let Y=d(k);Y||(Y=d(k,this.indexStore.get(k)));for(let ce=0;ce<Y[E].length;ce++)if(Y[E][ce].id===j){Object.isFrozen(Y[E])&&(Y[E]=Y[E].slice()),Y[E].splice(ce,1);break}}let ee=c[E],G=ee?.find(({id:k})=>k===y);if(G){let k=ee?.indexOf(G);ee.copied||(ee=[...ee],ee.copied=!0,c[E]=ee),ee.splice(k,1)}else this.addConnection(y,d(y,I),i,E,N,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...h})}else{if(l===i){let f=c.level??0;for(let m=f;m>=0&&(l=c[m][0]?.id,l===void 0);m--);if(l===void 0){let m=-1;for(let{key:p,value:h}of this.indexStore.getRange({start:0,end:1/0}))if(h.level>m){if(l=p,h.level===f)break;m=h.level}}if(l===void 0)this.indexStore.remove(bd);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);co.debug?.("setting entry point to",l),this.indexStore.put(bd,l)}}this.indexStore.remove(i)}let u=new Map;if(c.level!==void 0)for(let f=0;f<=c.level;f++){let m=c[f];for(let{id:p}of m){let h=d(p,this.indexStore.get(p));for(let E=0;E<=f;E++)h[E]=h[E]?.filter(({id:g})=>g!==i),h[E].length===0&&(co.info?.("node was left orphaned, will reindex",p),u.set(h.primaryKey,h.vector))}}function d(f,m){let p=o.get(f);return!p&&m&&(p={...m},o.set(f,p)),p}a(d,"updateNode");for(let[f,m]of o)this.indexStore.put(f,m);for(let[f,m]of u)this.index(f,m,m);this.checkSymmetry(i,this.indexStore.get(i))}getEntryPoint(){let t=this.indexStore.get(bd);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,o=this.distance){let c=new Set([r]),l=[{id:r,distance:this.distance(t,n.vector),node:n}],u=[...l];for(;l.length>0;){l.sort((p,h)=>p.distance-h.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:p}of m[i]||[]){if(c.has(p)||p===void 0)continue;c.add(p);let h=this.indexStore.get(p);if(!h)continue;this.nodesVisitedCount++;let E=o(t,h.vector);if(E<f||u.length<s){let g={id:p,distance:E,node:h};l.push(g),u.push(g)}}u.sort((p,h)=>p.distance-h.distance),u.length>s&&u.splice(s,u.length-s)}return u.visited=c.size,u}search({target:t,value:r,descending:n,distance:s,comparator:i}){let o=0;switch(i){case"lt":case"le":o=r;case"sort":break;default:throw new Ad.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Ad.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=fS;else if(s==="euclidean")c=dS;else{if(s)throw new Ad.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Ad.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Ad.ClientError("The target vector must be an array");let l=this.getEntryPoint();if(!l)return[];let u=l.id,d=[];for(let f=l.level;f>=0;f--)if(d=this.searchLayer(t,u,l,this.efConstructionSearch,f,c),d.length>0){let m=d[0];l=m.node,u=m.id}return o&&(d=d.filter(f=>f.distance<o)),d.map(f=>({key:f.node.primaryKey,distance:f.distance}))}checkSymmetry(t,r){if(!r)return;let n=0,s;for(;(s=r[n])&&s.length!==0;){for(let{id:i}of s){let o=this.indexStore.get(i);if(!o){co.info?.("could not find neighbor node",o);continue}o[n]?.find(({id:l})=>l==t)||co.info?.("asymmetry detected",o[n])}n++}}addConnection(t,r,n,s,i,o){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){co.warn?.("maxConnections reached, removing some connections",c);let l=[...r[s]];l.sort((f,m)=>f.distance-m.distance);let u=l.slice(0,c),d=l.slice(c);r[s]=u;for(let f of d){let m=o(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=o(f.id,m),m[s]=m[s].filter(({id:p})=>p!==t),s===0&&m[s].length===0&&co.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?co.debug?.("already connected",t,n):r[s]=[...r[s],{id:n,distance:i}]}validateConnectivity(t=0){let r=this.getEntryPoint(),n=new Set,s=[r.id];n.add(r.id);let i=0;for(;s.length>0;){let o=s.shift(),c=this.indexStore.get(o);for(let l=t;l<=c.level;l++)for(let{id:u}of c[l]||[])i++,n.has(u)||(n.add(u),s.push(u))}return n.size!==this.totalNodes&&console.log("visited",n.size,"total",this.totalNodes),{isFullyConnected:n.size===this.totalNodes,averageConnections:i/n.size}}get totalNodes(){return Array.from(this.indexStore.getKeys({start:0,end:1/0})).length}estimateCountAsSort(){return Math.sqrt(this.indexStore.getStats().entryCount*this.efConstructionSearch)}propertyResolver(t,r,n){let s=r?.sort;if(s){let i=s.vectorDistances;if(i){let l=i.get(n);if(l)return l}else i=r.vectorDistances=s.vectorDistances=new Map;let o=this.distance;s.type&&(o=s.distance==="euclidean"?dS:fS);let c=o(s.target,t);return i.set(n,c),c}return t}}});var TN,cq=se(()=>{aq();TN={HNSW:mS}});var ft={};ye(ft,{NON_REPLICATING_SYSTEM_TABLES:()=>pS,database:()=>ud,databaseEnvs:()=>Xo,databases:()=>Me,dropDatabase:()=>_w,dropTableMeta:()=>tce,getDatabases:()=>ct,getDefaultCompression:()=>yS,getTables:()=>Jae,onRemovedDB:()=>jp,onUpdatedTable:()=>Bl,readMetaDb:()=>$p,resetDatabases:()=>Od,table:()=>Xe,tables:()=>Rn});function zp(e,t){let r=SS.OpenDBIObject??SS.default.OpenDBIObject;return new r(e,t)}function Jae(){return gS||ct(),Rn||{}}function ct(){if(gS)return Me;gS=!0,Nd=new Map;let e=(0,zt.getHdbBasePath)()&&(0,kt.join)((0,zt.getHdbBasePath)(),jc),t=(0,zt.get)(F.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,zt.get)(F.STORAGE_PATH)||e&&((0,gs.existsSync)(e)?e:(0,kt.join)((0,zt.getHdbBasePath)(),l_)),!!e){if((0,gs.existsSync)(e))for(let r of(0,gs.readdirSync)(e,{withFileTypes:!0})){let n=(0,kt.basename)(r.name,".mdb");r.isFile()&&(0,kt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&$p((0,kt.join)(e,r.name),null,n)}if((0,gs.existsSync)((0,wd.getBaseSchemaPath)())){for(let r of(0,gs.readdirSync)((0,wd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,kt.join)((0,wd.getBaseSchemaPath)(),r.name),s=(0,kt.join)((0,wd.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,gs.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,kt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,kt.join)(s,i.name);$p((0,kt.join)(n,i.name),(0,kt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,gs.existsSync)(s))for(let o of(0,gs.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,kt.extname)(o.name).toLowerCase()===".mdb"&&$p((0,kt.join)(s,o.name),(0,kt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],l=(0,kt.join)(c.path,(0,kt.basename)(o+".mdb"));(0,gs.existsSync)(l)&&$p(l,o,r,null,!0)}}for(let r in Me){let n=Nd.get(r);if(n){let s=Me[r];r.includes("delete")&&Or.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Or.trace(`delete table class ${i}`),delete s[i])}else if(delete Me[r],r==="data"){for(let s in Rn)delete Rn[s];delete Rn[TS]}}if((0,zt.get)(F.ANALYTICS_REPLICATE)===!1?pS.includes("hdb_analytics")||pS.push("hdb_analytics"):(Me.system?.hdb_analytics?.enableAuditing(),Me.system?.hdb_analytics_hostname?.enableAuditing()),Me.system)for(let r of pS)Me.system[r]&&(Me.system[r].replicate=!1);return Nd=null,Me}}function Od(){gS=!1;for(let[,e]of Xo)e.needsDeletion=!0;ct();for(let[e,t]of Xo)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),Xo.delete(e);let r=Me[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete Me[t.databaseName],Kp.forEach(i=>i(t.databaseName));break}}return Me}function $p(e,t,r=bN,n,s){let i=new yN.default(e,!1);try{let o=Xo.get(e);o?o.needsDeletion=!1:(o=(0,Cd.open)(i),Xo.set(e,o));let c=new zp(!1),l=o.dbisDb||(o.dbisDb=o.openDB(hS.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,gs.existsSync)(n)&&(i.path=n,u=(0,Cd.open)(i),u.isLegacy=!0):u=W_(o));let d=mq(r),f=d[TS],m=new Map;for(let{key:p,value:h}of l.getRange({start:!1})){let[E,g]=p.toString().split("/");g===""?g=h.name:g||(g=E,E=t,h.name||(h.name=g,h.indexed=!h.is_hash_attribute)),f?.add(E);let R=m.get(E);R||m.set(E,R={attributes:[]}),(g==null||h.is_hash_attribute)&&(R.primary=h),g!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:p,configurable:!0})}for(let[p,h]of m){let{attributes:E,primary:g}=h;if(!g){for(let te of E)if(te.is_hash_attribute||te.isPrimaryKey){g=te;break}if(!g){Or.warn(`Unable to find a primary key attribute on table ${p}, with attributes: ${JSON.stringify(E)}`);continue}}let R=d[p],S={},y=[],N,I,$=typeof g.audit=="boolean"?g.audit:(0,zt.get)(F.LOGGING_AUDITLOG),ee=g.trackDeletes,G=g.expiration,k=g.eviction,j=g.sealed,Y=g.splitSegments,ce=g.replicate;if(R)S=R.indices,y=R.attributes,R.schemaVersion++;else{N=g.tableId,N?N>=(l.get(Id)||0)&&(l.putSync(Id,N+1),Or.info(`Updating next table id (it was out of sync) to ${N+1} for ${p}`)):(g.tableId=N=l.get(Id),N||(N=1),Or.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Id,N+1),l.putSync(g.key,g));let te=new zp(!g.is_hash_attribute,g.is_hash_attribute);if(te.compression=g.compression,te.compression){let ge=(0,zt.get)(F.STORAGE_COMPRESSION_THRESHOLD)||fq;te.compression.threshold=ge}I=cg(o.openDB(g.key,te),o),o.databaseName=r,I.tableId=N}let de;for(let te of E){te.attribute=te.name;try{if(!te.is_hash_attribute&&(te.indexed||te.attribute&&!te.name)){if(!S[te.name]){let be=hq(te.key,o,te);S[te.name]=be,S[te.name].indexNulls=te.indexNulls}let ge=y.find(be=>be.name===te.name);ge?y.splice(y.indexOf(ge),1,te):y.push(te),de=!0}}catch(ge){Or.error("Error trying to update attribute",te,y,S,ge)}}for(let te of y)if(!E.find(be=>be.name===te.name)){if(te.is_hash_attribute){Or.error("Unable to remove existing primary key attribute",te);continue}te.indexed&&(y.splice(y.indexOf(te),1),de=!0)}if(R)de&&(R.schemaVersion++,R.updatedAttributes());else{R=pq(d,p,uS({primaryStore:I,auditStore:u,audit:$,sealed:j,splitSegments:Y,replicate:ce,expirationMS:G&&G*1e3,evictionMS:k&&k*1e3,trackDeletes:ee,tableName:p,tableId:N,primaryKey:g.name,databasePath:s?r+"/"+p:r,databaseName:r,indices:S,attributes:E,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let te of Vp)te(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function mq(e){let t=Me[e];if(t||(e==="data"?t=Me[e]=Rn:e==="system"?Object.defineProperty(Me,"system",{value:t=Object.create(null),configurable:!0}):t=Me[e]=Object.create(null)),Nd&&!Nd.has(e)){let r=new Set;t[TS]=r,Nd.set(e,r)}return t}function pq(e,t,r){return e[t]=r,r}function ud({database:e,table:t}){e||(e=bN),ct();let r=mq(e),n=(0,kt.join)((0,zt.getHdbBasePath)(),jc),s=(0,zt.get)(F.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,zt.get)(F.STORAGE_PATH)||((0,gs.existsSync)(n)?n:(0,kt.join)((0,zt.getHdbBasePath)(),l_));let o=(0,kt.join)(n,(i?t:e)+".mdb"),c=Xo.get(o);if(!c||c.status==="closed"){let l=new yN.default(o,!1);c=(0,Cd.open)(l),Xo.set(o,c)}return c.auditStore||(c.auditStore=W_(c)),c}async function _w(e){if(!Me[e])throw new Error("Schema does not exist");let t=Me[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Xo.delete(r.path),r.status==="open"&&(await r.close(),await Yp.remove(r.path));if(r||(r=ud({database:e,table:null}),r.status==="open"&&(await r.close(),await Yp.remove(r.path))),e==="data"){for(let n in Rn)delete Rn[n];delete Rn[TS]}delete Me[e],Kp.forEach(n=>n(e)),await EA(r)}function hq(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&TN[r.indexed.type]?.useObjectStore,s=new zp(!n,n),i=t.openDB(e,s);if(r.indexed.type){let o=TN[r.indexed.type];o?i.customIndex=new o(i,r.indexed):Or.error(`The indexing type '${r.indexed.type}' is unknown`)}return i}function Xe(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:p}=e;r||(r=bN);let h=ud({database:r,table:t}),E=Me[r];Or.trace(`Defining ${t} in ${r}`);let g=E?.[t];if(h.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,S,y;m==null&&(m=!0);let N=new zp(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let I,$;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...o)}else{let Y=h.auditStore;S=o.find(ge=>ge.isPrimaryKey)||{},R=S.name,S.is_hash_attribute=S.isPrimaryKey=!0,S.schemaDefined=m,S.compression=yS(),f&&(S.trackDeletes=!0),c=S.audit=typeof c=="boolean"?c:(0,zt.get)(F.LOGGING_AUDITLOG),n&&(S.expiration=n),s&&(S.eviction=s),u??=!1,S.splitSegments=u,typeof l=="boolean"&&(S.sealed=l),typeof d=="boolean"&&(S.replicate=d),p&&(S.origins?S.origins.includes(p)||S.origins.push(p):S.origins=[p]),Or.trace(`${t} table loading, opening primary store`);let ce=new zp(!1,!0);ce.compression=S.compression;let de=t+"/";if(y=h.dbisDb=h.openDB(hS.INTERNAL_DBIS_NAME,N),j(),y.get(de))return $&&$(),Od(),Xe(e);let te=cg(h.openDB(de,ce),h);h.databaseName=r,te.tableId=y.get(Id),Or.trace(`Assigning new table id ${te.tableId} for ${t}`),te.tableId||(te.tableId=1),y.put(Id,te.tableId+1),S.tableId=te.tableId,g=pq(E,t,uS({primaryStore:te,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:te.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:m,dbisDB:y})),g.schemaVersion=1,I=!0,y.put(de,S)}let ee=g.indices;y=y||(h.dbisDb=h.openDB(hS.INTERNAL_DBIS_NAME,N)),g.dbisDB=y;let G=[];for(let{key:Y,value:ce}of y.getRange({start:!0})){let[de,te]=Y.toString().split("/");if(te===""&&(te=ce.name),te){if(de!==t)continue}else continue;let ge=o.find(Ye=>Ye.name===te),be=!ge?.indexed&&ce.indexed&&!ce.isPrimaryKey;if((!ge||be)&&(j(),I=!0,ge||y.remove(Y),be)){let Ye=g.indices[de];Ye&&G.push(Ye)}}let k=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(I=!0,Y.relationship))continue;let ce=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ce,configurable:!0});let de=y.get(ce);if(Y.isPrimaryKey){if(de=de||y.get(ce=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+de.expiration||void 0)||(+s||void 0)!==(+de.eviction||void 0)||Y.type!==de.type){let ge={...de};typeof c=="boolean"&&(c&&g.enableAuditing(c),ge.audit=c),n&&(ge.expiration=+n),s&&(ge.eviction=+s),l!==void 0&&(ge.sealed=l),d!==void 0&&(ge.replicate=d),Y.type&&(ge.type=Y.type),I=!0,j(),y.put(ce,ge)}continue}de?.attribute&&!de.name&&(de.indexed=!0);let te=!de||de.type!==Y.type||JSON.stringify(de.indexed)!==JSON.stringify(Y.indexed)||de.nullable!==Y.nullable||de.version!==Y.version||de.enumerable!==Y.enumerable||JSON.stringify(de.properties)!==JSON.stringify(Y.properties)||JSON.stringify(de.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let ge=hq(ce,h,Y);(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<Wp.workerData?.restartNumber)&&(I=!0,j(),de=y.get(ce),(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<Wp.workerData?.restartNumber)&&(I=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=de?.lastIndexedKey??void 0,Y.indexingPID=process.pid,ge.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:ge}),k.push(Y))),y.put(ce,Y)),de?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),ge.indexNulls=Y.indexNulls,ee[Y.name]=ge}else te&&(I=!0,j(),y.put(ce,Y))}}finally{$&&$()}if(I&&(g.schemaVersion++,g.updatedAttributes()),Or.trace(`${t} table loading, running index`),k.length>0||G.length>0?g.indexingOperation=ece(g,k,G):I&&ES.signalSchemaChange(new _S.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=p,I)for(let Y of Vp)Y(g,p!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Or.trace(`${t} table loaded`),g;function j(){$||h.transactionSync(()=>({then(Y){$=Y}}))}a(j,"startTxn")}async function ece(e,t,r){try{Or.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await ES.signalSchemaChange(new _S.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,Cd.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:p}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,p,()=>{for(let h=0;h<l;h++){let E=t[h],g=E.name,R=E.dbi;try{let S=E.resolve,y=m&&(S?S(m):m[g]);if(R.customIndex){R.customIndex.index(f,y);continue}let N=(0,lq.getIndexedValues)(y);if(N)for(let I=0,$=N.length;I<$;I++)R.put(N[I],f)}catch(S){o[g]||(o[g]=!0,Or.error(`Error indexing attribute ${g}`,S))}}}),s.then(()=>d--,h=>{d--,Or.error(h)}),Wp.workerData&&Wp.workerData.restartNumber!==dq.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=f,e.dbisDB.put(h.key,h);if(i)return}d>Xae?await s:d>Zae&&await new Promise(h=>setImmediate(h))}for(let f of t)delete f.lastIndexedKey,delete f.indexingPID,f.dbi.isIndexing=!1,s=e.dbisDB.put(f.key,f)}await s,await ES.signalSchemaChange(new _S.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Or.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Or.error("Error in indexing",n)}}function tce({table:e,database:t}){let r=ud({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 Bl(e){return Vp.push(e),{remove(){let t=Vp.indexOf(e);t>-1&&Vp.splice(t,1)}}}function jp(e){return Kp.push(e),{remove(){let t=Kp.indexOf(e);t>-1&&Kp.splice(t,1)}}}function yS(){let e=(0,zt.get)(F.STORAGE_COMPRESSION),t=(0,zt.get)(F.STORAGE_COMPRESSION_DICTIONARY),r=(0,zt.get)(F.STORAGE_COMPRESSION_THRESHOLD)||fq,n={startingOffset:32};return t&&(n.dictionary=Yp.readFileSync(t)),r&&(n.threshold=r),e&&n}var zt,hS,Cd,kt,gs,wd,yN,Yp,RN,lq,ES,_S,Wp,uq,dq,SS,Qae,Or,bN,TS,fq,pS,Rn,Me,Id,Vp,Kp,gS,Xo,Nd,Xae,Zae,we=se(()=>{zt=b(me()),hS=b(Yt()),Cd=require("lmdb"),kt=require("path"),gs=require("fs"),wd=b(Rt());mg();yN=b(rp());H();Yp=b(require("fs-extra")),RN=b(ci()),lq=b(Un()),ES=b(Wo()),_S=b(ls()),Wp=require("worker_threads"),uq=b(J()),dq=b(st());$i();al();ss();cq();SS=b(tp()),{forComponent:Qae}=uq.default;a(zp,"OpenDBIObject");Or=Qae("storage"),bN="data",TS=Symbol("defined-tables"),fq=((0,zt.get)(F.STORAGE_PAGESIZE)||4096)-60;(0,zt.initSync)();pS=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_info"],Rn=Object.create(null),Me=Object.create(null);(0,RN._assignPackageExport)("databases",Me);(0,RN._assignPackageExport)("tables",Rn);Id=Symbol.for("next-table-id"),Vp=[],Kp=[],Xo=new Map;a(Jae,"getTables");a(ct,"getDatabases");a(Od,"resetDatabases");a($p,"readMetaDb");a(mq,"ensureDB");a(pq,"setTable");a(ud,"database");a(_w,"dropDatabase");a(hq,"openIndex");a(Xe,"table");Xae=1e3,Zae=10;a(ece,"runIndexing");a(tce,"dropTableMeta");a(Bl,"onUpdatedTable");a(jp,"onRemovedDB");a(yS,"getDefaultCompression")});var wN={};ye(wN,{loadGQLSchema:()=>sce,start:()=>IN,startOnMainThread:()=>nce});function IN({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:d}=await import("graphql"),f=o(new c(r.toString(),s)),m=new Map,p=[],h;for(let R of f.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let $=function(G){if(G.kind==="NonNullType"){let Y=$(G.type);return Y.nullable=!1,Y}if(G.kind==="ListType")return{type:"array",elements:$(G.type)};let j={type:G.name?.value};return Object.defineProperty(j,"location",{value:G.loc.startToken}),j};a($,"getProperty");let S=R.name.value,y=[],N={table:null,database:null,properties:y};m.set(S,N),i.allTypes.set(S,N);for(let G of R.directives){if(G.name.value==="table"){for(let j of G.arguments)N[j.name.value]=j.value.value;N.schema&&(N.database=N.schema),N.table||(N.table=S),N.audit&&(N.audit=N.audit!=="false"),N.attributes=N.properties,p.push(N)}if(G.name.value==="sealed"&&(N.sealed=!0),G.name.value==="splitSegments"&&(N.splitSegments=!0),G.name.value==="replicate"&&(N.replicate=!0),G.name.value==="export"){N.export=!0;for(let j of G.arguments)typeof N.export!="object"&&(N.export={}),N.export[j.name.value]=j.value.value}}let I=!1,ee={};for(let G of R.fields){let k=$(G.type);k.name=G.name.value,y.push(k),ee[k.name]=void 0;for(let j of G.directives){let Y=j.name.value;if(Y==="primaryKey")I?console.warn("Can not define two attributes as a primary key at",j.loc):(k.isPrimaryKey=!0,I=!0);else if(Y==="indexed"){let ce={};for(let de of j.arguments||[])ce[de.name.value]=de.value.value;k.indexed=ce}else if(Y==="computed"){for(let ce of j.arguments||[])if(ce.name.value==="from"){let de=ce.value.value;k.computed={from:g(de,ce,ee)},k.version==null&&(k.version=de)}else ce.name.value==="version"&&(k.version=ce.value.value);k.computed=k.computed||!0}else if(Y==="relationship"){let ce={};for(let de of j.arguments)ce[de.name.value]=de.value.value;k.relationship=ce}else if(Y==="createdTime")k.assignCreatedTime=!0;else if(Y==="updatedTime")k.assignUpdatedTime=!0;else if(Y==="expiresAt")k.expiresAt=!0;else if(Y==="enumerable")k.enumerable=!0;else if(Y==="allow"){let ce=k.authorizedRoles=[];for(let de of j.arguments)de.name.value==="role"&&ce.push(de.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,j.loc)}}N.type=S,S==="Query"&&(h=N)}function E(R){let S=m.get(R.type);S?(Object.defineProperty(R,"properties",{value:S.properties}),Object.defineProperty(R,"definition",{value:S})):R.type==="array"?E(R.elements):rce.includes(R.type)||(0,_q.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(E,"connectPropertyType");for(let R of m.values())for(let S of R.properties)E(S);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,AN.dirname)(n),R.tableClass):i.set((0,AN.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,S,y){return new Eq.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:S.loc.startToken.line-1,columnOffset:S.loc.startToken.column}).runInThisContext()(y)}a(g,"createComputedFrom")}}var AN,Eq,_q,rce,nce,sce,gq=se(()=>{AN=require("path"),Eq=require("node:vm");we();_q=b(st());za();rce=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow","enumerable"]);a(IN,"start");nce=IN,sce=a(e=>IN({ensureTable:Xe}).handleFile(e,null,null,new ed),"loadGQLSchema")});var CN={};ye(CN,{start:()=>mce});function ice(e){if(e.kind!==He.Kind.OPERATION_DEFINITION&&e.kind!==He.Kind.FRAGMENT_DEFINITION)throw new Kr(`Unexpected non-executable definition type ${e.kind}.`)}function Sq(e){if(typeof e!="object"||e===null)throw new lo("Request body must be an object.");if(!("query"in e))throw new lo("Request body must contain a `query` field.");if(typeof e.query!="string")throw new lo("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new lo("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new lo("Request body `operationName` field must be a string.")}function NN(e){return parseInt(e.value,10)}function yq(e){return parseFloat(e.value)}function Rq(e,t,r){let n=r.get(e.name.value);return bq(n)?Aq(n,t):{attribute:t,value:n}}function bq(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function Aq(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],bq(n)?Aq(n,t):{attribute:t,value:n}))}function oce(e,t,r){switch(t=[...t,e.name.value],e.value.kind){case He.Kind.NULL:return{attribute:t,value:null};case He.Kind.INT:return{attribute:t,value:NN(e.value)};case He.Kind.FLOAT:return{attribute:t,value:yq(e.value)};case He.Kind.BOOLEAN:case He.Kind.STRING:return{attribute:t,value:e.value.value};case He.Kind.VARIABLE:return Rq(e.value,t,r);case He.Kind.OBJECT:return Iq(e.value,t,r);case He.Kind.LIST:case He.Kind.ENUM:default:throw new Kr(`Value type, ${e.value.kind}, is not supported.`)}}function Iq(e,t,r){return e.fields.flatMap(n=>oce(n,t,r))}function ace(e,t){switch(e.value.kind){case He.Kind.NULL:return{attribute:e.name.value,value:null};case He.Kind.INT:return{attribute:e.name.value,value:NN(e.value)};case He.Kind.FLOAT:return{attribute:e.name.value,value:yq(e.value)};case He.Kind.BOOLEAN:case He.Kind.STRING:return{attribute:e.name.value,value:e.value.value};case He.Kind.VARIABLE:return Rq(e.value,e.name.value,t);case He.Kind.OBJECT:return Iq(e.value,[e.name.value],t);case He.Kind.LIST:case He.Kind.ENUM:default:throw new Kr(`Argument type, ${e.value.kind}, is not supported.`)}}function cce(e,t){return e.flatMap(r=>ace(r,t))}function RS(e,t){return e.selections.flatMap(r=>{switch(r.kind){case He.Kind.FIELD:return r;case He.Kind.FRAGMENT_SPREAD:{let n=r.name.value,s=t.get(n);if(s==null)throw new Kr(`Fragment \`${n}\` not found.`);return RS(s.selectionSet,t)}case He.Kind.INLINE_FRAGMENT:return RS(r.selectionSet,t)}})}function wq(e,t){return RS(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:wq(r.selectionSet,t)}:r.name.value)}async function lce(e,t,r,n){let s=Bs.getMatch(e.name.value,"graphql");if(s===void 0)throw new Kr(`Resource \`${e.name.value}\` not found.`);let i=s.Resource,o={select:wq(e.selectionSet,r),conditions:cce(e.arguments,t)},c=[];n.authorize=!0;for await(let l of i.search(o,n))c.push(l);return[e.name.value,c]}function Nq(e){switch(e.kind){case He.Kind.NULL:return null;case He.Kind.INT:return NN(e);case He.Kind.FLOAT:return parseFloat(e.value);case He.Kind.STRING:case He.Kind.BOOLEAN:return e.value;case He.Kind.OBJECT:return e.fields.reduce((t,r)=>({[r.name.value]:Nq(r.value),...t}),{});case He.Kind.LIST:case He.Kind.ENUM:default:throw new Kr(`Value type, ${e.kind}, is not supported.`)}}function uce(e,t){let r=new Map;for(let n of e){let s=n.variable.name.value,i=t?.[s];if(i===void 0&&n.defaultValue!==void 0&&(i=Nq(n.defaultValue)),n.type.kind===He.Kind.NON_NULL_TYPE&&!(s in t)&&i===void 0)throw new Kr(`Variable $${s} is required, but not provided.`);r.set(n.variable.name.value,i??null)}return r}async function dce(e,t,r,n){if(e.operation===He.OperationTypeNode.SUBSCRIPTION)throw new Kr("Subscriptions are not supported.");if(e.operation===He.OperationTypeNode.MUTATION)throw new Kr("Mutations are not supported yet.");let s=uce(e.variableDefinitions,t),i=await Promise.all(RS(e.selectionSet,r).map(c=>lce(c,s,r,n))),o={data:{}};for(let[c,l]of i)o.data[c]=l;return o}async function Tq({query:e,variables:t={},operationName:r},n){let s=He.parse(e),i=new Map,o=new Map;for(let u of s.definitions)if(ice(u),u.kind===He.Kind.FRAGMENT_DEFINITION)o.set(u.name.value,u);else{if(u.name===void 0&&s.definitions.length>1)throw new Kr("Unnamed operations are only allowed when there is a single operation in the document.");let d=u.name?.value??"Unnamed Query";if(i.has(d))throw new Kr(`Duplicate operation definition: ${d}`);i.set(d,u)}let c;if(r==null)if(i.size===1)c=i.entries().next().value[1];else throw new Kr("Operation name is required when there are multiple operations in the document.");else if(c=i.get(r),c==null)throw new Kr(`Operation \`${r}\` not found.`);let l=await dce(c,t,o,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function fce(e){switch(e.method){case"GET":{let t=new URLSearchParams(e.url.split("?")[1]),r={};for(let[n,s]of t)r[n]=n==="variables"||n==="extensions"?JSON.parse(s):s;return Sq(r),Tq(r,e)}case"POST":{let r=await Bo(e.headers.get("content-type"),!0)(e._nodeRequest);return Sq(r),Tq(r,e)}default:throw new lo("Method Not Allowed",405,{Allow:"GET, POST"})}}function mce(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await fce(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof lo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json",...n.headers}};if(n instanceof He.GraphQLError)return{status:200,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/json"}};if(n instanceof Kr)return{status:200,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};break}default:logger.info(`Unsupported accept header, ${s}, defaulting to application/graphql-response+json`);case"application/graphql-response+json":{if(n instanceof lo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json",...n.headers}};if(n instanceof He.GraphQLError)return{status:400,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Kr)return{status:400,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};break}}throw n}},{port:e.port,securePort:e.securePort})}var He,Kr,lo,Cq=se(()=>{He=b(require("graphql"));Fo();za();a(ice,"assertExecutableDefinitionNode");a(Sq,"assertRequestParams");a(NN,"processIntValueNode");a(yq,"processFloatValueNode");a(Rq,"processVariableNode");a(bq,"isObject");a(Aq,"transformObjectIntoQueryCondition");a(oce,"processObjectFieldNode");a(Iq,"processObjectValueNode");a(ace,"processArgumentNode");a(cce,"buildConditionsQuery");a(RS,"fillInFragments");a(wq,"buildSelectQuery");a(lce,"processFieldNode");a(Nq,"processConstValueNode");a(uce,"resolveVariables");a(dce,"executeOperation");a(Tq,"resolver");Kr=class extends Error{static{a(this,"GraphQLQueryingError")}},lo=class extends Error{static{a(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};a(fce,"graphqlQueryingHandler");a(mce,"start")});var Mq=M((ZMe,vq)=>{var Pd=require("validate.js"),Pq=mt(),Ld=(H(),v(z)),{handleHDBError:pce,hdbErrors:hce}=_e(),{HDB_ERROR_MSGS:sr,HTTP_STATUS_CODES:Ece}=hce,ON=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),_ce={STRUCTURE_USER:"structure_user"},Oq=Object.values(Ld.ROLE_TYPES_ENUM),gce="attribute_permissions",Sce="attribute_name",{PERMS_CRUD_ENUM:Dd}=Ld,Tce=[gce,...Object.values(Dd)],Lq=[Dd.READ,Dd.INSERT,Dd.UPDATE],yce=[Sce,...Lq];function Rce(e){let t=ON();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,Dq(e,t)}a(Rce,"addRoleValidation");function bce(e){let t=ON();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,Dq(e,t)}a(bce,"alterRoleValidation");function Ace(e){let t=ON();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Pq.validateObject(e,t)}a(Ace,"dropRoleValidation");var Ice=["operation","role","id","permission","hdb_user","access"];function Dq(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Ice.includes(n[o])||s.push(n[o]);s.length>0&&pr(sr.INVALID_ROLE_JSON_KEYS(s),r);let i=Pq.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{pr(o,r)}),e.permission){let o=wce(e);o&&pr(o,r),Oq.forEach(c=>{e.permission[c]&&!Pd.isBoolean(e.permission[c])&&pr(sr.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(Oq.indexOf(o)<0){if(o===_ce.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let u=0,d=l.length;u<d;u++){let f=l[u];global.hdb_schema[f]||pr(sr.SCHEMA_NOT_FOUND(f),r)}continue}pr(sr.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){pr(sr.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let u=c.tables[l];if(!l||!global.hdb_schema[o][l]){pr(sr.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(u).forEach(d=>{Tce.includes(d)||pr(sr.INVALID_PERM_KEY(d),r,o,l)}),Object.values(Dd).forEach(d=>{Pd.isDefined(u[d])?Pd.isBoolean(u[d])||pr(sr.TABLE_PERM_NOT_BOOLEAN(d),r,o,l):pr(sr.TABLE_PERM_MISSING(d),r,o,l)}),u.attribute_permissions===void 0){pr(sr.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){pr(sr.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}if(u.attribute_permissions){let d=global.hdb_schema[o][l].attributes.map(({attribute:m})=>m),f={read:!1,insert:!1,update:!1};for(let m in u.attribute_permissions){let p=u.attribute_permissions[m];if(Object.keys(p).forEach(E=>{!yce.includes(E)&&E!==Dd.DELETE&&pr(sr.INVALID_ATTR_PERM_KEY(E),r,o,l)}),!Pd.isDefined(p.attribute_name)){pr(sr.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=p.attribute_name;if(!d.includes(h)){pr(sr.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}Lq.forEach(E=>{Pd.isDefined(p[E])?Pd.isBoolean(p[E])||pr(sr.ATTR_PERM_NOT_BOOLEAN(E,h),r,o,l):pr(sr.ATTR_PERM_MISSING(E,h),r,o,l)}),!f.read&&p.read===!0&&(f.read=!0),!f.insert&&p.insert===!0&&(f.insert=!0),!f.update&&p.update===!0&&(f.update=!0)}if(u.read===!1&&f.read===!0||u.insert===!1&&f.insert===!0||u.update===!1&&f.update===!0){let m=`${o}.${l}`;pr(sr.MISMATCHED_TABLE_ATTR_PERMS(m),r,o,l)}}}}return Nce(r)}a(Dq,"customValidate");vq.exports={addRoleValidation:Rce,alterRoleValidation:bce,dropRoleValidation:Ace};function wce(e){let{operation:t,permission:r}=e;if(t===Ld.OPERATIONS_ENUM.ADD_ROLE||t===Ld.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 sr.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Ld.ROLE_TYPES_ENUM.SUPER_USER:Ld.ROLE_TYPES_ENUM.CLUSTER_USER;return sr.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(wce,"validateNoSUPerms");function Nce(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:sr.ROLE_PERMS_ERROR,...e};return pce(new Error,n,Ece.BAD_REQUEST)}else return null}a(Nce,"generateRolePermResponse");function pr(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(pr,"addPermError")});var Jp=M((rUe,Fq)=>{"use strict";var Uq=Vn(),xq=gn(),Cce=Nl(),LN=Mq(),DN=Wo(),tUe=require("uuid").v4,Oce=require("util"),bS=(H(),v(z)),Pce=oe(),vN=xq.searchByValue,Lce=xq.searchByHash,Dce=Oce.promisify(Cce.delete),vce=mi(),Mce=cd(),{hdbErrors:Uce,handleHDBError:Fl}=_e(),{HDB_ERROR_MSGS:Bq,HTTP_STATUS_CODES:Qp}=Uce,{UserEventMsg:MN}=ls();Fq.exports={addRole:xce,alterRole:Bce,dropRole:Fce,listRoles:kce};function PN(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(PN,"scrubRoleDetails");async function xce(e){let t=LN.addRoleValidation(e);if(t)throw t;e=PN(e);let r={schema:"system",table:"hdb_role",attribute:"role",value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await vN(r)||[])}catch(i){throw Fl(i)}if(n&&n.length>0)throw Fl(new Error,Bq.ROLE_ALREADY_EXISTS(e.role),Qp.CONFLICT,void 0,void 0,!0);e.id||(e.id=e.role);let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await Uq.insert(s),DN.signalUserChange(new MN(process.pid)),e=PN(e),e}a(xce,"addRole");async function Bce(e){let t=LN.alterRoleValidation(e);if(t)throw t;e=PN(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await Uq.update(r)}catch(s){throw Fl(s)}if(n&&n?.message==="updated 0 of 1 records")throw Fl(new Error,"Invalid role id",Qp.BAD_REQUEST,void 0,void 0,!0);return await DN.signalUserChange(new MN(process.pid)),e}a(Bce,"alterRole");async function Fce(e){let t=LN.dropRoleValidation(e);if(t)throw Fl(new Error,t,Qp.BAD_REQUEST,void 0,void 0,!0);let r=new Mce(bS.SYSTEM_SCHEMA_NAME,bS.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Lce(r));if(n.length===0)throw Fl(new Error,Bq.ROLE_NOT_FOUND,Qp.NOT_FOUND,void 0,void 0,!0);let s=new vce(bS.SYSTEM_SCHEMA_NAME,bS.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await vN(s)),o=!1;if(Pce.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw Fl(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Qp.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Dce(c),DN.signalUserChange(new MN(process.pid)),`${n[0].role} successfully deleted`}a(Fce,"dropRole");async function kce(){return vN({table:"hdb_role",schema:"system",hash_attribute:"id",attribute:"id",value:"*",get_attributes:["*"]})}a(kce,"listRoles")});var UN={};ye(UN,{start:()=>Gq,startOnMainThread:()=>qce});function Gq({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,kq.parseDocument)(r.toString(),{simpleKeys:!0}).toJSON();for(let s in n){let i=n[s];i.permission||(i={permission:i},i.permission.access&&(i.access=i.permission.access,delete i.permission.access));for(let o in i.permission){if(Hce.includes(o))continue;let c=i.permission[o];c.tables||(i.permission[o]=c={tables:c});for(let l in c.tables){let u=c.tables[l];if(u.read=!!u.read,u.insert=!!u.insert,u.update=!!u.update,u.delete=!!u.delete,u.attributes){let d=[];for(let f in u.attributes){let m=u.attributes[f];m.attribute_name=f,d.push(m)}u.attribute_permissions=d,delete u.attributes}if(u.attribute_permissions){if(!Array.isArray(u.attribute_permissions))throw new Error("attribute_permissions must be an array if defined");for(let d of u.attribute_permissions)d.read=!!d.read,d.insert=!!d.insert,d.update=!!d.update}else u.attribute_permissions=null}}i.role=i.id=s,await Gce(i)}}}async function Gce(e){let t=ct().system.hdb_role;for await(let r of t.search([{attribute:"role",value:e.role}])){let{__createdtime__:n,__updatedtime__:s,...i}=r;return(0,Hq.isEqual)(i,e)?void 0:(e.id=r.id,(0,AS.alterRole)(e))}return(0,AS.addRole)(e)}var AS,kq,Hq,Hce,qce,qq=se(()=>{we();AS=b(Jp()),kq=require("yaml"),Hq=require("lodash"),Hce=["super_user","cluster_user","structure_user"];a(Gq,"start");a(Gce,"ensureRole");qce=Gq});async function IS(e){let t=(0,Kq.pathToFileURL)(e).toString();if($ce)return Xp||(Xp=Vce(Yce)),(await(await Xp).import(t)).namespace;try{return await import(t)}catch(r){try{(await import("internal/util")).default.decorateErrorStack(r)}catch{}throw r}}async function Vce(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Xp=new Compartment({console,Math,Date,fetch:Kce,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Vq.extname)(r)||(r+=".js"),r)},importHook:a(async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){s.Resource=lr,s.tables=Rn,s.databases=Me}};let n=await(0,$q.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),Xp}function Kce(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 Yce(){return{Resource:lr,tables:Rn}}var $q,Vq,Kq,$ce,Xp,xN=se(()=>{Vo();we();$q=require("fs/promises"),Vq=require("path"),Kq=require("url"),$ce=!1;a(IS,"secureImport");a(Vce,"getCompartment");a(Kce,"secureOnlyFetch");a(Yce,"getGlobalVars")});var BN={};ye(BN,{handleApplication:()=>Wce,suppressHandleApplicationWarning:()=>zce});function Yq(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function Wce(e){e.handleEntry(t=>{if(t.entryType!=="file"){e.logger.warn(`jsResource plugin cannot handle entry type ${t.entryType}. Modify the 'files' option in ${e.configFilePath} to only include files.`);return}if(t.eventType!=="add"){e.requestRestart();return}IS(t.absolutePath).then(r=>{let n=(0,wS.dirname)(t.urlPath);Yq(r.default)&&(e.resources.set(n,r.default),e.logger.debug(`Registered root resource: ${n}`)),Wq(e,r,n)}).catch(r=>{e.logger.error(`Failed to load resource module ${t.absolutePath}: ${r}`),e.requestRestart()})})}function Wq(e,t,r){for(let n in t){let s=t[n],i=(0,wS.join)(r,n);Yq(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&Wq(e,s,i)}}var wS,zce,zq=se(()=>{xN();wS=require("path");a(Yq,"isResource");a(Wce,"handleApplication");a(Wq,"recurseForResources");zce=!0});var kN={};ye(kN,{start:()=>jce});function jce({resources:e}){e.set("login",FN),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var FN,jq=se(()=>{Vo();a(jce,"start");FN=class extends lr{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)}}}});function CS(e,t){let r={openapi:Qce,info:{title:"HarperDB HTTP REST interface",version:t$.packageJson.version},servers:[{description:"REST API",url:t}],paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},n=[{basicAuth:[],bearerAuth:[]}],s=a(i=>{if(i.type&&!r.components.schemas[i.type]){r.components.schemas[i.type]={};let o={},c=[];for(let l of i.properties)NS[l.type]?o[l.name]=new GN(NS[l.type],l.type):l.properties?(o[l.name]=new n$(l.type),s(l)):l.elements?.properties&&(o[l.name]=new ele(l.elements.type),s(l.elements)),l.nullable===!1&&c.push(l.name);r.components.schemas[i.type]=new e$(o,!i.sealed,c)}},"includeDefinitionInSchema");for(let[,i]of e){if(!i.path||i.Resource.isError)continue;let{path:o}=i,c=o.split("/").pop(),{attributes:l,sealed:u}=i.Resource,{prototype:d,primaryKey:f="id"}=i.Resource;if(!l&&e.allTypes.has(i.path)){let k=e.allTypes.get(i.path);u=k.sealed,l=k.properties}if(!f)continue;let m={},p=[],h=[];if(l)for(let{type:k,name:j,elements:Y,relationship:ce,definition:de,nullable:te}of l){let ge=de??Y?.definition;ge&&s(ge),te===!1&&h.push(j),ce?k==="array"?m[j]={type:"array",items:{$ref:Vs+Y.type}}:m[j]={$ref:Vs+k}:ge?k==="array"?m[j]={type:"array",items:{$ref:Vs+ge.type}}:m[j]={$ref:Vs+ge.type}:k==="array"?Y.type==="Any"?m[j]={type:"array",items:{format:Y.type}}:m[j]={type:"array",items:new GN(NS[Y.type],Y.type)}:k==="Any"?m[j]={format:k}:m[j]=new GN(NS[k],k),p.push(new qN(j,"query",m[j]))}let E=Object.keys(m),g=new qN(f,"path",{type:"string",format:"ID"});g.required=!0,g.description="primary key of record";let R=new qN("property","path",{enum:E});R.required=!0,r.components.schemas[c]=new e$(m,!u,h);let S=d.post!==Resource.prototype.post||d.update,y=typeof d.put=="function",N=typeof d.get=="function",I=typeof d.delete=="function",$=typeof d.patch=="function",ee=`/${o}/`;r.paths[ee]||(r.paths[ee]={}),S&&(r.paths[ee].post=new Jce(c,n,{200:new vd({$ref:Vs+c},{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}})},"create a new record auto-assigning a primary key")),r.paths[ee].options=new Qq(p,n,{200:new Jq},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),N&&(r.paths[ee].get=new HN(p,n,{200:new vd({type:"array",items:{$ref:Vs+c}})},"search for records by the specified property name and value pairs")),I&&(r.paths[ee].delete=new Zq(p,n,"delete all the records that match the provided query",{204:new Xq}));let G="/"+o+"/{"+f+"}";if(r.paths[G]||(r.paths[G]={}),r.paths[G].options=new Qq(p,n,{200:new Jq},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),N&&(r.paths[G].get=new HN([g],n,{200:new vd({$ref:Vs+c})},"retrieve a record by its primary key")),y&&(r.paths[G].put=new Xce([g],n,c,{200:new vd({$ref:Vs+c})},"create or update the record with the URL path that maps to the record's primary key")),$&&(r.paths[G].patch=new Zce([g],n,c,{200:new vd({$ref:Vs+c})},"patch the record with the URL path that maps to the record's primary key")),I&&(r.paths[G].delete=new Zq([g],n,"delete a record with the given primary key",{204:new Xq})),N&&R.schema.enum.length>0){let k=`/${o}/{${f}}.{property}`;r.paths[k]||(r.paths[k]={}),r.paths[k].get=new HN([g,R],n,{200:new vd({enum:E})},"used to retrieve the specified property of the specified record")}}for(let[,i]of e.allTypes)s(i),i.sealed&&r.components.schemas[i.type].additionalProperties&&(r.components.schemas[i.type].additionalProperties=!1);return r}function Jce(e,t,r,n){this.description=n,this.requestBody={content:{"application/json":{schema:{$ref:Vs+e}}}},this.security=t,this.responses=r}function HN(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Qq(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Jq(){this.description=r$,this.headers={},this.content={}}function vd(e,t){this.description=r$,this.content={"application/json":{schema:e}},this.headers=t}function Xq(){this.description="successfully processed request, no content returned to client"}function Xce(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Vs+r}}}},this.responses=n}function Zce(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Vs+r}}}},this.responses=n}function Zq(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function e$(e,t,r){this.type="object",this.properties=e,this.additionalProperties=t,this.required=r}function GN(e,t){this.type=e,(e==="string"||e==="number"||e==="integer")&&t!=="String"&&(this.format=t)}function n$(e){this.$ref=`#/components/schemas/${e}`}function ele(e){this.type="array",this.items=new n$(e)}function qN(e,t,r){this.name=e,this.in=t,this.schema=r}var t$,Qce,NS,Vs,r$,$N=se(()=>{t$=b(yt()),Qce="3.0.3",NS={Int:"integer",Float:"number",Long:"integer",ID:"string",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer"},Vs="#/components/schemas/",r$="successful operation";a(CS,"generateJsonApi");a(Jce,"Post");a(HN,"Get");a(Qq,"Options");a(Jq,"ResponseOptions200");a(vd,"Response200");a(Xq,"Response204");a(Xce,"Put");a(Zce,"Patch");a(Zq,"Delete");a(e$,"ResourceSchema");a(GN,"Type");a(n$,"Ref");a(ele,"ArrayRef");a(qN,"Parameter")});var i$={};ye(i$,{Request:()=>cc,createReuseportFd:()=>OS});var s$,cc,VN,KN,OS,Zp=se(()=>{s$=require("os"),cc=class{static{a(this,"Request")}#e;#t;_nodeRequest;_nodeResponse;method;url;headers;isWebSocket;user;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new KN(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.#t===void 0&&(this.#t=this._nodeRequest.socket.getPeerCertificate?.(!0)||null),this.#t}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VN(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get hostname(){return this._nodeRequest.headers.host}get httpVersion(){return this._nodeRequest.httpVersion}get isAborted(){return!1}get nodeRequest(){return this._nodeRequest}sendEarlyHints(t,r={}){r.link=t,this._nodeResponse.writeEarlyHints(r)}},VN=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)}},KN=class{static{a(this,"Headers")}asObject;constructor(t){this.asObject=t}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return Object.prototype.hasOwnProperty.call(this.asObject,t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}delete(t){delete this.asObject[t.toLowerCase()]}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,s$.platform)()!="win32"&&(OS=require("node-unix-socket").createReuseportFd)});var LS={};ye(LS,{parseHeaderValue:()=>WN,start:()=>nle});async function rle(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&dg(e);let i=new Gs;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==o$){let g=PS.getMatch(o,n?"sse":"rest");if(!g)return t(e);e.handlerPath=g.path,c=new ui(g.relativeURL),c.async=!0,l=g.Resource}if(l?.isCaching){let g=r["cache-control"];if(g){let R=WN(g);for(let S of R)switch(S.name){case"max-age":e.expiresAt=S.value*1e3+Date.now();break;case"only-if-cached":e.onlyIfCached=!0;break;case"no-cache":e.noCache=!0;break;case"no-store":e.noCacheStore=!0;break;case"stale-if-error":e.staleIfError=!0;break;case"must-revalidate":e.mustRevalidate=!0;break}}}let u=r["x-replicate-to"];if(u){let g=WN(u).map(R=>(R.next?.name==="confirm"&&R.next.value>=0&&(e.replicatedConfirmation=+R.next.value),R.name));e.replicateTo=g.length===1&&+g[0]>=0?+g[0]:g[0]==="*"?void 0:g}r["x-replicate-from"]==="none"&&(e.replicateFrom=!1);let f=await bt(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Bo(r["content-type"],!0)(e.body,e.headers)}catch(g){throw new Md.ClientError(g,400)}if(e.authorize=!0,o===o$&&s==="GET"){if(e?.user?.role?.permission?.super_user)return CS(PS,`${e.protocol}://${e.hostname}`);throw new Md.ServerError("Forbidden",403)}switch(c.checkPermission=e.user?.role?.permission??{},s){case"GET":case"HEAD":return l.get(c,e);case"POST":return l.post(c,e.data,e);case"PUT":return l.put(c,e.data,e);case"DELETE":return l.delete(c,e);case"PATCH":return l.patch(c,e.data,e);case"OPTIONS":i.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(c,e.data,e);case"COPY":return l.copy(c,r.destination,e);case"MOVE":return l.move(c,r.destination,e);case"BREW":throw new Md.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Md.ServerError(`Method ${s} is not recognized`,501)}}),m=200,p=e.lastModified;if(f==null)m=s==="GET"||s==="HEAD"?404:204,YN.lastModified&&isFinite(p)&&i.setIfNone("Last-Modified",new Date(p).toUTCString());else if(f.status>0&&f.headers){let g=$G(f.headers,i);return f.headers!==g&&(f.headers=g),f.data!==void 0&&(f.body=xm(f.data,e,f)),f}else if(isFinite(p)){tle[0]=p;let g=String.fromCharCode(34,(sn[0]&63)+62,(sn[0]>>6)+(sn[1]<<2&63)+62,(sn[1]>>4)+(sn[2]<<4&63)+62,(sn[2]>>2)+62,(sn[3]&63)+62,(sn[3]>>6)+(sn[4]<<2&63)+62,(sn[4]>>4)+(sn[5]<<4&63)+62,(sn[5]>>2)+62,(sn[6]&63)+62,(sn[6]>>6)+(sn[7]<<2&63)+62,34),R=r["if-none-match"];R&&g==R?(f?.onDone&&f.onDone(),m=304,f=void 0):i.setIfNone("ETag",g),YN.lastModified&&i.setIfNone("Last-Modified",new Date(p).toUTCString())}e.createdResource&&(m=201),e.newLocation&&i.setIfNone("Location",e.newLocation);let h={status:m,headers:i,body:void 0},E=e.loadedFromSource??f?.wasLoadedFromSource?.();return E!==void 0&&(h.wasCacheMiss=E,!E&&isFinite(p)&&i.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||p))/1e3))),f!==void 0&&(h.body=xm(f,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?gi.warn(o):gi.info(o):gi.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.setIfNone("Allow",o.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:o.statusCode||500,headers:i,body:void 0};return c.body=xm(o.contentType?o:l$(o),e,c),c}}function nle(e){YN=e,e.includeExpensiveRecordCountEstimates&&(cc.prototype.includeExpensiveRecordCountEstimates=!0),!a$&&(a$=!0,PS=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return rle(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{eh++;let s=new ns;c$||(c$=!0,Qm(l=>{eh>0&&l.push({metric:"ws-connections",connections:eh,byThread:!0})}));let i;t.on("error",l=>{i=!0,gi.warn(l)});let o;t.on("message",a(function(u){o||(o=Bo(r.requestedContentType??r.headers.asObject["content-type"],!1));let d=o(u);Ve(u.length,"bytes-received",r.handlerPath,"message","ws"),s.push(d)},"message"));let c;t.on("close",()=>{eh--,tn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),u=PS.getMatch(l,"ws");if(tn(!!u,"connection","ws","connect"),u){r.handlerPath=u.path,Ve(h=>({count:h.count,total:eh}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let d=new ui(u.relativeURL);d.checkPermission=r.user?.role?.permission??{};let f=u.Resource;c=(await bt(r,()=>f.connect(d,s,r)))[Symbol.asyncIterator]();let p;for(;!(p=await c.next()).done;){let h=await xo(p.value,r);t.send(h),Ve(h.length,"bytes-sent",r.handlerPath,"message","ws"),t._socket.writableNeedDrain&&await new Promise(E=>t._socket.once("drain",E))}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){l.statusCode?l.statusCode===500?gi.warn(l):gi.info(l):gi.error(l),t.close(sle[l.statusCode]||1011,l$(l))}t.close()},e))}function WN(e){return e.trim().split(",").map(t=>{let r,n=t.trim().split(";"),s;for(;s=n.pop();)if(s.includes("=")){let[i,o]=s.trim().split("=");i=i.trim(),o&&(o=o.trim()),r={name:i.toLowerCase(),value:o,next:r}}else r={name:s.toLowerCase(),next:r};return r})}var gi,Md,l$,sn,tle,YN,o$,a$,PS,c$,eh,sle,u$=se(()=>{Fo();is();gi=b(J()),Md=b(_e());fg();Uu();Ga();kp();$N();Zp();pg();({errorToString:l$}=gi),sn=new Uint8Array(8),tle=new Float64Array(sn.buffer,0,1),YN={},o$="openapi";a(rle,"http");eh=0;a(nle,"start");sle={401:3e3,403:3003};a(WN,"parseHeaderValue")});var zN=M((CUe,f$)=>{var{recordAction:DS,recordActionBinary:d$}=(is(),v(ng)),ile=require("fastify-plugin"),ole=200;f$.exports=ile(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(),l=s.request.routeOptions,u,d,f;l.config?.isOperation?(u=n.body?.operation,d="operation"):(u=l.url,d="fastify-route",f=l.method),DS(o,"duration",u,f,d),d$(s.raw.statusCode<400,"success",u,f,d),d$(1,"response_"+s.raw.statusCode,u,f,d);let m=ole;i?.pipe?(i.on("data",g=>{m+=g.length}),i.on("end",()=>{DS(performance.now()-c,"transfer",u,f,d),DS(m,"bytes-sent",u,f,d)})):(m+=i?.length||0,DS(m,"bytes-sent",u,f,d));let p=o.toFixed(3),h=s.getHeader("Server-Timing"),E=`db;dur=${p}`;s.header("Server-Timing",h?`${h}, ${E}`:E)}),r()},{name:"hdb-request-time"})});var p$=M((OUe,m$)=>{var ale=mt(),cle={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};m$.exports=function(e){return ale.validateObject(e,cle)}});var vS=M((PUe,h$)=>{"use strict";var lle=(H(),v(z)).OPERATIONS_ENUM,jN=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=lle.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};h$.exports=jN});var nh={};ye(nh,{createTokens:()=>XN,getJWTRSAKeys:()=>FS,refreshOperationToken:()=>ZN,validateOperationToken:()=>eC,validateRefreshToken:()=>kS});async function FS(){if(MS)return MS;try{let e=th.default.join(rh.default.getHdbBasePath(),xb),t=await US.default.readFile(th.default.join(e,Sm.JWT_PASSPHRASE_NAME),"utf8"),r=await US.default.readFile(th.default.join(e,Sm.JWT_PRIVATE_KEY_NAME),"utf8");return MS={publicKey:await US.default.readFile(th.default.join(e,Sm.JWT_PUBLIC_KEY_NAME),"utf8"),privateKey:r,passphrase:t},MS}catch(e){throw BS.default.error(e),new Si.ClientError(xd.NO_ENCRYPTION_KEYS,Ud.INTERNAL_SERVER_ERROR)}}async function XN(e){let t=(0,QN.validateBySchema)(e,uo.default.object({username:uo.default.string().optional(),password:uo.default.string().optional(),role:uo.default.string().optional(),expires_in:uo.default.alternatives(uo.default.string(),uo.default.number()).optional()}));if(t)throw new Si.ClientError(t.message);let r;try{let f=e.bypass_auth!==!0;!e.username&&!e.password&&(e.username=e.hdb_user?.username,f=!1),r=await(0,JN.findAndValidateUser)(e.username,e.password,f)}catch(f){throw BS.default.error(f),new Si.ClientError(xd.INVALID_CREDENTIALS,Ud.UNAUTHORIZED)}if(!r)throw new Si.ClientError(xd.INVALID_CREDENTIALS,Ud.UNAUTHORIZED);let n=!1,s=!1;r.role?.permission&&(n=r.role.permission.super_user===!0,s=r.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s};e.role&&(i.role=e.role);let o=await FS(),c=await Bd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:e.expires_in??T$,algorithm:xS,subject:Fd.OPERATION}),l=await Bd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:ule,algorithm:xS,subject:Fd.REFRESH}),u=Ow(l,$r.SHA256);if((await(0,E$.update)(new _$.default(_m,Du.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new Si.ClientError(xd.REFRESH_TOKEN_SAVE_FAILED,Ud.INTERNAL_SERVER_ERROR);return g$.default.signalUserChange(new S$.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function ZN(e){let t=(0,QN.validateBySchema)(e,uo.default.object({refresh_token:uo.default.string().required()}).required());if(t)throw new Si.ClientError(t.message);let{refresh_token:r}=e;await kS(r);let n=await FS(),s=await Bd.default.decode(r);return{operation_token:await Bd.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:T$,algorithm:xS,subject:Fd.OPERATION})}}async function eC(e){return y$(e,Fd.OPERATION)}async function kS(e){return y$(e,Fd.REFRESH)}async function y$(e,t){try{let r=await FS(),n=await Bd.default.verify(e,r.publicKey,{algorithms:xS,subject:t});if(n.role)throw new Error("Invalid token");let s=await(0,JN.findAndValidateUser)(n.username,void 0,!1);if(t===Fd.REFRESH&&!Pw(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw BS.default.warn(r),r?.name==="TokenExpiredError"?new Si.ClientError(xd.TOKEN_EXPIRED,Ud.FORBIDDEN):new Si.ClientError(xd.INVALID_TOKEN,Ud.UNAUTHORIZED)}}var Bd,US,th,uo,QN,Si,BS,JN,E$,_$,g$,S$,rh,Ud,xd,T$,ule,xS,Fd,MS,kd=se(()=>{Bd=b(require("jsonwebtoken")),US=b(require("fs-extra")),th=b(require("node:path")),uo=b(require("joi")),QN=b(mt());H();Si=b(_e()),BS=b(J());Dw();JN=b(Es()),E$=b(Vn()),_$=b(vS()),g$=b(Wo()),S$=b(ls()),rh=b(me()),{HTTP_STATUS_CODES:Ud,AUTHENTICATION_ERROR_MSGS:xd}=Si.hdbErrors;rh.default.initSync();T$=rh.default.get(F.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",ule=rh.default.get(F.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",xS="RS256",Fd={OPERATION:"operation",REFRESH:"refresh"};a(FS,"getJWTRSAKeys");a(XN,"createTokens");a(ZN,"refreshOperationToken");a(eC,"validateOperationToken");a(kS,"validateRefreshToken");a(y$,"validateToken")});var tC=M((UUe,A$)=>{"use strict";var dle=p$(),Hd=require("passport"),fle=require("passport-local").Strategy,mle=require("passport-http").BasicStrategy,ple=require("util"),hle=Es(),b$=ple.callbackify(hle.findAndValidateUser),MUe=Jr(),Ele=(H(),v(z)),R$=(kd(),v(nh));Hd.use(new fle(function(e,t,r){b$(e,t,r)}));Hd.use(new mle(function(e,t,r){b$(e,t,r)}));Hd.serializeUser(function(e,t){t(null,e)});Hd.deserializeUser(function(e,t){t(null,e)});function _le(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":Hd.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===Ele.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?R$.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):R$.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Hd.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(_le,"authorize");function gle(e,t){let r=dle(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(gle,"checkPermissions");A$.exports={authorize:_le,checkPermissions:gle}});var aC=M((kUe,C$)=>{var $S=require("clone"),VS=mt(),Sle=oe(),GS=(H(),v(z)),BUe=J(),rC=require("fs"),sC=require("joi"),{string:qS}=sC.types(),{hdbErrors:Tle,handleHDBError:HS}=_e(),{HDB_ERROR_MSGS:FUe,HTTP_STATUS_CODES:nC}=Tle,{commonValidators:Gd}=Qi(),I$=" is required",yle=["insert","update","upsert"],iC={database:{presence:!1,format:Gd.schema_format,length:Gd.schema_length},schema:{presence:!1,format:Gd.schema_format,length:Gd.schema_length},table:{presence:!0,format:Gd.schema_format,length:Gd.schema_length},action:{inclusion:{within:yle,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Rle={schema:qS.required(),table:qS.required(),action:qS.valid("insert","update","upsert")},{AWS_ACCESS_KEY:ble,AWS_SECRET:Ale,AWS_BUCKET:Ile,AWS_FILE_KEY:wle,REGION:Nle}=GS.S3_BUCKET_AUTH_KEYS,Cle={s3:{presence:!0},[`s3.${ble}`]:{presence:!0,type:"String"},[`s3.${Ale}`]:{presence:!0,type:"String"},[`s3.${Ile}`]:{presence:!0,type:"String"},[`s3.${wle}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Nle}`]:{presence:!0,type:"String"}},w$=$S(iC);w$.data.presence={message:I$};var N$=$S(iC);N$.file_path.presence={message:I$};var Ole=Object.assign($S(iC),Cle),oC=$S(Rle);oC.csv_url=qS.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();oC.passthrough_headers=sC.object();function Ple(e){let t=VS.validateObject(e,w$);return KS(e,t)}a(Ple,"dataObject");function Lle(e){let t=VS.validateBySchema(e,sC.object(oC));return KS(e,t)}a(Lle,"urlObject");function Dle(e){let t=VS.validateObject(e,N$);return KS(e,t)}a(Dle,"fileObject");function vle(e){let t=VS.validateObject(e,Ole);return KS(e,t)}a(vle,"s3FileObject");function KS(e,t){if(!t){let r=Sle.checkGlobalSchemaTable(e.schema,e.table);if(r)return HS(new Error,r,nC.BAD_REQUEST);if(e.operation===GS.OPERATIONS_ENUM.CSV_FILE_LOAD)try{rC.accessSync(e.file_path,rC.constants.R_OK|rC.constants.F_OK)}catch(n){return n.code===GS.NODE_ERROR_CODES.ENOENT?HS(n,`No such file or directory ${n.path}`,nC.BAD_REQUEST):n.code===GS.NODE_ERROR_CODES.EACCES?HS(n,`Permission denied ${n.path}`,nC.BAD_REQUEST):HS(n)}}return t}a(KS,"postValidateChecks");C$.exports={dataObject:Ple,urlObject:Lle,fileObject:Dle,s3FileObject:vle}});var cC=M((GUe,O$)=>{"use strict";var sh=J(),YS=(H(),v(z));async function Mle(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===YS.OPERATIONS_ENUM.INSERT||t.operation===YS.OPERATIONS_ENUM.UPDATE||t.operation===YS.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===YS.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(sh.info(i.message),i):i.http_resp_msg?(sh.error(`Error calling operation: ${e.name}`),sh.error(i.http_resp_msg),i):(sh.error(`Error calling operation: ${e.name}`),sh.error(i),i)}}a(Mle,"callOperationFunctionAsAwait");O$.exports={callOperationFunctionAsAwait:Mle}});var lC=M(($Ue,L$)=>{"use strict";var{S3:Ule,GetObjectCommand:xle}=require("@aws-sdk/client-s3");L$.exports={getFileStreamFromS3:Ble,getS3AuthObj:P$};async function Ble(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await P$(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new xle(r))).Body}a(Ble,"getFileStreamFromS3");function P$(e,t,r){return new Ule({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(P$,"getS3AuthObj")});var v$=M((KUe,D$)=>{"use strict";var uC=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}},dC=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};D$.exports={BulkLoadFileObject:uC,BulkLoadDataObject:dC}});var U$=M((WUe,M$)=>{"use strict";var fC=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}};M$.exports=fC});var B$=M((jUe,x$)=>{"use strict";var mC=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};x$.exports=mC});var hC=M((JUe,k$)=>{"use strict";var F$=U$(),Fle=B$(),{HDB_ERROR_MSGS:kle}=Jr(),pC=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=kle.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 F$(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Fle(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new F$(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}};k$.exports=pC});var kl=M((exe,$$)=>{"use strict";var ZUe=gn(),ih=J(),{validateBySchema:H$}=mt(),Zo=require("joi"),Hle=no(),WS=oe(),{handleHDBError:zS,hdbErrors:Gle,ClientError:G$}=_e(),{HDB_ERROR_MSGS:jS,HTTP_STATUS_CODES:EC}=Gle,q$=me();q$.initSync();var{getDatabases:_C}=(we(),v(ft)),qle=require("fs-extra"),$le=(H(),v(z));$$.exports={describeAll:Vle,describeTable:QS,describeSchema:Kle};async function Vle(e={}){try{let t=WS.isEmptyOrZeroLength(e),r=!!e.bypass_auth,n,s;!t&&!r&&(n=e.hdb_user?.role?.permission,s=n?.super_user||n?.cluster_user);let i=_C(),o={},c={},l=[],u=e?.exact_count,d=e?.include_computed;for(let m in i){o[m]=!0,!t&&!s&&!r&&(c[m]=e.hdb_user?.role?.permission[m]?.describe);let p=i[m];for(let h in p)try{let E;if(t||s||r)E=await QS({schema:m,table:h,exact_count:u,include_computed:d});else if(n&&n[m].describe&&n[m].tables[h].describe){let g=n[m].tables[h].attribute_permissions;E=await QS({schema:m,table:h,exact_count:u,include_computed:d},g)}E&&l.push(E)}catch(E){ih.error(E)}}let f={};for(let m in l)t||s||r?(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]):c[l[m].schema]&&(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]);for(let m in o)t||s||r?f[m]={}:c[m]&&(f[m]={});return f}catch(t){return ih.error("Got an error in describeAll"),ih.error(t),zS(new Error,jS.DESCRIBE_ALL_ERR)}}a(Vle,"describeAll");async function QS(e,t){WS.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=H$(e,Zo.object({database:Zo.string(),table:Zo.string().required(),exact_count:Zo.boolean().strict(),include_computed:Zo.boolean().strict()}));if(i)throw new G$(i.message);let c=_C()[r];if(!c)throw zS(new Error,jS.SCHEMA_NOT_FOUND(e.schema),EC.NOT_FOUND);let l=c[n];if(!l)throw zS(new Error,jS.TABLE_NOT_FOUND(e.schema,e.table),EC.NOT_FOUND);function u(p){(!p.computed||e.include_computed)&&d.push({attribute:p.attribute,type:p.type,elements:p.elements?.type,indexed:p.indexed,is_primary_key:p.isPrimaryKey,assigned_created_time:p.assignCreatedTime,assigned_updated_time:p.assignUpdatedTime,nullable:p.nullable,computed:p.computed?!0:void 0,properties:p.properties?p.properties.map(h=>({type:h.type,name:h.name})):void 0})}a(u,"pushAtt");let d=[];if(s){let p={};s.forEach(h=>{h.describe&&(p[h.attribute_name]=!0)}),l.attributes.forEach(h=>{p[h.name]&&u(h)})}else l.attributes?.forEach(p=>u(p));let f;try{f=(await qle.stat(l.primaryStore.env.path)).size}catch(p){ih.warn("unable to get database size",p)}let m={schema:r,name:l.tableName,hash_attribute:l.attributes.find(p=>p.isPrimaryKey||p.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:d,db_size:f};l.replicate!==void 0&&(m.replicate=l.replicate),l.expirationMS!==void 0&&(m.expiration=l.expirationMS/1e3+"s"),l.sealed!==void 0&&(m.sealed=l.sealed),l.sources?.length>0&&(m.sources=l.sources.map(p=>p.name).filter(p=>p&&p!=="NATSReplicator"&&p!=="Replicator")),q$.get($le.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(m.clustering_stream_name=Hle.createNatsTableStreamName(m.schema,m.name));try{let p=await l.getRecordCount({exactCount:!!e.exact_count});m.record_count=p.recordCount,m.table_size=l.getSize(),m.db_audit_size=l.getAuditSize(),m.estimated_record_range=p.estimatedRange;let h=l.auditStore;if(h)for(let E of h.getKeys({reverse:!0,limit:1}))m.last_updated_record=E[0];if(!m.last_updated_record&&l.indices.__updatedtime__)for(let E of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))m.last_updated_record=E}catch(p){ih.warn(`unable to stat table dbi due to ${p}`)}return m}a(QS,"descTable");async function Kle(e){WS.transformReq(e);let t=H$(e,Zo.object({database:Zo.string(),exact_count:Zo.boolean().strict(),include_computed:Zo.boolean().strict()}));if(t)throw new G$(t.message);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=_C()[n];if(!i)throw zS(new Error,jS.SCHEMA_NOT_FOUND(e.schema),EC.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),WS.isEmpty(l)||l.describe){let u=await QS({schema:e.schema,table:c,exact_count:e.exact_count,include_computed:e.include_computed},l?l.attribute_permissions:null);u&&(o[u.name]=u)}}return o}a(Kle,"describeSchema")});var z$=M((rxe,W$)=>{"use strict";var Yle=kl(),{hdbErrors:V$}=_e(),{getDatabases:K$}=(we(),v(ft));W$.exports={checkSchemaExists:Y$,checkSchemaTableExists:Wle,schemaDescribe:Yle};async function Y$(e){if(!K$()[e])return V$.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Y$,"checkSchemaExists");async function Wle(e,t){let r=await Y$(e);if(r)return r;if(!K$()[e][t])return V$.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Wle,"checkSchemaTableExists")});function gC(e){let t=e.get(JS),r=t?(0,qd.unpack)(t):null;r||(r={remoteNameToId:{}});let n=tt(),s=!1;r.nodeName=tt();let i=r.remoteNameToId;if(i[n]!==0){let o=0,c;for(let l in i){let u=i[l];u===0?c=l:u>o&&(o=u)}if(c){o++,i[c]=o;let l=[Symbol.for("seq"),o];e.rootStore.dbisDb.transactionSync(()=>{e.rootStore.dbisDb.get(l)||e.rootStore.dbisDb.putSync(l,{seqId:ah(e)??1,nodes:[]})})}i[n]=0,e.putSync(JS,(0,qd.pack)(r))}return r}function oh(e){return gC(e).remoteNameToId}function Q$(e,t){let r=gC(t),n=r.remoteNameToId,s=new Map,i=!1;for(let o in e){let c=e[o],l=n[o];if(l==null){let u=0;for(let d in n){let f=n[d];f>u&&(u=f)}l=u+1,n[o]=l,i=!0}s.set(c,l)}return i&&t.putSync(JS,(0,qd.pack)(r)),s}function XS(e,t){let r=gC(t),n=r.remoteNameToId,s=n[e];if(s==null){let i=0;for(let o in n){let c=n[o];c>i&&(i=c)}s=i+1,n[e]=s,t.putSync(JS,(0,qd.pack)(r))}return j$.trace?.("The remote node name map",e,n,s),s}var j$,qd,JS,SC=se(()=>{j$=b(wr());Ss();qd=require("msgpackr"),JS=Symbol.for("remote-ids");a(gC,"getIdMappingRecord");a(oh,"exportIdMapping");a(Q$,"remoteToLocalNodeId");a(XS,"getIdOfRemoteNode")});var rV={};ye(rV,{commitsAwaitingReplication:()=>Vd,getHDBNodeTable:()=>Ht,getReplicationSharedStatus:()=>Kd,iterateRoutes:()=>lh,shouldReplicateToNode:()=>ch,subscribeToNodeUpdates:()=>Yd});function Ht(){return J$||(J$=Xe({table:"hdb_nodes",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"},{attribute:"ca"},{attribute:"ca_info"},{attribute:"replicates"},{attribute:"revoked_certificates"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]}))}function Kd(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(64),n&&{callback:n}))}function Yd(e){Ht().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;tV.debug?.("adding node",n,"on node",tt()," on process",process.pid),server.nodes=server.nodes.filter(i=>i.name!==n),r.type==="put"&&n!==tt()&&(r.value?server.nodes.push(r.value):console.error("Invalid node update event",r));let s=new Map;for await(let i of Ht().search({}))if(i.shard!=null){let o=s.get(i.shard);o||s.set(i.shard,o=[]),o.push(i)}server.shards=s,(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function ch(e,t){return(e.replicates===!0||e.replicates?.sends)&&databases[t]&&Ht().primaryStore.get(tt())?.replicates||e.subscriptions?.some(r=>(r.database||r.schema)===t&&r.subscribe)}function zle(){Yd(e=>{lc({},(t,r)=>{let n=e.name,s=X$.get(n);if(s||X$.set(n,s=new Map),s.has(r))return;let i;for(let o in t)if(i=t[o].auditStore,i)break;if(i){let o=Kd(i,r,n,()=>{let c=o[0],l=o.lastTime;for(let{txnTime:u,onConfirm:d}of Vd.get(r)||[])u>l&&u<=c&&d();o.lastTime=c});o.lastTime=0,s.set(r,o)}})})}function*lh(e){for(let t of e.routes||[]){let r=t.url,n;if(typeof t=="string"?t.includes("://")?r=t:n=t:n=t.hostname??t.host,n&&!r){let s=$d.default.get(F.REPLICATION_SECUREPORT)??(!$d.default.get(F.REPLICATION_PORT)&&$d.default.get(F.OPERATIONSAPI_NETWORK_SECUREPORT)),i;(i=n.match(/:(\d+)$/)?.[1])?n=n.slice(0,-i[0].length-1):t.port?i=t.port:i=s||$d.default.get(F.REPLICATION_PORT)||$d.default.get(F.OPERATIONSAPI_NETWORK_PORT);let o=i?.lastIndexOf?.(":");o>0&&(i=+i.slice(o+1).replace(/[\[\]]/g,"")),r=(s?"wss://":"ws://")+n+":"+i}if(!r){Z$.isMainThread&&console.error("Invalid route, must specify a url or host (with port)");continue}yield{replicates:!t.subscriptions,url:r,subscription:t.subscriptions,routes:t.routes,startTime:t.startTime,revoked_certificates:t.revokedCertificates}}}var Z$,eV,$d,tV,J$,X$,Vd,Wd=se(()=>{we();Ss();Pm();Z$=require("worker_threads"),eV=b(_e()),$d=b(me());H();tV=b(wr());server.nodes=[];a(Ht,"getHDBNodeTable");a(Kd,"getReplicationSharedStatus");a(Yd,"subscribeToNodeUpdates");a(ch,"shouldReplicateToNode");X$=new Map;BU((e,t,r)=>{if(r>server.nodes.length)throw new eV.ClientError(`Cannot confirm replication to more nodes (${r}) than are in the network (${server.nodes.length})`);Vd||(Vd=new Map,zle());let n=Vd.get(e);return n||(n=[],Vd.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:a(()=>{++i===r&&s()},"onConfirm")})})});a(zle,"startSubscriptionToReplications");a(lh,"iterateRoutes")});var lV={};ye(lV,{connectedToNode:()=>Hl,disconnectedFromNode:()=>jd,ensureNode:()=>ea,requestClusterStatus:()=>cV,startOnMainThread:()=>TC});async function TC(e){let t=0,r=ct();for(let o of Object.getOwnPropertyNames(r)){let c=r[o];for(let l in c){let u=c[l];if(u.auditStore){ZS.set(o,ah(u.auditStore));break}}}Ti.whenThreadsStarted.then(async()=>{let o=[];for await(let u of r.system.hdb_nodes?.search([])||[])o.push(u);let c=tt();function l(){let u=Ht().primaryStore.get(c);if(u!==null){let d=e.url??uc();if(u===void 0||u.url!==d||u.shard!==e.shard)return ea(c,{name:c,url:d,shard:e.shard,replicates:!0})}}a(l,"ensureThisNode"),Ht().primaryStore.get(c)&&l();for(let u of lh(e))try{let d=!u.subscriptions;if(d&&await l(),d&&u.replicates==null&&(u.replicates=!0),nV.push(u),o.find(f=>f.url===u.url))continue;s(u)}catch(d){console.error(d)}Yd(s)});let n;function s(o,c=o?.name){let l=tt()&&c===tt()||uc()&&o?.url===uc();if(l){let m=!!o?.replicates;if(n!==void 0&&n!==m)for(let p of Ht().search([]))p.replicates&&p.name!==c&&s(p,p.name);n=m}if(ot.trace("Setting up node replication for",o),!o){for(let[m,p]of fo){let h;for(let[E,{worker:g,nodes:R}]of p){let S=R[0];if(S&&S.name==c){h=!0;for(let[y,{worker:N}]of p)p.delete(y),ot.warn("Node was deleted, unsubscribing from node",c,y,m),N?.postMessage({type:"unsubscribe-from-node",node:c,nodes:R,database:y,url:m});break}}if(h){fo.get(m).iterator.remove(),fo.delete(m);return}}return}if(l)return;if(!o.url){ot.info(`Node ${o.name} is missing url`);return}let u=fo.get(o.url);if(u&&u.iterator.remove(),!(o.replicates===!0||o.replicates?.sends)&&!o.subscriptions?.length&&!u)return;if(ot.info(`Added node ${o.name} at ${o.url} for process ${tt()}`),o.replicates&&o.subscriptions&&(o={...o,subscriptions:null}),o.name){for(let[m,p]of zd)if(o.url===p.url){zd.delete(m);break}zd.set(o.name,o)}let d=ct();if(u||(u=new Map,fo.set(o.url,u)),u.iterator=lc(e,(m,p,h)=>{h?f(p,!0):f(p,!1)}),o.subscriptions)for(let m of o.subscriptions){let p=m.database||m.schema;d[p]||(ot.warn(`Database ${p} not found for node ${o.name}, making a subscription anyway`),f(p,!1))}function f(m,p){ot.trace("Setting up replication for database",m,"on node",o.name);let h=u.get(m),E,g=[{replicateByDefault:p,...o}];ZS.has(m)&&uh.default.get(F.REPLICATION_FAILOVER)&&(g.push({replicateByDefault:p,name:tt(),startTime:ZS.get(m),endTime:Date.now(),replicates:!0}),ZS.delete(m));let R=ch(o,m),S=Ti.workers.filter(y=>y.name==="http");if(h){if(E=h.worker,h.nodes=g,R)return}else R&&(t=t%S.length,E=S[t++],E||ot.warn("No http workers available to subscribe to node",o.name,o.url),u.set(m,{worker:E,nodes:g,url:o.url}),E?.on("exit",()=>{u.get(m)?.worker===E&&(u.delete(m),f(m,p))}));if(R){let y=jle.HDB_LEADER_URL??process.env.HDB_LEADER_URL??nV[0]?.url??Array.from(Ht().primaryStore.getRange({}).filter(N=>N.name!==tt()))[0]?.url;g[0].isLeader=!y||g[0].url===y,setTimeout(()=>{let N={...g[0],type:"subscribe-to-node",database:m,nodes:g};E?E.postMessage(N):dh(N)},Qle)}else{ot.info("Node no longer should be used, unsubscribing from node",{replicates:o.replicates,databaseName:m,node:o,subscriptions:o.subscriptions,hasDatabase:!!d[m],thisReplicates:Ht().primaryStore.get(tt())?.replicates}),Ht().primaryStore.get(tt())?.replicates||(n=!1,ot.info("Disabling replication, this node name",tt(),Ht().primaryStore.get(tt()),m));let y={type:"unsubscribe-from-node",database:m,url:o.url,name:o.name,nodes:g};E?E.postMessage(y):tT(y)}}a(f,"onDatabase")}a(s,"onNodeUpdate"),jd=a(function(o){try{ot.info("Disconnected from node",o.name,o.url,"finished",!!o.finished);let c=Array.from(zd.keys()),l=c.sort(),u=l.indexOf(o.name||yi(o.url));if(u===-1){ot.warn("Disconnected node not found in node map",o.name,c);return}let d=fo.get(o.url),f=d?.get(o.database);if(!f){ot.warn("Disconnected node not found in replication map",o.database,d);return}if(f.connected=!1,o.finished||!uh.default.get(F.REPLICATION_FAILOVER))return;let m=f.nodes[0];if(!(m.replicates===!0||m.replicates?.sends||m.subscriptions?.length))return;let p=m.shard,h=(u+1)%l.length;for(;u!==h;){let E=l[h],g=zd.get(E);d=fo.get(g.url);let R=d?.get(o.database);if(!R||R.connected===!1||R.nodes[0].shard!==p){h=(h+1)%l.length;continue}let{nodes:S}=R,y=!1;for(let N of f.nodes){if(S.some(I=>I.name===N.name)){ot.info(`Disconnected node is already failing over to ${E} for ${o.database}`);continue}N.endTime<Date.now()||(S.push(N),ot.info(`Failing over ${o.database} from ${o.name} to ${E}`),i(N,o.database,R.nodes[0]),y=!0)}f.nodes=[f.nodes[0]],y||ot.info(`Disconnected node ${o.name} has no nodes to fail over to ${E}`);return}ot.warn("Unable to find any other node to fail over to",o.name,o.url)}catch(c){ot.error("Error failing over node",c)}},"disconnectedFromNode"),Hl=a(function(o){let c=fo.get(o.url),l=c?.get(o.database);if(!l){ot.warn("Connected node not found in replication map, this may be because the node is being removed",o.database,c);return}l.connected=!0,l.latency=o.latency;let u=l.nodes[0];if(!u){ot.warn("Newly connected node has no node subscriptions",o.database,l);return}if(!u.name){ot.debug("Connected node is not named yet",o.database,l);return}if(!uh.default.get(F.REPLICATION_FAILOVER))return;l.nodes=[u];let d=!1;for(let f of fo.values()){let m=f.get(o.database);if(!m||m==l)continue;let{worker:p,nodes:h,connected:E}=m;if(h)if(E===!1&&h[0].shard===u.shard&&node.url===u.url)for(let g of h)i(g,o.database);else{let g=h.filter(R=>{if(R)return R.name===u.name&&R.worker?(R.worker.postMessage({type:"unsubscribe-to-node",database:o.database,url:o.url,nodes:[R]}),!1):!0});g.length<h.length&&(m.nodes=g)}}},"connectedToNode");function i(o,c,l=o){let u=Ti.workers.filter(f=>f.name==="http");t=t%u.length;let d=u[t++];Object.defineProperty(o,"worker",{value:d,configurable:!0}),d?d.postMessage({url:l.url,name:l.name,type:"subscribe-to-node",database:c,nodes:[o]}):dh({url:l.url,name:l.name,database:c,nodes:[o]})}a(i,"connectToNextWorker"),(0,Ti.onMessageByType)("disconnected-from-node",jd),(0,Ti.onMessageByType)("connected-to-node",Hl),(0,Ti.onMessageByType)("request-cluster-status",cV)}function cV(e,t){let r=[];for(let[n,s]of zd)try{let i=fo.get(s.url);ot.info("Getting cluster status for",n,s.url,"has dbs",i?.size);let o=[];if(i){for(let[l,{worker:u,connected:d,nodes:f,latency:m}]of i)o.push({database:l,connected:d,latency:m,threadId:u?.threadId,nodes:f.filter(p=>!(p.endTime<Date.now())).map(p=>p.name)});let c=iV(s);c.database_sockets=o,delete c.ca,delete c.node_name,delete c.__updatedtime__,delete c.__createdtime__,r.push(c)}}catch(i){ot.warn("Error getting cluster status for",s?.url,i)}return t?.postMessage({type:"cluster-status",connections:r}),{connections:r}}async function ea(e,t){let r=Ht();e=e??yi(t.url),t.name=e;try{if(t.ca){let s=new oV.X509Certificate(t.ca);t.ca_info={issuer:s.issuer.replace(/\n/g," "),subject:s.subject.replace(/\n/g," "),subjectAltName:s.subjectAltName,serialNumber:s.serialNumber,validFrom:s.validFrom,validTo:s.validTo}}}catch(s){ot.error("Error parsing replication CA info for hdb_nodes table",s.message)}let n=r.primaryStore.get(e);if(ot.debug(`Ensuring node ${e} at ${t.url}, existing record:`,n,"new record:",t),!n)await r.patch(t);else{t.replicates&&!uh.default.get(F.CLUSTERING_ENABLED)&&(t.subscriptions=null);for(let s in t)if(n[s]!==t[s]&&s==="subscriptions"&&t[s]&&n[s]){let i=[],o=iV(n[s]);for(let c of t[s]){let l=!1;for(let u of o)if((c.database??c.schema)===(u.database??u.schema)&&c.table===u.table){u.publish=c.publish,u.subscribe=c.subscribe,l=!0;break}l||i.push(c)}t.subscriptions=[...o,...i];break}if(Array.isArray(t.revoked_certificates)){let s=n.revoked_certificates||[];t.revoked_certificates=[...new Set([...s,...t.revoked_certificates])]}ot.info(`Updating node ${e} at ${t.url}`),await r.patch(t)}}var Ti,eT,ot,sV,uh,oV,aV,iV,jle,Qle,fo,jd,Hl,zd,ZS,nV,fh=se(()=>{we();Ti=b(st());Ss();eT=require("worker_threads");Wd();ot=b(J()),sV=b(require("lodash")),uh=b(me());H();oV=require("crypto"),aV=b(require("minimist")),{cloneDeep:iV}=sV.default,jle=(0,aV.default)(process.argv),Qle=200,fo=new Map,zd=new Map,ZS=new Map,nV=[];a(TC,"startOnMainThread");a(cV,"requestClusterStatus");eT.parentPort&&(jd=a(e=>{eT.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),Hl=a(e=>{eT.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,Ti.onMessageByType)("subscribe-to-node",e=>{dh(e)}),(0,Ti.onMessageByType)("unsubscribe-from-node",e=>{tT(e)}));a(ea,"ensureNode")});var ys=M(Gt=>{"use strict";var hr=require("path"),{watch:Jle}=require("chokidar"),Wn=require("fs-extra"),Qd=require("node-forge"),hV=require("net"),{generateKeyPair:yC,X509Certificate:ta,createPrivateKey:EV,randomBytes:Xle}=require("node:crypto"),Zle=require("util");yC=Zle.promisify(yC);var Pt=Qd.pki,Ri=require("joi"),{v4:_V}=require("uuid"),{validateBySchema:IC}=mt(),{forComponent:eue}=J(),Ts=me(),Ks=(H(),v(z)),{CONFIG_PARAMS:ql}=Ks,bi=Kw(),{ClientError:dc}=_e(),nT=require("node:tls"),{relative:gV,join:tue}=require("node:path"),{CERTIFICATE_VALUES:uV}=bi,rue=Qc(),RC=gt(),{table:nue,getDatabases:sue,databases:rT}=(we(),v(ft)),{getJWTRSAKeys:dV}=(kd(),v(nh)),Je=eue("tls").conditional;Gt.generateKeys=CC;Gt.updateConfigCert=wV;Gt.createCsr=due;Gt.signCertificate=fue;Gt.setCertTable=Jd;Gt.loadCertificates=bV;Gt.reviewSelfSignedCert=PC;Gt.createTLSSelector=CV;Gt.listCertificates=PV;Gt.addCertificate=gue;Gt.removeCertificate=Tue;Gt.createNatsCerts=hue;Gt.generateCertsKeys=pue;Gt.getReplicationCert=ph;Gt.getReplicationCertAuth=uue;Gt.renewSelfSigned=Eue;Gt.hostnamesFromCert=DC;Gt.getKey=yue;Gt.getHostnamesFromCertificate=Rue;Gt.getPrimaryHostName=LC;Gt.generateSerialNumber=oT;var{urlToNodeName:SV,getThisNodeUrl:iue,getThisNodeName:iT,clearThisNodeName:oue}=(Ss(),v(ra)),{readFileSync:aue,statSync:TV}=require("node:fs"),_xe=me(),{getTicketKeys:cue,onMessageFromWorkers:lue}=st(),{isMainThread:yV}=require("worker_threads"),{TLSSocket:RV,createSecureContext:gxe}=require("node:tls"),wC=3650,mh=["127.0.0.1","localhost","::1"],NC=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];function oT(){let e=Xle(8);return e[0]=e[0]&127|1,e.toString("hex")}a(oT,"generateSerialNumber");lue(async e=>{e.type===Ks.ITC_EVENT_TYPES.RESTART&&(Ts.initSync(!0),await PC())});var on;function mc(){return on||(on=sue().system.hdb_certificate,on||(on=nue({table:"hdb_certificate",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{attribute:"__updatedtime__"}]}))),on}a(mc,"getCertTable");async function ph(){let e=CV("operations-api"),t={secureContexts:null,setSecureContext:a(s=>{},"setSecureContext")};await e.initialize(t);let r=t.secureContexts.get(iT());if(!r)return;let n=new ta(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(ph,"getReplicationCert");async function uue(){mc();let e=(await ph()).options.cert,r=new ta(e).issuer.match(/CN=(.*)/)?.[1];return on.get(r)}a(uue,"getReplicationCertAuth");var fV,fc=new Map;function bV(){if(fV)return;fV=!0;let e=[{configKey:ql.TLS},{configKey:ql.OPERATIONSAPI_TLS}];mc();let t=hr.dirname(RC.getConfigFilePath()),r;for(let{configKey:n}of e){let s=RC.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&gV(tue(t,"keys"),o);c&&mV(o,l=>{fc.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&yV){let d;mV(u,f=>{if(uV.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let p=NV(u),h=new ta(p),E;try{E=LC(h)}catch(y){Je.error?.("error extracting host name from certificate",y);return}if(E==null){Je.error?.("No host name found on certificate");return}if(h.checkIssued(new ta(uV.cert)))return;let g=on.primaryStore.get(E),R=TV(u).mtimeMs,S=!g||g.is_self_signed?1:g.file_timestamp??g.__updatedtime__;if(g&&R<=S){R<S&&Je.info?.(`Certificate ${E} at ${u} is older (${new Date(R)}) than the certificate in the database (${S>1?new Date(S):"only self signed certificate available"})`);return}r=on.put({name:E,uses:["https",...n.includes("operations")?["operations"]:[]],ciphers:i.ciphers,certificate:p,private_key_name:c,is_authority:l,hostnames:m,fileTimestamp:R,details:{issuer:h.issuer.replace(/\n/g," "),subject:h.subject?.replace(/\n/g," "),subject_alt_name:h.subjectAltName,serial_number:h.serialNumber,valid_from:h.validFrom,valid_to:h.validTo}})},l?"certificate authority":"certificate")}}}}}return r}a(bV,"loadCertificates");function mV(e,t,r){let n,s=a((i,o)=>{try{let c=o.mtimeMs;c&&c!==n&&(n&&yV&&Je.warn?.(`Reloading ${r}:`,i),n=c,t(NV(i)))}catch(c){Je.error?.(`Error loading ${r}:`,i,c)}},"loadFile");Wn.existsSync(e)?s(e,TV(e)):Je.error?.(`${r} file not found:`,e),Jle(e,{persistent:!1}).on("change",s)}a(mV,"loadAndWatch");function bC(){let e=iue();if(e==null){let t=mh[0];return Je.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return SV(e)}a(bC,"getHost");function sT(){let e=iT();if(e==null){let t=mh[0];return Je.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(sT,"getCommonName");async function due(){let e=await ph(),t=Pt.certificateFromPem(e.options.cert),r=Pt.privateKeyFromPem(e.options.key);Je.info?.("Creating CSR with cert named:",e.name);let n=Pt.createCertificationRequest();n.publicKey=t.publicKey;let s=[{name:"commonName",value:sT()},...NC];Je.info?.("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:AV()}];return Je.info?.("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),Qd.pki.certificationRequestToPem(n)}a(due,"createCsr");function AV(){let e=mh.includes(sT())?mh:[...mh,sT()];return e.includes(bC())||e.push(bC()),[{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"nsCertType",client:!0,server:!0},{name:"subjectAltName",altNames:e.map(t=>hV.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(AV,"certExtensions");async function fue(e){let t={},r=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;mc();for await(let d of on.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(fc.has(d.private_key_name)){n=fc.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await Wn.exists(hr.join(r,d.private_key_name))){n=Wn.readFile(hr.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await AC();s=d.ca,n=d.private_key}n=Pt.privateKeyFromPem(n),t.signingCA=s.certificate;let i=Pt.certificateFromPem(s.certificate);Je.info?.("Signing CSR with cert named",s.name);let o=Pt.certificationRequestFromPem(e.csr);try{o.verify()}catch(d){return Je.error?.(d),new Error("Error verifying CSR: "+d.message)}let c=Qd.pki.createCertificate();c.serialNumber=oT(),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+wC),Je.info?.("sign cert setting validity:",c.validity),Je.info?.("sign cert setting subject from CSR:",o.subject.attributes),c.setSubject(o.subject.attributes),Je.info?.("sign cert setting issuer:",i.subject.attributes),c.setIssuer(i.subject.attributes);let u=o.getAttribute({name:"extensionRequest"}).extensions;Je.info?.("sign cert adding extensions from CSR:",u),c.setExtensions(u),c.publicKey=o.publicKey,c.sign(n,Qd.md.sha256.create()),t.certificate=Pt.certificateToPem(c)}else Je.info?.("Sign cert did not receive a CSR from:",e.url,"only the CA will be returned");return t}a(fue,"signCertificate");async function mue(e,t){await Jd({name:iT(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await Jd({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:Pt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}a(mue,"createCertificateTable");async function Jd(e){let t;try{t=new ta(e.certificate)}catch(r){Je.error?.(`Failed to parse certificate for ${e.name}:`,r.message),Je.debug?.("Certificate record details:",JSON.stringify(e,null,2));let n=new Error(`Invalid certificate format for ${e.name}: ${r.message}. This may be due to corrupted certificate data during transfer or encoding issues.`);throw n.code="INVALID_CERTIFICATE_FORMAT",n.cause=r,n}e.details={issuer:t.issuer.replace(/\n/g," "),subject:t.subject?.replace(/\n/g," "),subject_alt_name:t.subjectAltName,serial_number:t.serialNumber,valid_from:t.validFrom,valid_to:t.validTo},mc(),await on.patch(e)}a(Jd,"setCertTable");async function CC(){let e=await yC("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:Pt.publicKeyFromPem(e.publicKey),privateKey:Pt.privateKeyFromPem(e.privateKey)}}a(CC,"generateKeys");async function OC(e,t,r){let n=Pt.createCertificate();if(!t){let o=await ph();t=Pt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=oT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+wC);let i=[{name:"commonName",value:sT()},...NC];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(AV()),n.sign(e,Qd.md.sha256.create()),Pt.certificateToPem(n)}a(OC,"generateCertificates");async function AC(){let e=await PV(),t;for(let r of e){if(!r.is_authority)continue;let n=await OV(r.private_key_name);if(r.private_key_name&&n&&new ta(r.certificate).checkPrivateKey(EV(n))){Je.trace?.(`CA named: ${r.name} found with matching private key`),t={ca:r,private_key:n};break}}if(t)return t;Je.trace?.("No CA found with matching private key")}a(AC,"getCertAuthority");async function IV(e,t,r=!0){let n=Pt.createCertificate();n.publicKey=t,n.serialNumber=oT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+wC);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ts.get(ql.REPLICATION_HOSTNAME)??SV(Ts.get(ql.REPLICATION_URL))??_V().split("-")[0]}`},...NC];n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,critical:!0},{name:"subjectKeyIdentifier"}]),n.sign(e,Qd.md.sha256.create());let o=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),c=hr.join(o,bi.PRIVATEKEY_PEM_NAME);return r&&await Wn.writeFile(c,Pt.privateKeyToPem(e)),n}a(IV,"generateCertAuthority");async function pue(){let{privateKey:e,publicKey:t}=await CC(),r=await IV(e,t),n=await OC(e,t,r);await mue(n,r),wV()}a(pue,"generateCertsKeys");async function hue(){let e=await OC(Pt.privateKeyFromPem(bi.CERTIFICATE_VALUES.key),void 0,Pt.certificateFromPem(bi.CERTIFICATE_VALUES.cert)),t=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),r=hr.join(t,bi.NATS_CERTIFICATE_PEM_NAME);await Wn.exists(r)||await Wn.writeFile(r,e);let n=hr.join(t,bi.NATS_CA_PEM_NAME);await Wn.exists(n)||await Wn.writeFile(n,bi.CERTIFICATE_VALUES.cert)}a(hue,"createNatsCerts");async function Eue(){mc();for await(let e of on.search([{attribute:"is_self_signed",value:!0}]))await on.delete(e.name);await PC()}a(Eue,"renewSelfSigned");async function PC(){oue(),await bV(),mc();let e=await AC();if(!e){Je.notify?.("A matching Certificate Authority and key was not found. A new CA will be created in advance, so it's available if needed.");let r=a(u=>{try{return{key:Pt.privateKeyFromPem(Wn.readFileSync(u)),keyPath:u}}catch(d){return Je.warn?.(`Failed to parse private key from ${u}:`,d.message),{key:null,keyPath:u}}},"tryToParseKey"),n=Ts.get(ql.TLS),s,i;if(Array.isArray(n)){for(let u of n)if(u.privateKey){let d=r(u.privateKey);if(s=d.key,i=d.keyPath,d.key)break}}else{let u=Ts.get(ql.TLS_PRIVATEKEY),d=r(u);s=d.key,i=d.keyPath}let o=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),c=gV(o,i);s||(Je.warn?.("Unable to parse the TLS key",i,"A new key will be generated and used to create Certificate Authority"),{privateKey:s}=await CC(),Wn.existsSync(hr.join(o,bi.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${_V().split("-")[0]}.pem`),await Wn.writeFile(hr.join(o,c),Pt.privateKeyToPem(s)));let l=await IV(s,Pt.setRsaPublicKey(s.n,s.e),!1);await Jd({name:l.subject.getField("CN").value,uses:["https"],certificate:Pt.certificateToPem(l),private_key_name:c,is_authority:!0,is_self_signed:!0})}if(!await ph()){let r=iT();Je.notify?.(`A suitable replication certificate was not found, creating new self singed cert named: ${r}`),e=e??await AC();let n=Pt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await OC(Pt.privateKeyFromPem(e.private_key),s,n);await Jd({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}a(PC,"reviewSelfSignedCert");function wV(){let e=rue(Object.keys(Ks.CONFIG_PARAM_MAP),!0),t=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),r=hr.join(t,bi.PRIVATEKEY_PEM_NAME),n=hr.join(t,bi.NATS_CERTIFICATE_PEM_NAME),s=hr.join(t,bi.NATS_CA_PEM_NAME),i=Ks.CONFIG_PARAMS,o={[i.TLS_PRIVATEKEY]:e[i.TLS_PRIVATEKEY.toLowerCase()]?e[i.TLS_PRIVATEKEY.toLowerCase()]:r};e[i.TLS_CERTIFICATE.toLowerCase()]&&(o[i.TLS_CERTIFICATE]=e[i.TLS_CERTIFICATE.toLowerCase()]),e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.TLS_CERTIFICATEAUTHORITY]=e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATE]=e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_PRIVATEKEY]=e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),(e[i.CLUSTERING_ENABLED.toLowerCase()]||e.clustering)&&(o[i.CLUSTERING_TLS_CERTIFICATE]=e[i.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]??n,o[i.CLUSTERING_TLS_CERT_AUTH]=e[i.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]??s,o[i.CLUSTERING_TLS_PRIVATEKEY]=e[i.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]??r),RC.updateConfigValue(void 0,void 0,o,!1,!0)}a(wV,"updateConfigCert");function NV(e){return e.startsWith("-----BEGIN")?e:aue(e,"utf8")}a(NV,"readPEM");var pV=nT.createSecureContext;nT.createSecureContext=function(e){if(!e.cert||!e.key)return pV(e);let t={...e};delete t.key,delete t.cert;let r=pV(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var _ue=RV.prototype._init;RV.prototype._init=function(e,t){_ue.call(this,e,t);let r=this;this._handle.oncertcb=function(n){let s=n.servername;r._SNICallback(s,(i,o)=>{this.sni_context=o?.context||o,this.certCbDone()})}};var Gl=new Map;function CV(e,t){let r=new Map,n,s=!1;return i.initialize=o=>i.ready?i.ready:(o&&(o.secureContexts=r,o.secureContextsListeners=[]),i.ready=new Promise((c,l)=>{async function u(){try{r.clear(),Gl.clear();let d=0;if(rT===void 0){c();return}for await(let f of rT.system.hdb_certificate.search([])){let m=f.certificate,p=new ta(m);f.is_authority&&(p.asString=m,Gl.set(p.subject,m))}for await(let f of rT.system.hdb_certificate.search([]))try{if(f.is_authority)continue;let m=e==="operations-api",p=f.is_self_signed?1:3;m&&f.uses?.includes?.("operations")&&(p+=1);let h=await OV(f.private_key_name),E=f.certificate,g=new ta(E);if(Gl.has(g.issuer)&&(E+=`
15
+ `)}}});var wG,vl,NG,sc,Dp,yd,mae,tS,uN=se(()=>{wG=b(ls()),vl=b(st());H();NG=b(wr());_d();eS();sc=(0,NG.loggerWithTag)("componentStatus.crossThread"),Dp=class{static{a(this,"CrossThreadStatusCollector")}awaitingResponses=new Map;responseCheckers=new Map;nextRequestId=1;listenerAttached=!1;timeout;cleanupTimer=null;constructor(t=5e3){this.timeout=t}attachListener(){this.listenerAttached||((0,vl.onMessageByType)(f_.COMPONENT_STATUS_RESPONSE,({message:t})=>{let r=t.isMainThread?"main":`worker-${t.workerIndex}`;sc.trace?.("Received component status response from %s, with requestId: %d",r,t.requestId);let n=this.awaitingResponses.get(t.requestId);if(n){n.push({workerIndex:t.workerIndex,isMainThread:t.isMainThread||!1,statuses:t.statuses||[]});let s=this.responseCheckers.get(t.requestId);s&&s()}}),this.listenerAttached=!0)}scheduleCleanup(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.awaitingResponses.size>0&&(this.cleanupTimer=setTimeout(()=>{this.awaitingResponses.size>0&&(sc.debug?.(`Cleaning up ${this.awaitingResponses.size} stale pending requests`),this.awaitingResponses.clear()),this.cleanupTimer=null},3e4))}async collect(t){try{this.attachListener(),this.scheduleCleanup();let r=this.nextRequestId++,n=[];this.awaitingResponses.set(r,n);let o=((0,vl.getWorkerCount)()||1)+1-1,l=await new Promise((p,h)=>{let E=!1,g=a(()=>{let y=this.awaitingResponses.get(r);y&&y.length>=o&&!E&&(E=!0,S(),sc.trace?.(`Collected all ${y.length} expected responses for request ${r}`),p(y))},"checkComplete"),R=setTimeout(()=>{if(!E){E=!0;let y=this.awaitingResponses.get(r)||[];this.awaitingResponses.delete(r),sc.debug?.(`Collection timeout for request ${r}: collected ${y.length}/${o} responses`),p(y)}},this.timeout),S=a(()=>{this.awaitingResponses.delete(r),clearTimeout(R)},"cleanup");this.responseCheckers.set(r,g),(0,wG.sendItcEvent)({type:f_.COMPONENT_STATUS_REQUEST,message:{requestId:r}}).then(()=>{g()}).catch(y=>{E=!0,S(),this.responseCheckers.delete(r),h(new Sd("sendItcEvent",y))})});this.responseCheckers.delete(r);let u=new Map,d=t.getAllStatuses(),f=(0,vl.getWorkerIndex)(),m=f===void 0?"main":`worker-${f}`;for(let[p,h]of d)u.set(`${p}@${m}`,{...h,workerIndex:f});for(let p of l)for(let[h,E]of p.statuses){let g=p.isMainThread?"main":`worker-${p.workerIndex}`;u.set(`${h}@${g}`,{...E,workerIndex:p.workerIndex})}return sc.debug?.(`Collected component status from ${l.length+1} threads (including local)`),u}catch(r){return r instanceof Sd?sc.error?.(`ITC failure during component status collection: ${r.message}`):sc.warn?.("Failed to collect component status from all threads:",r),sc.debug?.(`Collection failed for request. Error: ${r instanceof Error?r.message:"Unknown error"}`),this.getLocalStatusOnly(t)}}getLocalStatusOnly(t){let r=t.getAllStatuses(),n=new Map,s=(0,vl.getWorkerIndex)(),i=s===void 0?"main":`worker-${s}`;for(let[o,c]of r)n.set(`${o}@${i}`,{...c,workerIndex:s});return n}cleanup(){this.awaitingResponses.clear(),this.responseCheckers.clear(),this.cleanupTimer&&(clearTimeout(this.cleanupTimer),this.cleanupTimer=null)}},yd=class{static{a(this,"StatusAggregator")}static aggregate(t){let r=new Map,n=new Map;for(let[s,i]of t){let o=s.indexOf("@"),c=o!==-1?s.substring(0,o):s,l=n.get(c);l||(l=[],n.set(c,l)),l.push([s,i])}for(let[s,i]of n){let o=this.aggregateComponentGroup(s,i);r.set(s,o)}return r}static aggregateComponentGroup(t,r){let n={workers:{}},s=0,i,o,c=new Map,l=new Map;for(let[m,p]of r){let h=m.lastIndexOf("@"),E=h!==-1?m.substring(h+1):"",g=p.lastChecked instanceof Date?p.lastChecked.getTime():new Date(p.lastChecked).getTime();if(E==="main")n.main=g;else if(E&&E.startsWith("worker-")){let R=parseInt(E.substring(7));isNaN(R)||(n.workers[R]=g)}c.set(p.status,(c.get(p.status)||0)+1),p.status!==Ne.HEALTHY&&p.message&&(!i||g>s)&&(s=g,i=p.message),p.error&&!o&&(o=p.error)}let u=this.determineOverallStatus(c);if(Array.from(c.keys()).length>1)for(let[m,p]of r)p.status!==u&&l.set(m,{workerIndex:p.workerIndex!==void 0?p.workerIndex:-1,status:p.status,message:p.message,error:p.error});let f={componentName:t,status:u,lastChecked:n,latestMessage:i,error:o};return l.size>0&&(f.abnormalities=l),f}static determineOverallStatus(t){let r=[Ne.ERROR,Ne.WARNING,Ne.LOADING,Ne.UNKNOWN,Ne.HEALTHY];for(let n of r)if(t.has(n)&&t.get(n)>0)return n;return Ne.UNKNOWN}},mae=parseInt(process.env.COMPONENT_STATUS_TIMEOUT||"5000"),tS=new Dp(mae)});var ic,rS=se(()=>{oN();_d();uN();eS();ic=class e{static{a(this,"ComponentStatusRegistry")}statusMap=new Map;reset(){this.statusMap=new Map}setStatus(t,r,n,s){if(!t||typeof t!="string")throw new Td(String(t),"setStatus","Component name must be a non-empty string");if(!Object.values(Ne).includes(r))throw new Td(t,"setStatus",`Invalid status level: ${r}. Must be one of: ${Object.values(Ne).join(", ")}`);this.statusMap.set(t,new gd(r,n,s))}getStatus(t){return this.statusMap.get(t)}getAllStatuses(){return this.statusMap}reportHealthy(t,r){this.setStatus(t,Ne.HEALTHY,r)}reportError(t,r,n){this.setStatus(t,Ne.ERROR,n,r)}reportWarning(t,r){this.setStatus(t,Ne.WARNING,r)}initializeLoading(t,r){this.setStatus(t,Ne.LOADING,r||"Component is loading")}markLoaded(t,r){this.setStatus(t,Ne.HEALTHY,r||"Component loaded successfully")}markFailed(t,r,n){this.setStatus(t,Ne.ERROR,n,r)}getComponentsByStatus(t){let r=[];for(let[n,s]of this.statusMap)s.status===t&&r.push({name:n,status:s});return r}getStatusSummary(){let t={[Ne.HEALTHY]:0,[Ne.ERROR]:0,[Ne.WARNING]:0,[Ne.LOADING]:0,[Ne.UNKNOWN]:0};for(let r of this.statusMap.values())t[r.status]++;return t}static async getAggregatedFromAllThreads(t){let r=await tS.collect(t);return yd.aggregate(r)}async getAggregatedStatusFor(t,r){r||(r=await e.getAggregatedFromAllThreads(this));let n=[],s=t+".",i=r.get(t);i&&n.push({key:t,...i});for(let[f,m]of r)f.startsWith(s)&&n.push({key:f,...m});if(n.length===0)return{status:Ne.UNKNOWN,message:"The component has not been loaded yet (may need a restart)",lastChecked:{workers:{}}};let o=n.some(f=>f.status===Ne.ERROR),c=n.some(f=>f.status===Ne.LOADING),l=o?Ne.ERROR:c?Ne.LOADING:Ne.HEALTHY,u="All components loaded successfully",d={};if(o||c){u=n.filter(m=>m.status===Ne.ERROR||m.status===Ne.LOADING).map(m=>`${m.key}: ${m.latestMessage||m.status}`).join("; ");for(let m of n)m.status!==Ne.HEALTHY&&(d[m.key]={status:m.status,message:m.latestMessage})}return{status:l,message:u,...Object.keys(d).length>0&&{details:d},lastChecked:n[0]?.lastChecked||{workers:{}}}}}});var mr,nS=se(()=>{rS();mr=new ic});function OG(e){let t=CG.get(e);return t||(t=new dN(e),CG.set(e,t)),t}function PG(){mr.reset()}var dN,CG,ao,LG,DG=se(()=>{nS();_d();dN=class{static{a(this,"ComponentStatusBuilder")}componentName;constructor(t){this.componentName=t}healthy(t){return mr.setStatus(this.componentName,Ne.HEALTHY,t),this}warning(t){return mr.setStatus(this.componentName,Ne.WARNING,t),this}error(t,r){return mr.setStatus(this.componentName,Ne.ERROR,t,r),this}loading(t){return mr.setStatus(this.componentName,Ne.LOADING,t||"Loading..."),this}unknown(t){return mr.setStatus(this.componentName,Ne.UNKNOWN,t),this}get(){return mr.getStatus(this.componentName)}},CG=new Map;a(OG,"statusForComponent");ao={loading(e,t){mr.initializeLoading(e,t)},loaded(e,t){mr.markLoaded(e,t)},failed(e,t,r){mr.markFailed(e,t,r)}};a(PG,"reset");LG=Ne});var vp={};ye(vp,{AggregationError:()=>cN,COMPONENT_STATUS_LEVELS:()=>Ne,ComponentStatus:()=>gd,ComponentStatusError:()=>nc,ComponentStatusOperationError:()=>Td,ComponentStatusRegistry:()=>ic,CrossThreadCollectionError:()=>lN,CrossThreadStatusCollector:()=>Dp,CrossThreadTimeoutError:()=>aN,ITCError:()=>Sd,StatusAggregator:()=>yd,componentStatusRegistry:()=>mr,crossThreadCollector:()=>tS,query:()=>pae});var pae,vG=se(()=>{nS();rS();oN();rS();uN();nS();eS();_d();pae={get(e){return mr.getStatus(e)},all(){return mr.getAllStatuses()},byStatus(e){return mr.getComponentsByStatus(e)},summary(){return mr.getStatusSummary()},async allThreads(){return ic.getAggregatedFromAllThreads(mr)}}});var fN={};ye(fN,{STATUS:()=>LG,internal:()=>vp,lifecycle:()=>ao,reset:()=>PG,statusForComponent:()=>OG});var Mp=se(()=>{DG();vG()});var xp=M((eMe,xG)=>{"use strict";var _s=J(),yn=(H(),v(z)),hae=tB(),Eae=Es(),{validateEvent:mN}=ls(),Up=fs(),_ae=require("process"),{resetDatabases:gae}=(we(),v(ft)),Sae={[yn.ITC_EVENT_TYPES.SCHEMA]:Tae,[yn.ITC_EVENT_TYPES.USER]:UG,[yn.ITC_EVENT_TYPES.COMPONENT_STATUS_REQUEST]:Rae};async function Tae(e){let t=mN(e);if(t){_s.error(t);return}_s.trace("ITC schemaHandler received schema event:",e),await hae(e.message),await yae(e.message)}a(Tae,"schemaHandler");async function yae(e){try{Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=gae();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){_s.error(t)}}a(yae,"syncSchemaMetadata");var MG=[];async function UG(e){try{try{Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Up.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){_s.warn(r)}let t=mN(e);if(t){_s.error(t);return}_s.trace(`ITC userHandler ${yn.HDB_ITC_CLIENT_PREFIX}${_ae.pid} received user event:`,e),await Eae.setUsersWithRolesCache();for(let r of MG)r()}catch(t){_s.error(t)}}a(UG,"userHandler");UG.addListener=function(e){MG.push(e)};async function Rae(e){try{let t=mN(e);if(t){_s.error(t);return}_s.trace("ITC componentStatusRequestHandler received request:",e);let{internal:r}=(Mp(),v(fN)),{getWorkerIndex:n}=st(),{sendItcEvent:s}=ls(),i=r.componentStatusRegistry.getAllStatuses(),o=Array.from(i.entries()),c=n(),l=c===void 0,u=e.message.originator,d={type:yn.ITC_EVENT_TYPES.COMPONENT_STATUS_RESPONSE,message:{requestId:e.message.requestId,statuses:o,workerIndex:c,isMainThread:l}};u!==void 0&&threads.sendToThread(u,d)?_s.trace(`Sent component status response directly to thread ${u}`):(u===void 0?_s.debug("No originator threadId, falling back to broadcast"):_s.warn(`Failed to send direct response to thread ${u}, falling back to broadcast`),await s(d))}catch(t){_s.error("Error handling component status request:",t)}}a(Rae,"componentStatusRequestHandler");xG.exports=Sae});var ls=M((oMe,FG)=>{"use strict";var rMe=J(),pN=oe(),bae=(H(),v(z)),{ITC_ERRORS:Bp}=Jr(),{parentPort:nMe,threadId:Aae,isMainThread:Iae,workerData:sMe}=require("worker_threads"),{onMessageFromWorkers:wae,broadcast:iMe,broadcastWithAcknowledgement:Nae}=st();FG.exports={sendItcEvent:Cae,validateEvent:BG,SchemaEventMsg:Oae,UserEventMsg:Pae};var sS;wae(async(e,t)=>{sS=sS||xp(),BG(e),sS[e.type]&&await sS[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function Cae(e){return!Iae&&e.message&&(e.message.originator=Aae),Nae(e)}a(Cae,"sendItcEvent");function BG(e){if(typeof e!="object")return Bp.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||pN.isEmpty(e.type))return Bp.MISSING_TYPE;if(!e.hasOwnProperty("message")||pN.isEmpty(e.message))return Bp.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||pN.isEmpty(e.message.originator))return Bp.MISSING_ORIGIN;if(bae.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Bp.INVALID_EVENT(e.type)}a(BG,"validateEvent");function Oae(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(Oae,"SchemaEventMsg");function Pae(e){this.originator=e}a(Pae,"UserEventMsg")});var Wo=M((lMe,qG)=>{"use strict";var kG=(H(),v(z)),cMe=oe(),iS=J(),HG=B0(),Rd,{sendItcEvent:GG}=ls();function Lae(e){try{iS.debug("signalSchemaChange called with message:",e),Rd=Rd||xp();let t=new HG(kG.ITC_EVENT_TYPES.SCHEMA,e);return Rd.schema(t),GG(t)}catch(t){iS.error(t)}}a(Lae,"signalSchemaChange");function Dae(e){try{iS.trace("signalUserChange called with message:",e),Rd=Rd||xp();let t=new HG(kG.ITC_EVENT_TYPES.USER,e);return Rd.user(t),GG(t)}catch(t){iS.error(t)}}a(Dae,"signalUserChange");qG.exports={signalSchemaChange:Lae,signalUserChange:Dae}});function Fp(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}function $G(e,t){(typeof e.set!="function"||typeof e.has!="function")&&(e=new Gs(e));for(let[r,n]of t)e.has(r)?r.toLowerCase()==="set-cookie"&&e.append?.(r,n,!0):e.set(r,n);return e}var Gs,kp=se(()=>{Gs=class extends Map{static{a(this,"Headers")}constructor(t){if(t)if(t[Symbol.iterator])super(t);else{super();for(let r in t)this.set(r,t[r])}else super()}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(Fp,"appendHeader");a($G,"mergeHeaders")});function oS(e,t,r=Mae){let n;return function(...i){return n?n.length*hN>r?t(...i):new Promise((o,c)=>{n.push({args:i,fn(){try{let l=e(...i);o(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,o){setImmediate(()=>{let c=performance.now();hN=(hN*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var YG,vae,Mae,VG,Uae,EN,KG,hN,_N=se(()=>{YG=b(wr()),vae=3e3,Mae=2e4,VG=0,Uae=3e4,EN=3e3,KG=performance.now()+EN,hN=0;a(oS,"throttle");setInterval(()=>{let e=performance.now();e-KG-EN>vae&&VG+Uae<e&&(YG.default.warn?.("JavaScript execution has taken too long and is not allowing proper event queue cycling, consider using 'await new Promise(setImmediate)' in code that will execute for a long duration"),VG=e),KG=e},EN).unref()});var nq={};ye(nq,{EVICTED:()=>dl,INVALIDATED:()=>Fn,coerceType:()=>cS,makeTable:()=>uS});function uS(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:p}=e,{expirationMS:h,evictionMS:E,audit:g,trackDeletes:R}=e;E??=0;let{attributes:S}=e;S||(S=[]);let y=WA(i,n,l),N,I,$={},ee=Promise.resolve(),G,k,j;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(G=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(k=K),K.expiresAt&&(j=K),K.isPrimaryKey&&($=K);let Y,ce=[],de=[],te=1,ge=2,be={},Ye={},qe=864e5,Ar=0,er,Qr,xr,wu=!1,Kc,Ut,ii,Ma=Ul.get(F.REPLICATION_DATABASES);if(Array.isArray(Ma)){for(let K of Ma)if(K.name===c&&K.replicateTo>=0){ii=K.replicateTo;break}}let ZE=i.getRange({start:!1,end:!1}).constructor,cm=10,e_=6;g&&mm(),Hm(i.env.path,K=>{if(I)return xa(K)});class lm extends yl{static{a(this,"Updatable")}getUpdatedTime(){return Ya.get(this.getRecord())?.version}getExpiresAt(){return Ya.get(this.getRecord())?.expiresAt}addTo(_,T){if(typeof T=="number"||typeof T=="bigint")this.set(_,new Sp(T));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(_,T){return this.addTo(_,-T)}}class ve extends lr{#e;#t;#r;#n;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=S;static replicate=p;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=G;static updatedTimeProperty=k;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return h}static dbisDB=d;static schemaDefined=u;static sourcedFrom(_,T){if(T&&(this.sourceOptions=T,(T.expiration||T.eviction||T.scanInterval)&&this.setTTLExpiration(T)),T?.intermediateSource)_.intermediateSource=!0,this.sources.unshift(_);else{if(this.sources.some(D=>!D.intermediateSource)){if(this.sources.some(D=>D.name===_.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(_)}I=I||_.get&&(!_.get.reliesOnPrototype||_.prototype.get),N=N||_.load;let C=a(D=>{let A=this.sources;if(A=A.filter(U=>U.intermediateSource&&U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),A.length>0)if(A.length===1){let U=A[0];return(w,L,q)=>{if(w?.source!==U)return U[D](L,q,w)}}else return(U,w,L)=>{let q=[];for(let W of A){if(U?.source===W)break;q.push(W[D](w,L,U))}return Promise.all(q)}},"getApplyToIntermediateSource"),P=this.sources[this.sources.length-1];P.intermediateSource&&(P={});let O=a(D=>{if(P[D]&&(!P[D].reliesOnPrototype||P.prototype[D]))return(A,U,w)=>{if(!A?.source)return P[D](U,w,A)}},"getApplyToCanonicalSource");be={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ye={put:C("put"),patch:C("patch"),delete:C("delete"),publish:C("publish"),invalidate:C("invalidate")};let x=P.shouldRevalidateEvents;return(async()=>{let D=!1,A,U=a(async(w,L)=>{let q=w.value,W=w.table?Me[c][w.table]:ve;if(c===_m&&(w.table===Du.ROLE_TABLE_NAME||w.table===Du.USER_TABLE_NAME)&&(D=!0),w.id===void 0&&(w.id=q[W.primaryKey],w.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(w));w.source=_;let Q={residencyId:Yc(w.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:w.nodeId,async:!0},B=w.id,Ee=await W.getResource(B,L,Q);switch(w.finished&&await w.finished,w.type){case"put":return x?Ee._writeInvalidate(B,q,Q):Ee._writeUpdate(B,q,!0,Q);case"patch":return x?Ee._writeInvalidate(B,q,Q):Ee._writeUpdate(B,q,!1,Q);case"delete":return Ee._writeDelete(B,Q);case"publish":case"message":return Ee._writePublish(B,q,Q);case"invalidate":return Ee._writeInvalidate(B,q,Q);case"relocate":return Ee._writeRelocate(B,Q);default:ke.default.error?.("Unknown operation",w.type,w.id)}},"writeUpdate");try{let w=_.subscribe;w&&R==null&&(R=!0);let L={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},q=_.subscribeOnThisThread?_.subscribeOnThisThread((0,Ml.getWorkerIndex)(),L):(0,Ml.getWorkerIndex)()===0,W=w&&q&&await _.subscribe?.(L);if(W){let Q;for await(let B of W)try{if(!(B.type==="transaction"?B.writes[0]:B)){ke.default.error?.("Bad subscription event",B);continue}if(B.source=_,B.type==="end_txn"){Q?.resolve();let pe;if(B.localTime&&A!==B.localTime&&B.remoteNodeIds?.length>0&&(pe=a(()=>{let re=[Symbol.for("seq"),B.remoteNodeIds[0]],ie=d.get(re),Oe=ie?.nodes;Oe||(Oe=[]);for(let ae of B.remoteNodeIds.slice(1)){let xe=Oe.find(Ce=>Ce.id===ae);Oe=Oe.filter(Ce=>Ce.id!==ae||Ce===xe),xe||(xe={id:ae,seqId:0},Oe.push(xe)),xe.seqId=Math.max(ie?.seqId??1,B.localTime),ae===Q?.nodeId&&(xe.lastTxnTime=B.timestamp)}let le=Math.max(ie?.seqId??1,B.localTime);ke.default.trace?.("Received txn",c,le,new Date(le),B.localTime,new Date(B.localTime),B.remoteNodeIds),d.put(re,{seqId:le,nodes:Oe})},"updateRecordedSequenceId"),A=B.localTime),B.onCommit){let re=Q?Q.committed.then(B.onCommit):B.onCommit();pe&&(re?.then?re.then(pe):pe())}else pe&&pe();continue}if(Q)if(B.beginTxn)Q.resolve();else{Q.writePromises.push(U(B,Q));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let fe=bt(B,()=>{if(B.type==="transaction"){let pe=[];for(let re of B.writes)try{pe.push(U(re,B))}catch(ie){throw ie.message+=" writing "+JSON.stringify(re)+" of event "+JSON.stringify(B),ie}return Promise.all(pe)}else if(B.type==="define_schema"){let pe=this.attributes.slice(0),re=!1;for(let ie of B.attributes)pe.find(Oe=>Oe.name===ie.name)||(pe.push(ie),re=!0);re&&(Xe({table:s,database:c,attributes:pe,origin:"cluster"}),Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,V.CREATE_TABLE,c,s)))}else return B.beginTxn?(Q=B,Q.writePromises=[U(B,B)],new Promise(pe=>{Q.resolve=()=>pe(Promise.all(Q.writePromises))})):U(B,B)});Q&&(Q.committed=fe),D&&fe&&!fe?.waitingForUserChange&&(fe.then(()=>Gp.signalUserChange(new qp.UserEventMsg(process.pid))),fe.waitingForUserChange=!0),B.onCommit&&(fe?fe.then(B.onCommit):B.onCommit())}catch(Ee){ke.default.error?.("error in subscription handler",Ee)}}}catch(w){ke.default.error?.(w)}})(),this}static get isCaching(){return I}static get shouldRevalidateEvents(){return this.prototype.get!==ve.prototype.get}static getResource(_,T,C){let P=super.getResource(_,T,C);if(this.loadAsInstance===!1&&(T._freezeRecords=!0),_!=null&&this.loadAsInstance!==!1){Hi(_);try{if(P.getRecord?.())return P;if(typeof _=="object"&&_&&!Array.isArray(_))throw new Error(`Invalid id ${JSON.stringify(_)}`);let O=!C?.async||i.cache?.get?.(_),x=Br(T),D=x.getReadTxn();if(D?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Lo(_,T,{transaction:D,ensureLoaded:C?.ensureLoaded},O,A=>{if(A?ve._updateResource(P,A):P.#e=null,T.onlyIfCached){if(!P.doesExist())throw new ut.ServerError("Entry is not cached",504)}else if(C?.ensureLoaded){let U=pn(_,A,T,P);if(U)return x?.disregardReadTxn(),P.#i=!0,T.loadedFromSource=!0,qs(U,w=>(ve._updateResource(P,w),P))}return P})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(_)),O}}return P}static _updateResource(_,T){_.#n=T,_.#e=T?.value??null,_.#r=T?.version}ensureLoaded(){let _=pn(this.getId(),this.#n,this.getContext());if(_)return this.#i=!0,this.getContext().loadedFromSource=!0,qs(_,T=>{this.#n=T,this.#e=T.value,this.#r=T.version})}static getNewId(){let _=$?.type;if(_==="String"||_==="ID")return super.getNewId();if(!Ut){let O=i.getEntry(Symbol.for("id_allocation")),x=O?.value,D;if(x&&x.nodeName===server.hostname&&(!Wae(i)||x.pid===process.pid)){let A=x.start,U=x.end;D=A;for(let w of i.getKeys({start:U,end:A,limit:1,reverse:!0}))D=w}else x=P(O?.version??null),D=x.start;Ut=new BigInt64Array([BigInt(D)+1n]),Ut=new BigInt64Array(i.getUserSharedBuffer("id",Ut.buffer)),Ut.maxSafeId=x.end}let T=Number(Atomics.add(Ut,0,1n)),C=_==="Int"?512:1048576;if(T+C>=Ut.maxSafeId){let O=a(x=>{Ut.maxSafeId=T+(_==="Int"?1023:4194303);let D=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,A=x?void 0:i.useReadTransaction(),U=Number(Ut[0]);for(let q of i.getKeys({start:U+1,end:D,limit:1,transaction:A}))D=q;A?.done();let{value:w,version:L}=i.getEntry(Symbol.for("id_allocation"));if(Ut.maxSafeId<D){if(w.end>Ut.maxSafeId-100)return;ke.default.info?.("New id allocation",T,Ut.maxSafeId,L),i.put(Symbol.for("id_allocation"),{start:w.start,end:Ut.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),L)}else{ke.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Ut.maxSafeId}, but id of ${D} detected`);let q=P(L);q.alreadyUpdated||Atomics.store(Ut,0,BigInt(q.start+1)),Ut.maxSafeId=q.end}},"updateEnd");T+C===Ut.maxSafeId?setImmediate(O):T+100>=Ut.maxSafeId&&(ke.default.warn?.(`Synchronous id allocation required on table ${s}${_=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>O(!0)))}return T;function P(O){let x=(_==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=x/4,A,U,w=!1,L,q;do{L=Math.floor(Math.random()*x),q={start:L,end:L+(_==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},A=0;for(let W of i.getKeys({start:L,limit:1,reverse:!0}))A=W;U=x;for(let W of i.getKeys({start:L+1,end:x,limit:1}))U=W;D*=.875,D<1e3&&!w&&(w=!0,ke.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${_==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,L,A,U,D))}while(!(D<U-L&&(D<L-A||A===0)));return i.transactionSync(()=>{let W=i.getEntry(Symbol.for("id_allocation"));return(W?.version??null)==O?(ke.default.info?.("Allocated new id range",q),i.put(Symbol.for("id_allocation"),q,Date.now()),q):(ke.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...W.value})})}}static setTTLExpiration(_){if(typeof _=="number")h=_*1e3,E||(E=0);else if(_&&typeof _=="object")h=_.expiration*1e3,E=(_.eviction||0)*1e3,qe=_.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(h<0)throw new Error("Expiration can not be negative");qe=qe||(h+E)/4,xa()}static getResidencyRecord(_){return d.get([Symbol.for("residency_by_id"),_])}static setResidency(_){ve.getResidency=_&&((T,C)=>{try{return _(T,C)}catch(P){throw P.message+=` in residency function for table ${s}`,P}})}static setResidencyById(_){ve.getResidencyById=_&&(T=>{try{return _(T)}catch(C){throw C.message+=` in residency function for table ${s}`,C}})}static getResidency(_,T){if(ve.getResidencyById)return ve.getResidencyById(_[t]);let C=ii;if(T.replicateTo!=null){if(Array.isArray(T.replicateTo))return T.replicateTo.includes(server.hostname)?T.replicateTo:[server.hostname,...T.replicateTo];T.replicateTo>=0&&(C=T.replicateTo)}if(C>=0&&server.nodes){let P=[server.hostname];if(T.previousResidency)P.push(...T.previousResidency.slice(0,C));else{let O=server.nodes.map(A=>A.name),x=Math.floor(O.length*Math.random());P.push(...O.slice(x,x+C));let D=x+C-O.length;D>0&&P.push(...O.slice(0,D))}return P}}static enableAuditing(){g||(g=!0,mm(),ve.audit=!0)}static coerceId(_){return _===""?null:cS(_,$)}static async dropTable(){delete Me[c][s];for(let _ of i.getRange({versions:!0,snapshot:!1,lazy:!0}))_.metadataFlags&Zr&&_.value&&$a(_.value);if(c===o){for(let _ of S)d.remove(ve.tableName+"/"+_.name),r[_.name]?.drop();d.remove(ve.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),SN.default.unlinkSync(i.env.path);Gp.signalSchemaChange(new qp.SchemaEventMsg(process.pid,V.DROP_TABLE,c,s))}get(_){let T=this.constructor;if(typeof _=="string"&&T.loadAsInstance!==!1)return this.getProperty(_);if(um(_))return this.search(_);if(_&&_.id===void 0&&!_.toString()){let C={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:S,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?ve.getRecordCount().then(P=>(C.recordCount=P.recordCount,C.estimatedRecordRange=P.estimatedRange,C)):C}if(_!==void 0&&T.loadAsInstance===!1){let C=this.getContext(),P=Br(C),O=P.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let x=Ds(_);Hi(x);let D=!0;return _.checkPermission&&(D=this.allowRead(C.user,_)),qs(qs(D,A=>{if(!A)throw new ut.AccessViolation(C.user);let U=!0;return Lo(x,C,{transaction:O,ensureLoaded:U},!1,w=>{if(C.onlyIfCached){if(!w?.value)throw new ut.ServerError("Entry is not cached",504)}else if(U){let L=pn(x,w,C);if(L)return P?.disregardReadTxn(),C.loadedFromSource=!0,L.then(q=>q?.value)}return w?.value})}),A=>{let U=_?.select;return U&&A!=null?Zu(U,this.constructor)(A):A})}if(_?.property)return this.getProperty(_.property);if(this.doesExist()||_?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(_,T){let C=Dn(_,T);if(C?.read){if(C.isSuperUser)return!0;let P=C.attribute_permissions,O=T?.select;if(P?.length>0||wu&&O){if(T||(T={}),O){let x=Array.isArray(O)?O:[O],D=P?.length>0&&gN(P,"read");T.select=x.map(A=>{let U=A.name||A;if(!D||D[U]){let w=xr[U]?.definition?.tableClass;if(w){if(A.name||(A={name:A}),!A.checkPermission&&T.checkPermission&&(A.checkPermission=T.checkPermission),!w.prototype.allowRead.call(null,_,A))return!1;if(!A.select)return A.name}return A}}).filter(Boolean)}else T.select=P.filter(x=>x.read&&!xr[x.attribute_name]).map(x=>x.attribute_name);return T}else return!0}}allowUpdate(_,T,C){let P=Dn(_,C);if(P?.update){let O=P.attribute_permissions;if(O?.length>0){let x=gN(O,"update");for(let D in T)if(!x[D])return!1;for(let D of O){let A=D.attribute_name;!D.update&&!(A in T)&&(T[A]=this.getProperty(A))}}return Ua(this.getContext())}}allowCreate(_,T,C){if(this.isCollection){let P=Dn(_,C);if(P?.insert){let O=P.attribute_permissions;if(O?.length>0){let x=gN(O,"insert");for(let D in T)if(!x[D])return!1;return Ua(this.getContext())}else return Ua(this.getContext())}}else return this.allowUpdate(_,{})}allowDelete(_,T){return Dn(_,T)?.delete&&Ua(this.getContext())}update(_,T){let C,P=typeof T=="boolean"||T===void 0&&(_==null||typeof _=="object"&&!(_ instanceof URLSearchParams)),O=!1;P?(O=T,T=_,C=this.getId()):C=Ds(_);let x=this.getContext();if(!Br(x))throw new Error("Can not update a table resource outside of a transaction");if(T===!1)return this;if(typeof T=="object"&&T)if(O)Object.isFrozen(T)&&(T={...T}),this.#e={},this.#t=T;else if(P){let A=this.#t;A&&(T=Object.assign(A,T)),this.#t=T}else{let A=!0;if(_==null)throw new TypeError("Can not put a record without a target");return _.checkPermission&&(A=this.allowUpdate(x.user,T,_)),qs(A,U=>{if(!U)throw new ut.AccessViolation(x.user);return qs(i.get(Ds(_)),w=>{let L=new lm(w);return L._setChanges(T),this._writeUpdate(C,L.getChanges(),!1),L})})}return this._writeUpdate(C,this.#t,O),this}addTo(_,T){if(typeof T=="number"||typeof T=="bigint")this.#s===zG?this.set(_,(+this.getProperty(_)||0)+T):(this.#s||this.update(),this.set(_,new Sp(T)));else throw new Error("Can not add a non-numeric value")}subtractFrom(_,T){if(typeof T=="number")return this.addTo(_,-T);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#n}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(_){this.#t=_}setRecord(_){this.#e=_}invalidate(_){let T=!0,C=this.getContext();return _?.checkPermission&&(T=this.allowDelete(C.user,_,C)),qs(T,P=>{if(!P)throw new ut.AccessViolation(C.user);this._writeInvalidate(_?Ds(_):this.getId())})}_writeInvalidate(_,T,C){let P=this.getContext();Hi(_),Br(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:be.invalidate?.bind(this,P,_),beforeIntermediate:Pu(T,Ye.invalidate?.bind(this,P,_)),commit:a((x,D)=>{if(!(Fr(x,D,C?.nodeId)<=0)){T??=null;for(let A in r)T||(T={}),T[A]===void 0&&(T[A]=this.getProperty(A));ke.default.trace?.(`Invalidating entry in ${s} id: ${_}, timestamp: ${new Date(x).toISOString()}`),y(_,T,D,x,Fn,g,{user:P?.user,residencyId:C?.residencyId,nodeId:C?.nodeId,tableToTrack:s},"invalidate")}},"commit")})}_writeRelocate(_,T){let C=this.getContext();Hi(_),Br(this.getContext()).addWrite({key:_,store:i,invalidated:!0,entry:this.#n,before:be.relocate?.bind(this,C,_),beforeIntermediate:Ye.relocate?.bind(this,C,_),commit:a((O,x)=>{if(Fr(O,x,T?.nodeId)<=0)return;let D=ve.getResidencyRecord(T.residencyId),A=0,U=null,w=x?.value;if(D&&!D.includes(server.hostname)){for(let L in r)U||(U={}),U[L]=w[L];A=Fn}else U=w;ke.default.trace?.(`Relocating entry id: ${_}, timestamp: ${new Date(O).toISOString()}`),y(_,U,x,O,A,g,{user:C.user,residencyId:T.residencyId,nodeId:T.nodeId,expiresAt:T.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(_,T){let C={previousResidency:this.getResidencyRecord(_.residencyId),isRelocation:!0},P=Ba(this.getResidency(T.value,C)),O;if(P){if(!P.includes(server.hostname))return!1;O=Yc(P)}let x=0;ke.default.debug?.("Performing a relocate of an entry",_.key,T.value,P);let D=y(_.key,T.value,_,_.version,x,!0,{residencyId:O,expiresAt:T.expiresAt},"relocate",!1,null);return!0}static evict(_,T,C){let P=this.Source,O;if(!((I||g)&&(!T||(O=i.getEntry(_),!O||!T)||O.version!==C))){if(I){if(i.hasLock(_,O.version))return;let x;for(let D in r)x||(x={}),x[D]=T[D];if(x)return y(_,x,O,C,dl,null,null,null,!0)}return i.ifVersion(_,C,()=>{Nu(_,T,null)}),ul(i,O??i.getEntry(_),C)}}lock(){throw new Error("Not yet implemented")}static operation(_,T){return _.table||=s,_.schema||=c,global.operation(_,T)}put(_,T){if(T===void 0||T instanceof URLSearchParams)this.update(_,!0);else{let C=!0;if(_==null)throw new TypeError("Can not put a record without a target");let P=this.getContext();return _.checkPermission&&(C=this.allowUpdate(P.user,T,_)),qs(C,O=>{if(!O)throw new ut.AccessViolation(P.user);if(Array.isArray(T))for(let x of T){let D=x[t];this._writeUpdate(D,x,!0)}else{let x=Ds(_);this._writeUpdate(x,T,!0)}})}}create(_,T){let C=!0,P=this.getContext();if(!T&&!(_ instanceof URLSearchParams)&&(T=_,_=void 0),!T||typeof T!="object"||Array.isArray(T))throw new TypeError("Can not create a record without an object");return _?.checkPermission&&(C=this.allowCreate(P.user,T,_)),qs(C,O=>{if(!O)throw new ut.AccessViolation(P.user);let x=Ds(_)??T[t];if(x===void 0)x=this.constructor.getNewId();else if(i.get(x))throw new ut.ClientError("Record already exists",409);return this._writeUpdate(x,T,!0),T})}patch(_,T){if(T===void 0||T instanceof URLSearchParams)this.update(_,!1);else{let C=this.update(_,T);if(C?.then)return C.then(()=>{})}}_writeUpdate(_,T,C,P){let O=this.getContext(),x=Br(O);Hi(_);let D=this.#n??i.getEntry(_);this.#s=C?zG:$ae;let A=a(w=>C?w.put?()=>w.put(O,_,T):null:w.patch?()=>w.patch(O,_,T):w.put?()=>w.put(O,_,Rl(this)):null,"writeToSources"),U={key:_,store:i,entry:D,nodeName:O?.nodeName,validate:a(w=>{T||(T=this.#t),C||T&&Ug(this.#t===T?this:T)?O?.source||(x.checkOverloaded(),this.validate(T,!C),k&&(T[k.name]=k.type==="Date"?new Date(w):k.type==="String"?new Date(w).toISOString():w),C&&(t&&T[t]!==_&&(T[t]=_),G&&(D?.value?T[G.name]=D?.value[G.name]:T[G.name]=G.type==="Date"?new Date(w):G.type==="String"?new Date(w).toISOString():w),T=Rl(T))):x.removeWrite(U)},"validate"),before:A(be),beforeIntermediate:Pu(T,A(Ye)),commit:a((w,L,q)=>{if(q){if(O&&L?.version>(O.lastModified||0)&&(O.lastModified=L.version),this.#n=L,L?.value&&L.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");C||(this.#e=L?.value??null)}this.#t=void 0,this.#r=w;let W=L?.value,Q;this.#s=0;let B=!1,Ee=Fr(w,L,P?.nodeId),fe;if(Ee<=0){if(g){let le=L.localTime,ae=L.version;ke.default.trace?.("Applying CRDT update to record with id: ",_,"txn time",new Date(w),"applying later update from:",new Date(ae),"local recorded time",new Date(le));let xe=[];for(;le>w||ae>=w&&le>0;){let Ce=l.get(le);if(!Ce)break;let Le=At(Ce);if(ae=Le.version,ae>=w){if(ae===w){if(Ee=Fr(w,{version:ae,localTime:le},P?.nodeId),Ee===0)return;if(Ee>0){le=Le.previousLocalTime;continue}}if(Le.type==="patch")xe.push(Le),fe=T;else if(Le.type==="put"||Le.type==="delete")return}le=Le.previousLocalTime}le||ke.default.debug?.("No further audit history, applying incremental updates based on available history",_,"existing version preserved",L),xe.sort((Ce,Le)=>Ce.version-Le.version);for(let Ce of xe){let Le=Ce.getValue(i);if(ke.default.debug?.("Rebuilding update with future patch:",new Date(Ce.version),Le,Ce),Q=w_(Q??T,Le,C),!Q)return}}else{if(C)return;Q=w_(Q??T,W,C),ke.default.debug?.("Rebuilding update without audit:",Q)}ke.default.trace?.("Rebuilt record to save:",Q," is full update:",C)}let pe;if(C&&!Q?pe=T:this.constructor.loadAsInstance===!1?pe=Rl(W,Q??T):(this.#e=W,pe=Rl(this,Q??T)),this.#e=pe,pe&&pe.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let re;if(P?.residencyId!=null)re=P.residencyId;else{D?.residencyId&&(O.previousResidency=ve.getResidencyRecord(D.residencyId));let le=Ba(ve.getResidency(pe,O));if(le&&!le.includes(server.hostname))if(fe??=pe,B=!0,ve.getResidencyById)pe=void 0;else{pe=null;for(let ae in r)pe||(pe={}),pe[ae]=fe[ae]}re=Yc(le)}C||(fe=T);let ie=O?.expiresAt??(h?h+Date.now():-1);ke.default.trace?.(`Saving record with id: ${_}, timestamp: ${new Date(w).toISOString()}${ie?", expires at: "+new Date(ie).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(pe).slice(0,100)}catch{return""}})()),Nu(_,W,pe);let Oe=C?"put":"patch";y(_,pe,L,w,B?Fn:0,g,{omitLocalRecord:B,user:O?.user,residencyId:re,expiresAt:ie,nodeId:P?.nodeId,originatingOperation:O?.originatingOperation,tableToTrack:c==="system"?null:s},Oe,!1,fe),O.expiresAt&&xa()},"commit")};x.addWrite(U)}async delete(_){if(um(_)){_.select=["$id"];for await(let T of this.search(_))this._writeDelete(T.$id);return!0}if(_){let T=!0,C=this.getContext();return _.checkPermission&&(T=this.allowDelete(C.user,_,C)),qs(T,P=>{if(!P)throw new ut.AccessViolation(C.user);let O=Ds(_);return this._writeDelete(O),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(_,T){let C=Br(this.getContext());Hi(_);let P=this.getContext();return C.addWrite({key:_,store:i,entry:this.#n,nodeName:P?.nodeName,before:be.delete?.bind(this,P,_),beforeIntermediate:Ye.delete?.bind(this,P,_),commit:a((O,x,D)=>{let A=x?.value;D&&(P&&x?.version>(P.lastModified||0)&&(P.lastModified=x.version),ve._updateResource(this,x)),!(Fr(O,x,T?.nodeId)<=0)&&(Nu(this.getId(),A),ke.default.trace?.(`Deleting record with id: ${_}, txn timestamp: ${new Date(O).toISOString()}`),g||R?(y(_,null,x,O,0,g,{user:P?.user,nodeId:T?.nodeId,tableToTrack:s},"delete"),g||xa()):ul(i,x))},"commit")}),!0}search(_){let T=this.getContext(),C=Br(T);if(!_)throw new Error("No query provided");if(_.parseError)throw _.parseError;if(_.checkPermission&&!this.allowRead(T.user,_))throw new ut.AccessViolation(T.user);T&&(T.lastModified=kae);let P=_.conditions;P?P.length===void 0&&(P=P[Symbol.iterator]?Array.from(P):[P]):P=Array.isArray(_)?_:_[Symbol.iterator]?Array.from(_):[];let O=_.id??this.getId();O&&(P=[{attribute:null,comparator:Array.isArray(O)?"prefix":"starts_with",value:O}].concat(P));let x,D={};function A(ie,Oe){let le;switch(Oe){case"and":case void 0:if(ie.length<1)throw new Error('An "and" operator requires at least one condition');le=!0;break;case"or":if(ie.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Oe)}for(let ae of ie){if(ae.conditions){ae.conditions=A(ae.conditions,ae.operator);continue}let xe=ae[0]??ae.attribute,Ce=xe==null?$:zi(S,xe);if(Ce)(Ce.type||jA[ae.comparator])&&(ae[1]===void 0?ae.value=w(ae.value,Ce):ae[1]=w(ae[1],Ce));else if(xe!=null&&!_.allowConditionsOnDynamicAttributes)throw(0,ut.handleHDBError)(new Error,`${xe} is not a defined attribute`,404);if(ae.chainedConditions)if(ae.chainedConditions.length===1&&(!ae.operator||ae.operator=="and")){let Le=ae.chainedConditions[0],De,pt;if(Le.comparator==="gt"||Le.comparator==="greater_than"||Le.comparator==="ge"||Le.comparator==="greater_than_equal"?(De=ae,pt=Le):(De=Le,pt=ae),De.comparator!=="lt"&&De.comparator!=="less_than"&&De.comparator!=="le"&&De.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let wt=pt.comparator==="ge"||pt.comparator==="greater_than_equal",xt=De.comparator==="le"||De.comparator==="less_than_equal";ae.comparator=(wt?"ge":"gt")+(xt?"le":"lt"),ae.value=[pt.value,De.value]}else throw new Error("Multiple chained conditions are not currently supported")}return ie}a(A,"prepareConditions");function U(ie,Oe){if(_.enforceExecutionOrder)return ie;for(let le of ie)le.conditions&&(le.conditions=U(le.conditions,le.operator));return ie.length>1&&Oe!=="or"?xae(ie,ug(ve)):ie}a(U,"orderConditions");function w(ie,Oe){return Array.isArray(ie)?ie.map(le=>cS(le,Oe)):cS(ie,Oe)}a(w,"coerceTypedValues");let L=_.operator;(P.length>0||L)&&(P=A(P,L));let q=typeof _.sort=="object"&&_.sort,W;if(q&&L!=="or"){let ie=q.attribute;if(ie==null)throw new ut.ClientError("Sort requires an attribute");if(x=P.find(Oe=>Qu(Oe.attribute)===Qu(ie)),!x){let Oe=zi(S,ie);if(!Oe)throw(0,ut.handleHDBError)(new Error,`${Array.isArray(ie)?ie.join("."):ie} is not a defined attribute`,404);if(Oe.indexed)x={...q,comparator:"sort"},P.push(x);else if(P.length===0&&!_.allowFullScan)throw(0,ut.handleHDBError)(new Error,`${Array.isArray(ie)?ie.join("."):ie} is not indexed and not combined with any other conditions`,404)}x&&(x.descending=!!q.descending)}P=U(P,L),q&&(x&&P[0]===x?q.next&&(W={dbOrderedAttribute:q.attribute,attribute:q.next.attribute,descending:q.next.descending,next:q.next.next}):(x&&P.splice(P.indexOf(x),1),W=q));let Q=_.select;if(P.length===0&&(P=[{attribute:t,comparator:"greater_than",value:!0}]),_.explain)return{conditions:P,operator:L,postOrdering:W,selectApplied:!!Q};let B=C.useReadTxn(),Ee=QA(P,L,ve,B,_,T,(ie,Oe)=>fm(ie,Q,T,B,Oe),D),fe=_.ensureLoaded!==!1,pe=ve.transformEntryForSelect(Q,T,B,D,fe,!0),re=ve.transformToOrderedSelect(Ee,Q,W,T,B,pe);return(_.offset||_.limit!==void 0)&&(re=re.slice(_.offset,_.limit!==void 0?(_.offset||0)+_.limit:void 0)),re.onDone=()=>{re.onDone=null,C.doneReadTxn()},re.selectApplied=!0,re.getColumns=()=>{if(Q){let ie=[];for(let Oe of Q)Oe==="*"?ie.push(...S.map(le=>le.name)):ie.push(Oe.name||Oe);return ie}return S.filter(ie=>!ie.computed&&!ie.relationship).map(ie=>ie.name)},re}static transformToOrderedSelect(_,T,C,P,O,x){let D=new ZE;if(C){_=fm(_,T,P,O,null);let A;D.iterate=function(){let w,L=_[Symbol.asyncIterator]?_[Symbol.asyncIterator]():_[Symbol.iterator](),q,W=C.dbOrderedAttribute,Q,B,Ee=!0;function fe(re){let ie=re.next&&fe(re.next),Oe=re.descending;return P.sort=re,(le,ae)=>{let xe=Cu(le,re.attribute,P),Ce=Cu(ae,re.attribute,P),Le=Oe?(0,xl.compareKeys)(Ce,xe):(0,xl.compareKeys)(xe,Ce);return Le===0?ie?.(le,ae)||0:Le}}a(fe,"createComparator");let pe=fe(C);return{async next(){let re;if(w)if(re=w.next(),re.done){if(q)return D.onDone&&D.onDone(),re}else return{value:await x.call(this,re.value)};A=[],Q&&A.push(Q);do if(re=await L.next(),re.done){if(q=!0,A.length)break;return D.onDone&&D.onDone(),re}else{let ie=re.value;if(ie?.then&&(ie=await ie),W){let Oe=Cu(ie,W,P);if(Ee)Ee=!1,B=Oe;else if(Oe!==B){B=Oe,Q=ie;break}}A.push(ie)}while(!0);return C.isGrouped,A.sort(pe),w=A[Symbol.iterator](),re=w.next(),re.done?(D.onDone&&D.onDone(),re):{value:await x.call(this,re.value)}},return(){return D.onDone&&D.onDone(),L.return()},throw(){return D.onDone&&D.onDone(),L.throw()}}};let U=a(w=>{if(typeof T=="object"&&Array.isArray(w.attribute))for(let L=0;L<T.length;L++){let q=T[L],W;if(q.name===w.attribute[0]){for(W=q.sort||(q.sort={});W.next;)W=W.next;W.attribute=w.attribute.slice(1),W.descending=w.descending}else q===w.attribute[0]&&(T[L]=W={name:q,sort:{attribute:w.attribute.slice(1),descending:w.descending}})}w.next&&U(w.next)},"applySortingOnSelect");U(C)}else D.iterate=(_[Symbol.asyncIterator]||_[Symbol.iterator]).bind(_),D=D.map(function(A){try{let U=x.call(this,A);return typeof U?.catch=="function"?U.catch(w=>{throw w.partialObject={[t]:A.key},w}):U}catch(U){throw U.partialObject={[t]:A.key},U}});return D}static transformEntryForSelect(_,T,C,P,O,x){let D;O&&I&&!(typeof _=="string"?[_]:_)?.every(w=>{let L;return typeof w=="object"?L=w.name:L=w,r[L]||L===t})&&(D=!0);let A,U=a(function(w){let L;if(T?.transaction?.stale&&(T.transaction.stale=!1),w!=null){if(L=w.deref?w.deref():w.value,!L&&(w.key===void 0||w.deref)||w.metadataFlags&Fn){if(w.metadataFlags&Fn&&T.replicateFrom===!1&&x&&w.residencyId)return ac.SKIP;if(w=Lo(w.key??w,T,{transaction:C,lazy:_?.length<4,ensureLoaded:O},this?.isSync,q=>q),w?.then)return w.then(U.bind(this));L=w?.value}if(D&&w?.metadataFlags&(Fn|dl)||w?.expiresAt!=null&&w?.expiresAt<Date.now()){if(T.onlyIfCached)return{[t]:w.key,message:"This entry has expired"};let q=pn(w.key??w,w,T);if(q?.then)return q.then(U)}}if(L==null)return x?ac.SKIP:L;if(_&&!(_[0]==="*"&&_.length===1)){let q,W=a((B,Ee)=>{let fe;typeof B=="object"?fe=B.name:fe=B;let pe=xr?.[fe],re;if(pe){let ie=P?.[fe];if(ie)if(ie.hasMappings){let le=pe.from?L[pe.from]:Qu(w.key);re=ie.get(le),re||(re=[])}else re=ie.fromRecord?.(L);else re=pe(L,T,w,!0);let Oe=a(le=>{if(pe.directReturn)return Ee(le,fe);if(le&&typeof le=="object"){let ae=pe.definition?.tableClass||ve;A||(A={});let xe=A[fe]||(A[fe]=ae.transformEntryForSelect(fe===B?null:B.select||(Array.isArray(B)?B:null),T,C,ie,O));if(Array.isArray(le)){let Ce=[],Le=ae.transformToOrderedSelect(le,B.select,typeof B.sort=="object"&&B.sort,T,C,xe)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),De=a(wt=>{for(;!wt.done;){if(wt?.then)return wt.then(De);Ce.push(wt.value),wt=Le.next()}Ee(Ce,fe)},"nextValue"),pt=De(Le.next());pt&&(q||(q=[]),q.push(pt));return}else if(le=xe.call(this,le),le?.then){q||(q=[]),q.push(le.then(Ce=>Ee(Ce,fe)));return}}Ee(le,fe)},"handleResolvedValue");re?.then?(q||(q=[]),q.push(re.then(Oe))):Oe(re);return}else re=L[fe],re&&typeof re=="object"&&fe!==B&&(re=ve.transformEntryForSelect(B.select||B,T,C,null)({value:re}));Ee(re,fe)},"selectAttribute"),Q;if(typeof _=="string")W(_,B=>{Q=B});else if(Array.isArray(_))if(_.asArray)Q=[],_.forEach((B,Ee)=>{B==="*"?_[Ee]=L:W(B,fe=>Q[Ee]=fe)});else{Q={};let B=_.forceNulls;for(let Ee of _)if(Ee==="*")for(let fe in L)Q[fe]=L[fe];else W(Ee,(fe,pe)=>{fe===void 0&&B&&(fe=null),Q[pe]=fe})}else throw new ut.ClientError("Invalid select"+_);return q?Promise.all(q).then(()=>Q):Q}return L},"transform");return U}async subscribe(_){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||Xe({table:s,database:c,schemaDefined:u,attributes:S,audit:!0}),_||(_={});let T=!_.rawEvents,C=[],P=nI(ve,this.getId()??null,function(D,A,U,w){try{let L=A.getValue?.(i,T),q=A.type;if(!L&&q==="patch"&&T){let Q=i.getEntry(D);Q?.version===A.version?L=Q.value:L=A.getValue?.(i,!0,U),q="put"}let W={id:D,localTime:U,value:L,version:A.version,type:q,beginTxn:w};C?C.push(W):(c!=="system"&&Ve(A.size??1,"db-message",s,null),this.send(W))}catch(L){ke.default.error?.(L)}},_.startTime||0,_),O=(async()=>{this.isCollection&&(P.includeDescendants=!0,_.onlyChildren&&(P.onlyChildren=!0)),_.supportsTransactions&&(P.supportsTransactions=!0);let D=this.getId(),A=_.previousCount;A>1e3&&(A=1e3);let U=_.startTime;if(this.isCollection){if(U){if(A)throw new ut.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:w,value:L}of l.getRange({start:U,exclusiveStart:!0,snapshot:!1})){let q=At(L);if(q.tableId!==n)continue;let W=q.recordId;if(D==null||XG(D,W)){let Q=q.getValue(i,T,w);if(x({id:W,localTime:w,value:Q,version:q.version,type:q.type,size:q.size}),P.queue?.length>QG&&await P.waitForDrain()===!1)return}P.startTime=w}}else if(A){let w=[];for(let{key:L,value:q}of l.getRange({start:"z",end:!1,reverse:!0}))try{let W=At(q);if(W.tableId!==n)continue;let Q=W.recordId;if(D==null||XG(D,Q)){let B=W.getValue(i,T,L);if(w.push({id:Q,localTime:L,value:B,version:W.version,type:W.type}),--A<=0)break}}catch(W){ke.default.error("Error getting history entry",L,W)}for(let L=w.length;L>0;)x(w[--L]);w[0]&&(P.startTime=w[0].localTime)}else if(!_.omitCurrent){for(let{key:w,value:L,version:q,localTime:W,size:Q}of i.getRange({start:D??!1,end:D==null?void 0:[D,xl.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(L&&(x({id:w,localTime:W,value:L,version:q,type:"put",size:Q}),P.queue?.length>QG&&await P.waitForDrain()===!1))return}}else{A&&!U&&(U=0);let w=this.#n?.localTime;if(w===YA&&(i.cache?.delete(D),this.#n=i.getEntry(D),ke.default.trace?.("re-retrieved record",w,this.#n?.localTime),w=this.#n?.localTime),ke.default.trace?.("Subscription from",U,"from",D,w),U<w){let L=[],q=w;do{let W=l.get(q);if(W){_.omitCurrent=!0;let Q=At(W),B=Q.getValue(i,T,q);T&&(Q.type="put"),L.push({id:D,value:B,localTime:q,...Q}),q=Q.previousLocalTime}else break;A&&A--}while(q>U&&A!==0);for(let W=L.length;W>0;)x(L[--W]);P.startTime=w}!_.omitCurrent&&this.doesExist()&&x({id:D,localTime:w,value:this.#e,version:this.#r,type:"put"})}for(let w of C)x(w);C=null})();function x(D){c!=="system"&&Ve(D.size??1,"db-message",s,null),P.send(D)}return a(x,"send"),_.listener&&P.on("data",_.listener),P}static subscribeOnThisThread(_,T){return _===0||T?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(_,T,C){if(T===void 0||T instanceof URLSearchParams)this._writePublish(this.getId(),_,T);else{let P=!0,O=this.getContext();return _.checkPermission&&(P=this.allowCreate(O.user,_,O)),qs(P,x=>{if(!x)throw new ut.AccessViolation(O.user);let D=Ds(_);this._writePublish(D,T,C)})}}_writePublish(_,T,C){let P=Br(this.getContext());_??=null,_!==null&&Hi(_);let O=this.getContext();P.addWrite({key:_,store:i,entry:this.#n,nodeName:O?.nodeName,validate:a(()=>{O?.source||(P.checkOverloaded(),this.validate(T))},"validate"),before:be.publish?.bind(this,O,_,T),beforeIntermediate:Pu(T,Ye.publish?.bind(this,O,_,T)),commit:a((x,D,A)=>{D===void 0&&R&&!g&&xa(),ke.default.trace?.(`Publishing message to id: ${_}, timestamp: ${new Date(x).toISOString()}`),y(_,D?.value??null,D,D?.version||x,0,!0,{user:O?.user,residencyId:C?.residencyId,expiresAt:O?.expiresAt,nodeId:C?.nodeId,tableToTrack:s},"message",!1,T)},"commit")})}validate(_,T){let C,P=a((O,x,D)=>{if(x.type&&O!=null)if(T&&O.__op__&&(O=O.value),x.properties){typeof O!="object"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an object${x.type?" ("+x.type+")":""}`);let A=x.properties;for(let U=0,w=A.length;U<w;U++){let L=A[U];if(L.relationship||L.computed){_.hasOwnProperty(L.name)&&(C||(C=[])).push(`Computed property ${D}.${L.name} may not be directly assigned a value`);continue}let q=P(O[L.name],L,D+"."+L.name);q&&(O[L.name]=q)}if(x.sealed&&O!=null&&typeof O=="object")for(let U in O)A.find(w=>w.name===U)||(C||(C=[])).push(`Property ${U} is not allowed within object in property ${D}`)}else switch(x.type){case"Int":(typeof O!="number"||O>>0!==O)&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(A=>typeof A=="string")||(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a string`);break;case"Boolean":typeof O!="boolean"&&(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a bigint`)}break;case"Bytes":if(!(O instanceof Uint8Array)){if(typeof O=="string")return Buffer.from(O);(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(O instanceof Ms)){if(typeof O=="string"&&(O=Buffer.from(O)),O instanceof Buffer)return createBlob(O,{type:"text/plain"});(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be a Blob`)}break;case"array":if(Array.isArray(O)){if(x.elements)for(let A=0,U=O.length;A<U;A++){let w=O[A],L=P(w,x.elements,D+"[*]");L&&(O[A]=L)}}else(C||(C=[])).push(`Value ${$s(O)} in property ${D} must be an Array`);break}x.nullable===!1&&O==null&&(C||(C=[])).push(`Property ${D} is required (and not does not allow null values)`)},"validateValue");for(let O=0,x=S.length;O<x;O++){let D=S[O];if(D.relationship||D.computed){Object.hasOwn(_,D.name)&&(C||(C=[])).push(`Computed property ${D.name} may not be directly assigned a value`);continue}if(!T||D.name in _){let A=P(_[D.name],D,D.name);A!==void 0&&(_[D.name]=A)}}if(f)for(let O in _)S.find(x=>x.name===O)||(C||(C=[])).push(`Property ${O} is not allowed`);if(C)throw new ut.ClientError(C.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return I?!!this.#i:void 0}static async addAttributes(_){let T=S.slice(0);for(let C of _){if(!C.name)throw new ut.ClientError("Attribute name is required");if(C.name.match(/[`/]/))throw new ut.ClientError("Attribute names cannot include backticks or forward slashes");Bae(C.name),T.push(C)}return Xe({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static async removeAttributes(_){let T=S.filter(C=>!_.includes(C.name));return Xe({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static getSize(){let _=i.getStats();return(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getAuditSize(){let _=l?.getStats();return _&&(_.treeBranchPageCount+_.treeLeafPageCount+_.overflowPages)*_.pageSize}static getStorageStats(){let _=i.env.path,T=SN.default.statfsSync?.(_)??{};return{available:T.bavail*T.bsize,free:T.bfree*T.bsize,size:T.blocks*T.bsize}}static async getRecordCount(_){let T=i.getStats().entryCount,C=1e3/2,P=performance.now(),O=Math.floor(T/2),x=_?.exactCount,D=0,A=0,U;for(let{value:w}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(w!=null&&D++,A++,await oc(),!x&&A<O&&performance.now()-P>C){U=A;break}if(U){let w=D;D=0;for(let{value:re}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:U,snapshot:!1}))re!=null&&D++,await oc();let L=U*2,q=(D+w)/L,W=Math.pow((D-w+1)/U/2,2)+q*(1-q)/L,Q=Math.max(Math.sqrt(W)*T,1),B=Math.round(q*T),Ee=Math.max(B-1.96*Q,D+w),fe=Math.min(B+1.96*Q,T),pe=Math.pow(10,Math.round(Math.log10(Q)));return pe>B&&(pe=pe/10),D=Math.round(B/pe)*pe,{recordCount:D,estimatedRange:[Math.round(Ee),Math.round(fe)]}}return{recordCount:D}}static updatedAttributes(){xr=this.propertyResolvers={$id:a((_,T,C)=>({value:C.key}),"$id"),$updatedtime:a((_,T,C)=>C.version,"$updatedtime"),$updatedTime:a((_,T,C)=>C.version,"$updatedTime"),$expiresAt:a((_,T,C)=>C.expiresAt,"$expiresAt"),$record:a((_,T,C)=>C?{value:_}:_,"$record"),$distance:a((_,T,C)=>C&&(C.distance??T?.vectorDistances?.get(C)),"$distance")};for(let _ of this.attributes){_.isPrimaryKey&&($=_),_.resolve=null;let T=_.relationship,C=_.computed;if(T)if(_.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),C&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),wu=!0,T.to)_.elements?.definition?(xr[_.name]=_.resolve=(P,O,x,D)=>{let A=P[T.from?T.from:t],U=_.elements.definition.tableClass;return D?ju({attribute:T.to,value:A},Br(O).getReadTxn(),!1,U,!1).map(w=>w&&w.key!==void 0?w:U.primaryStore.getEntry(w,{transaction:Br(O).getReadTxn()})).asArray:U.search([{attribute:T.to,value:A}],O).asArray},_.set=()=>{},_.resolve.definition=_.elements.definition,_.resolve.to=T.to,T.from&&(_.resolve.from=T.from)):console.error(`The one-to-many/many-to-many relationship property "${_.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(T.from){let P=_.definition||_.elements?.definition;P?(xr[_.name]=_.resolve=(O,x,D,A)=>{let U=O[T.from];if(U===void 0)return;if(_.elements){let L,q=U?.map(W=>{let Q=P.tableClass.primaryStore[A?"getEntry":"get"](W,{transaction:Br(x).getReadTxn()});return Q?.then&&(L=!0),ve.loadAsInstance===!1&&Object.freeze(A?Q?.value:Q),Q});return T.filterMissing?L?Promise.all(q).then(W=>W.filter(ZG)):q.filter(ZG):L?Promise.all(q):q}let w=P.tableClass.primaryStore[A?"getEntry":"get"](U,{transaction:Br(x).getReadTxn()});return ve.loadAsInstance===!1&&Object.freeze(A?w?.value:w),w},_.set=(O,x)=>{if(Array.isArray(x)){let D=x.map(A=>A.getId?.()||A[P.tableClass.primaryKey]);O[T.from]=D}else{let D=x.getId?.()||x[P.tableClass.primaryKey];O[T.from]=D}},_.resolve.definition=_.definition||_.elements?.definition,_.resolve.from=T.from):console.error(`The relationship property "${_.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${_.name}" in table "${s}" must use either "from" or "to" arguments`);else if(C)typeof C.from=="function"&&this.setComputedAttribute(_.name,C.from),xr[_.name]=_.resolve=(P,O,x)=>{let D=typeof C.from=="string"?P[C.from]:P,A=this.userResolvers[_.name];if(A)return A(D,O,x);ke.default.warn(`Computed attribute "${_.name}" does not have a function assigned to it. Please use setComputedAttribute('${_.name}', resolver) to assign a resolver function.`),this.userResolvers[_.name]=()=>{}},_.resolve.directReturn=!0;else if(r[_.name]?.customIndex?.propertyResolver){let P=r[_.name].customIndex;xr[_.name]=(O,x,D)=>{let A=O[_.name];return P.propertyResolver(A,x,D)},xr[_.name].directReturn=!0}}Tp(this,this),Tp(lm,this,!0);for(let _ of S){let T=_.name;_.resolve&&(Object.defineProperty(i.encoder.structPrototype,T,{get(){return _.resolve(this,Xu.getStore())},set(C){return _.set(this,C)},configurable:!0,enumerable:_.enumerable}),_.enumerable&&!i.encoder.structPrototype.toJSON&&Object.defineProperty(i.encoder.structPrototype,"toJSON",{configurable:!0,value(){let C={};for(let P in this)C[P]=this[P];return C}}))}}static setComputedAttribute(_,T){let C=zi(S,_);if(!C){console.error(`The attribute "${_}" does not exist in the table "${s}"`);return}if(!C.computed){console.error(`The attribute "${_}" is not defined as computed in the table "${s}"`);return}this.userResolvers[_]=T}static async deleteHistory(_=0,T=!1){let C;for(let{key:P,value:O}of l.getRange({start:0,end:_}))await oc(),At(O).tableId===n&&(C=z_(l,P,O));if(T)for(let P of i.getRange({start:0,versions:!0})){let{key:O,value:x,localTime:D}=P;await oc(),x===null&&D<_&&(C=ul(i,P))}await C}static async*getHistory(_=0,T=1/0){for(let{key:C,value:P}of l.getRange({start:_||1,end:T})){await oc();let O=At(P);O.tableId===n&&(yield{id:O.recordId,localTime:C,version:O.version,type:O.type,value:O.getValue(i,!0,C),user:O.user,operation:O.originatingOperation})}}static async getHistoryOfRecord(_){let T=[];if(_==null)throw new Error("An id is required");let C=i.getEntry(_);if(!C)return T;let P=C.localTime;if(!P)throw new Error("The entry does not have a local audit time");let O=0;do{await oc();let x=l.get(P);if(x){let D=At(x);T.push({id:D.recordId,localTime:P,version:D.version,type:D.type,value:D.getValue(i,!0,P),user:D.user}),P=D.previousLocalTime}else break}while(O<1e3&&P);return T.reverse()}static cleanup(){Y?.remove()}}let t_=oS(async(K,_,T)=>{for(let C of ve.sources)if(C.get&&(!C.get.reliesOnPrototype||C.prototype.get)){if(C.available?.(T)===!1)continue;_.source=C;let P=await C.get(K,_);if(P)return P}},()=>{throw new ut.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});ve.updatedAttributes();let wb=ve.prototype;return h&&ve.setTTLExpiration(h/1e3),j&&r_(),ve;function Nu(K,_,T){let C;for(let P in r){let O=r[P],x=O.isIndexing,D=xr[P],A=T&&(D?D(T):T[P]),U=_&&(D?D(_):_[P]);if(A===U&&!x)continue;if(O.customIndex){O.customIndex.index(K,A,U);continue}C=!0;let w=O.indexNulls,L=(0,Hp.getIndexedValues)(A,w),q=(0,Hp.getIndexedValues)(U,w);if(q?.length>0){let W=new Set(q);if(L=L?L.filter(Q=>{if(W.has(Q))W.delete(Q);else return!0}):[],q=Array.from(W),(q.length>0||L.length>0)&&WG){let Q=q.concat(L).map(B=>({key:B,value:K}));O.prefetch(Q,JG)}for(let Q=0,B=q.length;Q<B;Q++)O.remove(q[Q],K)}else L?.length>0&&WG&&O.prefetch(L.map(W=>({key:W,value:K})),JG);if(L)for(let W=0,Q=L.length;W<Q;W++)O.put(L[W],K)}return C}a(Nu,"updateIndices");function Hi(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>jG)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");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,xl.writeKey)(K,Vae,0)>jG)throw new Error("Primary key size is too large: "+K.length);return!0}a(Hi,"checkValidId");function Ds(K){return typeof K=="object"&&K?K.id:K}a(Ds,"requestTargetToId");function um(K){return typeof K=="object"&&K&&K.isCollection}a(um,"isSearchTarget");function dm(K){}a(dm,"isRequestTarget");function Lo(K,_,T,C,P){if(ve.getResidencyById&&T.ensureLoaded&&_?.replicateFrom!==!1){let x=Ba(ve.getResidencyById(K));if(x&&!x.includes(server.hostname)&&N)return N({key:K,residency:x}).then(P)}let O=a(()=>{if(_?.transaction?.stale&&(_.transaction.stale=!1),T.transaction?.isDone)return P(null,K);let x=i.getEntry(K,T);return(c!=="system"||s==="hdb_analytics")&&(rq.default.trace?.("Recording db-read action for",`${c}.${s}`),Ve(x?.size??1,"db-read",s,null)),_?._freezeRecords&&Object.freeze(x?.value),x?.residencyId&&x.metadataFlags&Fn&&N&&T.ensureLoaded&&_?.replicateFrom!==!1?N(x).then(D=>P(D,K),D=>(ke.default.error?.("Error loading remote record",K,x,T,D),P(null,K))):(x&&_&&(x?.version>(_.lastModified||0)&&(_.lastModified=x.version),x?.localTime&&!_.lastRefreshed&&(_.lastRefreshed=x.localTime)),P(x,K))},"whenPrefetched");return C?O():te>0?(te--,O()):new Promise((x,D)=>{te===0?(te--,i.prefetch([K],()=>{A(),U()})):(ce.push(K),de.push(U),ce.length>e_&&(te--,A()));function A(){if(ce.length>0){let w=de;i.prefetch(ce,()=>{te===-1?A():te++;for(let L of w)L()}),ce=[],de=[],ge>2&&ge--}else te=ge,ge<cm&&ge++}a(A,"prefetch");function U(){try{x(O())}catch(w){D(w)}}a(U,"load")})}a(Lo,"loadLocalRecord");function Dn(K,_){let T=_?.checkPermission;if(typeof T!="object"){if(!K?.role)return;T=K.role.permission}if(T.super_user)return Kae;let C=T[c],P,O=C?.tables;if(O)return O[s];if(c==="data"&&(P=T[s])&&!P.tables)return P}a(Dn,"getTablePermissions");function pn(K,_,T,C){if(I){let P=!1;if(T.noCache?P=!0:(_?(!_.value||_.metadataFlags&(Fn|dl)||_.expiresAt!=null&&_.expiresAt<Date.now())&&(P=!0):P=!0,tn(!P,"cache-hit",s)),P){let O=Ou(K,_,T).then(x=>(x?.value&&x?.value.getRecord?.()&&ke.default.error?.("Can not assign a record that is already a resource"),T&&(x?.version>(T.lastModified||0)&&(T.lastModified=x.version),T.lastRefreshed=Date.now()),x));if(T?.onlyIfCached||_?.value&&C?.allowStaleWhileRevalidate?.(_,K)){if(O.catch(x=>ke.default.warn?.(x)),T?.onlyIfCached&&!C.doesExist())throw new ut.ServerError("Entry is not cached",504);return}else return O}}else if(_?.value&&_.expiresAt!=null&&_.expiresAt<Date.now())return ve.evict(_.key,_.value,_.version),_.value=null,{then(P){return P(_)}}}a(pn,"ensureLoadedFromSource");function Br(K){let _=K?.transaction;if(_){if(!_.lmdbDb)return _.lmdbDb=i,_;do{if(_.lmdbDb?.path===i.path)return _;let T=_.next;if(!T)return _=_.next=new vo,_.lmdbDb=i,_;_=T}while(!0)}else return new A_}a(Br,"txnForContext");function Cu(K,_,T){if(!K)return;let C=(K.deref?K.deref():K.value)??i.getEntry(K.key)?.value;if(typeof _=="object"){let O=xr,x=C;for(let D=0,A=_.length;D<A;D++){let U=_[D],w=O?.[U];x=w&&x?w(x,T,K):x?.[U],K=null,O=w?.definition?.tableClass?.propertyResolvers}return x}let P=xr[_];return P?P(C,T,K):C[_]}a(Cu,"getAttributeValue");function fm(K,_,T,C,P){let O=P?.length,x={transaction:C,lazy:O>0||typeof _=="string"||_?.length<4,alwaysPrefetch:!0},D;function A(U,w){let L=U?.value;if(!L)return ac.SKIP;for(let q=0;q<O;q++)if(!D?.includes(q)&&!P[q](L,U))return ac.SKIP;return w!==void 0&&(U.key=w),U}if(a(A,"processEntry"),O>0||!K.hasEntries){let U=K.map(w=>{if(D=null,typeof w=="object"&&w?.key!==void 0)return O>0?A(w):w;if(w==null)return ac.SKIP;for(let L=0;L<O;L++){let W=P[L].idFilter;if(W){if(!W(w))return ac.SKIP;D||(D=[]),D.push(L)}}return Lo(w,T,x,!1,A)});return Array.isArray(K)&&(U=U.filter(w=>w!==ac.SKIP)),U.hasEntries=!0,U}return K}a(fm,"transformToEntries");function Fr(K,_,T=server.replication?.getThisNodeId(l)){if(K<=_?.version){if(_?.version===K&&T!==void 0){let C=server.replication?.exportIdMapping(l),P=_.localTime,O=P&&l.get(P);if(O){let x,D,A=At(O);for(let U in C)C[U]===T&&(x=U),C[U]===A.nodeId&&(D=U);if(x>D)return 1;if(x===D)return 0}}return-1}return 1}a(Fr,"precedesExistingVersion");async function Ou(K,_,T){let C=_?.metadataFlags,P=_?.version,O,x;if(!i.attemptLock(K,P,()=>{clearTimeout(x);let w=i.getEntry(K);!w||!w.value||w.metadataFlags&(Fn|dl)?O(Ou(K,i.getEntry(K),T)):O(w)}))return new Promise(w=>{O=w,x=setTimeout(()=>{i.unlock(K,P)},qae)});let D=_?.value,A={requestContext:T,replacingRecord:D,replacingEntry:_,replacingVersion:P,noCacheStore:!1,source:null,resourceCache:T?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},U=T?.responseHeaders;return new Promise((w,L)=>{let q;qs(bt(A,async W=>{let Q=performance.now(),B,Ee,fe;try{B=await t_(K,A,_),fe=C&Fn;let re=A.lastModified||fe&&P;Ee=fe||re>P||!D,re||(re=(0,Hp.getNextMonotonicTime)());let ie=performance.now()-Q;if(Ve(ie,"cache-resolution",s,null,"success"),U&&Fp(U,"Server-Timing",`cache-resolve;dur=${ie.toFixed(2)}`,!0),W.timestamp=re,h&&A.expiresAt==null&&(A.expiresAt=Date.now()+h),B){if(typeof B!="object")throw new Error("Only objects can be cached and stored in tables");if(B.status>0&&B.headers)if(B.status>=300)if(B.status===304)B=D,re=P;else throw new ut.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==K&&(B[t]=K)}q=!0,w({key:K,version:re,value:B})}catch(re){re.message+=` while resolving record ${K} for ${s}`,D&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!T?.mustRevalidate||T?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(w({key:K,version:P,value:D}),ke.default.trace?.(re.message,"(returned stale record)")):L(re);let ie=performance.now()-Q;Ve(ie,"cache-resolution",s,null,"fail"),U&&Fp(U,"Server-Timing",`cache-resolve;dur=${ie.toFixed(2)}`,!0),A.transaction.abort();return}if(T?.noCacheStore||A.noCacheStore){A.transaction.abort();return}Br(A).addWrite({key:K,store:i,entry:_,nodeName:"source",before:Pu(B),commit:a((re,ie)=>{if(ie?.version!==P)return;let Oe=Nu(K,D,B);if(B){Ye.put?.(A,K,B),ie&&(T.previousResidency=ve.getResidencyRecord(ie.residencyId));let le,ae=!1,xe,Ce=Ba(ve.getResidency(B,T));if(Ce){if(!Ce.includes(server.hostname))if(le=B,ae=!0,ve.getResidencyById)B=void 0;else{B=null;for(let Le in r)B||(B={}),B[Le]=le[Le]}xe=Yc(Ce)}ke.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),y(K,B,ie,re,ae?Fn:0,g&&(Ee||ae)||null,{user:A?.user,expiresAt:A.expiresAt,residencyId:xe,tableToTrack:s},"put",!!fe,le)}else ie&&(Ye.delete?.(A,K),ke.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),g||R?y(K,null,ie,re,0,g&&Ee||null,{user:A?.user,tableToTrack:s},"delete",!!fe):ul(i,ie,P))},"commit")})}),()=>{i.unlock(K,P)},W=>{i.unlock(K,P),q&&ke.default.error?.("Error committing cache update",W)})})}a(Ou,"getFromSource");function Ua(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new ut.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new ut.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Ua,"checkContextPermissions");function xa(K){let _=!1;if(K&&(K-Ar>1&&(_=!0),Ar=K),!(qe===er&&!_)&&(er=qe,(0,Ml.getWorkerIndex)()===(0,Ml.getWorkerCount)()-1))return Qr&&clearTimeout(Qr),qe?new Promise(T=>{let C=new Date;C.setMonth(0),C.setDate(1),C.setHours(0),C.setMinutes(0),C.setSeconds(0);let P=qe/(1+Ar),O=_?Date.now():Math.ceil((Date.now()-C.getTime())/P)*P+C.getTime(),x=a(D=>{ke.default.trace?.(`Scheduled next cleanup scan at ${new Date(D)}`),Qr=setTimeout(()=>ee=ee.then(async()=>{if(x(Math.max(D+qe,Date.now())),i.rootStore.status!=="open"){clearTimeout(Qr);return}let A=50,U=new Array(A),w=0,L=Math.pow(Ar,8)*(Ul.get(F.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),q=E/Math.pow(Math.max(Ar,1),4);ke.default.debug?.(`Starting cleanup scan for ${s}, evict threshold ${L}, adjusted eviction ${q}ms`);function W(Q,B,Ee,fe){let pe=Q+q-Date.now();if(pe<0)return!0;if(Ar){let re=i.lastSize;return Ee&Zr&&el(fe,ie=>{ie.size&&(re+=ie.size)}),ke.default.trace?.(`shouldEvict adjusted ${pe} ${re}, ${pe*(Q-B)/re} < ${L}`),pe*(Q-B)/re<L}return!1}a(W,"shouldEvict");try{let Q=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:Ee,value:fe,version:pe,expiresAt:re,metadataFlags:ie}=B,Oe;fe===null&&!g&&pe+Gae<Date.now()?Oe=ul(i,B,pe):re!=null&&W(re,pe,ie,fe)&&(Oe=ve.evict(Ee,fe,pe),Q++),Oe&&(await U[w],U[w]=Oe.catch(le=>{ke.default.error?.("Cleanup error",le)}),++w>=A&&(w=0)),await oc()}ke.default.debug?.(`Finished cleanup scan for ${s}, evicted ${Q} entries`)}catch(Q){ke.default.warn?.(`Error in cleanup scan for ${s}:`,Q)}T(void 0),Ar=0}),Math.min(D-Date.now(),2147483647)).unref()},"startNextTimer");x(O)}):void 0}a(xa,"scheduleCleanup");function mm(){Y=l?.addDeleteRemovalCallback(n,i,(K,_)=>{i.remove(K,_)})}a(mm,"addDeleteRemoval");function r_(){(0,Ml.getWorkerIndex)()===0&&setInterval(async()=>{if(!Kc){Kc=!0;try{let K=j.name,_=r[K];if(!_)throw new Error(`expiresAt attribute ${j} must be indexed`);for(let T of _.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let C of _.getValues(T)){let P=i.getEntry(C);P?.value?P.value[K]<Date.now()&&ve.evict(C,P.value,P.version):i.ifVersion(C,P?.version,()=>_.remove(T,C))}await oc()}}catch(K){ke.default.error?.("Error in evicting old records",K)}finally{Kc=!1}}},Hae).unref()}a(r_,"runRecordExpirationEviction");function Ba(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let _=server.shards?.get?.(K);if(_)return ke.default.trace?.(`Shard ${K} mapped to ${_.map(T=>T.name).join(", ")}`),_.map(T=>T.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(Ba,"residencyFromFunction");function Yc(K){if(K){let _=K.join(","),T=d.get([Symbol.for("residency_by_set"),_]);return T||(d.put([Symbol.for("residency_by_set"),_],T=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),T],K),T)}}a(Yc,"getResidencyId");function Pu(K,_){let T=_A(K,i.rootStore);if(T){let C=_;return C?async()=>{await C(),await T}:()=>T}return _}a(Pu,"preCommitBlobsForRecordBefore")}function gN(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 JG(){}function cS(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return aS(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return aS(+e);case"Float":return e==="null"?null:aS(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;Yae.test(e)||(e+="Z");let n=new Date(e);return aS(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,lS.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function aS(e){if(isNaN(e))throw new SyntaxError;return e}function XG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);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 qs(e,t,r){return e?.then?e.then(t,r):t(e)}function ZG(e){return e!=null}function $s(e){try{return JSON.stringify(e)}catch{return e}}function Wae(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var ac,Hp,eq,tq,Ul,ut,Gp,qp,ke,xl,Ml,lS,SN,rq,xae,Bae,Fae,kae,Hae,Gae,WG,qae,zG,$ae,Fn,dl,Vae,jG,QG,Kae,LMe,Yae,oc,mg=se(()=>{H();ac=require("lmdb"),Hp=b(Un()),eq=b(require("lodash")),tq=b(Cm());Vo();Pm();Ul=b(me());sI();ut=b(_e()),Gp=b(Wo()),qp=b(ls());we();fg();ke=b(wr());fw();Ga();xl=require("ordered-binary"),Ml=b(st());$i();lS=b(oe());al();is();N_();kp();SN=b(require("node:fs"));ss();V_();rq=b(J());_N();({sortBy:xae}=eq.default),{validateAttribute:Bae}=tq.default,Fae=new Uint8Array(9);Fae[8]=192;kae=1/0,Hae=6e4,Gae=864e5;Ul.initSync();WG=Ul.get(F.STORAGE_PREFETCHWRITES),qae=1e4,zG=1,$ae=2,Fn=1,dl=8,Vae=Buffer.allocUnsafeSlow(8192),jG=1978,QG=100,Kae={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},LMe=(0,lS.convertToMS)(Ul.get(F.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(uS,"makeTable");a(gN,"attributesAsObject");a(JG,"noop");Yae=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(cS,"coerceType");a(aS,"rejectNaN");a(XG,"isDescendantId");oc=a(()=>new Promise(setImmediate),"rest");a(qs,"when");a(ZG,"exists");a($s,"stringify");a(Wae,"hasOtherProcesses")});function dS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Euclidean distance comparison requires an array");let r=0,n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let i=e[s]||0,o=t[s]||0,c=i-o;r+=c*c}return r}function fS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Cosine distance comparison requires an array");let r=0,n=0,s=0,i=Math.max(e.length,t.length);for(let o=0;o<i;o++){let c=e[o]||0,l=t[o]||0;r+=c*l,n+=c*c,s+=l*l}return n=Math.sqrt(n),s=Math.sqrt(s),1-r/(n*s||1)}var sq=se(()=>{a(dS,"euclideanDistance");a(fS,"cosineDistance")});var iq,oq,Ad,co,bd,zae,jae,mS,aq=se(()=>{sq();iq=require("msgpackr"),oq=b(wr()),Ad=b(_e()),co=(0,oq.loggerWithTag)("HNSW"),bd=Symbol.for("entryPoint"),zae=Symbol.for("key"),jae=10,mS=class{static{a(this,"HierarchicalNavigableSmallWorld")}static useObjectStore=!0;indexStore;M=16;efConstruction=100;efConstructionSearch=50;mL=1/Math.log(this.M);optimizeRouting=.5;nodesVisitedCount=0;idIncrementer;distance;constructor(t,r){this.indexStore=t,t&&(this.indexStore.encoder.useFloat32=iq.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?dS:fS,r&&(r.M!==void 0&&(this.M=r.M,this.mL=1/Math.log(this.M)),r.efConstruction!==void 0&&(this.efConstruction=this.efConstructionSearch=r.efConstruction),r.efConstructionSearch!==void 0&&(this.efConstructionSearch=r.efConstructionSearch),r.mL!==void 0&&(this.mL=r.mL),r.optimizeRouting!==void 0&&(this.optimizeRouting=r.optimizeRouting))}index(t,r,n){let s=typeof t=="number"?[zae,t]:t,i=this.indexStore.get(s);if(!i){if(!r)return;if(!this.idIncrementer){let f=0;for(let m of this.indexStore.getKeys({reverse:!0,limit:1,start:1/0,end:0}))typeof m=="number"&&(f=m);this.idIncrementer=new BigInt64Array([BigInt(f)+1n]),this.idIncrementer=new BigInt64Array(this.indexStore.getUserSharedBuffer("next-id",this.idIncrementer.buffer))}i=Number(Atomics.add(this.idIncrementer,0,1n)),this.indexStore.put(s,i)}let o=new Map,c,l=this.indexStore.get(bd);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f===void 0){let E=Math.floor(-Math.log(Math.random())*this.mL),g={vector:r,level:E,primaryKey:t};for(let R=0;R<=E;R++)g[R]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);co.debug?.("setting entry point to",i),this.indexStore.put(bd,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),jae),p=f.level;if(m>=p){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);co.debug?.("setting entry point to",i),this.indexStore.put(bd,i)}for(;p>m;){let E=this.searchLayer(r,l,f,this.efConstruction,p);E.length>0&&(l=E[0].id,f=E[0].node),p--}let h=new Array(m+1);for(let E=0;E<=m;E++)h[E]=[];for(let E=Math.min(m,p);E>=0;E--){let g=this.searchLayer(r,l,f,this.efConstruction,E);g=g.slice(0,this.M<<1),g.length===0&&E===0&&co.info?.("should not have zero connections for",l);let R=h[E];for(let S=0;S<g.length;S++){let{id:y,distance:N,node:I}=g[S];if(y===i)continue;let $=[];if(this.optimizeRouting){let k=!1,j=I[E],Y=1+this.optimizeRouting*(1+.5*S/this.M);for(let ce=0;ce<j.length;ce++){let{id:de,distance:te}=j[ce],ge=1+this.optimizeRouting*(1+.5*ce/this.M);for(let be=0;be<R.length;be++){let{id:Ye,distance:qe}=R[be];if(Ye===de){N*Y>qe+te?k=!0:te*ge>N+qe&&($.push({fromId:Ye,toId:y}),$.push({fromId:y,toId:Ye}));break}}if(k)break}if(k)continue}else if(S>=(E>0?this.M:this.M<<1))continue;R.push({id:y,distance:N});for(let{fromId:k,toId:j}of $){let Y=d(k);Y||(Y=d(k,this.indexStore.get(k)));for(let ce=0;ce<Y[E].length;ce++)if(Y[E][ce].id===j){Object.isFrozen(Y[E])&&(Y[E]=Y[E].slice()),Y[E].splice(ce,1);break}}let ee=c[E],G=ee?.find(({id:k})=>k===y);if(G){let k=ee?.indexOf(G);ee.copied||(ee=[...ee],ee.copied=!0,c[E]=ee),ee.splice(k,1)}else this.addConnection(y,d(y,I),i,E,N,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...h})}else{if(l===i){let f=c.level??0;for(let m=f;m>=0&&(l=c[m][0]?.id,l===void 0);m--);if(l===void 0){let m=-1;for(let{key:p,value:h}of this.indexStore.getRange({start:0,end:1/0}))if(h.level>m){if(l=p,h.level===f)break;m=h.level}}if(l===void 0)this.indexStore.remove(bd);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);co.debug?.("setting entry point to",l),this.indexStore.put(bd,l)}}this.indexStore.remove(i)}let u=new Map;if(c.level!==void 0)for(let f=0;f<=c.level;f++){let m=c[f];for(let{id:p}of m){let h=d(p,this.indexStore.get(p));for(let E=0;E<=f;E++)h[E]=h[E]?.filter(({id:g})=>g!==i),h[E].length===0&&(co.info?.("node was left orphaned, will reindex",p),u.set(h.primaryKey,h.vector))}}function d(f,m){let p=o.get(f);return!p&&m&&(p={...m},o.set(f,p)),p}a(d,"updateNode");for(let[f,m]of o)this.indexStore.put(f,m);for(let[f,m]of u)this.index(f,m,m);this.checkSymmetry(i,this.indexStore.get(i))}getEntryPoint(){let t=this.indexStore.get(bd);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,o=this.distance){let c=new Set([r]),l=[{id:r,distance:this.distance(t,n.vector),node:n}],u=[...l];for(;l.length>0;){l.sort((p,h)=>p.distance-h.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:p}of m[i]||[]){if(c.has(p)||p===void 0)continue;c.add(p);let h=this.indexStore.get(p);if(!h)continue;this.nodesVisitedCount++;let E=o(t,h.vector);if(E<f||u.length<s){let g={id:p,distance:E,node:h};l.push(g),u.push(g)}}u.sort((p,h)=>p.distance-h.distance),u.length>s&&u.splice(s,u.length-s)}return u.visited=c.size,u}search({target:t,value:r,descending:n,distance:s,comparator:i}){let o=0;switch(i){case"lt":case"le":o=r;case"sort":break;default:throw new Ad.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Ad.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=fS;else if(s==="euclidean")c=dS;else{if(s)throw new Ad.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Ad.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Ad.ClientError("The target vector must be an array");let l=this.getEntryPoint();if(!l)return[];let u=l.id,d=[];for(let f=l.level;f>=0;f--)if(d=this.searchLayer(t,u,l,this.efConstructionSearch,f,c),d.length>0){let m=d[0];l=m.node,u=m.id}return o&&(d=d.filter(f=>f.distance<o)),d.map(f=>({key:f.node.primaryKey,distance:f.distance}))}checkSymmetry(t,r){if(!r)return;let n=0,s;for(;(s=r[n])&&s.length!==0;){for(let{id:i}of s){let o=this.indexStore.get(i);if(!o){co.info?.("could not find neighbor node",o);continue}o[n]?.find(({id:l})=>l==t)||co.info?.("asymmetry detected",o[n])}n++}}addConnection(t,r,n,s,i,o){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){co.warn?.("maxConnections reached, removing some connections",c);let l=[...r[s]];l.sort((f,m)=>f.distance-m.distance);let u=l.slice(0,c),d=l.slice(c);r[s]=u;for(let f of d){let m=o(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=o(f.id,m),m[s]=m[s].filter(({id:p})=>p!==t),s===0&&m[s].length===0&&co.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?co.debug?.("already connected",t,n):r[s]=[...r[s],{id:n,distance:i}]}validateConnectivity(t=0){let r=this.getEntryPoint(),n=new Set,s=[r.id];n.add(r.id);let i=0;for(;s.length>0;){let o=s.shift(),c=this.indexStore.get(o);for(let l=t;l<=c.level;l++)for(let{id:u}of c[l]||[])i++,n.has(u)||(n.add(u),s.push(u))}return n.size!==this.totalNodes&&console.log("visited",n.size,"total",this.totalNodes),{isFullyConnected:n.size===this.totalNodes,averageConnections:i/n.size}}get totalNodes(){return Array.from(this.indexStore.getKeys({start:0,end:1/0})).length}estimateCountAsSort(){return Math.sqrt(this.indexStore.getStats().entryCount*this.efConstructionSearch)}propertyResolver(t,r,n){let s=r?.sort;if(s){let i=s.vectorDistances;if(i){let l=i.get(n);if(l)return l}else i=r.vectorDistances=s.vectorDistances=new Map;let o=this.distance;s.type&&(o=s.distance==="euclidean"?dS:fS);let c=o(s.target,t);return i.set(n,c),c}return t}}});var TN,cq=se(()=>{aq();TN={HNSW:mS}});var ft={};ye(ft,{NON_REPLICATING_SYSTEM_TABLES:()=>pS,database:()=>ud,databaseEnvs:()=>Xo,databases:()=>Me,dropDatabase:()=>_w,dropTableMeta:()=>tce,getDatabases:()=>ct,getDefaultCompression:()=>yS,getTables:()=>Jae,onRemovedDB:()=>jp,onUpdatedTable:()=>Bl,readMetaDb:()=>$p,resetDatabases:()=>Od,table:()=>Xe,tables:()=>Rn});function zp(e,t){let r=SS.OpenDBIObject??SS.default.OpenDBIObject;return new r(e,t)}function Jae(){return gS||ct(),Rn||{}}function ct(){if(gS)return Me;gS=!0,Nd=new Map;let e=(0,zt.getHdbBasePath)()&&(0,kt.join)((0,zt.getHdbBasePath)(),jc),t=(0,zt.get)(F.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,zt.get)(F.STORAGE_PATH)||e&&((0,gs.existsSync)(e)?e:(0,kt.join)((0,zt.getHdbBasePath)(),l_)),!!e){if((0,gs.existsSync)(e))for(let r of(0,gs.readdirSync)(e,{withFileTypes:!0})){let n=(0,kt.basename)(r.name,".mdb");r.isFile()&&(0,kt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&$p((0,kt.join)(e,r.name),null,n)}if((0,gs.existsSync)((0,wd.getBaseSchemaPath)())){for(let r of(0,gs.readdirSync)((0,wd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,kt.join)((0,wd.getBaseSchemaPath)(),r.name),s=(0,kt.join)((0,wd.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,gs.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,kt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,kt.join)(s,i.name);$p((0,kt.join)(n,i.name),(0,kt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,gs.existsSync)(s))for(let o of(0,gs.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,kt.extname)(o.name).toLowerCase()===".mdb"&&$p((0,kt.join)(s,o.name),(0,kt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],l=(0,kt.join)(c.path,(0,kt.basename)(o+".mdb"));(0,gs.existsSync)(l)&&$p(l,o,r,null,!0)}}for(let r in Me){let n=Nd.get(r);if(n){let s=Me[r];r.includes("delete")&&Or.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Or.trace(`delete table class ${i}`),delete s[i])}else if(delete Me[r],r==="data"){for(let s in Rn)delete Rn[s];delete Rn[TS]}}if((0,zt.get)(F.ANALYTICS_REPLICATE)===!1?pS.includes("hdb_analytics")||pS.push("hdb_analytics"):(Me.system?.hdb_analytics?.enableAuditing(),Me.system?.hdb_analytics_hostname?.enableAuditing()),Me.system)for(let r of pS)Me.system[r]&&(Me.system[r].replicate=!1);return Nd=null,Me}}function Od(){gS=!1;for(let[,e]of Xo)e.needsDeletion=!0;ct();for(let[e,t]of Xo)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),Xo.delete(e);let r=Me[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete Me[t.databaseName],Kp.forEach(i=>i(t.databaseName));break}}return Me}function $p(e,t,r=bN,n,s){let i=new yN.default(e,!1);try{let o=Xo.get(e);o?o.needsDeletion=!1:(o=(0,Cd.open)(i),Xo.set(e,o));let c=new zp(!1),l=o.dbisDb||(o.dbisDb=o.openDB(hS.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,gs.existsSync)(n)&&(i.path=n,u=(0,Cd.open)(i),u.isLegacy=!0):u=W_(o));let d=mq(r),f=d[TS],m=new Map;for(let{key:p,value:h}of l.getRange({start:!1})){let[E,g]=p.toString().split("/");g===""?g=h.name:g||(g=E,E=t,h.name||(h.name=g,h.indexed=!h.is_hash_attribute)),f?.add(E);let R=m.get(E);R||m.set(E,R={attributes:[]}),(g==null||h.is_hash_attribute)&&(R.primary=h),g!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:p,configurable:!0})}for(let[p,h]of m){let{attributes:E,primary:g}=h;if(!g){for(let te of E)if(te.is_hash_attribute||te.isPrimaryKey){g=te;break}if(!g){Or.warn(`Unable to find a primary key attribute on table ${p}, with attributes: ${JSON.stringify(E)}`);continue}}let R=d[p],S={},y=[],N,I,$=typeof g.audit=="boolean"?g.audit:(0,zt.get)(F.LOGGING_AUDITLOG),ee=g.trackDeletes,G=g.expiration,k=g.eviction,j=g.sealed,Y=g.splitSegments,ce=g.replicate;if(R)S=R.indices,y=R.attributes,R.schemaVersion++;else{N=g.tableId,N?N>=(l.get(Id)||0)&&(l.putSync(Id,N+1),Or.info(`Updating next table id (it was out of sync) to ${N+1} for ${p}`)):(g.tableId=N=l.get(Id),N||(N=1),Or.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Id,N+1),l.putSync(g.key,g));let te=new zp(!g.is_hash_attribute,g.is_hash_attribute);if(te.compression=g.compression,te.compression){let ge=(0,zt.get)(F.STORAGE_COMPRESSION_THRESHOLD)||fq;te.compression.threshold=ge}I=cg(o.openDB(g.key,te),o),o.databaseName=r,I.tableId=N}let de;for(let te of E){te.attribute=te.name;try{if(!te.is_hash_attribute&&(te.indexed||te.attribute&&!te.name)){if(!S[te.name]){let be=hq(te.key,o,te);S[te.name]=be,S[te.name].indexNulls=te.indexNulls}let ge=y.find(be=>be.name===te.name);ge?y.splice(y.indexOf(ge),1,te):y.push(te),de=!0}}catch(ge){Or.error("Error trying to update attribute",te,y,S,ge)}}for(let te of y)if(!E.find(be=>be.name===te.name)){if(te.is_hash_attribute){Or.error("Unable to remove existing primary key attribute",te);continue}te.indexed&&(y.splice(y.indexOf(te),1),de=!0)}if(R)de&&(R.schemaVersion++,R.updatedAttributes());else{R=pq(d,p,uS({primaryStore:I,auditStore:u,audit:$,sealed:j,splitSegments:Y,replicate:ce,expirationMS:G&&G*1e3,evictionMS:k&&k*1e3,trackDeletes:ee,tableName:p,tableId:N,primaryKey:g.name,databasePath:s?r+"/"+p:r,databaseName:r,indices:S,attributes:E,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let te of Vp)te(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function mq(e){let t=Me[e];if(t||(e==="data"?t=Me[e]=Rn:e==="system"?Object.defineProperty(Me,"system",{value:t=Object.create(null),configurable:!0}):t=Me[e]=Object.create(null)),Nd&&!Nd.has(e)){let r=new Set;t[TS]=r,Nd.set(e,r)}return t}function pq(e,t,r){return e[t]=r,r}function ud({database:e,table:t}){e||(e=bN),ct();let r=mq(e),n=(0,kt.join)((0,zt.getHdbBasePath)(),jc),s=(0,zt.get)(F.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,zt.get)(F.STORAGE_PATH)||((0,gs.existsSync)(n)?n:(0,kt.join)((0,zt.getHdbBasePath)(),l_));let o=(0,kt.join)(n,(i?t:e)+".mdb"),c=Xo.get(o);if(!c||c.status==="closed"){let l=new yN.default(o,!1);c=(0,Cd.open)(l),Xo.set(o,c)}return c.auditStore||(c.auditStore=W_(c)),c}async function _w(e){if(!Me[e])throw new Error("Schema does not exist");let t=Me[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Xo.delete(r.path),r.status==="open"&&(await r.close(),await Yp.remove(r.path));if(r||(r=ud({database:e,table:null}),r.status==="open"&&(await r.close(),await Yp.remove(r.path))),e==="data"){for(let n in Rn)delete Rn[n];delete Rn[TS]}delete Me[e],Kp.forEach(n=>n(e)),await EA(r)}function hq(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&TN[r.indexed.type]?.useObjectStore,s=new zp(!n,n),i=t.openDB(e,s);if(r.indexed.type){let o=TN[r.indexed.type];o?i.customIndex=new o(i,r.indexed):Or.error(`The indexing type '${r.indexed.type}' is unknown`)}return i}function Xe(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:p}=e;r||(r=bN);let h=ud({database:r,table:t}),E=Me[r];Or.trace(`Defining ${t} in ${r}`);let g=E?.[t];if(h.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,S,y;m==null&&(m=!0);let N=new zp(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let I,$;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...o)}else{let Y=h.auditStore;S=o.find(ge=>ge.isPrimaryKey)||{},R=S.name,S.is_hash_attribute=S.isPrimaryKey=!0,S.schemaDefined=m,S.compression=yS(),f&&(S.trackDeletes=!0),c=S.audit=typeof c=="boolean"?c:(0,zt.get)(F.LOGGING_AUDITLOG),n&&(S.expiration=n),s&&(S.eviction=s),u??=!1,S.splitSegments=u,typeof l=="boolean"&&(S.sealed=l),typeof d=="boolean"&&(S.replicate=d),p&&(S.origins?S.origins.includes(p)||S.origins.push(p):S.origins=[p]),Or.trace(`${t} table loading, opening primary store`);let ce=new zp(!1,!0);ce.compression=S.compression;let de=t+"/";if(y=h.dbisDb=h.openDB(hS.INTERNAL_DBIS_NAME,N),j(),y.get(de))return $&&$(),Od(),Xe(e);let te=cg(h.openDB(de,ce),h);h.databaseName=r,te.tableId=y.get(Id),Or.trace(`Assigning new table id ${te.tableId} for ${t}`),te.tableId||(te.tableId=1),y.put(Id,te.tableId+1),S.tableId=te.tableId,g=pq(E,t,uS({primaryStore:te,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:te.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:m,dbisDB:y})),g.schemaVersion=1,I=!0,y.put(de,S)}let ee=g.indices;y=y||(h.dbisDb=h.openDB(hS.INTERNAL_DBIS_NAME,N)),g.dbisDB=y;let G=[];for(let{key:Y,value:ce}of y.getRange({start:!0})){let[de,te]=Y.toString().split("/");if(te===""&&(te=ce.name),te){if(de!==t)continue}else continue;let ge=o.find(Ye=>Ye.name===te),be=!ge?.indexed&&ce.indexed&&!ce.isPrimaryKey;if((!ge||be)&&(j(),I=!0,ge||y.remove(Y),be)){let Ye=g.indices[de];Ye&&G.push(Ye)}}let k=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(I=!0,Y.relationship))continue;let ce=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ce,configurable:!0});let de=y.get(ce);if(Y.isPrimaryKey){if(de=de||y.get(ce=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+de.expiration||void 0)||(+s||void 0)!==(+de.eviction||void 0)||Y.type!==de.type){let ge={...de};typeof c=="boolean"&&(c&&g.enableAuditing(c),ge.audit=c),n&&(ge.expiration=+n),s&&(ge.eviction=+s),l!==void 0&&(ge.sealed=l),d!==void 0&&(ge.replicate=d),Y.type&&(ge.type=Y.type),I=!0,j(),y.put(ce,ge)}continue}de?.attribute&&!de.name&&(de.indexed=!0);let te=!de||de.type!==Y.type||JSON.stringify(de.indexed)!==JSON.stringify(Y.indexed)||de.nullable!==Y.nullable||de.version!==Y.version||de.enumerable!==Y.enumerable||JSON.stringify(de.properties)!==JSON.stringify(Y.properties)||JSON.stringify(de.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let ge=hq(ce,h,Y);(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<Wp.workerData?.restartNumber)&&(I=!0,j(),de=y.get(ce),(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<Wp.workerData?.restartNumber)&&(I=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=de?.lastIndexedKey??void 0,Y.indexingPID=process.pid,ge.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:ge}),k.push(Y))),y.put(ce,Y)),de?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),ge.indexNulls=Y.indexNulls,ee[Y.name]=ge}else te&&(I=!0,j(),y.put(ce,Y))}}finally{$&&$()}if(I&&(g.schemaVersion++,g.updatedAttributes()),Or.trace(`${t} table loading, running index`),k.length>0||G.length>0?g.indexingOperation=ece(g,k,G):I&&ES.signalSchemaChange(new _S.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=p,I)for(let Y of Vp)Y(g,p!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Or.trace(`${t} table loaded`),g;function j(){$||h.transactionSync(()=>({then(Y){$=Y}}))}a(j,"startTxn")}async function ece(e,t,r){try{Or.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await ES.signalSchemaChange(new _S.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,Cd.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:p}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,p,()=>{for(let h=0;h<l;h++){let E=t[h],g=E.name,R=E.dbi;try{let S=E.resolve,y=m&&(S?S(m):m[g]);if(R.customIndex){R.customIndex.index(f,y);continue}let N=(0,lq.getIndexedValues)(y);if(N)for(let I=0,$=N.length;I<$;I++)R.put(N[I],f)}catch(S){o[g]||(o[g]=!0,Or.error(`Error indexing attribute ${g}`,S))}}}),s.then(()=>d--,h=>{d--,Or.error(h)}),Wp.workerData&&Wp.workerData.restartNumber!==dq.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=f,e.dbisDB.put(h.key,h);if(i)return}d>Xae?await s:d>Zae&&await new Promise(h=>setImmediate(h))}for(let f of t)delete f.lastIndexedKey,delete f.indexingPID,f.dbi.isIndexing=!1,s=e.dbisDB.put(f.key,f)}await s,await ES.signalSchemaChange(new _S.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Or.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Or.error("Error in indexing",n)}}function tce({table:e,database:t}){let r=ud({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 Bl(e){return Vp.push(e),{remove(){let t=Vp.indexOf(e);t>-1&&Vp.splice(t,1)}}}function jp(e){return Kp.push(e),{remove(){let t=Kp.indexOf(e);t>-1&&Kp.splice(t,1)}}}function yS(){let e=(0,zt.get)(F.STORAGE_COMPRESSION),t=(0,zt.get)(F.STORAGE_COMPRESSION_DICTIONARY),r=(0,zt.get)(F.STORAGE_COMPRESSION_THRESHOLD)||fq,n={startingOffset:32};return t&&(n.dictionary=Yp.readFileSync(t)),r&&(n.threshold=r),e&&n}var zt,hS,Cd,kt,gs,wd,yN,Yp,RN,lq,ES,_S,Wp,uq,dq,SS,Qae,Or,bN,TS,fq,pS,Rn,Me,Id,Vp,Kp,gS,Xo,Nd,Xae,Zae,we=se(()=>{zt=b(me()),hS=b(Yt()),Cd=require("lmdb"),kt=require("path"),gs=require("fs"),wd=b(Rt());mg();yN=b(rp());H();Yp=b(require("fs-extra")),RN=b(ci()),lq=b(Un()),ES=b(Wo()),_S=b(ls()),Wp=require("worker_threads"),uq=b(J()),dq=b(st());$i();al();ss();cq();SS=b(tp()),{forComponent:Qae}=uq.default;a(zp,"OpenDBIObject");Or=Qae("storage"),bN="data",TS=Symbol("defined-tables"),fq=((0,zt.get)(F.STORAGE_PAGESIZE)||4096)-60;(0,zt.initSync)();pS=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_info"],Rn=Object.create(null),Me=Object.create(null);(0,RN._assignPackageExport)("databases",Me);(0,RN._assignPackageExport)("tables",Rn);Id=Symbol.for("next-table-id"),Vp=[],Kp=[],Xo=new Map;a(Jae,"getTables");a(ct,"getDatabases");a(Od,"resetDatabases");a($p,"readMetaDb");a(mq,"ensureDB");a(pq,"setTable");a(ud,"database");a(_w,"dropDatabase");a(hq,"openIndex");a(Xe,"table");Xae=1e3,Zae=10;a(ece,"runIndexing");a(tce,"dropTableMeta");a(Bl,"onUpdatedTable");a(jp,"onRemovedDB");a(yS,"getDefaultCompression")});var wN={};ye(wN,{loadGQLSchema:()=>sce,start:()=>IN,startOnMainThread:()=>nce});function IN({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:d}=await import("graphql"),f=o(new c(r.toString(),s)),m=new Map,p=[],h;for(let R of f.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let $=function(G){if(G.kind==="NonNullType"){let Y=$(G.type);return Y.nullable=!1,Y}if(G.kind==="ListType")return{type:"array",elements:$(G.type)};let j={type:G.name?.value};return Object.defineProperty(j,"location",{value:G.loc.startToken}),j};a($,"getProperty");let S=R.name.value,y=[],N={table:null,database:null,properties:y};m.set(S,N),i.allTypes.set(S,N);for(let G of R.directives){if(G.name.value==="table"){for(let j of G.arguments)N[j.name.value]=j.value.value;N.schema&&(N.database=N.schema),N.table||(N.table=S),N.audit&&(N.audit=N.audit!=="false"),N.attributes=N.properties,p.push(N)}if(G.name.value==="sealed"&&(N.sealed=!0),G.name.value==="splitSegments"&&(N.splitSegments=!0),G.name.value==="replicate"&&(N.replicate=!0),G.name.value==="export"){N.export=!0;for(let j of G.arguments)typeof N.export!="object"&&(N.export={}),N.export[j.name.value]=j.value.value}}let I=!1,ee={};for(let G of R.fields){let k=$(G.type);k.name=G.name.value,y.push(k),ee[k.name]=void 0;for(let j of G.directives){let Y=j.name.value;if(Y==="primaryKey")I?console.warn("Can not define two attributes as a primary key at",j.loc):(k.isPrimaryKey=!0,I=!0);else if(Y==="indexed"){let ce={};for(let de of j.arguments||[])ce[de.name.value]=de.value.value;k.indexed=ce}else if(Y==="computed"){for(let ce of j.arguments||[])if(ce.name.value==="from"){let de=ce.value.value;k.computed={from:g(de,ce,ee)},k.version==null&&(k.version=de)}else ce.name.value==="version"&&(k.version=ce.value.value);k.computed=k.computed||!0}else if(Y==="relationship"){let ce={};for(let de of j.arguments)ce[de.name.value]=de.value.value;k.relationship=ce}else if(Y==="createdTime")k.assignCreatedTime=!0;else if(Y==="updatedTime")k.assignUpdatedTime=!0;else if(Y==="expiresAt")k.expiresAt=!0;else if(Y==="enumerable")k.enumerable=!0;else if(Y==="allow"){let ce=k.authorizedRoles=[];for(let de of j.arguments)de.name.value==="role"&&ce.push(de.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,j.loc)}}N.type=S,S==="Query"&&(h=N)}function E(R){let S=m.get(R.type);S?(Object.defineProperty(R,"properties",{value:S.properties}),Object.defineProperty(R,"definition",{value:S})):R.type==="array"?E(R.elements):rce.includes(R.type)||(0,_q.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(E,"connectPropertyType");for(let R of m.values())for(let S of R.properties)E(S);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,AN.dirname)(n),R.tableClass):i.set((0,AN.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,S,y){return new Eq.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:S.loc.startToken.line-1,columnOffset:S.loc.startToken.column}).runInThisContext()(y)}a(g,"createComputedFrom")}}var AN,Eq,_q,rce,nce,sce,gq=se(()=>{AN=require("path"),Eq=require("node:vm");we();_q=b(st());za();rce=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow","enumerable"]);a(IN,"start");nce=IN,sce=a(e=>IN({ensureTable:Xe}).handleFile(e,null,null,new ed),"loadGQLSchema")});var CN={};ye(CN,{start:()=>mce});function ice(e){if(e.kind!==He.Kind.OPERATION_DEFINITION&&e.kind!==He.Kind.FRAGMENT_DEFINITION)throw new Kr(`Unexpected non-executable definition type ${e.kind}.`)}function Sq(e){if(typeof e!="object"||e===null)throw new lo("Request body must be an object.");if(!("query"in e))throw new lo("Request body must contain a `query` field.");if(typeof e.query!="string")throw new lo("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new lo("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new lo("Request body `operationName` field must be a string.")}function NN(e){return parseInt(e.value,10)}function yq(e){return parseFloat(e.value)}function Rq(e,t,r){let n=r.get(e.name.value);return bq(n)?Aq(n,t):{attribute:t,value:n}}function bq(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function Aq(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],bq(n)?Aq(n,t):{attribute:t,value:n}))}function oce(e,t,r){switch(t=[...t,e.name.value],e.value.kind){case He.Kind.NULL:return{attribute:t,value:null};case He.Kind.INT:return{attribute:t,value:NN(e.value)};case He.Kind.FLOAT:return{attribute:t,value:yq(e.value)};case He.Kind.BOOLEAN:case He.Kind.STRING:return{attribute:t,value:e.value.value};case He.Kind.VARIABLE:return Rq(e.value,t,r);case He.Kind.OBJECT:return Iq(e.value,t,r);case He.Kind.LIST:case He.Kind.ENUM:default:throw new Kr(`Value type, ${e.value.kind}, is not supported.`)}}function Iq(e,t,r){return e.fields.flatMap(n=>oce(n,t,r))}function ace(e,t){switch(e.value.kind){case He.Kind.NULL:return{attribute:e.name.value,value:null};case He.Kind.INT:return{attribute:e.name.value,value:NN(e.value)};case He.Kind.FLOAT:return{attribute:e.name.value,value:yq(e.value)};case He.Kind.BOOLEAN:case He.Kind.STRING:return{attribute:e.name.value,value:e.value.value};case He.Kind.VARIABLE:return Rq(e.value,e.name.value,t);case He.Kind.OBJECT:return Iq(e.value,[e.name.value],t);case He.Kind.LIST:case He.Kind.ENUM:default:throw new Kr(`Argument type, ${e.value.kind}, is not supported.`)}}function cce(e,t){return e.flatMap(r=>ace(r,t))}function RS(e,t){return e.selections.flatMap(r=>{switch(r.kind){case He.Kind.FIELD:return r;case He.Kind.FRAGMENT_SPREAD:{let n=r.name.value,s=t.get(n);if(s==null)throw new Kr(`Fragment \`${n}\` not found.`);return RS(s.selectionSet,t)}case He.Kind.INLINE_FRAGMENT:return RS(r.selectionSet,t)}})}function wq(e,t){return RS(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:wq(r.selectionSet,t)}:r.name.value)}async function lce(e,t,r,n){let s=Bs.getMatch(e.name.value,"graphql");if(s===void 0)throw new Kr(`Resource \`${e.name.value}\` not found.`);let i=s.Resource,o={select:wq(e.selectionSet,r),conditions:cce(e.arguments,t)},c=[];n.authorize=!0;for await(let l of i.search(o,n))c.push(l);return[e.name.value,c]}function Nq(e){switch(e.kind){case He.Kind.NULL:return null;case He.Kind.INT:return NN(e);case He.Kind.FLOAT:return parseFloat(e.value);case He.Kind.STRING:case He.Kind.BOOLEAN:return e.value;case He.Kind.OBJECT:return e.fields.reduce((t,r)=>({[r.name.value]:Nq(r.value),...t}),{});case He.Kind.LIST:case He.Kind.ENUM:default:throw new Kr(`Value type, ${e.kind}, is not supported.`)}}function uce(e,t){let r=new Map;for(let n of e){let s=n.variable.name.value,i=t?.[s];if(i===void 0&&n.defaultValue!==void 0&&(i=Nq(n.defaultValue)),n.type.kind===He.Kind.NON_NULL_TYPE&&!(s in t)&&i===void 0)throw new Kr(`Variable $${s} is required, but not provided.`);r.set(n.variable.name.value,i??null)}return r}async function dce(e,t,r,n){if(e.operation===He.OperationTypeNode.SUBSCRIPTION)throw new Kr("Subscriptions are not supported.");if(e.operation===He.OperationTypeNode.MUTATION)throw new Kr("Mutations are not supported yet.");let s=uce(e.variableDefinitions,t),i=await Promise.all(RS(e.selectionSet,r).map(c=>lce(c,s,r,n))),o={data:{}};for(let[c,l]of i)o.data[c]=l;return o}async function Tq({query:e,variables:t={},operationName:r},n){let s=He.parse(e),i=new Map,o=new Map;for(let u of s.definitions)if(ice(u),u.kind===He.Kind.FRAGMENT_DEFINITION)o.set(u.name.value,u);else{if(u.name===void 0&&s.definitions.length>1)throw new Kr("Unnamed operations are only allowed when there is a single operation in the document.");let d=u.name?.value??"Unnamed Query";if(i.has(d))throw new Kr(`Duplicate operation definition: ${d}`);i.set(d,u)}let c;if(r==null)if(i.size===1)c=i.entries().next().value[1];else throw new Kr("Operation name is required when there are multiple operations in the document.");else if(c=i.get(r),c==null)throw new Kr(`Operation \`${r}\` not found.`);let l=await dce(c,t,o,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function fce(e){switch(e.method){case"GET":{let t=new URLSearchParams(e.url.split("?")[1]),r={};for(let[n,s]of t)r[n]=n==="variables"||n==="extensions"?JSON.parse(s):s;return Sq(r),Tq(r,e)}case"POST":{let r=await Bo(e.headers.get("content-type"),!0)(e._nodeRequest);return Sq(r),Tq(r,e)}default:throw new lo("Method Not Allowed",405,{Allow:"GET, POST"})}}function mce(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await fce(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof lo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json",...n.headers}};if(n instanceof He.GraphQLError)return{status:200,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/json"}};if(n instanceof Kr)return{status:200,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};break}default:logger.info(`Unsupported accept header, ${s}, defaulting to application/graphql-response+json`);case"application/graphql-response+json":{if(n instanceof lo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json",...n.headers}};if(n instanceof He.GraphQLError)return{status:400,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Kr)return{status:400,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};break}}throw n}},{port:e.port,securePort:e.securePort})}var He,Kr,lo,Cq=se(()=>{He=b(require("graphql"));Fo();za();a(ice,"assertExecutableDefinitionNode");a(Sq,"assertRequestParams");a(NN,"processIntValueNode");a(yq,"processFloatValueNode");a(Rq,"processVariableNode");a(bq,"isObject");a(Aq,"transformObjectIntoQueryCondition");a(oce,"processObjectFieldNode");a(Iq,"processObjectValueNode");a(ace,"processArgumentNode");a(cce,"buildConditionsQuery");a(RS,"fillInFragments");a(wq,"buildSelectQuery");a(lce,"processFieldNode");a(Nq,"processConstValueNode");a(uce,"resolveVariables");a(dce,"executeOperation");a(Tq,"resolver");Kr=class extends Error{static{a(this,"GraphQLQueryingError")}},lo=class extends Error{static{a(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};a(fce,"graphqlQueryingHandler");a(mce,"start")});var Mq=M((ZMe,vq)=>{var Pd=require("validate.js"),Pq=mt(),Ld=(H(),v(z)),{handleHDBError:pce,hdbErrors:hce}=_e(),{HDB_ERROR_MSGS:sr,HTTP_STATUS_CODES:Ece}=hce,ON=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),_ce={STRUCTURE_USER:"structure_user"},Oq=Object.values(Ld.ROLE_TYPES_ENUM),gce="attribute_permissions",Sce="attribute_name",{PERMS_CRUD_ENUM:Dd}=Ld,Tce=[gce,...Object.values(Dd)],Lq=[Dd.READ,Dd.INSERT,Dd.UPDATE],yce=[Sce,...Lq];function Rce(e){let t=ON();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,Dq(e,t)}a(Rce,"addRoleValidation");function bce(e){let t=ON();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,Dq(e,t)}a(bce,"alterRoleValidation");function Ace(e){let t=ON();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Pq.validateObject(e,t)}a(Ace,"dropRoleValidation");var Ice=["operation","role","id","permission","hdb_user","access"];function Dq(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Ice.includes(n[o])||s.push(n[o]);s.length>0&&pr(sr.INVALID_ROLE_JSON_KEYS(s),r);let i=Pq.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{pr(o,r)}),e.permission){let o=wce(e);o&&pr(o,r),Oq.forEach(c=>{e.permission[c]&&!Pd.isBoolean(e.permission[c])&&pr(sr.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(Oq.indexOf(o)<0){if(o===_ce.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let u=0,d=l.length;u<d;u++){let f=l[u];global.hdb_schema[f]||pr(sr.SCHEMA_NOT_FOUND(f),r)}continue}pr(sr.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){pr(sr.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let u=c.tables[l];if(!l||!global.hdb_schema[o][l]){pr(sr.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(u).forEach(d=>{Tce.includes(d)||pr(sr.INVALID_PERM_KEY(d),r,o,l)}),Object.values(Dd).forEach(d=>{Pd.isDefined(u[d])?Pd.isBoolean(u[d])||pr(sr.TABLE_PERM_NOT_BOOLEAN(d),r,o,l):pr(sr.TABLE_PERM_MISSING(d),r,o,l)}),u.attribute_permissions===void 0){pr(sr.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){pr(sr.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}if(u.attribute_permissions){let d=global.hdb_schema[o][l].attributes.map(({attribute:m})=>m),f={read:!1,insert:!1,update:!1};for(let m in u.attribute_permissions){let p=u.attribute_permissions[m];if(Object.keys(p).forEach(E=>{!yce.includes(E)&&E!==Dd.DELETE&&pr(sr.INVALID_ATTR_PERM_KEY(E),r,o,l)}),!Pd.isDefined(p.attribute_name)){pr(sr.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=p.attribute_name;if(!d.includes(h)){pr(sr.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}Lq.forEach(E=>{Pd.isDefined(p[E])?Pd.isBoolean(p[E])||pr(sr.ATTR_PERM_NOT_BOOLEAN(E,h),r,o,l):pr(sr.ATTR_PERM_MISSING(E,h),r,o,l)}),!f.read&&p.read===!0&&(f.read=!0),!f.insert&&p.insert===!0&&(f.insert=!0),!f.update&&p.update===!0&&(f.update=!0)}if(u.read===!1&&f.read===!0||u.insert===!1&&f.insert===!0||u.update===!1&&f.update===!0){let m=`${o}.${l}`;pr(sr.MISMATCHED_TABLE_ATTR_PERMS(m),r,o,l)}}}}return Nce(r)}a(Dq,"customValidate");vq.exports={addRoleValidation:Rce,alterRoleValidation:bce,dropRoleValidation:Ace};function wce(e){let{operation:t,permission:r}=e;if(t===Ld.OPERATIONS_ENUM.ADD_ROLE||t===Ld.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 sr.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Ld.ROLE_TYPES_ENUM.SUPER_USER:Ld.ROLE_TYPES_ENUM.CLUSTER_USER;return sr.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(wce,"validateNoSUPerms");function Nce(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:sr.ROLE_PERMS_ERROR,...e};return pce(new Error,n,Ece.BAD_REQUEST)}else return null}a(Nce,"generateRolePermResponse");function pr(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(pr,"addPermError")});var Jp=M((rUe,Fq)=>{"use strict";var Uq=Vn(),xq=gn(),Cce=Nl(),LN=Mq(),DN=Wo(),tUe=require("uuid").v4,Oce=require("util"),bS=(H(),v(z)),Pce=oe(),vN=xq.searchByValue,Lce=xq.searchByHash,Dce=Oce.promisify(Cce.delete),vce=mi(),Mce=cd(),{hdbErrors:Uce,handleHDBError:Fl}=_e(),{HDB_ERROR_MSGS:Bq,HTTP_STATUS_CODES:Qp}=Uce,{UserEventMsg:MN}=ls();Fq.exports={addRole:xce,alterRole:Bce,dropRole:Fce,listRoles:kce};function PN(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(PN,"scrubRoleDetails");async function xce(e){let t=LN.addRoleValidation(e);if(t)throw t;e=PN(e);let r={schema:"system",table:"hdb_role",attribute:"role",value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await vN(r)||[])}catch(i){throw Fl(i)}if(n&&n.length>0)throw Fl(new Error,Bq.ROLE_ALREADY_EXISTS(e.role),Qp.CONFLICT,void 0,void 0,!0);e.id||(e.id=e.role);let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await Uq.insert(s),DN.signalUserChange(new MN(process.pid)),e=PN(e),e}a(xce,"addRole");async function Bce(e){let t=LN.alterRoleValidation(e);if(t)throw t;e=PN(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await Uq.update(r)}catch(s){throw Fl(s)}if(n&&n?.message==="updated 0 of 1 records")throw Fl(new Error,"Invalid role id",Qp.BAD_REQUEST,void 0,void 0,!0);return await DN.signalUserChange(new MN(process.pid)),e}a(Bce,"alterRole");async function Fce(e){let t=LN.dropRoleValidation(e);if(t)throw Fl(new Error,t,Qp.BAD_REQUEST,void 0,void 0,!0);let r=new Mce(bS.SYSTEM_SCHEMA_NAME,bS.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Lce(r));if(n.length===0)throw Fl(new Error,Bq.ROLE_NOT_FOUND,Qp.NOT_FOUND,void 0,void 0,!0);let s=new vce(bS.SYSTEM_SCHEMA_NAME,bS.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await vN(s)),o=!1;if(Pce.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw Fl(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Qp.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Dce(c),DN.signalUserChange(new MN(process.pid)),`${n[0].role} successfully deleted`}a(Fce,"dropRole");async function kce(){return vN({table:"hdb_role",schema:"system",hash_attribute:"id",attribute:"id",value:"*",get_attributes:["*"]})}a(kce,"listRoles")});var UN={};ye(UN,{start:()=>Gq,startOnMainThread:()=>qce});function Gq({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,kq.parseDocument)(r.toString(),{simpleKeys:!0}).toJSON();for(let s in n){let i=n[s];i.permission||(i={permission:i},i.permission.access&&(i.access=i.permission.access,delete i.permission.access));for(let o in i.permission){if(Hce.includes(o))continue;let c=i.permission[o];c.tables||(i.permission[o]=c={tables:c});for(let l in c.tables){let u=c.tables[l];if(u.read=!!u.read,u.insert=!!u.insert,u.update=!!u.update,u.delete=!!u.delete,u.attributes){let d=[];for(let f in u.attributes){let m=u.attributes[f];m.attribute_name=f,d.push(m)}u.attribute_permissions=d,delete u.attributes}if(u.attribute_permissions){if(!Array.isArray(u.attribute_permissions))throw new Error("attribute_permissions must be an array if defined");for(let d of u.attribute_permissions)d.read=!!d.read,d.insert=!!d.insert,d.update=!!d.update}else u.attribute_permissions=null}}i.role=i.id=s,await Gce(i)}}}async function Gce(e){let t=ct().system.hdb_role;for await(let r of t.search([{attribute:"role",value:e.role}])){let{__createdtime__:n,__updatedtime__:s,...i}=r;return(0,Hq.isEqual)(i,e)?void 0:(e.id=r.id,(0,AS.alterRole)(e))}return(0,AS.addRole)(e)}var AS,kq,Hq,Hce,qce,qq=se(()=>{we();AS=b(Jp()),kq=require("yaml"),Hq=require("lodash"),Hce=["super_user","cluster_user","structure_user"];a(Gq,"start");a(Gce,"ensureRole");qce=Gq});async function IS(e){let t=(0,Kq.pathToFileURL)(e).toString();if($ce)return Xp||(Xp=Vce(Yce)),(await(await Xp).import(t)).namespace;try{return await import(t)}catch(r){try{(await import("internal/util")).default.decorateErrorStack(r)}catch{}throw r}}async function Vce(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Xp=new Compartment({console,Math,Date,fetch:Kce,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Vq.extname)(r)||(r+=".js"),r)},importHook:a(async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){s.Resource=lr,s.tables=Rn,s.databases=Me}};let n=await(0,$q.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),Xp}function Kce(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 Yce(){return{Resource:lr,tables:Rn}}var $q,Vq,Kq,$ce,Xp,xN=se(()=>{Vo();we();$q=require("fs/promises"),Vq=require("path"),Kq=require("url"),$ce=!1;a(IS,"secureImport");a(Vce,"getCompartment");a(Kce,"secureOnlyFetch");a(Yce,"getGlobalVars")});var BN={};ye(BN,{handleApplication:()=>Wce,suppressHandleApplicationWarning:()=>zce});function Yq(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function Wce(e){e.handleEntry(t=>{if(t.entryType!=="file"){e.logger.warn(`jsResource plugin cannot handle entry type ${t.entryType}. Modify the 'files' option in ${e.configFilePath} to only include files.`);return}if(t.eventType!=="add"){e.requestRestart();return}IS(t.absolutePath).then(r=>{let n=(0,wS.dirname)(t.urlPath);Yq(r.default)&&(e.resources.set(n,r.default),e.logger.debug(`Registered root resource: ${n}`)),Wq(e,r,n)}).catch(r=>{e.logger.error(`Failed to load resource module ${t.absolutePath}: ${r}`),e.requestRestart()})})}function Wq(e,t,r){for(let n in t){let s=t[n],i=(0,wS.join)(r,n);Yq(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&Wq(e,s,i)}}var wS,zce,zq=se(()=>{xN();wS=require("path");a(Yq,"isResource");a(Wce,"handleApplication");a(Wq,"recurseForResources");zce=!0});var kN={};ye(kN,{start:()=>jce});function jce({resources:e}){e.set("login",FN),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var FN,jq=se(()=>{Vo();a(jce,"start");FN=class extends lr{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)}}}});function CS(e,t){let r={openapi:Qce,info:{title:"HarperDB HTTP REST interface",version:t$.packageJson.version},servers:[{description:"REST API",url:t}],paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},n=[{basicAuth:[],bearerAuth:[]}],s=a(i=>{if(i.type&&!r.components.schemas[i.type]){r.components.schemas[i.type]={};let o={},c=[];for(let l of i.properties)NS[l.type]?o[l.name]=new GN(NS[l.type],l.type):l.properties?(o[l.name]=new n$(l.type),s(l)):l.elements?.properties&&(o[l.name]=new ele(l.elements.type),s(l.elements)),l.nullable===!1&&c.push(l.name);r.components.schemas[i.type]=new e$(o,!i.sealed,c)}},"includeDefinitionInSchema");for(let[,i]of e){if(!i.path||i.Resource.isError)continue;let{path:o}=i,c=o.split("/").pop(),{attributes:l,sealed:u}=i.Resource,{prototype:d,primaryKey:f="id"}=i.Resource;if(!l&&e.allTypes.has(i.path)){let k=e.allTypes.get(i.path);u=k.sealed,l=k.properties}if(!f)continue;let m={},p=[],h=[];if(l)for(let{type:k,name:j,elements:Y,relationship:ce,definition:de,nullable:te}of l){let ge=de??Y?.definition;ge&&s(ge),te===!1&&h.push(j),ce?k==="array"?m[j]={type:"array",items:{$ref:Vs+Y.type}}:m[j]={$ref:Vs+k}:ge?k==="array"?m[j]={type:"array",items:{$ref:Vs+ge.type}}:m[j]={$ref:Vs+ge.type}:k==="array"?Y.type==="Any"?m[j]={type:"array",items:{format:Y.type}}:m[j]={type:"array",items:new GN(NS[Y.type],Y.type)}:k==="Any"?m[j]={format:k}:m[j]=new GN(NS[k],k),p.push(new qN(j,"query",m[j]))}let E=Object.keys(m),g=new qN(f,"path",{type:"string",format:"ID"});g.required=!0,g.description="primary key of record";let R=new qN("property","path",{enum:E});R.required=!0,r.components.schemas[c]=new e$(m,!u,h);let S=d.post!==Resource.prototype.post||d.update,y=typeof d.put=="function",N=typeof d.get=="function",I=typeof d.delete=="function",$=typeof d.patch=="function",ee=`/${o}/`;r.paths[ee]||(r.paths[ee]={}),S&&(r.paths[ee].post=new Jce(c,n,{200:new vd({$ref:Vs+c},{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}})},"create a new record auto-assigning a primary key")),r.paths[ee].options=new Qq(p,n,{200:new Jq},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),N&&(r.paths[ee].get=new HN(p,n,{200:new vd({type:"array",items:{$ref:Vs+c}})},"search for records by the specified property name and value pairs")),I&&(r.paths[ee].delete=new Zq(p,n,"delete all the records that match the provided query",{204:new Xq}));let G="/"+o+"/{"+f+"}";if(r.paths[G]||(r.paths[G]={}),r.paths[G].options=new Qq(p,n,{200:new Jq},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),N&&(r.paths[G].get=new HN([g],n,{200:new vd({$ref:Vs+c})},"retrieve a record by its primary key")),y&&(r.paths[G].put=new Xce([g],n,c,{200:new vd({$ref:Vs+c})},"create or update the record with the URL path that maps to the record's primary key")),$&&(r.paths[G].patch=new Zce([g],n,c,{200:new vd({$ref:Vs+c})},"patch the record with the URL path that maps to the record's primary key")),I&&(r.paths[G].delete=new Zq([g],n,"delete a record with the given primary key",{204:new Xq})),N&&R.schema.enum.length>0){let k=`/${o}/{${f}}.{property}`;r.paths[k]||(r.paths[k]={}),r.paths[k].get=new HN([g,R],n,{200:new vd({enum:E})},"used to retrieve the specified property of the specified record")}}for(let[,i]of e.allTypes)s(i),i.sealed&&r.components.schemas[i.type].additionalProperties&&(r.components.schemas[i.type].additionalProperties=!1);return r}function Jce(e,t,r,n){this.description=n,this.requestBody={content:{"application/json":{schema:{$ref:Vs+e}}}},this.security=t,this.responses=r}function HN(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Qq(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Jq(){this.description=r$,this.headers={},this.content={}}function vd(e,t){this.description=r$,this.content={"application/json":{schema:e}},this.headers=t}function Xq(){this.description="successfully processed request, no content returned to client"}function Xce(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Vs+r}}}},this.responses=n}function Zce(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Vs+r}}}},this.responses=n}function Zq(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function e$(e,t,r){this.type="object",this.properties=e,this.additionalProperties=t,this.required=r}function GN(e,t){this.type=e,(e==="string"||e==="number"||e==="integer")&&t!=="String"&&(this.format=t)}function n$(e){this.$ref=`#/components/schemas/${e}`}function ele(e){this.type="array",this.items=new n$(e)}function qN(e,t,r){this.name=e,this.in=t,this.schema=r}var t$,Qce,NS,Vs,r$,$N=se(()=>{t$=b(yt()),Qce="3.0.3",NS={Int:"integer",Float:"number",Long:"integer",ID:"string",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer"},Vs="#/components/schemas/",r$="successful operation";a(CS,"generateJsonApi");a(Jce,"Post");a(HN,"Get");a(Qq,"Options");a(Jq,"ResponseOptions200");a(vd,"Response200");a(Xq,"Response204");a(Xce,"Put");a(Zce,"Patch");a(Zq,"Delete");a(e$,"ResourceSchema");a(GN,"Type");a(n$,"Ref");a(ele,"ArrayRef");a(qN,"Parameter")});var i$={};ye(i$,{Request:()=>cc,createReuseportFd:()=>OS});var s$,cc,VN,KN,OS,Zp=se(()=>{s$=require("os"),cc=class{static{a(this,"Request")}#e;#t;_nodeRequest;_nodeResponse;method;url;headers;isWebSocket;user;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new KN(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.#t===void 0&&(this.#t=this._nodeRequest.socket.getPeerCertificate?.(!0)||null),this.#t}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VN(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get hostname(){return this._nodeRequest.headers.host}get httpVersion(){return this._nodeRequest.httpVersion}get isAborted(){return!1}get nodeRequest(){return this._nodeRequest}sendEarlyHints(t,r={}){r.link=t,this._nodeResponse.writeEarlyHints(r)}},VN=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)}},KN=class{static{a(this,"Headers")}asObject;constructor(t){this.asObject=t}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return Object.prototype.hasOwnProperty.call(this.asObject,t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}delete(t){delete this.asObject[t.toLowerCase()]}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,s$.platform)()!="win32"&&(OS=require("node-unix-socket").createReuseportFd)});var LS={};ye(LS,{parseHeaderValue:()=>WN,start:()=>nle});async function rle(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&dg(e);let i=new Gs;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==o$){let g=PS.getMatch(o,n?"sse":"rest");if(!g)return t(e);e.handlerPath=g.path,c=new ui(g.relativeURL),c.async=!0,l=g.Resource}if(l?.isCaching){let g=r["cache-control"];if(g){let R=WN(g);for(let S of R)switch(S.name){case"max-age":e.expiresAt=S.value*1e3+Date.now();break;case"only-if-cached":e.onlyIfCached=!0;break;case"no-cache":e.noCache=!0;break;case"no-store":e.noCacheStore=!0;break;case"stale-if-error":e.staleIfError=!0;break;case"must-revalidate":e.mustRevalidate=!0;break}}}let u=r["x-replicate-to"];if(u){let g=WN(u).map(R=>(R.next?.name==="confirm"&&R.next.value>=0&&(e.replicatedConfirmation=+R.next.value),R.name));e.replicateTo=g.length===1&&+g[0]>=0?+g[0]:g[0]==="*"?void 0:g}r["x-replicate-from"]==="none"&&(e.replicateFrom=!1);let f=await bt(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Bo(r["content-type"],!0)(e.body,e.headers)}catch(g){throw new Md.ClientError(g,400)}if(e.authorize=!0,o===o$&&s==="GET"){if(e?.user?.role?.permission?.super_user)return CS(PS,`${e.protocol}://${e.hostname}`);throw new Md.ServerError("Forbidden",403)}switch(c.checkPermission=e.user?.role?.permission??{},s){case"GET":case"HEAD":return l.get(c,e);case"POST":return l.post(c,e.data,e);case"PUT":return l.put(c,e.data,e);case"DELETE":return l.delete(c,e);case"PATCH":return l.patch(c,e.data,e);case"OPTIONS":i.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(c,e.data,e);case"COPY":return l.copy(c,r.destination,e);case"MOVE":return l.move(c,r.destination,e);case"BREW":throw new Md.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Md.ServerError(`Method ${s} is not recognized`,501)}}),m=200,p=e.lastModified;if(f==null)m=s==="GET"||s==="HEAD"?404:204,YN.lastModified&&isFinite(p)&&i.setIfNone("Last-Modified",new Date(p).toUTCString());else if(f.status>0&&f.headers){let g=$G(f.headers,i);return f.headers!==g&&(f.headers=g),f.data!==void 0&&(f.body=xm(f.data,e,f)),f}else if(isFinite(p)){tle[0]=p;let g=String.fromCharCode(34,(sn[0]&63)+62,(sn[0]>>6)+(sn[1]<<2&63)+62,(sn[1]>>4)+(sn[2]<<4&63)+62,(sn[2]>>2)+62,(sn[3]&63)+62,(sn[3]>>6)+(sn[4]<<2&63)+62,(sn[4]>>4)+(sn[5]<<4&63)+62,(sn[5]>>2)+62,(sn[6]&63)+62,(sn[6]>>6)+(sn[7]<<2&63)+62,34),R=r["if-none-match"];R&&g==R?(f?.onDone&&f.onDone(),m=304,f=void 0):i.setIfNone("ETag",g),YN.lastModified&&i.setIfNone("Last-Modified",new Date(p).toUTCString())}e.createdResource&&(m=201),e.newLocation&&i.setIfNone("Location",e.newLocation);let h={status:m,headers:i,body:void 0},E=e.loadedFromSource??f?.wasLoadedFromSource?.();return E!==void 0&&(h.wasCacheMiss=E,!E&&isFinite(p)&&i.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||p))/1e3))),f!==void 0&&(h.body=xm(f,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?gi.warn(o):gi.info(o):gi.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.setIfNone("Allow",o.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:o.statusCode||500,headers:i,body:void 0};return c.body=xm(o.contentType?o:l$(o),e,c),c}}function nle(e){YN=e,e.includeExpensiveRecordCountEstimates&&(cc.prototype.includeExpensiveRecordCountEstimates=!0),!a$&&(a$=!0,PS=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return rle(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{eh++;let s=new ns;c$||(c$=!0,Qm(l=>{eh>0&&l.push({metric:"ws-connections",connections:eh,byThread:!0})}));let i;t.on("error",l=>{i=!0,gi.warn(l)});let o;t.on("message",a(function(u){o||(o=Bo(r.requestedContentType??r.headers.asObject["content-type"],!1));let d=o(u);Ve(u.length,"bytes-received",r.handlerPath,"message","ws"),s.push(d)},"message"));let c;t.on("close",()=>{eh--,tn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),u=PS.getMatch(l,"ws");if(tn(!!u,"connection","ws","connect"),u){r.handlerPath=u.path,Ve(h=>({count:h.count,total:eh}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let d=new ui(u.relativeURL);d.checkPermission=r.user?.role?.permission??{};let f=u.Resource;c=(await bt(r,()=>f.connect(d,s,r)))[Symbol.asyncIterator]();let p;for(;!(p=await c.next()).done;){let h=await xo(p.value,r);t.send(h),Ve(h.length,"bytes-sent",r.handlerPath,"message","ws"),t._socket.writableNeedDrain&&await new Promise(E=>t._socket.once("drain",E))}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){l.statusCode?l.statusCode===500?gi.warn(l):gi.info(l):gi.error(l),t.close(sle[l.statusCode]||1011,l$(l))}t.close()},e))}function WN(e){return e.trim().split(",").map(t=>{let r,n=t.trim().split(";"),s;for(;s=n.pop();)if(s.includes("=")){let[i,o]=s.trim().split("=");i=i.trim(),o&&(o=o.trim()),r={name:i.toLowerCase(),value:o,next:r}}else r={name:s.toLowerCase(),next:r};return r})}var gi,Md,l$,sn,tle,YN,o$,a$,PS,c$,eh,sle,u$=se(()=>{Fo();is();gi=b(J()),Md=b(_e());fg();Uu();Ga();kp();$N();Zp();pg();({errorToString:l$}=gi),sn=new Uint8Array(8),tle=new Float64Array(sn.buffer,0,1),YN={},o$="openapi";a(rle,"http");eh=0;a(nle,"start");sle={401:3e3,403:3003};a(WN,"parseHeaderValue")});var zN=M((CUe,f$)=>{var{recordAction:DS,recordActionBinary:d$}=(is(),v(ng)),ile=require("fastify-plugin"),ole=200;f$.exports=ile(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(),l=s.request.routeOptions,u,d,f;l.config?.isOperation?(u=n.body?.operation,d="operation"):(u=l.url,d="fastify-route",f=l.method),DS(o,"duration",u,f,d),d$(s.raw.statusCode<400,"success",u,f,d),d$(1,"response_"+s.raw.statusCode,u,f,d);let m=ole;i?.pipe?(i.on("data",g=>{m+=g.length}),i.on("end",()=>{DS(performance.now()-c,"transfer",u,f,d),DS(m,"bytes-sent",u,f,d)})):(m+=i?.length||0,DS(m,"bytes-sent",u,f,d));let p=o.toFixed(3),h=s.getHeader("Server-Timing"),E=`db;dur=${p}`;s.header("Server-Timing",h?`${h}, ${E}`:E)}),r()},{name:"hdb-request-time"})});var p$=M((OUe,m$)=>{var ale=mt(),cle={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};m$.exports=function(e){return ale.validateObject(e,cle)}});var vS=M((PUe,h$)=>{"use strict";var lle=(H(),v(z)).OPERATIONS_ENUM,jN=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=lle.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};h$.exports=jN});var nh={};ye(nh,{createTokens:()=>XN,getJWTRSAKeys:()=>FS,refreshOperationToken:()=>ZN,validateOperationToken:()=>eC,validateRefreshToken:()=>kS});async function FS(){if(MS)return MS;try{let e=th.default.join(rh.default.getHdbBasePath(),xb),t=await US.default.readFile(th.default.join(e,Sm.JWT_PASSPHRASE_NAME),"utf8"),r=await US.default.readFile(th.default.join(e,Sm.JWT_PRIVATE_KEY_NAME),"utf8");return MS={publicKey:await US.default.readFile(th.default.join(e,Sm.JWT_PUBLIC_KEY_NAME),"utf8"),privateKey:r,passphrase:t},MS}catch(e){throw BS.default.error(e),new Si.ClientError(xd.NO_ENCRYPTION_KEYS,Ud.INTERNAL_SERVER_ERROR)}}async function XN(e){let t=(0,QN.validateBySchema)(e,uo.default.object({username:uo.default.string().optional(),password:uo.default.string().optional(),role:uo.default.string().optional(),expires_in:uo.default.alternatives(uo.default.string(),uo.default.number()).optional()}));if(t)throw new Si.ClientError(t.message);let r;try{let f=e.bypass_auth!==!0;!e.username&&!e.password&&(e.username=e.hdb_user?.username,f=!1),r=await(0,JN.findAndValidateUser)(e.username,e.password,f)}catch(f){throw BS.default.error(f),new Si.ClientError(xd.INVALID_CREDENTIALS,Ud.UNAUTHORIZED)}if(!r)throw new Si.ClientError(xd.INVALID_CREDENTIALS,Ud.UNAUTHORIZED);let n=!1,s=!1;r.role?.permission&&(n=r.role.permission.super_user===!0,s=r.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s};e.role&&(i.role=e.role);let o=await FS(),c=await Bd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:e.expires_in??T$,algorithm:xS,subject:Fd.OPERATION}),l=await Bd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:ule,algorithm:xS,subject:Fd.REFRESH}),u=Ow(l,$r.SHA256);if((await(0,E$.update)(new _$.default(_m,Du.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new Si.ClientError(xd.REFRESH_TOKEN_SAVE_FAILED,Ud.INTERNAL_SERVER_ERROR);return g$.default.signalUserChange(new S$.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function ZN(e){let t=(0,QN.validateBySchema)(e,uo.default.object({refresh_token:uo.default.string().required()}).required());if(t)throw new Si.ClientError(t.message);let{refresh_token:r}=e;await kS(r);let n=await FS(),s=await Bd.default.decode(r);return{operation_token:await Bd.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:T$,algorithm:xS,subject:Fd.OPERATION})}}async function eC(e){return y$(e,Fd.OPERATION)}async function kS(e){return y$(e,Fd.REFRESH)}async function y$(e,t){try{let r=await FS(),n=await Bd.default.verify(e,r.publicKey,{algorithms:xS,subject:t});if(n.role)throw new Error("Invalid token");let s=await(0,JN.findAndValidateUser)(n.username,void 0,!1);if(t===Fd.REFRESH&&!Pw(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw BS.default.warn(r),r?.name==="TokenExpiredError"?new Si.ClientError(xd.TOKEN_EXPIRED,Ud.FORBIDDEN):new Si.ClientError(xd.INVALID_TOKEN,Ud.UNAUTHORIZED)}}var Bd,US,th,uo,QN,Si,BS,JN,E$,_$,g$,S$,rh,Ud,xd,T$,ule,xS,Fd,MS,kd=se(()=>{Bd=b(require("jsonwebtoken")),US=b(require("fs-extra")),th=b(require("node:path")),uo=b(require("joi")),QN=b(mt());H();Si=b(_e()),BS=b(J());Dw();JN=b(Es()),E$=b(Vn()),_$=b(vS()),g$=b(Wo()),S$=b(ls()),rh=b(me()),{HTTP_STATUS_CODES:Ud,AUTHENTICATION_ERROR_MSGS:xd}=Si.hdbErrors;rh.default.initSync();T$=rh.default.get(F.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",ule=rh.default.get(F.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",xS="RS256",Fd={OPERATION:"operation",REFRESH:"refresh"};a(FS,"getJWTRSAKeys");a(XN,"createTokens");a(ZN,"refreshOperationToken");a(eC,"validateOperationToken");a(kS,"validateRefreshToken");a(y$,"validateToken")});var tC=M((UUe,A$)=>{"use strict";var dle=p$(),Hd=require("passport"),fle=require("passport-local").Strategy,mle=require("passport-http").BasicStrategy,ple=require("util"),hle=Es(),b$=ple.callbackify(hle.findAndValidateUser),MUe=Jr(),Ele=(H(),v(z)),R$=(kd(),v(nh));Hd.use(new fle(function(e,t,r){b$(e,t,r)}));Hd.use(new mle(function(e,t,r){b$(e,t,r)}));Hd.serializeUser(function(e,t){t(null,e)});Hd.deserializeUser(function(e,t){t(null,e)});function _le(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":Hd.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===Ele.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?R$.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):R$.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Hd.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(_le,"authorize");function gle(e,t){let r=dle(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(gle,"checkPermissions");A$.exports={authorize:_le,checkPermissions:gle}});var aC=M((kUe,C$)=>{var $S=require("clone"),VS=mt(),Sle=oe(),GS=(H(),v(z)),BUe=J(),rC=require("fs"),sC=require("joi"),{string:qS}=sC.types(),{hdbErrors:Tle,handleHDBError:HS}=_e(),{HDB_ERROR_MSGS:FUe,HTTP_STATUS_CODES:nC}=Tle,{commonValidators:Gd}=Qi(),I$=" is required",yle=["insert","update","upsert"],iC={database:{presence:!1,format:Gd.schema_format,length:Gd.schema_length},schema:{presence:!1,format:Gd.schema_format,length:Gd.schema_length},table:{presence:!0,format:Gd.schema_format,length:Gd.schema_length},action:{inclusion:{within:yle,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Rle={schema:qS.required(),table:qS.required(),action:qS.valid("insert","update","upsert")},{AWS_ACCESS_KEY:ble,AWS_SECRET:Ale,AWS_BUCKET:Ile,AWS_FILE_KEY:wle,REGION:Nle}=GS.S3_BUCKET_AUTH_KEYS,Cle={s3:{presence:!0},[`s3.${ble}`]:{presence:!0,type:"String"},[`s3.${Ale}`]:{presence:!0,type:"String"},[`s3.${Ile}`]:{presence:!0,type:"String"},[`s3.${wle}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Nle}`]:{presence:!0,type:"String"}},w$=$S(iC);w$.data.presence={message:I$};var N$=$S(iC);N$.file_path.presence={message:I$};var Ole=Object.assign($S(iC),Cle),oC=$S(Rle);oC.csv_url=qS.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();oC.passthrough_headers=sC.object();function Ple(e){let t=VS.validateObject(e,w$);return KS(e,t)}a(Ple,"dataObject");function Lle(e){let t=VS.validateBySchema(e,sC.object(oC));return KS(e,t)}a(Lle,"urlObject");function Dle(e){let t=VS.validateObject(e,N$);return KS(e,t)}a(Dle,"fileObject");function vle(e){let t=VS.validateObject(e,Ole);return KS(e,t)}a(vle,"s3FileObject");function KS(e,t){if(!t){let r=Sle.checkGlobalSchemaTable(e.schema,e.table);if(r)return HS(new Error,r,nC.BAD_REQUEST);if(e.operation===GS.OPERATIONS_ENUM.CSV_FILE_LOAD)try{rC.accessSync(e.file_path,rC.constants.R_OK|rC.constants.F_OK)}catch(n){return n.code===GS.NODE_ERROR_CODES.ENOENT?HS(n,`No such file or directory ${n.path}`,nC.BAD_REQUEST):n.code===GS.NODE_ERROR_CODES.EACCES?HS(n,`Permission denied ${n.path}`,nC.BAD_REQUEST):HS(n)}}return t}a(KS,"postValidateChecks");C$.exports={dataObject:Ple,urlObject:Lle,fileObject:Dle,s3FileObject:vle}});var cC=M((GUe,O$)=>{"use strict";var sh=J(),YS=(H(),v(z));async function Mle(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===YS.OPERATIONS_ENUM.INSERT||t.operation===YS.OPERATIONS_ENUM.UPDATE||t.operation===YS.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===YS.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(sh.info(i.message),i):i.http_resp_msg?(sh.error(`Error calling operation: ${e.name}`),sh.error(i.http_resp_msg),i):(sh.error(`Error calling operation: ${e.name}`),sh.error(i),i)}}a(Mle,"callOperationFunctionAsAwait");O$.exports={callOperationFunctionAsAwait:Mle}});var lC=M(($Ue,L$)=>{"use strict";var{S3:Ule,GetObjectCommand:xle}=require("@aws-sdk/client-s3");L$.exports={getFileStreamFromS3:Ble,getS3AuthObj:P$};async function Ble(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await P$(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new xle(r))).Body}a(Ble,"getFileStreamFromS3");function P$(e,t,r){return new Ule({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(P$,"getS3AuthObj")});var v$=M((KUe,D$)=>{"use strict";var uC=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}},dC=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};D$.exports={BulkLoadFileObject:uC,BulkLoadDataObject:dC}});var U$=M((WUe,M$)=>{"use strict";var fC=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}};M$.exports=fC});var B$=M((jUe,x$)=>{"use strict";var mC=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};x$.exports=mC});var hC=M((JUe,k$)=>{"use strict";var F$=U$(),Fle=B$(),{HDB_ERROR_MSGS:kle}=Jr(),pC=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=kle.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 F$(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Fle(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new F$(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}};k$.exports=pC});var kl=M((exe,$$)=>{"use strict";var ZUe=gn(),ih=J(),{validateBySchema:H$}=mt(),Zo=require("joi"),Hle=no(),WS=oe(),{handleHDBError:zS,hdbErrors:Gle,ClientError:G$}=_e(),{HDB_ERROR_MSGS:jS,HTTP_STATUS_CODES:EC}=Gle,q$=me();q$.initSync();var{getDatabases:_C}=(we(),v(ft)),qle=require("fs-extra"),$le=(H(),v(z));$$.exports={describeAll:Vle,describeTable:QS,describeSchema:Kle};async function Vle(e={}){try{let t=WS.isEmptyOrZeroLength(e),r=!!e.bypass_auth,n,s;!t&&!r&&(n=e.hdb_user?.role?.permission,s=n?.super_user||n?.cluster_user);let i=_C(),o={},c={},l=[],u=e?.exact_count,d=e?.include_computed;for(let m in i){o[m]=!0,!t&&!s&&!r&&(c[m]=e.hdb_user?.role?.permission[m]?.describe);let p=i[m];for(let h in p)try{let E;if(t||s||r)E=await QS({schema:m,table:h,exact_count:u,include_computed:d});else if(n&&n[m].describe&&n[m].tables[h].describe){let g=n[m].tables[h].attribute_permissions;E=await QS({schema:m,table:h,exact_count:u,include_computed:d},g)}E&&l.push(E)}catch(E){ih.error(E)}}let f={};for(let m in l)t||s||r?(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]):c[l[m].schema]&&(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]);for(let m in o)t||s||r?f[m]={}:c[m]&&(f[m]={});return f}catch(t){return ih.error("Got an error in describeAll"),ih.error(t),zS(new Error,jS.DESCRIBE_ALL_ERR)}}a(Vle,"describeAll");async function QS(e,t){WS.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=H$(e,Zo.object({database:Zo.string(),table:Zo.string().required(),exact_count:Zo.boolean().strict(),include_computed:Zo.boolean().strict()}));if(i)throw new G$(i.message);let c=_C()[r];if(!c)throw zS(new Error,jS.SCHEMA_NOT_FOUND(e.schema),EC.NOT_FOUND);let l=c[n];if(!l)throw zS(new Error,jS.TABLE_NOT_FOUND(e.schema,e.table),EC.NOT_FOUND);function u(p){(!p.computed||e.include_computed)&&d.push({attribute:p.attribute,type:p.type,elements:p.elements?.type,indexed:p.indexed,is_primary_key:p.isPrimaryKey,assigned_created_time:p.assignCreatedTime,assigned_updated_time:p.assignUpdatedTime,nullable:p.nullable,computed:p.computed?!0:void 0,properties:p.properties?p.properties.map(h=>({type:h.type,name:h.name})):void 0})}a(u,"pushAtt");let d=[];if(s){let p={};s.forEach(h=>{h.describe&&(p[h.attribute_name]=!0)}),l.attributes.forEach(h=>{p[h.name]&&u(h)})}else l.attributes?.forEach(p=>u(p));let f;try{f=(await qle.stat(l.primaryStore.env.path)).size}catch(p){ih.warn("unable to get database size",p)}let m={schema:r,name:l.tableName,hash_attribute:l.attributes.find(p=>p.isPrimaryKey||p.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:d,db_size:f};l.replicate!==void 0&&(m.replicate=l.replicate),l.expirationMS!==void 0&&(m.expiration=l.expirationMS/1e3+"s"),l.sealed!==void 0&&(m.sealed=l.sealed),l.sources?.length>0&&(m.sources=l.sources.map(p=>p.name).filter(p=>p&&p!=="NATSReplicator"&&p!=="Replicator")),q$.get($le.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(m.clustering_stream_name=Hle.createNatsTableStreamName(m.schema,m.name));try{let p=await l.getRecordCount({exactCount:!!e.exact_count});m.record_count=p.recordCount,m.table_size=l.getSize(),m.db_audit_size=l.getAuditSize(),m.estimated_record_range=p.estimatedRange;let h=l.auditStore;if(h)for(let E of h.getKeys({reverse:!0,limit:1}))m.last_updated_record=E[0];if(!m.last_updated_record&&l.indices.__updatedtime__)for(let E of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))m.last_updated_record=E}catch(p){ih.warn(`unable to stat table dbi due to ${p}`)}return m}a(QS,"descTable");async function Kle(e){WS.transformReq(e);let t=H$(e,Zo.object({database:Zo.string(),exact_count:Zo.boolean().strict(),include_computed:Zo.boolean().strict()}));if(t)throw new G$(t.message);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=_C()[n];if(!i)throw zS(new Error,jS.SCHEMA_NOT_FOUND(e.schema),EC.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),WS.isEmpty(l)||l.describe){let u=await QS({schema:e.schema,table:c,exact_count:e.exact_count,include_computed:e.include_computed},l?l.attribute_permissions:null);u&&(o[u.name]=u)}}return o}a(Kle,"describeSchema")});var z$=M((rxe,W$)=>{"use strict";var Yle=kl(),{hdbErrors:V$}=_e(),{getDatabases:K$}=(we(),v(ft));W$.exports={checkSchemaExists:Y$,checkSchemaTableExists:Wle,schemaDescribe:Yle};async function Y$(e){if(!K$()[e])return V$.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Y$,"checkSchemaExists");async function Wle(e,t){let r=await Y$(e);if(r)return r;if(!K$()[e][t])return V$.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Wle,"checkSchemaTableExists")});function gC(e){let t=e.get(JS),r=t?(0,qd.unpack)(t):null;r||(r={remoteNameToId:{}});let n=tt(),s=!1;r.nodeName=tt();let i=r.remoteNameToId;if(i[n]!==0){let o=0,c;for(let l in i){let u=i[l];u===0?c=l:u>o&&(o=u)}if(c){o++,i[c]=o;let l=[Symbol.for("seq"),o];e.rootStore.dbisDb.transactionSync(()=>{e.rootStore.dbisDb.get(l)||e.rootStore.dbisDb.putSync(l,{seqId:ah(e)??1,nodes:[]})})}i[n]=0,e.putSync(JS,(0,qd.pack)(r))}return r}function oh(e){return gC(e).remoteNameToId}function Q$(e,t){let r=gC(t),n=r.remoteNameToId,s=new Map,i=!1;for(let o in e){let c=e[o],l=n[o];if(l==null){let u=0;for(let d in n){let f=n[d];f>u&&(u=f)}l=u+1,n[o]=l,i=!0}s.set(c,l)}return i&&t.putSync(JS,(0,qd.pack)(r)),s}function XS(e,t){let r=gC(t),n=r.remoteNameToId,s=n[e];if(s==null){let i=0;for(let o in n){let c=n[o];c>i&&(i=c)}s=i+1,n[e]=s,t.putSync(JS,(0,qd.pack)(r))}return j$.trace?.("The remote node name map",e,n,s),s}var j$,qd,JS,SC=se(()=>{j$=b(wr());Ss();qd=require("msgpackr"),JS=Symbol.for("remote-ids");a(gC,"getIdMappingRecord");a(oh,"exportIdMapping");a(Q$,"remoteToLocalNodeId");a(XS,"getIdOfRemoteNode")});var rV={};ye(rV,{commitsAwaitingReplication:()=>Vd,getHDBNodeTable:()=>Ht,getReplicationSharedStatus:()=>Kd,iterateRoutes:()=>lh,shouldReplicateToNode:()=>ch,subscribeToNodeUpdates:()=>Yd});function Ht(){return J$||(J$=Xe({table:"hdb_nodes",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"},{attribute:"ca"},{attribute:"ca_info"},{attribute:"replicates"},{attribute:"revoked_certificates"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]}))}function Kd(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(64),n&&{callback:n}))}function Yd(e){Ht().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;tV.debug?.("adding node",n,"on node",tt()," on process",process.pid),server.nodes=server.nodes.filter(i=>i.name!==n),r.type==="put"&&n!==tt()&&(r.value?server.nodes.push(r.value):console.error("Invalid node update event",r));let s=new Map;for await(let i of Ht().search({}))if(i.shard!=null){let o=s.get(i.shard);o||s.set(i.shard,o=[]),o.push(i)}server.shards=s,(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function ch(e,t){return(e.replicates===!0||e.replicates?.sends)&&databases[t]&&Ht().primaryStore.get(tt())?.replicates||e.subscriptions?.some(r=>(r.database||r.schema)===t&&r.subscribe)}function zle(){Yd(e=>{lc({},(t,r)=>{let n=e.name,s=X$.get(n);if(s||X$.set(n,s=new Map),s.has(r))return;let i;for(let o in t)if(i=t[o].auditStore,i)break;if(i){let o=Kd(i,r,n,()=>{let c=o[0],l=o.lastTime;for(let{txnTime:u,onConfirm:d}of Vd.get(r)||[])u>l&&u<=c&&d();o.lastTime=c});o.lastTime=0,s.set(r,o)}})})}function*lh(e){for(let t of e.routes||[]){let r=t.url,n;if(typeof t=="string"?t.includes("://")?r=t:n=t:n=t.hostname??t.host,n&&!r){let s=$d.default.get(F.REPLICATION_SECUREPORT)??(!$d.default.get(F.REPLICATION_PORT)&&$d.default.get(F.OPERATIONSAPI_NETWORK_SECUREPORT)),i;(i=n.match(/:(\d+)$/)?.[1])?n=n.slice(0,-i[0].length-1):t.port?i=t.port:i=s||$d.default.get(F.REPLICATION_PORT)||$d.default.get(F.OPERATIONSAPI_NETWORK_PORT);let o=i?.lastIndexOf?.(":");o>0&&(i=+i.slice(o+1).replace(/[\[\]]/g,"")),r=(s?"wss://":"ws://")+n+":"+i}if(!r){Z$.isMainThread&&console.error("Invalid route, must specify a url or host (with port)");continue}yield{replicates:!t.subscriptions,url:r,subscription:t.subscriptions,routes:t.routes,startTime:t.startTime,revoked_certificates:t.revokedCertificates}}}var Z$,eV,$d,tV,J$,X$,Vd,Wd=se(()=>{we();Ss();Pm();Z$=require("worker_threads"),eV=b(_e()),$d=b(me());H();tV=b(wr());server.nodes=[];a(Ht,"getHDBNodeTable");a(Kd,"getReplicationSharedStatus");a(Yd,"subscribeToNodeUpdates");a(ch,"shouldReplicateToNode");X$=new Map;BU((e,t,r)=>{if(r>server.nodes.length)throw new eV.ClientError(`Cannot confirm replication to more nodes (${r}) than are in the network (${server.nodes.length})`);Vd||(Vd=new Map,zle());let n=Vd.get(e);return n||(n=[],Vd.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:a(()=>{++i===r&&s()},"onConfirm")})})});a(zle,"startSubscriptionToReplications");a(lh,"iterateRoutes")});var lV={};ye(lV,{connectedToNode:()=>Hl,disconnectedFromNode:()=>jd,ensureNode:()=>ea,requestClusterStatus:()=>cV,startOnMainThread:()=>TC});async function TC(e){let t=0,r=ct();for(let o of Object.getOwnPropertyNames(r)){let c=r[o];for(let l in c){let u=c[l];if(u.auditStore){ZS.set(o,ah(u.auditStore));break}}}Ti.whenThreadsStarted.then(async()=>{let o=[];for await(let u of r.system.hdb_nodes?.search([])||[])o.push(u);let c=tt();function l(){let u=Ht().primaryStore.get(c);if(u!==null){let d=e.url??uc();if(u===void 0||u.url!==d||u.shard!==e.shard)return ea(c,{name:c,url:d,shard:e.shard,replicates:!0})}}a(l,"ensureThisNode"),Ht().primaryStore.get(c)&&l();for(let u of lh(e))try{let d=!u.subscriptions;if(d&&await l(),d&&u.replicates==null&&(u.replicates=!0),nV.push(u),o.find(f=>f.url===u.url))continue;s(u)}catch(d){console.error(d)}Yd(s)});let n;function s(o,c=o?.name){let l=tt()&&c===tt()||uc()&&o?.url===uc();if(l){let m=!!o?.replicates;if(n!==void 0&&n!==m)for(let p of Ht().search([]))p.replicates&&p.name!==c&&s(p,p.name);n=m}if(ot.trace("Setting up node replication for",o),!o){for(let[m,p]of fo){let h;for(let[E,{worker:g,nodes:R}]of p){let S=R[0];if(S&&S.name==c){h=!0;for(let[y,{worker:N}]of p)p.delete(y),ot.warn("Node was deleted, unsubscribing from node",c,y,m),N?.postMessage({type:"unsubscribe-from-node",node:c,nodes:R,database:y,url:m});break}}if(h){fo.get(m).iterator.remove(),fo.delete(m);return}}return}if(l)return;if(!o.url){ot.info(`Node ${o.name} is missing url`);return}let u=fo.get(o.url);if(u&&u.iterator.remove(),!(o.replicates===!0||o.replicates?.sends)&&!o.subscriptions?.length&&!u)return;if(ot.info(`Added node ${o.name} at ${o.url} for process ${tt()}`),o.replicates&&o.subscriptions&&(o={...o,subscriptions:null}),o.name){for(let[m,p]of zd)if(o.url===p.url){zd.delete(m);break}zd.set(o.name,o)}let d=ct();if(u||(u=new Map,fo.set(o.url,u)),u.iterator=lc(e,(m,p,h)=>{h?f(p,!0):f(p,!1)}),o.subscriptions)for(let m of o.subscriptions){let p=m.database||m.schema;d[p]||(ot.warn(`Database ${p} not found for node ${o.name}, making a subscription anyway`),f(p,!1))}function f(m,p){ot.trace("Setting up replication for database",m,"on node",o.name);let h=u.get(m),E,g=[{replicateByDefault:p,...o}];ZS.has(m)&&uh.default.get(F.REPLICATION_FAILOVER)&&(g.push({replicateByDefault:p,name:tt(),startTime:ZS.get(m),endTime:Date.now(),replicates:!0}),ZS.delete(m));let R=ch(o,m),S=Ti.workers.filter(y=>y.name==="http");if(h){if(E=h.worker,h.nodes=g,R)return}else R&&(t=t%S.length,E=S[t++],E||ot.warn("No http workers available to subscribe to node",o.name,o.url),u.set(m,{worker:E,nodes:g,url:o.url}),E?.on("exit",()=>{u.get(m)?.worker===E&&(u.delete(m),f(m,p))}));if(R){let y=jle.HDB_LEADER_URL??process.env.HDB_LEADER_URL??nV[0]?.url,N=y?new URL(y).hostname:Array.from(Ht().primaryStore.getKeys({}).filter(I=>I!==tt()))[0];ot.warn(`Setting up subscription with leader ${N} for node ${g[0].name}`),g[0].isLeader=!N||g[0].name===N,setTimeout(()=>{let I={...g[0],type:"subscribe-to-node",database:m,nodes:g};E?E.postMessage(I):dh(I)},Qle)}else{ot.info("Node no longer should be used, unsubscribing from node",{replicates:o.replicates,databaseName:m,node:o,subscriptions:o.subscriptions,hasDatabase:!!d[m],thisReplicates:Ht().primaryStore.get(tt())?.replicates}),Ht().primaryStore.get(tt())?.replicates||(n=!1,ot.info("Disabling replication, this node name",tt(),Ht().primaryStore.get(tt()),m));let y={type:"unsubscribe-from-node",database:m,url:o.url,name:o.name,nodes:g};E?E.postMessage(y):tT(y)}}a(f,"onDatabase")}a(s,"onNodeUpdate"),jd=a(function(o){try{ot.info("Disconnected from node",o.name,o.url,"finished",!!o.finished);let c=Array.from(zd.keys()),l=c.sort(),u=l.indexOf(o.name||yi(o.url));if(u===-1){ot.warn("Disconnected node not found in node map",o.name,c);return}let d=fo.get(o.url),f=d?.get(o.database);if(!f){ot.warn("Disconnected node not found in replication map",o.database,d);return}if(f.connected=!1,o.finished||!uh.default.get(F.REPLICATION_FAILOVER))return;let m=f.nodes[0];if(!(m.replicates===!0||m.replicates?.sends||m.subscriptions?.length))return;let p=m.shard,h=(u+1)%l.length;for(;u!==h;){let E=l[h],g=zd.get(E);d=fo.get(g.url);let R=d?.get(o.database);if(!R||R.connected===!1||R.nodes[0].shard!==p){h=(h+1)%l.length;continue}let{nodes:S}=R,y=!1;for(let N of f.nodes){if(S.some(I=>I.name===N.name)){ot.info(`Disconnected node is already failing over to ${E} for ${o.database}`);continue}N.endTime<Date.now()||(S.push(N),ot.info(`Failing over ${o.database} from ${o.name} to ${E}`),i(N,o.database,R.nodes[0]),y=!0)}f.nodes=[f.nodes[0]],y||ot.info(`Disconnected node ${o.name} has no nodes to fail over to ${E}`);return}ot.warn("Unable to find any other node to fail over to",o.name,o.url)}catch(c){ot.error("Error failing over node",c)}},"disconnectedFromNode"),Hl=a(function(o){let c=fo.get(o.url),l=c?.get(o.database);if(!l){ot.warn("Connected node not found in replication map, this may be because the node is being removed",o.database,c);return}l.connected=!0,l.latency=o.latency;let u=l.nodes[0];if(!u){ot.warn("Newly connected node has no node subscriptions",o.database,l);return}if(!u.name){ot.debug("Connected node is not named yet",o.database,l);return}if(!uh.default.get(F.REPLICATION_FAILOVER))return;l.nodes=[u];let d=!1;for(let f of fo.values()){let m=f.get(o.database);if(!m||m==l)continue;let{worker:p,nodes:h,connected:E}=m;if(h)if(E===!1&&h[0].shard===u.shard&&node.url===u.url)for(let g of h)i(g,o.database);else{let g=h.filter(R=>{if(R)return R.name===u.name&&R.worker?(R.worker.postMessage({type:"unsubscribe-to-node",database:o.database,url:o.url,nodes:[R]}),!1):!0});g.length<h.length&&(m.nodes=g)}}},"connectedToNode");function i(o,c,l=o){let u=Ti.workers.filter(f=>f.name==="http");t=t%u.length;let d=u[t++];Object.defineProperty(o,"worker",{value:d,configurable:!0}),d?d.postMessage({url:l.url,name:l.name,type:"subscribe-to-node",database:c,nodes:[o]}):dh({url:l.url,name:l.name,database:c,nodes:[o]})}a(i,"connectToNextWorker"),(0,Ti.onMessageByType)("disconnected-from-node",jd),(0,Ti.onMessageByType)("connected-to-node",Hl),(0,Ti.onMessageByType)("request-cluster-status",cV)}function cV(e,t){let r=[];for(let[n,s]of zd)try{let i=fo.get(s.url);ot.info("Getting cluster status for",n,s.url,"has dbs",i?.size);let o=[];if(i){for(let[l,{worker:u,connected:d,nodes:f,latency:m}]of i)o.push({database:l,connected:d,latency:m,threadId:u?.threadId,nodes:f.filter(p=>!(p.endTime<Date.now())).map(p=>p.name)});let c=iV(s);c.database_sockets=o,delete c.ca,delete c.node_name,delete c.__updatedtime__,delete c.__createdtime__,r.push(c)}}catch(i){ot.warn("Error getting cluster status for",s?.url,i)}return t?.postMessage({type:"cluster-status",connections:r}),{connections:r}}async function ea(e,t){let r=Ht();e=e??yi(t.url),t.name=e;try{if(t.ca){let s=new oV.X509Certificate(t.ca);t.ca_info={issuer:s.issuer.replace(/\n/g," "),subject:s.subject.replace(/\n/g," "),subjectAltName:s.subjectAltName,serialNumber:s.serialNumber,validFrom:s.validFrom,validTo:s.validTo}}}catch(s){ot.error("Error parsing replication CA info for hdb_nodes table",s.message)}let n=r.primaryStore.get(e);if(ot.debug(`Ensuring node ${e} at ${t.url}, existing record:`,n,"new record:",t),!n)await r.patch(t);else{t.replicates&&!uh.default.get(F.CLUSTERING_ENABLED)&&(t.subscriptions=null);for(let s in t)if(n[s]!==t[s]&&s==="subscriptions"&&t[s]&&n[s]){let i=[],o=iV(n[s]);for(let c of t[s]){let l=!1;for(let u of o)if((c.database??c.schema)===(u.database??u.schema)&&c.table===u.table){u.publish=c.publish,u.subscribe=c.subscribe,l=!0;break}l||i.push(c)}t.subscriptions=[...o,...i];break}if(Array.isArray(t.revoked_certificates)){let s=n.revoked_certificates||[];t.revoked_certificates=[...new Set([...s,...t.revoked_certificates])]}ot.info(`Updating node ${e} at ${t.url}`),await r.patch(t)}}var Ti,eT,ot,sV,uh,oV,aV,iV,jle,Qle,fo,jd,Hl,zd,ZS,nV,fh=se(()=>{we();Ti=b(st());Ss();eT=require("worker_threads");Wd();ot=b(J()),sV=b(require("lodash")),uh=b(me());H();oV=require("crypto"),aV=b(require("minimist")),{cloneDeep:iV}=sV.default,jle=(0,aV.default)(process.argv),Qle=200,fo=new Map,zd=new Map,ZS=new Map,nV=[];a(TC,"startOnMainThread");a(cV,"requestClusterStatus");eT.parentPort&&(jd=a(e=>{eT.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),Hl=a(e=>{eT.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,Ti.onMessageByType)("subscribe-to-node",e=>{dh(e)}),(0,Ti.onMessageByType)("unsubscribe-from-node",e=>{tT(e)}));a(ea,"ensureNode")});var ys=M(Gt=>{"use strict";var hr=require("path"),{watch:Jle}=require("chokidar"),Wn=require("fs-extra"),Qd=require("node-forge"),hV=require("net"),{generateKeyPair:yC,X509Certificate:ta,createPrivateKey:EV,randomBytes:Xle}=require("node:crypto"),Zle=require("util");yC=Zle.promisify(yC);var Pt=Qd.pki,Ri=require("joi"),{v4:_V}=require("uuid"),{validateBySchema:IC}=mt(),{forComponent:eue}=J(),Ts=me(),Ks=(H(),v(z)),{CONFIG_PARAMS:ql}=Ks,bi=Kw(),{ClientError:dc}=_e(),nT=require("node:tls"),{relative:gV,join:tue}=require("node:path"),{CERTIFICATE_VALUES:uV}=bi,rue=Qc(),RC=gt(),{table:nue,getDatabases:sue,databases:rT}=(we(),v(ft)),{getJWTRSAKeys:dV}=(kd(),v(nh)),Je=eue("tls").conditional;Gt.generateKeys=CC;Gt.updateConfigCert=wV;Gt.createCsr=due;Gt.signCertificate=fue;Gt.setCertTable=Jd;Gt.loadCertificates=bV;Gt.reviewSelfSignedCert=PC;Gt.createTLSSelector=CV;Gt.listCertificates=PV;Gt.addCertificate=gue;Gt.removeCertificate=Tue;Gt.createNatsCerts=hue;Gt.generateCertsKeys=pue;Gt.getReplicationCert=ph;Gt.getReplicationCertAuth=uue;Gt.renewSelfSigned=Eue;Gt.hostnamesFromCert=DC;Gt.getKey=yue;Gt.getHostnamesFromCertificate=Rue;Gt.getPrimaryHostName=LC;Gt.generateSerialNumber=oT;var{urlToNodeName:SV,getThisNodeUrl:iue,getThisNodeName:iT,clearThisNodeName:oue}=(Ss(),v(ra)),{readFileSync:aue,statSync:TV}=require("node:fs"),_xe=me(),{getTicketKeys:cue,onMessageFromWorkers:lue}=st(),{isMainThread:yV}=require("worker_threads"),{TLSSocket:RV,createSecureContext:gxe}=require("node:tls"),wC=3650,mh=["127.0.0.1","localhost","::1"],NC=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];function oT(){let e=Xle(8);return e[0]=e[0]&127|1,e.toString("hex")}a(oT,"generateSerialNumber");lue(async e=>{e.type===Ks.ITC_EVENT_TYPES.RESTART&&(Ts.initSync(!0),await PC())});var on;function mc(){return on||(on=sue().system.hdb_certificate,on||(on=nue({table:"hdb_certificate",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{attribute:"__updatedtime__"}]}))),on}a(mc,"getCertTable");async function ph(){let e=CV("operations-api"),t={secureContexts:null,setSecureContext:a(s=>{},"setSecureContext")};await e.initialize(t);let r=t.secureContexts.get(iT());if(!r)return;let n=new ta(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(ph,"getReplicationCert");async function uue(){mc();let e=(await ph()).options.cert,r=new ta(e).issuer.match(/CN=(.*)/)?.[1];return on.get(r)}a(uue,"getReplicationCertAuth");var fV,fc=new Map;function bV(){if(fV)return;fV=!0;let e=[{configKey:ql.TLS},{configKey:ql.OPERATIONSAPI_TLS}];mc();let t=hr.dirname(RC.getConfigFilePath()),r;for(let{configKey:n}of e){let s=RC.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&gV(tue(t,"keys"),o);c&&mV(o,l=>{fc.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&yV){let d;mV(u,f=>{if(uV.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let p=NV(u),h=new ta(p),E;try{E=LC(h)}catch(y){Je.error?.("error extracting host name from certificate",y);return}if(E==null){Je.error?.("No host name found on certificate");return}if(h.checkIssued(new ta(uV.cert)))return;let g=on.primaryStore.get(E),R=TV(u).mtimeMs,S=!g||g.is_self_signed?1:g.file_timestamp??g.__updatedtime__;if(g&&R<=S){R<S&&Je.info?.(`Certificate ${E} at ${u} is older (${new Date(R)}) than the certificate in the database (${S>1?new Date(S):"only self signed certificate available"})`);return}r=on.put({name:E,uses:["https",...n.includes("operations")?["operations"]:[]],ciphers:i.ciphers,certificate:p,private_key_name:c,is_authority:l,hostnames:m,fileTimestamp:R,details:{issuer:h.issuer.replace(/\n/g," "),subject:h.subject?.replace(/\n/g," "),subject_alt_name:h.subjectAltName,serial_number:h.serialNumber,valid_from:h.validFrom,valid_to:h.validTo}})},l?"certificate authority":"certificate")}}}}}return r}a(bV,"loadCertificates");function mV(e,t,r){let n,s=a((i,o)=>{try{let c=o.mtimeMs;c&&c!==n&&(n&&yV&&Je.warn?.(`Reloading ${r}:`,i),n=c,t(NV(i)))}catch(c){Je.error?.(`Error loading ${r}:`,i,c)}},"loadFile");Wn.existsSync(e)?s(e,TV(e)):Je.error?.(`${r} file not found:`,e),Jle(e,{persistent:!1}).on("change",s)}a(mV,"loadAndWatch");function bC(){let e=iue();if(e==null){let t=mh[0];return Je.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return SV(e)}a(bC,"getHost");function sT(){let e=iT();if(e==null){let t=mh[0];return Je.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(sT,"getCommonName");async function due(){let e=await ph(),t=Pt.certificateFromPem(e.options.cert),r=Pt.privateKeyFromPem(e.options.key);Je.info?.("Creating CSR with cert named:",e.name);let n=Pt.createCertificationRequest();n.publicKey=t.publicKey;let s=[{name:"commonName",value:sT()},...NC];Je.info?.("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:AV()}];return Je.info?.("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),Qd.pki.certificationRequestToPem(n)}a(due,"createCsr");function AV(){let e=mh.includes(sT())?mh:[...mh,sT()];return e.includes(bC())||e.push(bC()),[{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"nsCertType",client:!0,server:!0},{name:"subjectAltName",altNames:e.map(t=>hV.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(AV,"certExtensions");async function fue(e){let t={},r=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;mc();for await(let d of on.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(fc.has(d.private_key_name)){n=fc.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await Wn.exists(hr.join(r,d.private_key_name))){n=Wn.readFile(hr.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await AC();s=d.ca,n=d.private_key}n=Pt.privateKeyFromPem(n),t.signingCA=s.certificate;let i=Pt.certificateFromPem(s.certificate);Je.info?.("Signing CSR with cert named",s.name);let o=Pt.certificationRequestFromPem(e.csr);try{o.verify()}catch(d){return Je.error?.(d),new Error("Error verifying CSR: "+d.message)}let c=Qd.pki.createCertificate();c.serialNumber=oT(),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+wC),Je.info?.("sign cert setting validity:",c.validity),Je.info?.("sign cert setting subject from CSR:",o.subject.attributes),c.setSubject(o.subject.attributes),Je.info?.("sign cert setting issuer:",i.subject.attributes),c.setIssuer(i.subject.attributes);let u=o.getAttribute({name:"extensionRequest"}).extensions;Je.info?.("sign cert adding extensions from CSR:",u),c.setExtensions(u),c.publicKey=o.publicKey,c.sign(n,Qd.md.sha256.create()),t.certificate=Pt.certificateToPem(c)}else Je.info?.("Sign cert did not receive a CSR from:",e.url,"only the CA will be returned");return t}a(fue,"signCertificate");async function mue(e,t){await Jd({name:iT(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await Jd({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:Pt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}a(mue,"createCertificateTable");async function Jd(e){let t;try{t=new ta(e.certificate)}catch(r){Je.error?.(`Failed to parse certificate for ${e.name}:`,r.message),Je.debug?.("Certificate record details:",JSON.stringify(e,null,2));let n=new Error(`Invalid certificate format for ${e.name}: ${r.message}. This may be due to corrupted certificate data during transfer or encoding issues.`);throw n.code="INVALID_CERTIFICATE_FORMAT",n.cause=r,n}e.details={issuer:t.issuer.replace(/\n/g," "),subject:t.subject?.replace(/\n/g," "),subject_alt_name:t.subjectAltName,serial_number:t.serialNumber,valid_from:t.validFrom,valid_to:t.validTo},mc(),await on.patch(e)}a(Jd,"setCertTable");async function CC(){let e=await yC("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:Pt.publicKeyFromPem(e.publicKey),privateKey:Pt.privateKeyFromPem(e.privateKey)}}a(CC,"generateKeys");async function OC(e,t,r){let n=Pt.createCertificate();if(!t){let o=await ph();t=Pt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=oT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+wC);let i=[{name:"commonName",value:sT()},...NC];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(AV()),n.sign(e,Qd.md.sha256.create()),Pt.certificateToPem(n)}a(OC,"generateCertificates");async function AC(){let e=await PV(),t;for(let r of e){if(!r.is_authority)continue;let n=await OV(r.private_key_name);if(r.private_key_name&&n&&new ta(r.certificate).checkPrivateKey(EV(n))){Je.trace?.(`CA named: ${r.name} found with matching private key`),t={ca:r,private_key:n};break}}if(t)return t;Je.trace?.("No CA found with matching private key")}a(AC,"getCertAuthority");async function IV(e,t,r=!0){let n=Pt.createCertificate();n.publicKey=t,n.serialNumber=oT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+wC);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ts.get(ql.REPLICATION_HOSTNAME)??SV(Ts.get(ql.REPLICATION_URL))??_V().split("-")[0]}`},...NC];n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,critical:!0},{name:"subjectKeyIdentifier"}]),n.sign(e,Qd.md.sha256.create());let o=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),c=hr.join(o,bi.PRIVATEKEY_PEM_NAME);return r&&await Wn.writeFile(c,Pt.privateKeyToPem(e)),n}a(IV,"generateCertAuthority");async function pue(){let{privateKey:e,publicKey:t}=await CC(),r=await IV(e,t),n=await OC(e,t,r);await mue(n,r),wV()}a(pue,"generateCertsKeys");async function hue(){let e=await OC(Pt.privateKeyFromPem(bi.CERTIFICATE_VALUES.key),void 0,Pt.certificateFromPem(bi.CERTIFICATE_VALUES.cert)),t=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),r=hr.join(t,bi.NATS_CERTIFICATE_PEM_NAME);await Wn.exists(r)||await Wn.writeFile(r,e);let n=hr.join(t,bi.NATS_CA_PEM_NAME);await Wn.exists(n)||await Wn.writeFile(n,bi.CERTIFICATE_VALUES.cert)}a(hue,"createNatsCerts");async function Eue(){mc();for await(let e of on.search([{attribute:"is_self_signed",value:!0}]))await on.delete(e.name);await PC()}a(Eue,"renewSelfSigned");async function PC(){oue(),await bV(),mc();let e=await AC();if(!e){Je.notify?.("A matching Certificate Authority and key was not found. A new CA will be created in advance, so it's available if needed.");let r=a(u=>{try{return{key:Pt.privateKeyFromPem(Wn.readFileSync(u)),keyPath:u}}catch(d){return Je.warn?.(`Failed to parse private key from ${u}:`,d.message),{key:null,keyPath:u}}},"tryToParseKey"),n=Ts.get(ql.TLS),s,i;if(Array.isArray(n)){for(let u of n)if(u.privateKey){let d=r(u.privateKey);if(s=d.key,i=d.keyPath,d.key)break}}else{let u=Ts.get(ql.TLS_PRIVATEKEY),d=r(u);s=d.key,i=d.keyPath}let o=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),c=gV(o,i);s||(Je.warn?.("Unable to parse the TLS key",i,"A new key will be generated and used to create Certificate Authority"),{privateKey:s}=await CC(),Wn.existsSync(hr.join(o,bi.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${_V().split("-")[0]}.pem`),await Wn.writeFile(hr.join(o,c),Pt.privateKeyToPem(s)));let l=await IV(s,Pt.setRsaPublicKey(s.n,s.e),!1);await Jd({name:l.subject.getField("CN").value,uses:["https"],certificate:Pt.certificateToPem(l),private_key_name:c,is_authority:!0,is_self_signed:!0})}if(!await ph()){let r=iT();Je.notify?.(`A suitable replication certificate was not found, creating new self singed cert named: ${r}`),e=e??await AC();let n=Pt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await OC(Pt.privateKeyFromPem(e.private_key),s,n);await Jd({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}a(PC,"reviewSelfSignedCert");function wV(){let e=rue(Object.keys(Ks.CONFIG_PARAM_MAP),!0),t=hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME),r=hr.join(t,bi.PRIVATEKEY_PEM_NAME),n=hr.join(t,bi.NATS_CERTIFICATE_PEM_NAME),s=hr.join(t,bi.NATS_CA_PEM_NAME),i=Ks.CONFIG_PARAMS,o={[i.TLS_PRIVATEKEY]:e[i.TLS_PRIVATEKEY.toLowerCase()]?e[i.TLS_PRIVATEKEY.toLowerCase()]:r};e[i.TLS_CERTIFICATE.toLowerCase()]&&(o[i.TLS_CERTIFICATE]=e[i.TLS_CERTIFICATE.toLowerCase()]),e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.TLS_CERTIFICATEAUTHORITY]=e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATE]=e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_PRIVATEKEY]=e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),(e[i.CLUSTERING_ENABLED.toLowerCase()]||e.clustering)&&(o[i.CLUSTERING_TLS_CERTIFICATE]=e[i.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]??n,o[i.CLUSTERING_TLS_CERT_AUTH]=e[i.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]??s,o[i.CLUSTERING_TLS_PRIVATEKEY]=e[i.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]??r),RC.updateConfigValue(void 0,void 0,o,!1,!0)}a(wV,"updateConfigCert");function NV(e){return e.startsWith("-----BEGIN")?e:aue(e,"utf8")}a(NV,"readPEM");var pV=nT.createSecureContext;nT.createSecureContext=function(e){if(!e.cert||!e.key)return pV(e);let t={...e};delete t.key,delete t.cert;let r=pV(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var _ue=RV.prototype._init;RV.prototype._init=function(e,t){_ue.call(this,e,t);let r=this;this._handle.oncertcb=function(n){let s=n.servername;r._SNICallback(s,(i,o)=>{this.sni_context=o?.context||o,this.certCbDone()})}};var Gl=new Map;function CV(e,t){let r=new Map,n,s=!1;return i.initialize=o=>i.ready?i.ready:(o&&(o.secureContexts=r,o.secureContextsListeners=[]),i.ready=new Promise((c,l)=>{async function u(){try{r.clear(),Gl.clear();let d=0;if(rT===void 0){c();return}for await(let f of rT.system.hdb_certificate.search([])){let m=f.certificate,p=new ta(m);f.is_authority&&(p.asString=m,Gl.set(p.subject,m))}for await(let f of rT.system.hdb_certificate.search([]))try{if(f.is_authority)continue;let m=e==="operations-api",p=f.is_self_signed?1:3;m&&f.uses?.includes?.("operations")&&(p+=1);let h=await OV(f.private_key_name),E=f.certificate,g=new ta(E);if(Gl.has(g.issuer)&&(E+=`
16
16
  `+Gl.get(g.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:cue(),availableCAs:Gl,ca:t&&Array.from(Gl.values()),cert:E,key:h,key_file:f.private_key_name,is_self_signed:f.is_self_signed};o&&(R.sessionIdContext=o.sessionIdContext);let S=f.hostnames??DC(g);Array.isArray(S)||(S=[S]);for(let I of S)I===bC()&&(p+=1);let y=nT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Gl),y.certStart=E.toString().slice(0,100);let N;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),hV.isIP(I)&&(N=!0);let $=r.get(I)?.quality??0;Je.trace?.("Assigning TLS for hostname",I,"if",p,">",$),p>$&&r.set(I,y)}else Je.error?.("No hostname found for certificate at",nT.certificate);Je.trace?.("Adding TLS",y.name,"for",o.ports||"client","cert named",f.name,"hostnames",S,"quality",p,"best quality",d),p>d&&(i.defaultContext=n=y,d=p,o&&(o.defaultContext=y))}catch(m){Je.error?.("Error applying TLS for",f.name,m)}o?.secureContextsListeners.forEach(f=>f()),c(n)}catch(d){l(d)}}a(u,"updateTLS"),rT?.system.hdb_certificate.subscribe({listener:a(()=>setTimeout(()=>u(),1500).unref(),"listener"),omitCurrent:!0}),u()})),i;function i(o,c){Je.info?.("TLS requested for",o||"(no SNI)");let l=o;for(;;){let d=r.get(l);if(d)return Je.debug?.("Found certificate for",o,d.certStart),d.updatedContext&&(d=d.updatedContext),c(null,d);if(s&&l){let f=l.indexOf(".",1);f<0?l="":l=l.slice(f)}else break}o?Je.debug?.("No certificate found to match",o,"using the default certificate"):Je.debug?.("No SNI, using the default certificate",n?.name);let u=n;u?u.updatedContext&&(u=u.updatedContext):Je.info?.("No default certificate found"),c(null,u)}a(i,"SNICallback")}a(CV,"createTLSSelector");async function OV(e){let t=fc.get(e);return!t&&e?await Wn.readFile(hr.join(Ts.get(ql.ROOTPATH),Ks.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(OV,"getPrivateKeyByName");async function PV(){mc();let e=[];for await(let t of on.search([]))e.push(t);return e}a(PV,"listCertificates");async function gue(e){let t=IC(e,Ri.object({name:Ri.string().required(),certificate:Ri.string().required(),is_authority:Ri.boolean().required(),private_key:Ri.string(),hosts:Ri.array(),uses:Ri.array()}));if(t)throw new dc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new ta(n),c=!1,l=!1,u;for(let[p,h]of fc)!s&&!c&&o.checkPrivateKey(EV(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new dc("A suitable private key was not found for this certificate");let d;if(!r){try{d=LC(o)}catch(p){Je.error?.(p)}if(d==null)throw new dc("Error extracting certificate host name, please provide a name parameter")}let f=Sue(r??d);s&&!c&&!l&&(await Wn.writeFile(hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME,f+".pem"),s),fc.set(f,s));let m={name:r??d,certificate:n,is_authority:i,hosts:e.hosts,uses:e.uses};return(!i||i&&u||i&&s)&&(m.private_key_name=u??f+".pem"),e.ciphers&&(m.ciphers=e.ciphers),await Jd(m),"Successfully added certificate: "+f}a(gue,"addCertificate");function Sue(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(Sue,"sanitizeName");async function Tue(e){let t=IC(e,Ri.object({name:Ri.string().required()}));if(t)throw new dc(t.message);let{name:r}=e;mc();let n=await on.get(r);if(!n)throw new dc(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await on.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Je.info?.("Removing private key named",s),await Wn.remove(hr.join(Ts.getHdbBasePath(),Ks.LICENSE_KEY_DIR_NAME,s)))}return await on.delete(r),"Successfully removed "+r}a(Tue,"removeCertificate");function LC(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||DC(e)[0]}a(LC,"getPrimaryHostName");function DC(e){if(e.subjectAltName)return e.subjectAltName.split(",").map(r=>{let n=r.indexOf(":");if(r=r.slice(n+1),r=r.trim(),r[0]==='"')try{r=JSON.parse(r)}catch{}return r.indexOf("=")>-1?r.match(/CN=([^,]*)/)?.[1]:r}).filter(r=>r);let t=e.subject?.match(/CN=(.*)/)?.[1];return t?[t]:[]}a(DC,"hostnamesFromCert");async function yue(e){if(e.bypass_auth!==!0)throw new dc("Unauthorized","401");let t=IC(e,Ri.object({name:Ri.string().required()}));if(t)throw new dc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await dV()).privateKey;if(r===".jwtPublic")return(await dV()).publicKey;if(fc.get(r))return fc.get(e.name);throw new dc("Key not found")}a(yue,"getKey");function Rue(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(Rue,"getHostnamesFromCertificate")});var e1={};ye(e1,{BACK_PRESSURE_RATIO_POSITION:()=>JV,CONFIRMATION_STATUS_POSITION:()=>QV,LATENCY_POSITION:()=>dT,NodeReplicationConnection:()=>Zd,OPERATION_REQUEST:()=>BC,RECEIVED_TIME_POSITION:()=>kC,RECEIVED_VERSION_POSITION:()=>FC,RECEIVING_STATUS_POSITION:()=>HC,RECEIVING_STATUS_RECEIVING:()=>ZV,RECEIVING_STATUS_WAITING:()=>XV,SENDING_TIME_POSITION:()=>Eh,createWebSocket:()=>fT,databaseSubscriptions:()=>hc,replicateOverWS:()=>_h,tableUpdateListeners:()=>$C});async function fT(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=tt(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!UC){let l=(0,YV.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),UC=u.secureContexts}if(i=UC.get(s),i&&ue.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,zV.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((Xd?.caCount!==na.size||Xd?.derivedFromContext!==i)&&(Xd=WV.createSecureContext({...i.options,ca:[...na,...i.options.availableCAs.values()]}),Xd.caCount=na.size,Xd.derivedFromContext=i),c.secureContext=Xd),new $V.WebSocket(e,"harperdb-replication-v1",c)}function _h(e,t,r){let n=t.port||t.securePort,s=qC.pid%1e3+"-"+VV.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);ue.debug?.(s,"Initializing replication connection",r);let i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||hc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&ct()[u],g,R=new Map,S=[];g=r.name,g&&t.connection&&(t.connection.nodeName=g);let y,N,I,$,ee,G,k,j=6e4,Y,ce=0,de=0,te=0,ge=qV.default.get(F.REPLICATION_BLOBTIMEOUT)??12e4,be=new Map,Ye=[],qe=0,Ar;if(t.url){let A=a(()=>{ee&&de===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(ee=performance.now(),e.ping(),de=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,HV).unref(),A()}else er();e._socket?.setMaxListeners(200);function er(){clearTimeout($),de=e._socket?.bytesRead,te=e._socket?.bytesWritten,$=setTimeout(()=>{de===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(ue.warn?.(`Timeout waiting for ping from ${g}, terminating connection and reconnecting`),e.terminate())},HV*2).unref()}a(er,"resetPingTimer");let Qr=0,xr=0,wu=!1,Kc=3e4;function Ut(){if(pn?.length>0){let A=performance.now(),U=A-xr;Qr=(Qr*Kc+(wu?U:0))/(Kc+U),m&&(m[JV]=Qr),xr=A}}a(Ut,"updateBackPressureRatio"),setInterval(Ut,Kc).unref();function ii(){if(!(!g||!u))return m||(m=Kd(f,u,g)),m}a(ii,"getSharedStatus"),u&&Yc(u);let Ma,ZE,cm=[],e_=[],lm,ve=[],t_=[],wb=[],Nu=150,Hi=25,Ds=0,um=0,dm=!1,Lo,Dn,pn,Br;e.on("message",Cu);async function Cu(A){if(r=await r,!r){ue.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}fm(A),e.off("message",Cu),e.on("message",fm)}a(Cu,"onWSMessageWhenAuthorized");function fm(A){ce=performance.now();try{let U=A.dataView=new nl(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let W=(0,at.decode)(A),[Q,B,Ee]=W;switch(Q){case DV:{if(B){if(g){if(g!==B){ue.error?.(s,`Node name mismatch, expecting to connect to ${g}, but peer reported name as ${B}, disconnecting`),e.send((0,at.encode)([hh])),Fr(1008,"Node name mismatch");return}}else if(g=B,t.connection?.tentativeNode){let le=t.connection.tentativeNode;le.name=g,t.connection.tentativeNode=null,ea(g,le)}if(t.connection&&(t.connection.nodeName=g),ue.debug?.(s,"received node name:",g,"db:",u??W[2]),!u)try{Yc(u=W[2]),u==="system"&&(Ma=lc(t,(le,ae)=>{Ba(ae)&&K(ae)}),e.on("close",()=>{Ma?.remove()}))}catch(le){ue.warn?.(s,"Error setting database",le),e.send((0,at.encode)([hh])),Fr(1008,le.message);return}mm()}break}case FV:{ue.debug?.(s,"Received table definitions for",B.map(le=>le.table));for(let le of B){let ae=W[2];le.database=ae;let xe;if(Ba(ae)){if(u==="system")Me[ae]?.[le.table]||(xe=D(le,Me[ae]?.[le.table]));else{if(ae!=="data"&&!Me[ae]){ue.warn?.("Database not found",ae);return}xe=D(le,Me[ae]?.[le.table])}f||(f=xe?.auditStore),E||(E=ct()?.[ae])}}break}case hh:Fr();break;case BC:try{let le=r?.replicates||r?.subscribers||r?.name;ue.debug?.("Received operation request",B,"from",g),server.operation(B,{user:r},!le).then(ae=>{ue.debug?.("Requested request from finished",g,ae),Array.isArray(ae)&&(ae={results:ae}),ae.requestId=B.requestId,e.send((0,at.encode)([cT,ae]))},ae=>{ue.debug?.("Failed requested operation from",g,ae),e.send((0,at.encode)([cT,{requestId:B.requestId,error:vC(ae)}]))})}catch(le){e.send((0,at.encode)([cT,{requestId:B.requestId,error:vC(le)}]))}break;case cT:let{resolve:fe,reject:pe}=R.get(B.requestId);ue.debug?.("Received completed operation request",g,B),B.error?pe(new Error(B.error)):fe(B),R.delete(B.requestId);break;case MC:let re=W[3];if(!E){u?ue.error?.(s,"No database found for",u):ue.error?.(s,"Database name never received"),Fr();return}let ie=E[re];ie=D({table:re,database:u,attributes:B.attributes,schemaDefined:B.schemaDefined},ie),cm[Ee]={name:re,decoder:new at.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:B.typedStructs,structures:B.structures}),getEntry(le){return ie.primaryStore.getEntry(le)},rootStore:ie.primaryStore.rootStore};break;case vV:Br=f?Q$(B,f):new Map,lm=W[2],ue.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${lm}`);break;case MV:let Oe=Ee;wb[Oe]=B;break;case BV:ii()[QV]=B,ue.trace?.(s,"received and broadcasting committed update",B),ii().buffer.notify();break;case xV:y=B,h.send({type:"end_txn",localTime:y,remoteNodeIds:S});break;case lT:{let le=W[1],{fileId:ae,size:xe,finished:Ce,error:Le}=le,De=be.get(ae);ue.debug?.("Received blob",ae,"has stream",!!De,"connectedToBlob",!!De?.connectedToBlob,"length",W[2].length,"finished",Ce),De||(De=new xC.PassThrough,De.expectedSize=xe,be.set(ae,De)),De.lastChunk=Date.now();let pt=W[2];Ve(pt.byteLength,"bytes-received",`${g}.${u}`,"replication","blob");try{Ce?(Le?(De.on("error",()=>{}),De.destroy(new Error("Blob error: "+Le+" for record "+(De.recordId??"unknown")+" from "+g))):De.end(pt),De.connectedToBlob&&be.delete(ae)):De.write(pt)}catch(wt){ue.error?.(`Error receiving blob for ${De.recordId} from ${g} and streaming to storage`,wt),be.delete(ae)}break}case UV:{let le=B,ae;try{let xe=W[3],Ce=e_[Ee]||(e_[Ee]=E[W[4]]);if(!Ce)return ue.warn?.("Unknown table id trying to handle record request",Ee);let Le=Ce.primaryStore.getBinaryFast(Symbol.for("structures")),De=Le?.length??0;if(De>0&&De!==um){um=De;let wt=(0,at.decode)(Le);e.send((0,at.encode)([MC,{typedStructs:wt.typed,structures:wt.named},Ee,Ce.tableName]))}let pt=Ce.primaryStore.getBinaryFast(xe);if(pt){let wt=Ce.primaryStore.decoder.decode(pt,{valueAsBuffer:!0}),xt=lt||{};xt.version=(0,jV.getLastVersion)(),lt&&lt[Ku]&Zr&&(wt=Buffer.from(wt),km(()=>Ce.primaryStore.decoder.decode(pt),n_=>Ua(n_,xe),Ce.primaryStore.rootStore)),ae=(0,at.encode)([aT,le,{value:wt,expiresAt:xt.expiresAt,version:xt.version,residencyId:xt.residencyId,nodeId:xt.nodeId,user:xt.user}])}else ae=(0,at.encode)([aT,le])}catch(xe){ae=(0,at.encode)([aT,le,{error:xe.message}])}e.send(ae);break}case aT:{let{resolve:le,reject:ae,tableId:xe,key:Ce}=R.get(W[1]),Le=W[2];if(Le?.error)ae(new Error(Le.error));else if(Le){let De;k_(()=>{let pt=cm[xe].decoder.decode(Le.value);Le.value=pt,Le.key=Ce,le(Le)||De&&setTimeout(()=>De.forEach(x_),6e4).unref()},f?.rootStore,pt=>{let wt=xa(pt,Ce);return De||(De=[]),De.push(wt),wt})}else le();R.delete(W[1]);break}case LV:{pn=B;let le,ae,xe=!1;if(h){if(u!==h.databaseName&&!h.then){ue.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(ue.debug?.(s,"received subscription request for",u,"at",pn),!h){let Pe;h=new Promise(tr=>{ue.debug?.("Waiting for subscription to database "+u),Pe=tr}),h.ready=Pe,hc.set(u,h)}if(r.name)ae=Ht().subscribe(r.name),ae.then(async Pe=>{le=Pe;for await(let tr of le){let ht=tr.value;if(!(ht?.replicates===!0||ht?.replicates?.receives||ht?.subscriptions?.some(kr=>(kr.database||kr.schema)===u&&kr.publish!==!1))){xe=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},Pe=>{ue.error?.(s,"Error subscribing to HDB nodes",Pe)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,at.encode)([hh])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(Dn&&(ue.debug?.(s,"stopping previous subscription",u),Dn.emit("close")),pn.length===0)return;let Ce=pn[0],Le=a(Pe=>{if(Pe&&(Ce.replicateByDefault?!Ce.tables.includes(Pe.tableName):Ce.tables.includes(Pe.tableName)))return{table:Pe}},"tableToTableEntry"),De={txnTime:0},pt,wt,xt=1/0,n_,s_=a((Pe,tr)=>{if(Pe.type==="end_txn"){De.txnTime&&(o[i]!==66&&ue.error?.("Invalid encoding of message"),C(9),C(Q_),O(n_=tr),AM()),i=c,De.txnTime=0;return}let ht=Pe.nodeId,kr=Pe.tableId,Nt=wt[kr];if(!Nt&&(Nt=wt[kr]=Le(h.tableById[kr]),!Nt))return ue.debug?.("Not subscribed to table",kr);let vs=Nt.table,Kt=vs.primaryStore,oi=Kt.encoder;(Pe.extendedType&ag||!oi.typedStructs)&&(oi._mergeStructures(oi.getStructures()),oi.typedStructs&&(oi.lastTypedStructuresLength=oi.typedStructs.length));let Lu=pt[ht];if(!(Lu&&Lu.startTime<tr&&(!Lu.endTime||Lu.endTime>tr)))return uT&&ue.trace?.(s,"skipping replication update",Pe.recordId,"to:",g,"from:",ht,"subscribed:",pt),IM();uT&&ue.trace?.(s,"sending replication update",Pe.recordId,"to:",g,"from:",ht,"subscribed:",pt);let Nb=Pe.version;De.txnTime!==Nb&&(De.txnTime&&(uT&&ue.trace?.(s,"new txn time, sending queued txn",De.txnTime),o[i]!==66&&ue.error?.("Invalid encoding of message"),AM()),De.txnTime=Nb,i=c,O(Nb));let Wc=Pe.residencyId,Cb=r_(Wc,vs),i_;if(Cb&&!Cb.includes(g)){let Gi=r_(Pe.previousResidencyId,vs);if(Gi&&!Gi.includes(g)&&(Pe.type==="put"||Pe.type==="patch")||vs.getResidencyById)return IM();let zc=Pe.recordId;ue.trace?.(s,"sending invalidation",zc,g,"from",ht);let pm=0;Wc&&(pm|=sl),Pe.previousResidencyId&&(pm|=il);let Lb,o_=null;for(let wM in vs.indices){if(!o_){if(Lb=Pe.getValue(Kt,!0),!Lb)break;o_={}}o_[wM]=Lb[wM]}i_=ol(Pe.version,kr,zc,null,ht,Pe.user,Pe.type==="put"||Pe.type==="patch"?"invalidate":Pe.type,oi.encode(o_),pm,Wc,Pe.previousResidencyId,Pe.expiresAt)}function IM(){return ue.trace?.(s,"skipping audit record",Pe.recordId),G||(G=setTimeout(()=>{G=null,(n_||0)+kV/2<xt&&(uT&&ue.trace?.(s,"sending skipped sequence update",xt),e.send((0,at.encode)([xV,xt])))},kV).unref()),new Promise(setImmediate)}a(IM,"skipAuditRecord");let Ob=oi.typedStructs,Pb=oi.structures;if((Ob?.length!=Nt.typed_length||Pb?.length!=Nt.structure_length)&&(Nt.typed_length=Ob?.length,Nt.structure_length=Pb.length,ue.debug?.(s,"send table struct",Nt.typed_length,Nt.structure_length),Nt.sentName||(Nt.sentName=!0),e.send((0,at.encode)([MC,{typedStructs:Ob,structures:Pb,attributes:vs.attributes,schemaDefined:vs.schemaDefined},kr,Nt.table.tableName]))),Wc&&!t_[Wc]&&(e.send((0,at.encode)([MV,Cb,Wc])),t_[Wc]=!0),i_)C(i_.length),P(i_);else{let Gi=Pe.encoded;Pe.extendedType&Zr&&km(()=>Pe.getValue(Kt),pm=>Ua(pm,Pe.recordId),Kt.rootStore);let zc=Gi[0]===66?8:0;C(Gi.length-zc),P(Gi,zc),ue.trace?.("wrote record",Pe.recordId,"length:",Gi.length)}if(e._socket.writableNeedDrain){let Gi=performance.now();return wu=!0,Ut(),new Promise(zc=>{ue.debug?.(`Waiting for remote node ${g} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",()=>{zc(),wu=!1,Ut()})})}else return qe>Hi?new Promise(Gi=>{Ar=Gi}):new Promise(setImmediate)},"sendAuditRecord"),AM=a(()=>{c-i>8?(e.send(o.subarray(i,c)),ue.debug?.(s,"Sent message, size:",c-i),u!=="system"&&Ve(c-i,"bytes-sent",`${g}.${u}`,"replication","egress")):ue.debug?.(s,"skipping empty transaction")},"sendQueuedData");Dn=new GC.EventEmitter,Dn.once("close",()=>{xe=!0,le?.end()});for(let{startTime:Pe}of pn)Pe<xt&&(xt=Pe);(ae||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,wt=h.tableById.map(Le),pt=[];for(let{name:tr,startTime:ht,endTime:kr}of pn){let Nt=XS(tr,f);ue.debug?.("subscription to",tr,"using local id",Nt,"starting",ht),pt[Nt]={startTime:ht,endTime:kr}}K(u),Ma||(Ma=Bl(tr=>{tr.databaseName===u&&K(u)}),ZE=jp(tr=>{tr===u&&(e.send((0,at.encode)([hh])),Fr())}),e.on("close",()=>{Ma?.remove(),ZE?.remove()})),e.send((0,at.encode)([vV,oh(h.auditStore),pn.map(({name:tr})=>tr)]));let Pe=!0;do{isFinite(xt)||(ue.warn?.("Invalid sequence id "+xt),Fr(1008,"Invalid sequence id"+xt));let tr;if(Pe&&!xe&&(Pe=!1,xt===0)){ue.info?.("Replicating all tables to",g);let ht=Date.now(),kr=mT(f);for(let Nt in E){if(!Le(Nt))continue;let vs=E[Nt];for(let Kt of vs.primaryStore.getRange({snapshot:!1,versions:!0})){if(xe)return;ue.trace?.(s,"Copying record from",u,Nt,Kt.key,Kt.localTime),ht=Math.max(Kt.localTime??1,ht),tr=!0,ii()[Eh]=1;let oi=ol(Kt.version,vs.tableId,Kt.key,null,kr,null,"put",km(()=>vs.primaryStore.encoder.encode(Kt.value),Lu=>Ua(Lu,Kt.key)),Kt.metadataFlags&-256,Kt.residencyId,null,Kt.expiresAt);await s_({recordId:Kt.key,tableId:vs.tableId,type:"put",getValue(){return Kt.value},encoded:oi,version:Kt.version,residencyId:Kt.residencyId,nodeId:kr,extendedType:Kt.metadataFlags},Kt.localTime)}}De.txnTime||(De.txnTime=ht,O(ht)),s_({type:"end_txn"},ht),ii()[Eh]=0,xt=ht}for(let{key:ht,value:kr}of f.getRange({start:xt||1,exclusiveStart:!0,snapshot:!1})){if(xe)return;let Nt=At(kr);ue.debug?.("sending audit record",ht,Nt.recordId),ii()[Eh]=ht,xt=ht,await s_(Nt,ht),Dn.startTime=ht,tr=!0}tr&&s_({type:"end_txn"},xt),ii()[Eh]=0,await U0(f)}while(!xe)}).catch(Pe=>{ue.error?.(s,"Error handling subscription to node",Pe),Fr(1008,"Error handling subscription to node")});break}}return}U.position=8;let w=!0,L,q;do{ii();let W=U.readInt();if(W===9&&U.getUint8(U.position)==Q_){U.position++,y=q=U.readFloat64(),m[FC]=y,m[kC]=Date.now(),m[HC]=XV,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),ue.trace?.("received remote sequence update",y,u);break}let Q=U.position,B=At(A,Q,Q+W),Ee=cm[B.tableId];Ee||ue.error?.(`No table found with an id of ${B.tableId}`);let fe;B.residencyId&&(fe=wb[B.residencyId],ue.trace?.(s,"received residency list",fe,B.type,B.recordId));let pe=B.recordId;try{k_(()=>{L={table:Ee.name,id:B.recordId,type:B.type,nodeId:Br.get(B.nodeId),residencyList:fe,timestamp:B.version,value:B.getValue(Ee),user:B.user,beginTxn:w,expiresAt:B.expiresAt}},f?.rootStore,re=>xa(re,pe))}catch(re){throw re.message+=" record id: "+pe,re.message+=" typed structures for current decoder"+JSON.stringify(Ee.decoder.typedStructs),re.message+=" structures for current decoder"+JSON.stringify(Ee.decoder.structures),re}w=!1,ue.debug?.(s,"received replication message",B.type,"id",L.id,"version",new Date(B.version),"nodeId",L.nodeId),m[FC]=B.version,m[kC]=Date.now(),m[HC]=ZV,h.send(L),U.position=Q+W}while(U.position<A.byteLength);Ds++,u!=="system"&&Ve(A.byteLength,"bytes-received",`${g}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ds>Nu&&!dm&&(dm=!0,e.pause(),ue.debug?.(`Commit backlog causing replication back-pressure, requesting that ${g} pause replication`)),h.send({type:"end_txn",localTime:y,remoteNodeIds:S,async onCommit(){if(L){let W=Date.now()-L.timestamp;u!=="system"&&Ve(W,"replication-latency",g+"."+u+"."+L.table,L.type,"ingest")}Ds--,dm&&(dm=!1,e.resume(),ue.debug?.(`Replication resuming ${g}`)),Ye.length>0&&await Promise.all(Ye),ue.trace?.("All blobs finished"),!N&&q&&(ue.trace?.(s,"queuing confirmation of a commit at",q),setTimeout(()=>{e.send((0,at.encode)([BV,N])),ue.trace?.(s,"sent confirmation of a commit at",N),N=null},Aue)),N=q,ue.debug?.("last sequence committed",new Date(q),u)}})}catch(U){ue.error?.(s,"Error handling incoming replication message",U)}}a(fm,"onWSMessage"),e.on("ping",er),e.on("pong",()=>{if(t.connection){let A=performance.now()-ee;t.connection.latency=A,ii()&&(m[dT]=A),t.isSubscriptionConnection&&Hl({name:g,database:u,url:t.url,latency:A})}ee=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout($),clearInterval(k),Dn&&Dn.emit("close"),Lo&&Lo.end();for(let[w,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));ue.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,ue.debug?.(s,"closing",g,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(w){ue.error?.(s,"Error closing connection",w)}}a(Fr,"close");let Ou=new Set;async function Ua(A,U){let w=B_(A);if(Ou.has(w)){ue.debug?.("Blob already being sent",w);return}Ou.add(w);try{let L;qe++;for await(let q of A.stream())L&&(ue.debug?.("Sending blob chunk",w,"length",L.length),e.send((0,at.encode)([lT,{fileId:w,size:A.size},L]))),L=q,e._socket.writableNeedDrain&&(ue.debug?.("draining",w),await new Promise(W=>e._socket.once("drain",W)),ue.debug?.("drained",w)),Ve(q.length,"bytes-sent",`${g}.${u}`,"replication","blob");ue.debug?.("Sending final blob chunk",w,"length",L.length),e.send((0,at.encode)([lT,{fileId:w,size:A.size,finished:!0},L]))}catch(L){ue.warn?.("Error sending blob",L,"blob id",w,"for record",U),e.send((0,at.encode)([lT,{fileId:w,finished:!0,error:vC(L)},Buffer.alloc(0)]))}finally{Ou.delete(w),qe--,qe<Hi&&Ar?.()}}a(Ua,"sendBlobs");function xa(A,U){let w=B_(A),L=be.get(w);ue.debug?.("Received transaction with blob",w,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&be.delete(w):(L=new xC.PassThrough,be.set(w,L)),L.connectedToBlob=!0,L.lastChunk=Date.now(),L.recordId=U,A.size===void 0&&L.expectedSize&&(A.size=L.expectedSize);let q=L.blob??createBlob(L,A);L.blob=q;let W=Ho(()=>Fm(q).saving,h.auditStore?.rootStore);return W&&(W.blobId=w,Ye.push(W),W.finally(()=>{ue.debug?.(`Finished receiving blob stream ${w}`),Ye.splice(Ye.indexOf(W),1)})),q}a(xa,"receiveBlobs");function mm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",mm)),!f&&h&&(f=h.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let A=new Map;f||(f=h?.auditStore);try{for(let L of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let q of L.value.nodes||[])q.lastTxnTime>(A.get(q.id)??0)&&A.set(q.id,q.lastTxnTime)}catch(L){if(!L.message.includes("Can not re"))throw L}let U=t.connection?.nodeSubscriptions?.[0];S=[];let w=t.connection?.nodeSubscriptions.map((L,q)=>{let W=[],{replicateByDefault:Q}=L;if(L.subscriptions){for(let pe of L.subscriptions)if(pe.subscribe&&(pe.schema||pe.database)===u){let re=pe.table;E?.[re]?.replicate!==!1&&W.push(re)}Q=!1}else for(let pe in E)(Q?E[pe].replicate===!1:E[pe].replicate)&&W.push(pe);let B=f&&XS(L.name,f),Ee=h?.dbisDB?.get([Symbol.for("seq"),B])??1,fe=Math.max(Ee?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(ue.debug?.("Starting time recorded in db",L.name,B,u,Ee?.seqId,"start time:",fe,new Date(fe)),U!==L){let pe=f&&XS(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),pe])??1;for(let ie of re?.nodes||[])ie.name===L.name&&(fe=ie.seqId,ue.debug?.("Using sequence id from proxy node",U.name,fe))}return B===void 0?ue.warn("Starting subscription request from node",L,"but no node id found"):S.push(B),A.get(B)>fe&&(fe=A.get(B),ue.debug?.("Updating start time from more recent txn recorded",U.name,fe)),fe===1&&(L.isLeader?(ue.warn?.(`Requesting full copy of database ${u} from ${L.url}`),fe=0):fe=Date.now()-6e4),ue.trace?.(s,"defining subscription request",L.name,u,new Date(fe)),{name:L.name,replicateByDefault:Q,tables:W,startTime:fe,isLeader:L.isLeader,endTime:L.endTime}});if(w)if(ue.debug?.(s,"sending subscription request",w,h?.dbisDB?.path),clearTimeout(Y),w.length>0)e.send((0,at.encode)([LV,w]));else{let L=a(()=>{let q=performance.now();Y=setTimeout(()=>{ce<=q?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},j).unref()},"scheduleClose");L()}}a(mm,"sendSubscriptionRequestUpdate");function r_(A,U){if(!A)return;let w=ve[A];return w||(w=U.getResidencyRecord(A),ve[A]=w),w}a(r_,"getResidence");function Ba(A){return!(pc&&pc!="*"&&!pc[A]&&!pc.includes?.(A)&&!pc.some?.(U=>U.name===A))}a(Ba,"checkDatabaseAccess");function Yc(A){if(h=h||d.get(A),!Ba(A))throw new Error(`Access to database "${A}" is not permitted`);h||ue.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=ct()?.[A]);let U=tt();if(U===g)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return Pu(U,A),!0}a(Yc,"setDatabase");function Pu(A,U){let w=ct()?.[U],L=[];for(let q in w){let W=w[q];L.push({table:q,schemaDefined:W.schemaDefined,attributes:W.attributes.map(Q=>({name:Q.name,type:Q.type,isPrimaryKey:Q.isPrimaryKey}))})}ue.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([DV,A,U,L]))}a(Pu,"sendNodeDBName");function K(A){let U=ct()?.[A],w=[];for(let L in U){if(pn&&!pn.some(W=>W.replicateByDefault?!W.tables.includes(L):W.tables.includes(L)))continue;let q=U[L];w.push({table:L,schemaDefined:q.schemaDefined,attributes:q.attributes.map(W=>({name:W.name,type:W.type,isPrimaryKey:W.isPrimaryKey}))})}e.send((0,at.encode)([FV,w,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of be)U.lastChunk+ge<Date.now()&&(ue.warn?.(`Timeout waiting for blob stream to finish ${A} for record ${U.recordId??"unknown"} from ${g}`),be.delete(A),U.end())},ge).unref();let _=1,T=[];return{end(){Lo&&Lo.end(),Dn&&Dn.emit("close")},getRecord(A){let U=_++;return new Promise((w,L)=>{let q=[UV,U,A.table.tableId,A.id];T[A.table.tableId]||(q.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,at.encode)(q)),ce=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(W){let{table:Q,entry:B}=A;if(w(W),W)return Q._recordRelocate(B,W)},reject:L})})},sendOperation(A){let U=_++;return A.requestId=U,e.send((0,at.encode)([BC,A])),new Promise((w,L)=>{R.set(U,{resolve:w,reject:L})})}};function C(A){x(5),A<128?o[c++]=A:A<16384?(l.setUint16(c,A|32768),c+=2):A<1056964608?(l.setUint32(c,A|3221225472),c+=4):(o[c]=255,l.setUint32(c+1,A),c+=5)}function P(A,U=0,w=A.length){let L=w-U;x(L),A.copy(o,c,U,w),c+=L}function O(A){x(8),l.setFloat64(c,A),c+=8}function x(A){if(A+16>o.length-c){let U=Buffer.allocUnsafeSlow(c+A-i+65536>>10<<11);o.copy(U,0,i,c),c=c-i,i=0,o=U,l=new DataView(o.buffer,0,o.length)}}function D(A,U){let w=A.database??"data";U||(U={});let L=U.schemaDefined,q=!1,W=A.schemaDefined,Q=U.attributes||[];for(let B=0;B<A.attributes?.length;B++){let Ee=A.attributes[B],fe=Q.find(pe=>pe.name===Ee.name);(!fe||fe.type!==Ee.type)&&(L?ue.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${Ee.name}: ${Ee.type}' from '${g}' does not match local attribute ${fe?"'"+fe.name+": "+fe.type+"'":"which does not exist"}`):(q=!0,W||(Ee.indexed=!0),fe?Q[Q.indexOf(fe)]=Ee:Q.push(Ee)))}return q?(ue.debug?.("(Re)creating",A),Xe({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:Q,...U})):U}}var qV,at,$V,VV,KV,GC,YV,WV,qC,zV,xC,jV,bue,vC,ue,LV,DV,vV,hh,MV,MC,UV,aT,BC,cT,xV,BV,FV,lT,QV,FC,kC,Eh,dT,HC,JV,XV,ZV,$C,hc,uT,kV,Aue,HV,UC,Xd,GV,Zd,VC=se(()=>{we();$i();SC();sI();Ss();qV=b(me());H();al();at=require("msgpackr"),$V=require("ws"),VV=require("worker_threads"),KV=b(J());fh();GC=require("events"),YV=b(ys()),WV=b(require("node:tls"));Wd();qC=b(require("node:process")),zV=require("node:net");is();ss();xC=require("node:stream"),jV=require("lmdb"),{forComponent:bue,errorToString:vC}=KV.default,ue=bue("replication").conditional,LV=129,DV=140,vV=141,hh=142,MV=130,MC=132,UV=133,aT=134,BC=136,cT=137,xV=143,BV=144,FV=145,lT=146,QV=0,FC=1,kC=2,Eh=3,dT=4,HC=5,JV=6,XV=0,ZV=1,$C=new Map,hc=new Map,uT=!0,kV=300,Aue=2,HV=3e4;a(fT,"createWebSocket");GV=500,Zd=class extends GC.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=GV;retries=0;isConnected=!0;isFinished=!1;nodeSubscriptions;latency=0;replicateTablesByDefault;session;sessionResolve;sessionReject;url;subscription;databaseName;nodeName;authorization;constructor(t,r,n,s,i){super(),this.url=t,this.subscription=r,this.databaseName=n,this.authorization=i,this.nodeName=this.nodeName??yi(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await fT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;ue.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${qC.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),ue[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=GV,this.nodeSubscriptions&&Hl({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=_h(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this,isSubscriptionConnection:this.nodeSubscriptions!==void 0},{replicates:!0}),this.sessionResolve(r)}),this.socket.on("error",n=>{n.code==="SELF_SIGNED_CERT_IN_CHAIN"?(ue.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),n.isHandled=!0):n.code!=="ECONNREFUSED"&&(n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?ue.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):ue.error?.(`Error in connection to ${this.url} due to ${n.message}`)),this.sessionReject(n)}),this.socket.on("close",(n,s)=>{if(this.isConnected&&(this.nodeSubscriptions&&jd({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.removeAllListeners("subscriptions-updated"),this.socket.isFinished){this.isFinished=!0,r?.end(),this.emit("finished");return}if(++this.retries%20===1){let i=s?.toString();ue.warn?.(`${r?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${i?'"'+i+'" ':""}(code: ${n})`)}r=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>8})}resetSession(){this.session=new Promise((t,r)=>{this.sessionResolve=t,this.sessionReject=r})}subscribe(t,r){this.nodeSubscriptions=t,this.replicateTablesByDefault=r,this.emit("subscriptions-updated",t)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(t){return this.session.then(r=>r.getRecord(t))}};a(_h,"replicateOverWS")});function Ec(e,t){let r=e.toString("base64"),n=[`-----BEGIN ${t}-----`];for(let s=0;s<r.length;s+=64)n.push(r.substring(s,s+64));return n.push(`-----END ${t}-----`),n.join(`
17
17
  `)}function r1(e){let t=[],r=e;for(;r?.raw;){let n={cert:r.raw};if(r.issuerCertificate&&r.issuerCertificate!==r&&r.issuerCertificate.raw&&(n.issuer=r.issuerCertificate.raw),t.push(n),r.issuerCertificate&&r.issuerCertificate!==r)r=r.issuerCertificate;else break}return t}function WC(e){try{let t=$l(e),n=mo.Certificate.fromBER(t).extensions?.find(c=>c.extnID==="2.5.29.31");if(!n)return sa.debug?.("Certificate has no CRL Distribution Points extension"),[];let s=ia.fromBER(n.extnValue.valueBlock.valueHexView);if(s.offset===-1)throw new Error("Failed to parse ASN.1 structure in CRL Distribution Points extension");let i=new mo.CRLDistributionPoints({schema:s.result}),o=[];for(let c of i.distributionPoints)if(c.distributionPoint&&Array.isArray(c.distributionPoint)){for(let l of c.distributionPoint)if(l.type===6&&typeof l.value=="string"){let u=l.value;(u.startsWith("http://")||u.startsWith("https://"))&&o.push(u)}}return sa.debug?.(`Found ${o.length} CRL distribution points: ${o}`),o}catch(t){return sa.warn?.(`Failed to extract CRL distribution points: ${t}`),[]}}function n1(e){try{let t=$l(e),r=mo.Certificate.fromBER(t),n=[],s=[];for(let i of r.extensions||[])if(i.extnID==="2.5.29.31")try{let o=ia.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1){let c=new mo.CRLDistributionPoints({schema:o.result});for(let l of c.distributionPoints)if(l.distributionPoint&&Array.isArray(l.distributionPoint)){for(let u of l.distributionPoint)if(u.type===6&&typeof u.value=="string"){let d=u.value;(d.startsWith("http://")||d.startsWith("https://"))&&n.push(d)}}}}catch(o){sa.warn?.(`Failed to parse CRL Distribution Points extension: ${o}`)}else if(i.extnID==="1.3.6.1.5.5.7.1.1")try{let o=ia.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1&&o.result instanceof ia.Sequence){for(let c of o.result.valueBlock.value)if(c instanceof ia.Sequence&&c.valueBlock.value.length>=2){let l=c.valueBlock.value[0],u=c.valueBlock.value[1];if(l instanceof ia.ObjectIdentifier&&l.valueBlock.toString()==="1.3.6.1.5.5.7.48.1"&&u.idBlock.tagNumber===6){let d=String.fromCharCode(...Array.from(u.valueBlock.valueHexView));(d.startsWith("http://")||d.startsWith("https://"))&&s.push(d)}}}}catch(o){sa.warn?.(`Failed to parse Authority Information Access extension: ${o}`)}return sa.debug?.(`Found ${n.length} CRL distribution points and ${s.length} OCSP responder URLs`),{crlUrls:n,ocspUrls:s}}catch(t){return sa.warn?.(`Failed to extract revocation URLs: ${t}`),{crlUrls:[],ocspUrls:[]}}}function $l(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s/g,""),r=atob(t),n=new ArrayBuffer(r.length),s=new Uint8Array(n);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return n}function pT(e,t,r,n){let s={certPem:e,issuerPem:t,method:r,...n},i=(0,YC.createHash)("sha256").update(JSON.stringify(s)).digest("hex");return`${r}:${i}`}function zC(e,t){return`${e}:${t}`}function s1(e){try{let t=$l(e),n=mo.Certificate.fromBER(t).serialNumber.valueBlock.valueHexView;return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw sa.error?.(`Failed to extract serial number: ${t}`),new Error(`Failed to extract certificate serial number: ${t.message}`)}}function jC(e){try{let t=$l(e),r=mo.Certificate.fromBER(t),n=r.extensions?.find(i=>i.extnID==="2.5.29.35");if(n){let i=new mo.AuthorityKeyIdentifier({schema:n.parsedValue});if(i.keyIdentifier){let o=i.keyIdentifier.valueBlock.valueHexView;return Array.from(o).map(c=>c.toString(16).padStart(2,"0")).join("")}}let s=r.issuer.typesAndValues.map(i=>`${i.type}=${i.value.valueBlock.value}`).join(",");return(0,YC.createHash)("sha256").update(s).digest("hex")}catch(t){throw sa.error?.(`Failed to extract issuer key ID: ${t}`),new Error(`Failed to extract issuer key ID: ${t.message}`)}}function hT(){return KC||(KC=Xe({table:"hdb_certificate_cache",database:"system",attributes:[{name:"certificate_id",isPrimaryKey:!0},{name:"status"},{name:"reason"},{name:"checked_at"},{name:"expiresAt",expiresAt:!0,indexed:!0},{name:"method"}]})),KC}var YC,mo,ia,t1,sa,KC,ET=se(()=>{YC=require("node:crypto"),mo=b(require("pkijs")),ia=b(require("asn1js")),t1=b(wr());we();sa=(0,t1.loggerWithTag)("cert-verification-utils");a(Ec,"bufferToPem");a(r1,"extractCertificateChain");a(WC,"extractCRLDistributionPoints");a(n1,"extractRevocationUrls");a($l,"pemToBuffer");a(pT,"createCacheKey");a(zC,"createRevokedCertificateId");a(s1,"extractSerialNumber");a(jC,"extractIssuerKeyId");KC=null;a(hT,"getCertificateCacheTable")});function i1(e){let{error:t,value:r}=Cue.validate(e,{abortEarly:!1,allowUnknown:!1});if(t){let n=t.details.map(s=>s.message).join("; ");throw new Error(`Invalid certificate verification configuration: ${n}`)}return r}var Yr,Iue,ef,tf,QC,wue,Nue,Cue,o1=se(()=>{Yr=b(require("joi")),Iue="fail-closed",ef={timeout:5e3,cacheTtl:36e5,errorCacheTtl:3e5,failureMode:"fail-closed"},tf={timeout:1e4,cacheTtl:864e5,failureMode:"fail-closed",gracePeriod:864e5},QC=Yr.default.string().valid("fail-open","fail-closed"),wue=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...tf}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(tf.timeout).messages({"number.min":"CRL timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(tf.cacheTtl).messages({"number.min":"CRL cacheTtl must be at least 1000ms (1 second)"}),failureMode:QC.default(tf.failureMode),gracePeriod:Yr.default.number().min(0).default(tf.gracePeriod).messages({"number.min":"CRL gracePeriod must be at least 0ms"})})),Nue=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...ef}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(ef.timeout).messages({"number.min":"OCSP timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(ef.cacheTtl).messages({"number.min":"OCSP cacheTtl must be at least 1000ms (1 second)"}),errorCacheTtl:Yr.default.number().min(1e3).default(ef.errorCacheTtl).messages({"number.min":"OCSP errorCacheTtl must be at least 1000ms (1 second)"}),failureMode:QC.default(ef.failureMode)})),Cue=Yr.default.object({failureMode:QC.default(Iue),crl:wue.default({enabled:!0,...tf}),ocsp:Nue.default({enabled:!0,...ef})});a(i1,"validateAndParseCertificateVerificationConfig")});function h1(e){if(typeof e=="boolean"||e==null){if(e===JC&&XC)return po.trace?.("Using cached validation error result (primitive) - returning disabled"),!1;if(e===JC&&_T!==null)return po.trace?.("Using cached certificate verification config (primitive)"),_T;po.trace?.("Parsing and caching certificate verification config (primitive)"),JC=e;try{return _T=l1(e),XC=null,_T}catch(n){return XC=n,po.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}if(c1.get(e))return po.trace?.("Using cached validation error result (object) - returning disabled"),!1;let r=a1.get(e);if(r!==void 0)return po.trace?.("Using cached certificate verification config (object)"),r;po.trace?.("Parsing and caching certificate verification config (object)");try{let n=l1(e);return a1.set(e,n),n}catch(n){return c1.set(e,n),po.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}function l1(e){if(po.trace?.(`getCertificateVerificationConfig called with: ${JSON.stringify({mtlsConfig:e})}`),!e)return!1;let t=e===!0?void 0:e.certificateVerification;return po.trace?.(`Certificate verification config: ${JSON.stringify({verificationConfig:t})}`),t==null||t===!1?!1:i1(t===!0?{}:t)}var u1,d1,po,f1,m1,p1,a1,JC,_T,c1,XC,ZC=se(()=>{u1=b(wr()),d1=b(yt());o1();po=(0,u1.loggerWithTag)("cert-verification-config"),f1=10080*60*1e3,m1=3e5,p1=`Harper/${d1.packageJson.version} CRL-Client`,a1=new WeakMap,JC=null,_T=null,c1=new WeakMap,XC=null;a(h1,"getCachedCertificateVerificationConfig");a(l1,"getCertificateVerificationConfig")});function gh(e){return e===_1||e===Oue}function Pue(e){return e===g1||e===S1}function eO(e){return e===_1?g1:S1}function Lue(){if(E1)return;E1=!0;let e=Vl.CryptoEngine.prototype,t=Vl.Certificate.prototype,r={getHashAlgorithm:e.getHashAlgorithm,getAlgorithmByOID:e.getAlgorithmByOID,getAlgorithmParameters:e.getAlgorithmParameters,verifyWithPublicKey:e.verifyWithPublicKey,certificateVerify:t.verify,getPublicKey:t.getPublicKey};e.getHashAlgorithm=function(...n){let[s]=n;return gh(s.algorithmId)?"UNUSED-EDDSA-BUILTIN-HASH":r.getHashAlgorithm.call(this,s)},e.getAlgorithmByOID=function(...n){let[s]=n;return gh(s)?{name:eO(s)}:r.getAlgorithmByOID.call(this,...n)},e.getAlgorithmParameters=function(...n){let[s,i]=n;return Pue(s)?{algorithm:{name:s},usages:i==="sign"?["sign"]:["verify"]}:r.getAlgorithmParameters.call(this,...n)},t.getPublicKey=async function(...n){let[,s=Vl.getCrypto(!0)]=n,i=this.subjectPublicKeyInfo.algorithm.algorithmId;if(gh(i)){let o=eO(i);return s.importKey("spki",this.subjectPublicKeyInfo.toSchema().toBER(!1),o,!0,["verify"])}return r.getPublicKey.call(this,...n)},t.verify=async function(...n){let[s]=n;if(gh(this.signatureAlgorithm.algorithmId))try{let i=this.toSchema().toBER(!1),o=s.toSchema().toBER(!1),c=new Sh.X509Certificate(Buffer.from(i)),l=new Sh.X509Certificate(Buffer.from(o));return c.verify(l.publicKey)}catch{return!1}return r.certificateVerify.call(this,...n)},r.verifyWithPublicKey&&(e.verifyWithPublicKey=async function(...n){let[s,i,o]=n,c=o.algorithm.algorithmId;if(gh(c)){let l=eO(c);try{let u=this.crypto?.subtle||this.subtle||Vl.getCrypto(!0)?.subtle||Sh.webcrypto?.subtle;if(!u)throw new Error("No crypto.subtle available");let d=await u.importKey("spki",o.toSchema().toBER(!1),l,!1,["verify"]),f=i.valueBlock.valueHexView;return"unusedBits"in i.valueBlock&&i.valueBlock.unusedBits>0&&(f=f.slice(0,f.length-1)),await u.verify(l,d,f,s)}catch{return!1}}return r.verifyWithPublicKey.call(this,...n)})}var Vl,Sh,_1,Oue,g1,S1,E1,T1=se(()=>{Vl=b(require("pkijs")),Sh=require("node:crypto"),_1="1.3.101.112",Oue="1.3.101.113",g1="Ed25519",S1="Ed448",E1=!1;a(gh,"isEd25519OrEd448");a(Pue,"isEdDSAAlgorithmName");a(eO,"getEdDSAAlgorithmName");a(Lue,"applyEd25519Patch");Lue()});var A1={};ye(A1,{CRLSignatureVerificationError:()=>Th,performCRLCheck:()=>Mue,verifyCRL:()=>nO});function Due(){return gT||(gT=hT(),gT.sourcedFrom(rf)),gT}function vue(){return ST||(ST=Xe({table:"hdb_crl_cache",database:"system",attributes:[{name:"distribution_point",isPrimaryKey:!0},{name:"issuer_dn"},{name:"crl_blob"},{name:"this_update"},{name:"next_update"},{name:"signature_valid"},{name:"expiresAt",expiresAt:!0,indexed:!0}]}),ST.sourcedFrom(rO)),ST}function R1(){return tO||(tO=Xe({table:"hdb_revoked_certificates",database:"system",attributes:[{name:"composite_id",isPrimaryKey:!0},{name:"serial_number",indexed:!0},{name:"issuer_key_id",indexed:!0},{name:"revocation_date"},{name:"revocation_reason"},{name:"crl_source",indexed:!0},{name:"crl_next_update"},{name:"expiresAt",expiresAt:!0,indexed:!0}]})),tO}async function nO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Ec(e,"CERTIFICATE"),i=Ec(t,"CERTIFICATE"),o=n??WC(s);if(o.length===0)return{valid:!0,status:"no-crl-distribution-points",method:"crl"};let c=pT(s,i,"crl"),l=await Due().get(c,{certPem:s,issuerPem:i,distributionPoint:o[0],config:{crl:r??{}}});if(!l)return Pr.error?.("Cache fetch returned null - this indicates a source configuration issue"),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:"Cache fetch failed",method:"crl"}:(Pr.warn?.("CRL cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"});let u=l,d=l.wasLoadedFromSource?.();return Pr.trace?.(`CRL ${d?"source fetch":"cache hit"} for certificate`),{valid:u.status==="good",status:u.status,cached:!d,method:u.method||"crl"}}catch(s){return Pr.error?.(`CRL verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"crl"}:(Pr.warn?.("CRL check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"})}}async function Mue(e,t,r,n){let s=n??WC(e);if(s.length===0)return{status:"good"};let i=s1(e),o=jC(t),c=zC(o,i);try{let u=await R1().get(c);if(u){let f=Date.now(),m=u;return m.crl_next_update>f?{status:"revoked",reason:m.revocation_reason||"unspecified",source:m.crl_source}:m.crl_next_update+r.gracePeriod>f?(Pr.warn?.("Using expired CRL data within grace period"),{status:"revoked",reason:m.revocation_reason||"unspecified",source:m.crl_source}):(Pr.warn?.("CRL data is too old, treating as unknown"),{status:"unknown",reason:"crl-expired"})}let d=await Uue(s,t,r);return d.upToDate?{status:"good",source:d.source}:(Pr.warn?.("CRL data is stale or missing, treating as unknown"),{status:"unknown",reason:d.reason||"crl-unavailable"})}catch(l){return Pr.error?.(`CRL lookup error: ${l}`),{status:"unknown",reason:l.message}}}async function Uue(e,t,r){let n=Date.now();for(let s of e)try{let i=vue(),o=null,c=null;try{c=await i.get(s),(c&&c.next_update>n||c&&c.next_update+r.gracePeriod>n)&&(o=c)}catch{}o||(o=await b1(s,t,r.timeout));let l=o.next_update;if(l>n){if(!c)try{await i.put(s,o)}catch{}return{upToDate:!0,source:s}}else return l+r.gracePeriod>n?{upToDate:!0,source:s}:{upToDate:!1,reason:"crl-expired"}}catch(i){if(i instanceof Th)throw i}return{upToDate:!1,reason:"no-current-crl-data"}}async function b1(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let i=await fetch(e,{signal:n.signal,headers:{"User-Agent":p1}});if(clearTimeout(s),!i.ok)throw new Error(`CRL download failed: ${i.status}`);let o=Buffer.from(await i.arrayBuffer()),c,l=o.toString("utf8");l.includes("-----BEGIN X509 CRL-----")?c=Buffer.from($l(l)):c=o;let u=TT.CertificateRevocationList.fromBER(c),d=TT.Certificate.fromBER($l(t)),f=await u.verify({issuerCertificate:d});if(!f){let g=`CRL signature verification failed for: ${e}`;throw Pr.error?.(g),new Th(g)}let m=u.thisUpdate.value.getTime(),p=u.nextUpdate?.value.getTime()??m+f1,h=d.issuer.typesAndValues.map(g=>`${g.type}=${g.value.valueBlock.value}`).join(","),E={distribution_point:e,issuer_dn:h,crl_blob:o,this_update:m,next_update:p,signature_valid:f,expiresAt:p};return xue(u,t,e,p).catch(g=>{Pr.error?.(`Error processing revoked certificates: ${g}`)}),E}finally{clearTimeout(s)}}async function xue(e,t,r,n){let s=R1(),i=jC(t),o=r;try{await Bue(s,o)}catch(c){Pr.warn?.(`Failed to clear existing CRL entries: ${c}`)}if(e.revokedCertificates)for(let c of e.revokedCertificates)try{let l=c.userCertificate.valueBlock.valueHexView;if(!l){Pr.warn?.("Could not extract serial number from revoked certificate");continue}let u=Array.from(l).map(h=>h.toString(16).padStart(2,"0")).join(""),d=zC(i,u),f=c.revocationDate.value.getTime(),p={composite_id:d,serial_number:u,issuer_key_id:i,revocation_date:f,revocation_reason:"unspecified",crl_source:o,crl_next_update:n,expiresAt:n};await s.create(p.composite_id,p)}catch(l){Pr.warn?.(`Failed to process revoked certificate: ${l}`)}}async function Bue(e,t){try{let r=e.search([{attribute:"crl_source",value:t}]);for await(let n of r)try{await e.delete(n.composite_id)}catch(s){Pr.warn?.(`Failed to delete revoked certificate entry: ${s}`)}}catch(r){throw Pr.error?.(`Failed to search for existing CRL entries: ${r}`),r}}var TT,y1,Th,Pr,gT,rO,ST,tO,sO=se(()=>{TT=b(require("pkijs")),y1=b(wr());we();Vo();ET();ZC();iO();Th=class extends Error{static{a(this,"CRLSignatureVerificationError")}constructor(t){super(t),this.name="CRLSignatureVerificationError"}},Pr=(0,y1.loggerWithTag)("crl-verification");a(Due,"getCertificateCacheTable");rO=class extends lr{static{a(this,"CertificateRevocationListSource")}async get(t){let n=this.getContext()?.requestContext;if(!n?.distributionPoint||!n?.issuerPem)throw new Error(`No CRL data provided for cache key: ${t}`);let{distributionPoint:s,issuerPem:i,config:o}=n;try{let c=await b1(s,i,o.timeout),l=c.next_update,u=Date.now()+o.cacheTtl,d=Math.min(l,u);return{...c,expiresAt:d}}catch(c){if(Pr.error?.(`CRL fetch error for: ${s} - ${c}`),o.failureMode==="fail-closed"){let l=Date.now()+m1;return{crl_id:t,distribution_point:s,issuer_dn:"unknown",crl_blob:Buffer.alloc(0),this_update:Date.now(),next_update:l,signature_valid:!1,expiresAt:l}}return Pr.warn?.("CRL fetch failed, not caching (fail-open mode)"),null}}};a(vue,"getCRLCacheTable");a(R1,"getRevokedCertificateTable");a(nO,"verifyCRL");a(Mue,"performCRLCheck");a(Uue,"checkCRLFreshness");a(b1,"downloadAndParseCRL");a(xue,"processRevokedCertificates");a(Bue,"clearExistingCRLEntries")});async function Fue(){oO||(oO=(await Promise.resolve().then(()=>(sO(),A1))).performCRLCheck),aO||(aO=(await Promise.resolve().then(()=>(cO(),w1))).performOCSPCheck)}var I1,Qxe,oO,aO,rf,iO=se(()=>{Vo();I1=b(wr()),Qxe=(0,I1.loggerWithTag)("cert-verification-source");a(Fue,"loadVerificationFunctions");rf=class extends lr{static{a(this,"CertificateVerificationSource")}async get(t){let r=t.id,s=this.getContext()?.requestContext;if(!s||!s.certPem||!s.issuerPem)return null;let{certPem:i,issuerPem:o,ocspUrls:c,config:l}=s,u;r.startsWith("crl:")?u="crl":r.startsWith("ocsp:")?u="ocsp":u="unknown",await Fue();let d,f;if(u==="crl"){f=l.crl;let p=s.distributionPoint?[s.distributionPoint]:void 0;d=await oO(i,o,f,p)}else if(u==="ocsp")f=l.ocsp,d=await aO(i,o,f,c);else throw new Error(`Unsupported verification method: ${u} for ID: ${r}`);let m=Date.now()+f.cacheTtl;return{certificate_id:r,status:d.status,reason:d.reason,checked_at:Date.now(),expiresAt:m,method:u}}}});var w1={};ye(w1,{performOCSPCheck:()=>Hue,verifyOCSP:()=>lO});function kue(){return RT||(RT=hT(),RT.sourcedFrom(rf)),RT}async function lO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Ec(e,"CERTIFICATE"),i=Ec(t,"CERTIFICATE"),o=pT(s,i,"ocsp"),c=await kue().get(o,{certPem:s,issuerPem:i,ocspUrls:n,config:{ocsp:r??{}}});if(!c)return r.failureMode==="fail-closed"?{valid:!1,status:"error",error:"Cache fetch failed",method:"ocsp"}:(yT.warn?.("OCSP cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"});let l=c,u=c.wasLoadedFromSource?.();return yT.trace?.(`OCSP ${u?"source fetch":"cache hit"} for certificate`),{valid:l.status==="good",status:l.status,cached:!u,method:l.method||"ocsp"}}catch(s){return yT.error?.(`OCSP verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"ocsp"}:(yT.warn?.("OCSP check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"})}}async function Hue(e,t,r,n){try{let s=await(0,N1.getCertStatus)(e,{ca:t,timeout:r.timeout,...n?.length&&{ocspUrl:n[0]}});switch(s.status){case"good":return{status:"good"};case"revoked":return{status:"revoked",reason:s.revocationReason?.toString()||"unspecified"};default:return{status:"unknown",reason:"unknown-status"}}}catch(s){return{status:"unknown",reason:s.name==="AbortError"?"timeout":"ocsp-error"}}}var N1,C1,yT,RT,cO=se(()=>{T1();N1=require("easy-ocsp"),C1=b(wr());ET();iO();yT=(0,C1.loggerWithTag)("ocsp-verification");a(kue,"getCertificateCacheTable");a(lO,"verifyOCSP");a(Hue,"performOCSPCheck")});async function nf(e,t){an.debug?.(`verifyCertificate called for: ${e.subject?.CN||"unknown"}`);let r=h1(t);if(r===!1)return an.debug?.("Certificate verification disabled"),{valid:!0,status:"disabled",method:"disabled"};let n=r1(e);if(an.trace?.(`Certificate chain length: ${n.length}`),n.length<2||!n[0].issuer)return an.debug?.("Certificate chain insufficient for revocation checking - need certificate and issuer"),{valid:!0,status:"no-issuer-cert",method:"disabled"};let s=Ec(n[0].cert,"CERTIFICATE"),{crlUrls:i,ocspUrls:o}=n1(s);if(an.debug?.(`Certificate extensions: CRL distribution points=${i.length}, OCSP URLs=${o.length}`),i.length>0)if(r.crl.enabled)try{an.debug?.("Attempting CRL verification");let c=await nO(n[0].cert,n[0].issuer,r.crl,i);if(c.status==="good"||c.status==="revoked")return an.debug?.(`CRL verification result: ${c.status}`),c;an.debug?.(`CRL verification inconclusive: ${c.status}, trying OCSP fallback`)}catch(c){an.warn?.(`CRL verification failed: ${c}`)}else an.debug?.("Skipping CRL - disabled in configuration");else an.debug?.("Skipping CRL - no distribution points in certificate");if(o.length>0)if(r.ocsp.enabled)try{an.debug?.("Attempting OCSP verification");let c=await lO(n[0].cert,n[0].issuer,r.ocsp,o);return an.debug?.(`OCSP verification result: ${c.status}`),c}catch(c){an.warn?.(`OCSP verification failed: ${c}`)}else an.debug?.("Skipping OCSP - disabled in configuration");else an.debug?.("Skipping OCSP - no responder URLs in certificate");return r.failureMode==="fail-closed"?{valid:!1,status:"no-verification-available",method:"disabled"}:{valid:!0,status:"verification-unavailable-allowed",method:"disabled"}}var O1,an,bT=se(()=>{O1=b(wr());ET();ZC();cO();sO();an=(0,O1.loggerWithTag)("cert-verification");a(nf,"verifyCertificate")});var ra={};ye(ra,{buildReplicationMtlsConfig:()=>F1,clearThisNodeName:()=>jue,disableReplication:()=>Vue,enabledDatabases:()=>pc,forEachReplicatedDatabase:()=>lc,getThisNodeId:()=>mT,getThisNodeName:()=>tt,getThisNodeUrl:()=>uc,hostnameToUrl:()=>NT,lastTimeInAuditStore:()=>ah,monitorNodeCAs:()=>k1,replicateOperation:()=>Jue,replicationCertificateAuthorities:()=>na,sendOperationToNode:()=>yh,servers:()=>que,setReplicator:()=>G1,start:()=>$ue,startOnMainThread:()=>TC,subscribeToNode:()=>dh,unsubscribeFromNode:()=>tT,urlToNodeName:()=>yi});function F1(e){return e?.mtls&&typeof e.mtls=="object"?e.mtls:!0}function $ue(e){if(!e.port&&!e.securePort&&(e.port=Ys.default.get(F.OPERATIONSAPI_NETWORK_PORT),e.securePort=Ys.default.get(F.OPERATIONSAPI_NETWORK_SECUREPORT)),!tt())throw new Error("Can not load replication without a url (see replication.url in the config)");let t=new Map;for(let i of lh(e))t.set(yi(i.url),i);Kue(e);let r=F1(e);e={isOperationsServer:!0,maxPayload:10*1024*1024*1024,...e,mtls:r};let n=Be.ws(async(i,o,c,l)=>{if(It.debug("Incoming WS connection received "+o.url),o.headers.get("sec-websocket-protocol")!=="harperdb-replication-v1")return l(i,o,c);i._socket.unref(),_h(i,e,c.then(()=>o?.user)),i.on("error",u=>{u.code!=="ECONNREFUSED"&&It.error("Error in connection to "+this.url,u.message)})},e);e.runFirst=!0,Be.http(async(i,o)=>{if(i.isWebSocket&&i.headers.get("Sec-WebSocket-Protocol")==="harperdb-replication-v1"){It.debug("Incoming replication WS connection received, authorized: "+i.authorized),!i.authorized&&i._nodeRequest.socket.authorizationError&&It.error(`Incoming client connection from ${i.ip} did not have valid certificate, you may need turn on enableRootCAs in the config if you are using a publicly signed certificate, or add the CA to the server's trusted CAs`,i._nodeRequest.socket.authorizationError);let c=Ht().primaryStore;if(i.authorized&&i.peerCertificate.subjectaltname){let l=(0,x1.getHostnamesFromCertificate)(i.peerCertificate),u;for(let d of l)if(u=d&&(c.get(d)||t.get(d)),u)break;if(u){let d=await nf(i.peerCertificate,e.mtls);if(!d.valid){It.warn("Certificate verification failed:",d.status,"for node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}if(u?.revoked_certificates?.includes(i.peerCertificate.serialNumber)){It.warn("Revoked certificate used in attempt to connect to node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}else i.user=u}else It.warn(`No node found for certificate common name/SANs: ${l}, available nodes are ${Array.from(c.getRange({}).filter(({value:d})=>d).map(({key:d})=>d)).join(", ")} and routes ${Array.from(t.keys()).join(", ")}, connection will require credentials.`)}else{let l=c.get(i.ip)||t.get(i.ip);l?i.user=l:It.warn(`No node found for IP address ${i.ip}, available nodes are ${Array.from(new Set([...c.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}}return o(i)},e);let s=[];for(let i of n)if(i.secureContexts){let o=a(()=>{let c=new Set(i.secureContexts.values());i.defaultContext&&c.add(i.defaultContext);for(let l of c)try{let u=Array.from(na);l.options.availableCAs&&u.push(...l.options.availableCAs.values());let d={...l.options,ca:u};l.updatedContext=wT.createSecureContext(d)}catch(u){It.error("Error creating replication TLS config",u)}},"updateContexts");i.secureContextsListeners.push(o),s.push(o),Ys.default.get(F.REPLICATION_ENABLEROOTCAS)!==!1&&o()}k1(()=>{for(let i of s)i()})}function k1(e){let t=0;Yd(r=>{r?.ca&&(na.add(r.ca),na.size!==t&&(t=na.size,e?.()))})}function Vue(e=!0){B1=e}function Kue(e){B1||(ct(),pc=e.databases,lc(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||hc;for(let[s,i]of IT){let o=i.get(r);o&&(o.subscribe([],!1),i.delete(r))}n.delete(r);return}for(let n in t){let s=t[n];G1(r,s,e),$C.get(s)?.forEach(i=>i(s))}}))}function G1(e,t,r){if(!t)return console.error(`Attempt to replicate non-existent table ${t.name} from database ${e}`);if(t.replicate===!1||t.sources?.some(s=>s.isReplicator))return;let n;t.sourcedFrom(class H1 extends lr{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||hc,o=i.get(e),c=o?.tableById||[];c[t.tableId]=t;let l=o?.ready;if(It.trace("Setting up replicator subscription to database",e),!o?.auditStore)return this.subscription=o=new ns,i.set(e,o),o.tableById=c,o.auditStore=t.auditStore,o.dbisDB=t.dbisDB,o.databaseName=e,l&&l(o),o;this.subscription=o}static subscribeOnThisThread(i,o){return!0}static async load(i){if(i){let o=i.residencyId,c=i.residency||t.dbisDB.get([Symbol.for("residency_by_id"),o]);if(c){let l,u=new Set;do{let d,f="",m=1/0;for(let h of c){if(u.has(h)||h===Be.hostname)continue;let E=Wue(h,H1.subscription,e);if(E?.isConnected){let g=Kd(t.auditStore,e,h)[dT];(!d||g<m)&&(d=E,f=h,m=g)}}if(!d)throw l||new M1.ServerError(`No connection to any other nodes are available: ${c}`,502);let p={requestId:Gue++,table:t,entry:i,id:i.key};u.add(f);try{return await d.getRecord(p)}catch(h){if(d.isConnected)throw h;It.warn("Error in load from node",Kl,h),l||(l=h)}}while(!0)}}}static isReplicator=!0},{intermediateSource:!0})}function Yue(e,t,r,n,s,i){let o=t+"-"+e,c=IT.get(o);c||(c=new Map,IT.set(o,c));let l=c.get(n);if(l)return l;if(r)return c.set(n,l=new Zd(t,r,n,s,i)),l.connect(),l.once("finished",()=>c.delete(n)),l}function Wue(e,t,r){let n=P1.get(Kl);n||(n=new Map,P1.set(Kl,n));let s=n.get(r);if(s)return s;let i=Ht().primaryStore.get(e);return i?.url&&(s=new Zd(i.url,t,r,Kl,i.authorization),n.set(r,s),s.connect(),s.once("finished",()=>n.delete(r))),s}async function yh(e,t,r){r||(r={}),r.serverName=e.name;let n=await fT(e.url,r),s=_h(n,{},{});return new Promise((i,o)=>{n.on("open",()=>{It.debug("Sending operation connection to "+e.url+" opened",t),i(s.sendOperation(t))}),n.on("error",c=>{o(c)}),n.on("close",c=>{It.info("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function dh(e){try{U1.isMainThread&&It.warn("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=hc.get(e.database);if(!t){let n;t=new Promise(s=>{It.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,hc.set(e.database,t)}let r=Yue(e.nodes[0].url,e.url,t,e.database,e.name,e.nodes[0].authorization);e.nodes[0].name===void 0?r.tentativeNode=e.nodes[0]:r.nodeName=e.nodes[0].name,r.subscribe(e.nodes.filter(n=>ch(n,e.database)),e.replicateByDefault)}catch(t){It.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function tT({url:e,nodes:t,database:r}){It.trace("Unsubscribing from node",e,r,"nodes",Array.from(Ht().primaryStore.getRange({})));let n=e+"-"+(t[0]?.url??e),s=IT.get(n);if(s){let i=s.get(r);i&&(i.unsubscribe(),s.delete(r))}}function zue(){if(uO!==void 0)return uO;let e=Ys.default.get(F.OPERATIONSAPI_TLS_CERTIFICATE)||Ys.default.get(F.TLS_CERTIFICATE);if(e)return uO=new D1.X509Certificate((0,v1.readFileSync)(e)).subject?.match(/CN=(.*)/)?.[1]??null}function tt(){return Kl||(Kl=Ys.default.get("replication_hostname")??yi(Ys.default.get("replication_url"))??zue()??L1("operationsapi_network_secureport")??L1("operationsapi_network_port")??"127.0.0.1")}function jue(){Kl=void 0}function L1(e){let t=Ys.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function AT(e){let t=Ys.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function mT(e){return oh(e)?.[tt()]}function uc(){let e=Ys.default.get("replication_url");return e||NT(tt())}function NT(e){let t=AT("replication_port");if(t)return`ws://${e}:${t}`;if(t=AT("replication_secureport"),t)return`wss://${e}:${t}`;if(t=AT("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=AT("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function yi(e){if(e)return new URL(e).hostname}function lc(e,t){for(let n of Object.getOwnPropertyNames(Me))r(n);return jp(n=>{r(n)}),Bl((n,s)=>{r(n.databaseName)});function r(n){let s=Me[n];It.trace("Checking replication status of ",n,e?.databases),e?.databases===void 0||e.databases==="*"||e.databases.includes(n)||e.databases.some?.(i=>i.name===n)||!s?t(s,n,!0):Que(n)&&t(s,n,!1)}a(r,"forDatabase")}function Que(e){let t=Me[e];for(let r in t)if(t[r].replicate)return!0}function ah(e){for(let t of e.getKeys({limit:1,reverse:!0}))return t}async function Jue(e){let t={message:""};if(e.replicated){e.replicated=!1,It.trace?.("Replicating operation",e.operation,"to nodes",Be.nodes.map(n=>n.name));let r=await Promise.allSettled(Be.nodes.map(n=>yh(n,e)));t.replicated=r.map((n,s)=>{let i=n.status==="rejected"?{status:"failed",reason:n.reason.toString()}:n.value;return i.node=Be.nodes[s]?.name,i})}return t}var Ys,It,D1,v1,wT,M1,U1,x1,B1,Gue,que,na,pc,IT,P1,uO,Kl,Ss=se(()=>{we();Vo();Uu();VC();Hr();Ys=b(me()),It=b(J()),D1=require("crypto");bT();v1=require("fs");fh();Wd();H();SC();wT=b(require("node:tls")),M1=b(_e()),U1=require("worker_threads"),x1=b(ys()),Gue=1,que=[],na=Ys.default.get(F.REPLICATION_ENABLEROOTCAS)!==!1?new Set(wT.rootCertificates):new Set;a(F1,"buildReplicationMtlsConfig");a($ue,"start");a(k1,"monitorNodeCAs");a(Vue,"disableReplication");a(Kue,"assignReplicationSource");a(G1,"setReplicator");IT=new Map;a(Yue,"getSubscriptionConnection");P1=new Map;a(Wue,"getRetrievalConnectionByName");a(yh,"sendOperationToNode");a(dh,"subscribeToNode");a(tT,"unsubscribeFromNode");a(zue,"getCommonNameFromCert");a(tt,"getThisNodeName");a(jue,"clearThisNodeName");Object.defineProperty(Be,"hostname",{get(){return tt()}});a(L1,"getHostFromListeningPort");a(AT,"getPortFromListeningPort");a(mT,"getThisNodeId");Be.replication={getThisNodeId:mT,exportIdMapping:oh};a(uc,"getThisNodeUrl");a(NT,"hostnameToUrl");a(yi,"urlToNodeName");a(lc,"forEachReplicatedDatabase");a(Que,"hasExplicitlyReplicatedTable");a(ah,"lastTimeInAuditStore");a(Jue,"replicateOperation")});var DT=M((T0e,Y1)=>{"use strict";var sf=z$(),{validateBySchema:Rh}=mt(),{commonValidators:of,schemaRegex:dO}=Qi(),Er=require("joi"),Xue=J(),Zue=require("uuid").v4,PT=Wo(),af=(H(),v(z)),ede=require("util"),_c=fs(),{handleHDBError:oa,hdbErrors:tde,ClientError:Yl}=_e(),{HDB_ERROR_MSGS:CT,HTTP_STATUS_CODES:aa}=tde,{SchemaEventMsg:LT}=ls(),q1=_r(),{getDatabases:rde}=(we(),v(ft)),{transformReq:cf}=oe(),{replicateOperation:$1}=(Ss(),v(ra)),{cleanupOrphans:nde}=(ss(),v(H_)),OT=Er.string().min(1).max(of.schema_length.maximum).pattern(dO).messages({"string.pattern.base":"{:#label} "+of.schema_format.message}),sde=Er.string().min(1).max(of.schema_length.maximum).pattern(dO).messages({"string.pattern.base":"{:#label} "+of.schema_format.message}).required(),ide=Er.string().min(1).max(of.schema_length.maximum).pattern(dO).messages({"string.pattern.base":"{:#label} "+of.schema_format.message,"any.required":"'primary_key' is required","string.base":"'primary_key' must be a string"}).required();Y1.exports={createSchema:ode,createSchemaStructure:V1,createTable:ade,createTableStructure:K1,createAttribute:fde,dropSchema:cde,dropTable:lde,dropAttribute:ude,getBackup:mde,cleanupOrphanBlobs:pde};async function ode(e){let t=await V1(e);return PT.signalSchemaChange(new LT(process.pid,e.operation,e.schema)),t}a(ode,"createSchema");async function V1(e){let t=Rh(e,Er.object({database:OT,schema:OT}));if(t)throw new Yl(t.message);if(cf(e),!await sf.checkSchemaExists(e.schema))throw oa(new Error,CT.SCHEMA_EXISTS_ERR(e.schema),aa.BAD_REQUEST,af.LOG_LEVELS.ERROR,CT.SCHEMA_EXISTS_ERR(e.schema),!0);return await _c.createSchema(e),`database '${e.schema}' successfully created`}a(V1,"createSchemaStructure");async function ade(e){return cf(e),e.hash_attribute=e.primary_key??e.hash_attribute,await K1(e)}a(ade,"createTable");async function K1(e){let t=Rh(e,Er.object({database:OT,schema:OT,table:sde,residence:Er.array().items(Er.string().min(1)).optional(),hash_attribute:ide}));if(t)throw new Yl(t.message);if(!await sf.checkSchemaTableExists(e.schema,e.table))throw oa(new Error,CT.TABLE_EXISTS_ERR(e.schema,e.table),aa.BAD_REQUEST,af.LOG_LEVELS.ERROR,CT.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:Zue(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await _c.createTable(n,e);else throw oa(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",aa.BAD_REQUEST);else await _c.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(K1,"createTableStructure");async function cde(e){let t=Rh(e,Er.object({database:Er.string(),schema:Er.string()}).or("database","schema").messages({"object.missing":"'database' is required"}));if(t)throw new Yl(t.message);cf(e);let r=await sf.checkSchemaExists(e.schema);if(r)throw oa(new Error,r,aa.NOT_FOUND,af.LOG_LEVELS.ERROR,r,!0);let n=await sf.schemaDescribe.describeSchema({schema:e.schema}),s=Object.keys(global.hdb_schema[e.schema]);await _c.dropSchema(e),PT.signalSchemaChange(new LT(process.pid,e.operation,e.schema)),await q1.purgeSchemaTableStreams(e.schema,s);let i=await $1(e);return i.message=`successfully deleted '${e.schema}'`,i}a(cde,"dropSchema");async function lde(e){let t=Rh(e,Er.object({database:Er.string(),schema:Er.string(),table:Er.string().required()}));if(t)throw new Yl(t.message);cf(e);let r=await sf.checkSchemaTableExists(e.schema,e.table);if(r)throw oa(new Error,r,aa.NOT_FOUND,af.LOG_LEVELS.ERROR,r,!0);await _c.dropTable(e),await q1.purgeTableStream(e.schema,e.table);let n=await $1(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}a(lde,"dropTable");async function ude(e){let t=Rh(e,Er.object({database:Er.string(),schema:Er.string(),table:Er.string().required(),attribute:Er.string().required()}));if(t)throw new Yl(t.message);cf(e);let r=await sf.checkSchemaTableExists(e.schema,e.table);if(r)throw oa(new Error,r,aa.NOT_FOUND,af.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw oa(new Error,"You cannot drop a hash attribute",aa.BAD_REQUEST,void 0,void 0,!0);if(af.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw oa(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,aa.BAD_REQUEST,void 0,void 0,!0);try{return await _c.dropAttribute(e),dde(e),PT.signalSchemaChange(new LT(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Xue.error(`Got an error deleting attribute ${ede.inspect(e)}.`),n}}a(ude,"dropAttribute");function dde(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(dde,"dropAttributeFromGlobal");async function fde(e){cf(e);let t=rde()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw oa(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,aa.BAD_REQUEST,void 0,void 0,!0);return await _c.createAttribute(e),PT.signalSchemaChange(new LT(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(fde,"createAttribute");function mde(e){return _c.getBackup(e)}a(mde,"getBackup");function pde(e){if(!e.database)throw new Yl('Must provide "database" name for search for orphaned blobs');if(!databases[e.database])throw new Yl(`Unknown database '${e.database}'`);return nde(databases[e.database]),{message:"Orphaned blobs cleanup started, check logs for progress"}}a(pde,"cleanupOrphanBlobs")});var z1=M((R0e,W1)=>{"use strict";var{OPERATIONS_ENUM:hde}=(H(),v(z)),fO=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=hde.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};W1.exports=fO});var mO=M((I0e,Z1)=>{"use strict";var Ede=fs(),A0e=z1(),vT=oe(),MT=(H(),v(z)),_de=me(),{handleHDBError:j1,hdbErrors:gde}=_e(),{HDB_ERROR_MSGS:Q1,HTTP_STATUS_CODES:J1}=gde,Sde=Object.values(MT.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),X1="To use this operation audit log must be enabled in harperdb-config.yaml";Z1.exports=Tde;async function Tde(e){if(vT.isEmpty(e.schema))throw new Error(Q1.SCHEMA_REQUIRED_ERR);if(vT.isEmpty(e.table))throw new Error(Q1.TABLE_REQUIRED_ERR);if(!_de.get(MT.CONFIG_PARAMS.LOGGING_AUDITLOG))throw j1(new Error,X1,J1.BAD_REQUEST,MT.LOG_LEVELS.ERROR,X1,!0);let t=vT.checkSchemaTableExist(e.schema,e.table);if(t)throw j1(new Error,t,J1.NOT_FOUND,MT.LOG_LEVELS.ERROR,t,!0);if(!vT.isEmpty(e.search_type)&&Sde.indexOf(e.search_type)<0)throw new Error(`Invalid searchType '${read_audit_log_object.search_type}'`);return await Ede.readAuditLog(e)}a(Tde,"readAuditLog")});var tK=M((N0e,eK)=>{"use strict";var{OPERATIONS_ENUM:yde}=(H(),v(z)),pO=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=yde.GET_BACKUP,this.schema=t,this.table=r}};eK.exports=pO});var sK=M((L0e,nK)=>{"use strict";var Rde=fs(),O0e=tK(),hO=oe(),bde=(H(),v(z)),P0e=me(),{handleHDBError:Ade,hdbErrors:Ide}=_e(),{HDB_ERROR_MSGS:rK,HTTP_STATUS_CODES:wde}=Ide;nK.exports=Nde;async function Nde(e){if(hO.isEmpty(e.schema))throw new Error(rK.SCHEMA_REQUIRED_ERR);if(hO.isEmpty(e.table))throw new Error(rK.TABLE_REQUIRED_ERR);let t=hO.checkSchemaTableExist(e.schema,e.table);if(t)throw Ade(new Error,t,wde.NOT_FOUND,bde.LOG_LEVELS.ERROR,t,!0);return await Rde.getBackup(readAuditLogObject)}a(Nde,"getBackup")});var cK=M((v0e,aK)=>{"use strict";var Cde=me(),gc=require("joi"),Ode=mt(),iK=require("moment"),Pde=require("fs-extra"),EO=require("path"),Lde=require("lodash"),bh=(H(),v(z)),{LOG_LEVELS:Wl}=(H(),v(z)),Dde="YYYY-MM-DD hh:mm:ss",vde=EO.resolve(__dirname,"../logs");aK.exports=function(e){return Ode.validateBySchema(e,Mde)};var Mde=gc.object({from:gc.custom(oK),until:gc.custom(oK),level:gc.valid(Wl.NOTIFY,Wl.FATAL,Wl.ERROR,Wl.WARN,Wl.INFO,Wl.DEBUG,Wl.TRACE),order:gc.valid("asc","desc"),limit:gc.number().min(1),start:gc.number().min(0),log_name:gc.custom(Ude)});function oK(e,t){if(iK(e,iK.ISO_8601).format(Dde)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(oK,"validateDatetime");function Ude(e,t){if(Lde.invert(bh.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=Cde.get(bh.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?bh.LOG_NAMES.HDB:e,i=s===bh.LOG_NAMES.INSTALL?EO.join(vde,bh.LOG_NAMES.INSTALL):EO.join(n,s);return Pde.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Ude,"validateReadLogPath")});var gO=M((U0e,uK)=>{"use strict";var UT=(H(),v(z)),xde=J(),Bde=me(),Fde=cK(),_O=require("path"),lK=require("fs-extra"),{once:kde}=require("events"),{handleHDBError:Hde,hdbErrors:Gde}=_e(),{PACKAGE_ROOT:qde}=yt(),{replicateOperation:$de}=(Ss(),v(ra)),Vde=_O.join(qde,"logs"),Kde=1e3,Yde=200;uK.exports=Wde;async function Wde(e){let t=Fde(e);if(t)throw Hde(t,t.message,Gde.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=$de(e),n=Bde.get(UT.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?UT.LOG_NAMES.HDB:e.log_name,i=s===UT.LOG_NAMES.INSTALL?_O.join(Vde,UT.LOG_NAMES.INSTALL):_O.join(n,s),o=e.level!==void 0,c=o?e.level:void 0,l=e.from!==void 0,u=l?new Date(e.from):void 0,d=e.until!==void 0,f=d?new Date(e.until):void 0,m=e.limit===void 0?Kde:e.limit,p=e.order===void 0?void 0:e.order,h=e.start===void 0?0:e.start,E=h+m,g=0;p==="desc"&&!u&&!f&&(g=Math.max(lK.statSync(i).size-(E+5)*Yde,0));let R=lK.createReadStream(i,{start:g});R.on("error",G=>{xde.error(G)});let S=0,y=[],N="",I;R.on("data",G=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;G=N+G;let j=0,Y;for(;(Y=k.exec(G))&&!R.destroyed;){I&&(I.message=G.slice(j,Y.index),$(I));let[ce,de,te]=Y,ge=te.split("] ["),be=ge[0],Ye=ge[1];ge.splice(0,2),I={timestamp:de,thread:be,level:Ye,tags:ge,message:""},j=Y.index+ce.length}N=G.slice(j)}),R.on("end",G=>{R.destroyed||I&&(I.message=N.trim(),$(I))}),R.resume();function $(G){let k,j,Y;switch(!0){case(o&&l&&d):k=new Date(G.timestamp),j=new Date(u),Y=new Date(f),G.level===c&&k>=j&&k<=Y&&S<h?S++:G.level===c&&k>=j&&k<=Y&&(ho(G,p,y),S++,S===E&&R.destroy());break;case(o&&l):k=new Date(G.timestamp),j=new Date(u),G.level===c&&k>=j&&S<h?S++:G.level===c&&k>=j&&(ho(G,p,y),S++,S===E&&R.destroy());break;case(o&&d):k=new Date(G.timestamp),Y=new Date(f),G.level===c&&k<=Y&&S<h?S++:G.level===c&&k<=Y&&(ho(G,p,y),S++,S===E&&R.destroy());break;case(l&&d):k=new Date(G.timestamp),j=new Date(u),Y=new Date(f),k>=j&&k<=Y&&S<h?S++:k>=j&&k<=Y&&(ho(G,p,y),S++,S===E&&R.destroy());break;case o:G.level===c&&S<h?S++:G.level===c&&(ho(G,p,y),S++,S===E&&R.destroy());break;case l:k=new Date(G.timestamp),j=new Date(u),k>=j&&S<h?S++:k>=j&&S>=h&&(ho(G,p,y),S++,S===E&&R.destroy());break;case d:k=new Date(G.timestamp),Y=new Date(f),k<=Y&&S<h?S++:k<=Y&&S>=h&&(ho(G,p,y),S++,S===E&&R.destroy());break;default:S<h?S++:(ho(G,p,y),S++,S===E&&R.destroy())}}a($,"onLogMessage"),await kde(R,"close");let ee=await r;if(ee.replicated){for(let G of y)G.node=server.hostname;for(let G of ee.replicated){let k=G.node;if(G.status==="failed")ho({timestamp:new Date().toISOString(),level:"error",node:k,message:`Error retrieving logs: ${G.reason}`},p,y);else for(let j of G.results)j.node=k,ho(j,p,y)}}return y}a(Wde,"readLog");function ho(e,t,r){t==="desc"?zde(e,r):t==="asc"?jde(e,r):r.push(e)}a(ho,"pushLineToResult");function zde(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(zde,"insertDescending");function jde(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(jde,"insertAscending")});var xT=M((G0e,pK)=>{"use strict";var SO=require("joi"),{string:lf,boolean:dK,date:Qde}=SO.types(),Jde=mt(),{validateSchemaExists:B0e,validateTableExists:F0e,validateSchemaName:k0e}=Qi(),Xde=(H(),v(z)),Zde=Ct(),fK=me();fK.initSync();var H0e=lf.invalid(fK.get(Xde.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(Zde.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),mK={operation:lf.valid("add_node","update_node","set_node_replication"),node_name:lf.optional(),subscriptions:SO.array().items({table:lf.optional(),schema:lf.optional(),database:lf.optional(),subscribe:dK.required(),publish:dK.required().custom(tfe),start_time:Qde.iso()})};function efe(e){return Jde.validateBySchema(e,SO.object(mK))}a(efe,"addUpdateNodeValidator");function tfe(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(tfe,"checkForFalsy");pK.exports={addUpdateNodeValidator:efe,validationSchema:mK}});var uf=M(($0e,hK)=>{"use strict";var TO=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},yO=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};hK.exports={Node:TO,NodeSubscription:yO}});var _K=M((K0e,EK)=>{"use strict";var rfe=(H(),v(z)).OPERATIONS_ENUM,RO=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=rfe.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};EK.exports=RO});var Ah=M((W0e,gK)=>{"use strict";var bO=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},AO=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)}};gK.exports={RemotePayloadObject:bO,RemotePayloadSubscription:AO}});var TK=M((j0e,SK)=>{"use strict";var IO=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}};SK.exports=IO});var RK=M((tBe,yK)=>{"use strict";var nfe=TK(),J0e=Yt(),X0e=Et(),sfe=J(),{getSchemaPath:Z0e,getTransactionAuditStorePath:eBe}=Rt(),{getDatabases:ife}=(we(),v(ft));yK.exports=ofe;async function ofe(e){let t=new nfe;try{let r=ife()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats();t.schema=e.schema,t.table=e.name,t.record_count=n.entryCount,t.transaction_log_record_count=s.entryCount}catch(r){sfe.warn(`unable to stat table dbi due to ${r}`)}return t}a(ofe,"lmdbGetTableSize")});var AK=M((nBe,bK)=>{"use strict";var wO=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}};bK.exports=wO});var wh=M((lBe,CK)=>{"use strict";var afe=require("fs-extra"),cfe=require("path"),bn=require("systeminformation"),Sc=J(),IK=_r(),iBe=Ct(),df=(H(),v(z)),lfe=RK(),ufe=kl(),{getThreadInfo:wK}=st(),Ih=me();Ih.initSync();var dfe=AK(),{openEnvironment:oBe}=Et(),{getSchemaPath:aBe}=Rt(),{database:cBe,databases:NO}=(we(),v(ft)),BT;CK.exports={getHDBProcessInfo:LO,getNetworkInfo:vO,getDiskInfo:DO,getMemoryInfo:PO,getCPUInfo:OO,getTimeInfo:CO,getSystemInformation:MO,systemInformation:ffe,getTableSize:UO,getMetrics:xO};function CO(){return bn.time()}a(CO,"getTimeInfo");async function OO(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:u,...d}=await bn.cpu();d.cpu_speed=await bn.cpuCurrentSpeed();let{rawCurrentload:f,rawCurrentloadIdle:m,rawCurrentloadIrq:p,rawCurrentloadNice:h,rawCurrentloadSystem:E,rawCurrentloadUser:g,cpus:R,...S}=await bn.currentLoad();return S.cpus=[],R.forEach(y=>{let{rawLoad:N,rawLoadIdle:I,rawLoadIrq:$,rawLoadNice:ee,rawLoadSystem:G,rawLoadUser:k,...j}=y;S.cpus.push(j)}),d.current_load=S,d}catch(e){return Sc.error(`error in getCPUInfo: ${e}`),{}}}a(OO,"getCPUInfo");async function PO(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await bn.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Sc.error(`error in getMemoryInfo: ${e}`),{}}}a(PO,"getMemoryInfo");async function LO(){let e={core:[],clustering:[]};try{let t=await bn.processes(),r;try{r=Number.parseInt(await afe.readFile(cfe.join(Ih.get(df.CONFIG_PARAMS.ROOTPATH),df.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===df.NODE_ERROR_CODES.ENOENT)Sc.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 Sc.error(`error in getHDBProcessInfo: ${t}`),e}}a(LO,"getHDBProcessInfo");async function DO(){let e={};try{if(!Ih.get(df.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK))return e;let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await bn.disksIO();e.io=i;let{rxSec:o,txSec:c,wxSec:l,...u}=await bn.fsStats();return e.read_write=u,e.size=await bn.fsSize(),e}catch(t){return Sc.error(`error in getDiskInfo: ${t}`),e}}a(DO,"getDiskInfo");async function vO(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return Ih.get(df.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)&&(e.default_interface=await bn.networkInterfaceDefault(),e.latency=await bn.inetChecksite("google.com"),(await bn.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:l,ieee8021xAuth:u,ieee8021xState:d,carrierChanges:f,...m}=n;e.interfaces.push(m)}),(await bn.networkStats()).forEach(n=>{let{rxSec:s,txSec:i,ms:o,...c}=n;e.stats.push(c)})),e}catch(t){return Sc.error(`error in getNetworkInfo: ${t}`),e}}a(vO,"getNetworkInfo");async function MO(){if(BT!==void 0)return BT;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await bn.osInfo();e=c;let l=await bn.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,BT=e,BT}catch(t){return Sc.error(`error in getSystemInformation: ${t}`),e}}a(MO,"getSystemInformation");async function UO(){let e=[],t=await ufe.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await lfe(n));return e}a(UO,"getTableSize");async function xO(){let e={};for(let t in NO){let r=e[t]={},n=r.tables={};for(let s in NO[t])try{let i=NO[t][s];if(!r.readers&&(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(l=>{let[u,d,f]=l.trim().split(" ");return{pid:u,thread:d,txnid:f}}),i.auditStore)){let{treeDepth:l,treeBranchPageCount:u,treeLeafPageCount:d,entryCount:f,overflowPages:m}=i.auditStore.getStats();r.audit={treeDepth:l,treeBranchPageCount:u,treeLeafPageCount:d,entryCount:f,overflowPages:m}}let o=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=o[l];n[s]=c}catch(i){Sc.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(xO,"getMetrics");async function NK(){if(Ih.get(df.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await IK.getNATSReferences(),t=await IK.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(NK,"getNatsStreamInfo");async function ffe(e){let t=new dfe;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await MO(),t.time=CO(),t.cpu=await OO(),t.memory=await PO(),t.disk=await DO(),t.network=await vO(),t.harperdb_processes=await LO(),t.table_size=await UO(),t.metrics=await xO(),t.threads=await wK(),t.replication=await NK(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await MO();break;case"time":t.time=CO();break;case"cpu":t.cpu=await OO();break;case"memory":t.memory=await PO();break;case"disk":t.disk=await DO();break;case"network":t.network=await vO();break;case"harperdb_processes":t.harperdb_processes=await LO();break;case"table_size":t.table_size=await UO();break;case"database_metrics":case"metrics":t.metrics=await xO();break;case"threads":t.threads=await wK();break;case"replication":t.replication=await NK();break;default:break}return t}a(ffe,"systemInformation")});var ca=M((pBe,DK)=>{"use strict";var mfe=Vn(),BO=oe(),pfe=require("util"),zl=(H(),v(z)),OK=me();OK.initSync();var hfe=tC(),PK=gn(),{Node:dBe,NodeSubscription:fBe}=uf(),Efe=cd(),_fe=_K(),{RemotePayloadObject:gfe,RemotePayloadSubscription:Sfe}=Ah(),{handleHDBError:Tfe,hdbErrors:yfe}=_e(),{HTTP_STATUS_CODES:Rfe,HDB_ERROR_MSGS:bfe}=yfe,Afe=mi(),Ife=wh(),{packageJson:wfe}=yt(),{getDatabases:Nfe}=(we(),v(ft)),mBe=pfe.promisify(hfe.authorize),Cfe=PK.searchByHash,Ofe=PK.searchByValue;DK.exports={isEmpty:Pfe,getNodeRecord:Lfe,upsertNodeRecord:Dfe,buildNodePayloads:vfe,checkClusteringEnabled:Mfe,getAllNodeRecords:Ufe,getSystemInfo:xfe,reverseSubscription:LK};function Pfe(e){return e==null}a(Pfe,"isEmpty");async function Lfe(e){let t=new Efe(zl.SYSTEM_SCHEMA_NAME,zl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return Cfe(t)}a(Lfe,"getNodeRecord");async function Dfe(e){let t=new _fe(zl.SYSTEM_SCHEMA_NAME,zl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return mfe.upsert(t)}a(Dfe,"upsertNodeRecord");function LK(e){if(BO.isEmpty(e.subscribe)||BO.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(LK,"reverseSubscription");function vfe(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:l,table:u}=c,d=BO.getTableHashAttribute(l,u),{subscribe:f,publish:m}=LK(c),p=Nfe()[l]?.[u],h=new Sfe(l,u,d,m,f,c.start_time,p.schemaDefined?p.attributes:void 0);s.push(h)}return new gfe(r,t,s,n)}a(vfe,"buildNodePayloads");function Mfe(){if(!OK.get(zl.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Tfe(new Error,bfe.CLUSTERING_NOT_ENABLED,Rfe.BAD_REQUEST,void 0,void 0,!0)}a(Mfe,"checkClusteringEnabled");async function Ufe(){let e=new Afe(zl.SYSTEM_SCHEMA_NAME,zl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await Ofe(e))}a(Ufe,"getAllNodeRecords");async function xfe(){let e=await Ife.getSystemInformation();return{hdb_version:wfe.version,node_version:e.node_version,platform:e.platform}}a(xfe,"getSystemInfo")});var FO=M((EBe,HK)=>{"use strict";var FT=_r(),vK=oe(),MK=Ct(),UK=(H(),v(z)),kT=J(),xK=DT(),Bfe=hp(),{RemotePayloadObject:Ffe}=Ah(),{handleHDBError:BK,hdbErrors:kfe}=_e(),{HTTP_STATUS_CODES:FK}=kfe,{NodeSubscription:kK}=uf();HK.exports=Hfe;async function Hfe(e,t){let r;try{r=await FT.request(`${t}.${MK.REQUEST_SUFFIX}`,new Ffe(UK.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),kT.trace("Response from remote describe all request:",r)}catch(o){kT.error(`addNode received error from describe all request to remote node: ${o}`);let c=FT.requestErrorHandler(o,"add_node",t);throw BK(new Error,c,FK.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===MK.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw BK(new Error,o,FK.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,l=o.database??o.schema??"data";if(l===UK.SYSTEM_SCHEMA_NAME){await FT.createLocalTableStream(l,c);let h=new kK(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let u=vK.doesSchemaExist(l),d=n[l]!==void 0,f=c?vK.doesTableExist(l,c):!0,m=c?n?.[l]?.[c]!==void 0:!0;if(!u&&!d||!f&&!m){s.push(o);continue}if(!u&&d&&(kT.trace(`addNode creating schema: ${l}`),await xK.createSchema({operation:"create_schema",schema:l})),!f&&m){kT.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new Bfe(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await xK.createTable(h)}await FT.createLocalTableStream(l,c);let p=new kK(l,c,o.publish,o.subscribe);p.start_time=o.start_time,i.push(p)}return{added:i,skipped:s}}a(Hfe,"reviewSubscriptions")});var ff={};ye(ff,{addNodeBack:()=>kO,removeNodeBack:()=>HO,setNode:()=>Vfe});async function Vfe(e){e.node_name&&!e.hostname&&(e.hostname=e.node_name),e.verify_tls!==void 0&&(e.rejectUnauthorized=e.verify_tls);let{url:t,hostname:r}=e;t?r||(r=e.hostname=yi(t)):t=NT(r);let n=(0,qK.validateBySchema)(e,$fe);if(n)throw(0,la.handleHDBError)(n,n.message,qfe.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new la.ClientError("url or hostname is required for remove_node operation");let p=r,h=Ht(),E=await h.get(p);if(!E)throw new la.ClientError(p+" does not exist");try{await yh({url:E.url},{operation:V.REMOVE_NODE_BACK,name:E?.subscriptions?.length>0?tt():p},void 0)}catch(g){Rs.warn(`Error removing node from target node ${p}, if it is offline and we be online in the future, you may need to clean up this node manually, or retry:`,g)}return await h.delete(p),`Successfully removed '${p}' from cluster`}if(!t)throw new la.ClientError("url required for this operation");let s=uc();if(s==null)throw new la.ClientError("replication url is missing from harperdb-config.yaml");let i,o,c;if(t?.startsWith("wss:")){i=await(0,Ws.getReplicationCert)();let p=await(0,Ws.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(o=await(0,Ws.createCsr)(),Rs.info("Sending CSR to target node:",t)):p&&(c=p.certificate,Rs.info("Sending CA named",p.name,"to target node",t))}let l={operation:V.ADD_NODE_BACK,hostname:(0,yc.get)(F.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c,authorization:e.retain_authorization?e.authorization:null};if((0,yc.get)(F.REPLICATION_SHARD)!==void 0&&(l.shard=(0,yc.get)(F.REPLICATION_SHARD)),e.subscriptions?l.subscriptions=e.subscriptions.map(GK):l.subscriptions=null,e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let p=GK(e);l.subscribe=p.subscribe,l.publish=p.publish}e?.authorization?.username&&e?.authorization?.password&&(e.authorization="Basic "+Buffer.from(e.authorization.username+":"+e.authorization.password).toString("base64"));let u,d;try{u=await yh({url:t},l,e)}catch(p){p.message=`Error returned from ${t}: `+p.message,Rs.warn("Error adding node:",t,"to cluster:",p),d=p}if(o&&(!u?.certificate||!u?.certificate?.includes?.("BEGIN CERTIFICATE")))throw d?(d.message+=" and connection was required to sign certificate",d):new Error(`Unexpected certificate signature response from node ${t} response: ${JSON.stringify(u)}`);o&&(Rs.info("CSR response received from node:",t,"saving certificate and CA in hdb_certificate"),await(0,Ws.setCertTable)({name:Gfe.certificateFromPem(u.signingCA).issuer.getField("CN").value,certificate:u.signingCA,is_authority:!0}),u.certificate&&await(0,Ws.setCertTable)({name:tt(),uses:["https","operations","wss"],certificate:u.certificate,private_key_name:i?.options?.key_file,is_authority:!1,is_self_signed:!1}),c=u.signingCA);let f={url:t,ca:u?.usingCA};if(e.hostname&&(f.name=e.hostname),e.subscriptions?f.subscriptions=e.subscriptions:f.replicates=!0,e.start_time&&(f.start_time=typeof e.start_time=="string"?new Date(e.start_time).getTime():e.start_time),e.retain_authorization&&(f.authorization=e.authorization),e.revoked_certificates&&(f.revoked_certificates=e.revoked_certificates),u?.shard!==void 0?f.shard=u.shard:e.shard!==void 0&&(f.shard=e.shard),f.replicates){let p={url:s,ca:c,replicates:!0,subscriptions:null};(0,yc.get)(F.REPLICATION_SHARD)!==void 0&&(p.shard=(0,yc.get)(F.REPLICATION_SHARD)),e.retain_authorization&&(p.authorization=e.authorization),e.start_time&&(p.start_time=e.start_time),await ea(tt(),p)}await ea(u?u.nodeName:f.name??yi(t),f);let m;return e.operation==="update_node"?m=`Successfully updated '${t}'`:m=`Successfully added '${t}' to cluster`,d&&(m+=" but there was an error updating target node: "+d.message),m}async function kO(e){Rs.trace("addNodeBack received request:",e);let t=await(0,Ws.signCertificate)(e),r;e.csr?(r=t.signingCA,Rs.info("addNodeBack received CSR from node:",e.url,"this node will use and respond with CA that was used to issue CSR")):(r=e?.cert_auth,Rs.info("addNodeBack received CA from node:",e.url));let n={url:e.url,ca:r};e.subscriptions?n.subscriptions=e.subscriptions:(n.replicates=!0,n.subscriptions=null),e.start_time&&(n.start_time=e.start_time),e.authorization&&(n.authorization=e.authorization),e.shard!==void 0&&(n.shard=e.shard);let s=await(0,Ws.getReplicationCertAuth)();if(n.replicates){let i={url:uc(),ca:s?.certificate,replicates:!0,subscriptions:null};(0,yc.get)(F.REPLICATION_SHARD)!==void 0&&(i.shard=(0,yc.get)(F.REPLICATION_SHARD),t.shard=i.shard),e.start_time&&(i.start_time=e.start_time),e.authorization&&(i.authorization=e.authorization),await ea(tt(),i)}return await ea(e.hostname,n),t.nodeName=tt(),t.usingCA=s?.certificate,Rs.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function HO(e){Rs.trace("removeNodeBack received request:",e),await Ht().delete(e.name)}function GK(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Ws,qK,Tc,yc,Rs,la,Gfe,qfe,$fe,mf=se(()=>{Ws=b(ys()),qK=b(mt()),Tc=b(require("joi")),yc=b(me());H();fh();Wd();Ss();Rs=b(J()),la=b(_e()),{pki:Gfe}=require("node-forge"),{HTTP_STATUS_CODES:qfe}=la.hdbErrors,$fe=Tc.default.object({hostname:Tc.default.string(),verify_tls:Tc.default.boolean(),replicates:Tc.default.boolean(),subscriptions:Tc.default.array(),revoked_certificates:Tc.default.array(),shard:Tc.default.number()});a(Vfe,"setNode");a(kO,"addNodeBack");a(HO,"removeNodeBack");a(GK,"reverseSubscription")});var VT=M((IBe,VK)=>{"use strict";var{handleHDBError:HT,hdbErrors:Kfe}=_e(),{HTTP_STATUS_CODES:GT}=Kfe,{addUpdateNodeValidator:Yfe}=xT(),qT=J(),$T=(H(),v(z)),$K=Ct(),Wfe=oe(),Nh=_r(),Ch=ca(),GO=me(),zfe=FO(),{Node:jfe,NodeSubscription:Qfe}=uf(),{broadcast:Jfe}=st(),{setNode:Xfe}=(mf(),v(ff)),bBe=me(),ABe=(H(),v(z)),Zfe="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",eme="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",tme=GO.get($T.CONFIG_PARAMS.CLUSTERING_NODENAME);VK.exports=rme;async function rme(e,t=!1){if(qT.trace("addNode called with:",e),GO.get($T.CONFIG_PARAMS.REPLICATION_URL)||GO.get($T.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Xfe(e);Ch.checkClusteringEnabled();let r=Yfe(e);if(r)throw HT(r,r.message,GT.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let f=await Ch.getNodeRecord(n);if(!Wfe.isEmptyOrZeroLength(f))throw HT(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,GT.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await zfe(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=Zfe,o;let c=Ch.buildNodePayloads(s,tme,$T.OPERATIONS_ENUM.ADD_NODE,await Ch.getSystemInfo()),l=[];for(let f=0,m=s.length;f<m;f++){let p=s[f];s[f].start_time===void 0&&delete s[f].start_time,l.push(new Qfe(p.schema,p.table,p.publish,p.subscribe))}qT.trace("addNode sending remote payload:",c);let u;try{u=await Nh.request(`${n}.${$K.REQUEST_SUFFIX}`,c)}catch(f){qT.error(`addNode received error from request: ${f}`);for(let p=0,h=s.length;p<h;p++){let E=s[p];E.publish=!1,E.subscribe=!1,await Nh.updateRemoteConsumer(E,n)}let m=Nh.requestErrorHandler(f,"add_node",n);throw HT(new Error,m,GT.INTERNAL_SERVER_ERROR,"error",m)}if(u.status===$K.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let f=`Error returned from remote node ${n}: ${u.message}`;throw HT(new Error,f,GT.INTERNAL_SERVER_ERROR,"error",f)}qT.trace(u);for(let f=0,m=s.length;f<m;f++){let p=s[f];await Nh.updateRemoteConsumer(p,n),p.subscribe===!0&&await Nh.updateConsumerIterator(p.schema,p.table,n,"start")}let d=new jfe(n,l,u.system_info);return await Ch.upsertNodeRecord(d),Jfe({type:"nats_update"}),i.length>0?o.message=eme:o.message=`Successfully added '${n}' to manifest`,o}a(rme,"addNode")});var KO=M((CBe,YK)=>{"use strict";var{handleHDBError:qO,hdbErrors:nme}=_e(),{HTTP_STATUS_CODES:$O}=nme,{addUpdateNodeValidator:sme}=xT(),Oh=J(),KT=(H(),v(z)),KK=Ct(),NBe=oe(),Ph=_r(),Lh=ca(),VO=me(),{cloneDeep:ime}=require("lodash"),ome=FO(),{Node:ame,NodeSubscription:cme}=uf(),{broadcast:lme}=st(),{setNode:ume}=(mf(),v(ff)),dme="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",fme="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",mme=VO.get(KT.CONFIG_PARAMS.CLUSTERING_NODENAME);YK.exports=pme;async function pme(e){if(Oh.trace("updateNode called with:",e),VO.get(KT.CONFIG_PARAMS.REPLICATION_URL)??VO.get(KT.CONFIG_PARAMS.REPLICATION_HOSTNAME))return ume(e);Lh.checkClusteringEnabled();let t=sme(e);if(t)throw qO(t,t.message,$O.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Lh.getNodeRecord(r);s.length>0&&(n=ime(s));let{added:i,skipped:o}=await ome(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=dme,c;let l=Lh.buildNodePayloads(i,mme,KT.OPERATIONS_ENUM.UPDATE_NODE,await Lh.getSystemInfo());for(let d=0,f=i.length;d<f;d++){let m=i[d];Oh.trace(`updateNode updating work stream for node: ${r} subscription:`,m),i[d].start_time===void 0&&delete i[d].start_time}Oh.trace("updateNode sending remote payload:",l);let u;try{u=await Ph.request(`${r}.${KK.REQUEST_SUFFIX}`,l)}catch(d){Oh.error(`updateNode received error from request: ${d}`);let f=Ph.requestErrorHandler(d,"update_node",r);throw qO(new Error,f,$O.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===KK.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${r}: ${u.message}`;throw qO(new Error,d,$O.INTERNAL_SERVER_ERROR,"error",d)}Oh.trace(u);for(let d=0,f=i.length;d<f;d++){let m=i[d];await Ph.updateRemoteConsumer(m,r),m.subscribe===!0?await Ph.updateConsumerIterator(m.schema,m.table,r,"start"):await Ph.updateConsumerIterator(m.schema,m.table,r,"stop")}return n||(n=[new ame(r,[],u.system_info)]),await hme(n[0],i,u.system_info),o.length>0?c.message=fme:c.message=`Successfully updated '${r}'`,c}a(pme,"updateNode");async function hme(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let l=0,u=e.subscriptions.length;l<u;l++){let d=n.subscriptions[l];if(d.schema===o.schema&&d.table===o.table){d.publish=o.publish,d.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new cme(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Lh.upsertNodeRecord(n),lme({type:"nats_update"})}a(hme,"updateNodeTable")});var JK=M((PBe,QK)=>{"use strict";var jK=require("joi"),{string:WK}=jK.types(),Eme=mt(),zK=(H(),v(z)),_me=me(),gme=Ct();QK.exports=Sme;function Sme(e){let t=WK.invalid(_me.get(zK.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(gme.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=jK.object({operation:WK.valid(zK.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Eme.validateBySchema(e,r)}a(Sme,"removeNodeValidator")});var YT=M((DBe,rY)=>{"use strict";var{handleHDBError:XK,hdbErrors:Tme}=_e(),{HTTP_STATUS_CODES:ZK}=Tme,yme=JK(),Dh=J(),eY=ca(),Rme=oe(),pf=(H(),v(z)),tY=Ct(),YO=_r(),WO=me(),{RemotePayloadObject:bme}=Ah(),{NodeSubscription:Ame}=uf(),Ime=pp(),wme=Nl(),{broadcast:Nme}=st(),{setNode:Cme}=(mf(),v(ff)),Ome=WO.get(pf.CONFIG_PARAMS.CLUSTERING_NODENAME);rY.exports=Pme;async function Pme(e){if(Dh.trace("removeNode called with:",e),WO.get(pf.CONFIG_PARAMS.REPLICATION_URL)??WO.get(pf.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Cme(e);eY.checkClusteringEnabled();let t=yme(e);if(t)throw XK(t,t.message,ZK.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await eY.getNodeRecord(r);if(Rme.isEmptyOrZeroLength(n))throw XK(new Error,`Node '${r}' was not found.`,ZK.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new bme(pf.OPERATIONS_ENUM.REMOVE_NODE,Ome,[]),i,o=!1;for(let l=0,u=n.subscriptions.length;l<u;l++){let d=n.subscriptions[l];d.subscribe===!0&&await YO.updateConsumerIterator(d.schema,d.table,r,"stop");try{await YO.updateRemoteConsumer(new Ame(d.schema,d.table,!1,!1),r)}catch(f){Dh.error(f)}}try{i=await YO.request(`${r}.${tY.REQUEST_SUFFIX}`,s),Dh.trace("Remove node reply from remote node:",r,i)}catch(l){Dh.error("removeNode received error from request:",l),o=!0}let c=new Ime(pf.SYSTEM_SCHEMA_NAME,pf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await wme.deleteRecord(c),Nme({type:"nats_update"}),i?.status===tY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Dh.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(Pme,"removeNode")});var iY=M((MBe,sY)=>{"use strict";var nY=require("joi"),{string:Lme,array:Dme}=nY.types(),vme=mt(),Mme=xT();sY.exports=Ume;function Ume(e){let t=nY.object({operation:Lme.valid("configure_cluster").required(),connections:Dme.items(Mme.validationSchema).required()});return vme.validateBySchema(e,t)}a(Ume,"configureClusterValidator")});var zO=M((xBe,uY)=>{"use strict";var oY=(H(),v(z)),WT=J(),xme=oe(),Bme=me(),Fme=YT(),kme=VT(),Hme=ca(),Gme=iY(),{handleHDBError:aY,hdbErrors:qme}=_e(),{HTTP_STATUS_CODES:cY}=qme,$me="Configure cluster complete.",Vme="Failed to configure the cluster. Check the logs for more details.",Kme="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";uY.exports=Yme;async function Yme(e){WT.trace("configure cluster called with:",e);let t=Gme(e);if(t)throw aY(t,t.message,cY.BAD_REQUEST,void 0,void 0,!0);let r=await Hme.getAllNodeRecords(),n=[];if(Bme.get(oY.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let d=0,f=r.length;d<f;d++){let m=await lY(Fme,{operation:oY.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name);n.push(m)}WT.trace("All results from configure_cluster remove node:",n)}let s=[],i=e.connections.length;for(let d=0;d<i;d++){let f=e.connections[d],m=await lY(kme,f,f.node_name);s.push(m)}WT.trace("All results from configure_cluster add node:",s);let o=[],c=[],l=!1,u=n.concat(s);for(let d=0,f=u.length;d<f;d++){let m=u[d];m.status==="rejected"&&(WT.error(m.node_name,m?.error?.message,m?.error?.stack),o.includes(m.node_name)||o.push(m.node_name)),(m?.result?.message?.includes?.("Successfully")||m?.result?.includes?.("Successfully"))&&(l=!0),!(typeof m.result=="string"&&m.result.includes("Successfully removed")||m.status==="rejected")&&c.push({node_name:m?.node_name,response:m?.result})}if(xme.isEmptyOrZeroLength(o))return{message:$me,connections:c};if(l)return{message:Kme,failed_nodes:o,connections:c};throw aY(new Error,Vme,cY.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(Yme,"configureCluster");async function lY(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(lY,"functionWrapper")});var pY=M((FBe,mY)=>{"use strict";var vh=require("joi"),Wme=mt(),{validateSchemaExists:dY,validateTableExists:zme,validateSchemaName:fY}=Qi(),jme=vh.object({operation:vh.string().valid("purge_stream"),schema:vh.string().custom(dY).custom(fY).optional(),database:vh.string().custom(dY).custom(fY).optional(),table:vh.string().custom(zme).required()});function Qme(e){return Wme.validateBySchema(e,jme)}a(Qme,"purgeStreamValidator");mY.exports=Qme});var jO=M((HBe,hY)=>{"use strict";var{handleHDBError:Jme,hdbErrors:Xme}=_e(),{HTTP_STATUS_CODES:Zme}=Xme,epe=pY(),tpe=_r(),rpe=ca();hY.exports=npe;async function npe(e){e.schema=e.schema??e.database;let t=epe(e);if(t)throw Jme(t,t.message,Zme.BAD_REQUEST,void 0,void 0,!0);rpe.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await tpe.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(npe,"purgeStream")});var XO=M((qBe,bY)=>{"use strict";var JO=ca(),spe=_r(),jT=me(),hf=(H(),v(z)),jl=Ct(),ipe=oe(),QO=J(),{RemotePayloadObject:ope}=Ah(),{ErrorCode:EY}=require("nats"),{parentPort:_Y}=require("worker_threads"),{onMessageByType:ape}=st(),{getThisNodeName:cpe}=(Ss(),v(ra)),{requestClusterStatus:lpe}=(fh(),v(lV)),{getReplicationSharedStatus:upe,getHDBNodeTable:dpe}=(Wd(),v(rV)),{CONFIRMATION_STATUS_POSITION:fpe,RECEIVED_VERSION_POSITION:gY,RECEIVED_TIME_POSITION:mpe,SENDING_TIME_POSITION:ppe,RECEIVING_STATUS_POSITION:hpe,RECEIVING_STATUS_RECEIVING:Epe,BACK_PRESSURE_RATIO_POSITION:_pe}=(VC(),v(e1)),SY=jT.get(hf.CONFIG_PARAMS.CLUSTERING_ENABLED),TY=jT.get(hf.CONFIG_PARAMS.CLUSTERING_NODENAME);bY.exports={clusterStatus:gpe,buildNodeStatus:RY};var yY;ape("cluster-status",async e=>{yY(e)});async function gpe(){if(jT.get(hf.CONFIG_PARAMS.REPLICATION_URL)||jT.get(hf.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;_Y?(_Y.postMessage({type:"request-cluster-status"}),n=await new Promise(i=>{yY=i})):n=lpe();for(let i of n.connections){let o=i.name;for(let c of i.database_sockets){let l=c.database,u;for(let f of Object.values(databases[l]||{}))if(u=f.auditStore,u)break;if(!u)continue;let d=upe(u,l,o);c.lastCommitConfirmed=zT(d[fpe]),c.lastReceivedRemoteTime=zT(d[gY]),c.lastReceivedLocalTime=zT(d[mpe]),c.lastReceivedVersion=d[gY],c.sendingMessage=zT(d[ppe]),c.backPressurePercent=d[_pe]*100,c.lastReceivedStatus=d[hpe]===Epe?"Receiving":"Waiting"}}n.node_name=cpe();let s=dpe().primaryStore.get(n.node_name);return s?.shard&&(n.shard=s.shard),s?.url&&(n.url=s.url),n.is_enabled=!0,n}let e={node_name:TY,is_enabled:SY,connections:[]};if(!SY)return e;let t=await JO.getAllNodeRecords();if(ipe.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(RY(t[n],e.connections));return await Promise.allSettled(r),e}a(gpe,"clusterStatus");function zT(e){return e?e===1?"Copying":new Date(e).toUTCString():void 0}a(zT,"asDate");async function RY(e,t){let r=e.name,n=new ope(hf.OPERATIONS_ENUM.CLUSTER_STATUS,TY,void 0,await JO.getSystemInfo()),s,i,o=jl.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await spe.request(jl.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===jl.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=jl.CLUSTER_STATUS_STATUSES.CLOSED,QO.error(`Error getting node status from ${r} `,s))}catch(l){QO.warn(`Error getting node status from ${r}`,l),l.code===EY.NoResponders?o=jl.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===EY.Timeout?o=jl.CLUSTER_STATUS_STATUSES.TIMEOUT:o=jl.CLUSTER_STATUS_STATUSES.CLOSED}let c=new Spe(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let l={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==hf.PRE_4_0_0_VERSION&&await JO.upsertNodeRecord(l)}catch(l){QO.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(RY,"buildNodeStatus");function Spe(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(Spe,"NodeStatusObject")});var eP=M((VBe,AY)=>{"use strict";var{handleHDBError:Tpe,hdbErrors:ype}=_e(),{HTTP_STATUS_CODES:Rpe}=ype,bpe=_r(),Ape=ca(),ZO=oe(),QT=require("joi"),Ipe=mt(),wpe=2e3,Npe=QT.object({timeout:QT.number().min(1),connected_nodes:QT.boolean(),routes:QT.boolean()});AY.exports=Cpe;async function Cpe(e){Ape.checkClusteringEnabled();let t=Ipe.validateBySchema(e,Npe);if(t)throw Tpe(t,t.message,Rpe.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||ZO.autoCastBoolean(n),o=s===void 0||ZO.autoCastBoolean(s),c={nodes:[]},l=await bpe.getServerList(r??wpe),u={};if(i)for(let d=0,f=l.length;d<f;d++){let m=l[d].statsz;m&&(u[l[d].server.name]=m.routes)}for(let d=0,f=l.length;d<f;d++){if(l[d].statsz)continue;let m=l[d].server,p=l[d].data;if(m.name.endsWith("-hub")){let h={name:m.name.slice(0,-4),response_time:l[d].response_time};i&&(h.connected_nodes=[],u[m.name]&&u[m.name].forEach(E=>{h.connected_nodes.includes(E.name.slice(0,-4))||h.connected_nodes.push(E.name.slice(0,-4))})),o&&(h.routes=p.cluster?.urls?p.cluster?.urls.map(E=>({host:E.split(":")[0],port:ZO.autoCast(E.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Cpe,"clusterNetwork")});var CY=M((YBe,NY)=>{"use strict";var tP=require("joi"),IY=mt(),{routeConstraints:wY}=Ww();NY.exports={setRoutesValidator:Ope,deleteRoutesValidator:Ppe};function Ope(e){let t=tP.object({server:tP.valid("hub","leaf"),routes:wY.required()});return IY.validateBySchema(e,t)}a(Ope,"setRoutesValidator");function Ppe(e){let t=tP.object({routes:wY.required()});return IY.validateBySchema(e,t)}a(Ppe,"deleteRoutesValidator")});var JT=M((zBe,UY)=>{"use strict";var ua=gt(),rP=oe(),zs=(H(),v(z)),Ef=me(),OY=CY(),{handleHDBError:PY,hdbErrors:Lpe}=_e(),{HTTP_STATUS_CODES:LY}=Lpe,DY="cluster routes successfully set",vY="cluster routes successfully deleted";UY.exports={setRoutes:vpe,getRoutes:Mpe,deleteRoutes:Upe};function Dpe(e){let t=ua.getClusteringRoutes(),r=e.server==="hub"?t.hub_routes:t.leaf_routes,n=e.server==="hub"?t.leaf_routes:t.hub_routes,s=[],i=[];for(let o=0,c=e.routes.length;o<c;o++){let l=e.routes[o];l.port=rP.autoCast(l.port);let u=r.some(f=>f.host===l.host&&f.port===l.port),d=n.some(f=>f.host===l.host&&f.port===l.port);u||d?s.push(l):(r.push(l),i.push(l))}return e.server==="hub"?ua.updateConfigValue(zs.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):ua.updateConfigValue(zs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:DY,set:i,skipped:s}}a(Dpe,"setRoutesNats");function vpe(e){let t=OY.setRoutesValidator(e);if(t)throw PY(t,t.message,LY.BAD_REQUEST,void 0,void 0,!0);if(Ef.get(zs.CONFIG_PARAMS.CLUSTERING_ENABLED))return Dpe(e);let r=[],n=[],s=Ef.get(zs.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{MY(s,i)?n.push(i):(s.push(i),r.push(i))}),ua.updateConfigValue(zs.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:DY,set:r,skipped:n}}a(vpe,"setRoutes");function MY(e,t){return typeof t=="string"?e.includes(t):typeof t=="object"&&t!==null?e.some(r=>(r.host===t.host||r.hostname===t.hostname)&&r.port===t.port):!1}a(MY,"existsInArray");function Mpe(){if(Ef.get(zs.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=ua.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return Ef.get(zs.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(Mpe,"getRoutes");function Upe(e){let t=OY.deleteRoutesValidator(e);if(t)throw PY(t,t.message,LY.BAD_REQUEST,void 0,void 0,!0);if(Ef.get(zs.CONFIG_PARAMS.CLUSTERING_ENABLED))return xpe(e);let r=[],n=[],s=Ef.get(zs.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{MY(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),ua.updateConfigValue(zs.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:vY,deleted:r,skipped:n}}a(Upe,"deleteRoutes");function xpe(e){let t=ua.getClusteringRoutes(),r=t.hub_routes,n=t.leaf_routes,s=[],i=[],o=!1,c=!1;for(let l=0,u=e.routes.length;l<u;l++){let d=e.routes[l],f=!1;for(let m=0,p=r.length;m<p;m++){let h=r[m];if(d.host===h.host&&d.port===h.port){r.splice(m,1),f=!0,o=!0,s.push(d);break}}if(!f){let m=!0;for(let p=0,h=n.length;p<h;p++){let E=n[p];if(d.host===E.host&&d.port===E.port){n.splice(p,1),c=!0,m=!1,s.push(d);break}}m&&i.push(d)}}return o&&(r=rP.isEmptyOrZeroLength(r)?null:r,ua.updateConfigValue(zs.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=rP.isEmptyOrZeroLength(n)?null:n,ua.updateConfigValue(zs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:vY,deleted:s,skipped:i}}a(xpe,"deleteRoutesNats")});var BY=M((QBe,xY)=>{"use strict";var Bpe=Ct(),nP=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,l,u,d,f,m,p,h){this.port=t,o===null&&(o=void 0),this.server_name=r+Bpe.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:l},this.leafnodes={port:u,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:d,port:f,routes:m,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l}},this.accounts={SYS:{users:p},HDB:{users:h}},this.system_account="SYS"}};xY.exports=nP});var HY=M((XBe,kY)=>{"use strict";var FY=Ct(),sP=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,l,u,d,f){this.port=t,f===null&&(f=void 0),this.server_name=r+FY.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+FY.SERVER_SUFFIX.LEAF},this.tls={cert_file:u,key_file:d,ca_file:f,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:f,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:f,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};kY.exports=sP});var qY=M((eFe,GY)=>{"use strict";var iP=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};GY.exports=iP});var VY=M((rFe,$Y)=>{"use strict";var Fpe=Ct(),oP=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+Fpe.SERVER_SUFFIX.ADMIN,this.password=r}};$Y.exports=oP});var ty=M((sFe,WY)=>{"use strict";var Ql=require("path"),Jl=require("fs-extra"),kpe=BY(),Hpe=HY(),Gpe=qY(),qpe=VY(),aP=Es(),gf=oe(),zn=gt(),ZT=(H(),v(z)),Mh=Ct(),{CONFIG_PARAMS:ir}=ZT,Sf=J(),Uh=me(),KY=no(),cP=_r(),$pe=ys(),_f="clustering",Vpe=1e4,YY=50;WY.exports={generateNatsConfig:Ype,removeNatsConfig:Wpe,getHubConfigPath:Kpe};function Kpe(){let e=Uh.get(ir.ROOTPATH);return Ql.join(e,_f,Mh.NATS_CONFIG_FILES.HUB_SERVER)}a(Kpe,"getHubConfigPath");async function Ype(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=Uh.get(ir.ROOTPATH);Jl.ensureDirSync(Ql.join(r,"clustering","leaf")),Uh.initSync();let n=zn.getConfigFromFile(ir.CLUSTERING_TLS_CERT_AUTH),s=zn.getConfigFromFile(ir.CLUSTERING_TLS_PRIVATEKEY),i=zn.getConfigFromFile(ir.CLUSTERING_TLS_CERTIFICATE);!await Jl.exists(i)&&!await Jl.exists(!n)&&await $pe.createNatsCerts();let o=Ql.join(r,_f,Mh.PID_FILES.HUB),c=Ql.join(r,_f,Mh.PID_FILES.LEAF),l=zn.getConfigFromFile(ir.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=Ql.join(r,_f,Mh.NATS_CONFIG_FILES.HUB_SERVER),d=Ql.join(r,_f,Mh.NATS_CONFIG_FILES.LEAF_SERVER),f=zn.getConfigFromFile(ir.CLUSTERING_TLS_INSECURE),m=zn.getConfigFromFile(ir.CLUSTERING_TLS_VERIFY),p=zn.getConfigFromFile(ir.CLUSTERING_NODENAME),h=zn.getConfigFromFile(ir.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await cP.checkNATSServerInstalled()||ey("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let E=await aP.listUsers(),g=zn.getConfigFromFile(ir.CLUSTERING_USER),R=await aP.getClusterUser();(gf.isEmpty(R)||R.active!==!0)&&ey(`Invalid cluster user '${g}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await XT(ir.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await XT(ir.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await XT(ir.CLUSTERING_HUBSERVER_NETWORK_PORT),await XT(ir.CLUSTERING_LEAFSERVER_NETWORK_PORT));let S=[],y=[];for(let[j,Y]of E.entries())Y.role?.role===ZT.ROLE_TYPES_ENUM.CLUSTER_USER&&Y.active&&(S.push(new qpe(Y.username,KY.decrypt(Y.hash))),y.push(new Gpe(Y.username,KY.decrypt(Y.hash))));let N=[],{hub_routes:I}=zn.getClusteringRoutes();if(!gf.isEmptyOrZeroLength(I))for(let j of I)N.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${j.host}:${j.port}`);let $=new kpe(zn.getConfigFromFile(ir.CLUSTERING_HUBSERVER_NETWORK_PORT),p,o,i,s,n,f,m,h,zn.getConfigFromFile(ir.CLUSTERING_HUBSERVER_CLUSTER_NAME),zn.getConfigFromFile(ir.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),N,S,y);n==null&&(delete $.tls.ca_file,delete $.leafnodes.tls.ca_file),t=gf.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===ZT.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Jl.writeJson(u,$),Sf.trace(`Hub server config written to ${u}`));let ee=`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,G=`tls://${R.uri_encoded_name}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,k=new Hpe(zn.getConfigFromFile(ir.CLUSTERING_LEAFSERVER_NETWORK_PORT),p,c,l,[ee],[G],S,y,i,s,n,f);n==null&&delete k.tls.ca_file,(t===void 0||t===ZT.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Jl.writeJson(d,k),Sf.trace(`Leaf server config written to ${d}`))}a(Ype,"generateNatsConfig");async function XT(e){let t=Uh.get(e);return gf.isEmpty(t)&&ey(`port undefined for '${e}'`),await gf.isPortTaken(t)&&ey(`'${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(XT,"isPortAvailable");function ey(e){let t=`Error generating clustering config: ${e}`;Sf.error(t),console.error(t),process.exit(1)}a(ey,"generateNatsConfigError");async function Wpe(e){let{port:t,config_file:r}=cP.getServerConfig(e),{username:n,decrypt_hash:s}=await aP.getClusterUser(),i=0,o=2e3;for(;i<YY;){try{let d=await cP.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){Sf.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=YY)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 u=o*(i*2);u>3e4&&Sf.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await gf.asyncSetTimeout(u)}let c="0".repeat(Vpe),l=Ql.join(Uh.get(ir.ROOTPATH),_f,r);await Jl.writeFile(l,c),await Jl.remove(l),Sf.notify(e,"started.")}a(Wpe,"removeNatsConfig")});var ZY=M((oFe,XY)=>{"use strict";var bs=me(),et=(H(),v(z)),xh=Ct(),da=require("path"),{PACKAGE_ROOT:ny}=yt(),zY=me(),ry=oe(),Tf="/dev/null",zpe=da.join(ny,"launchServiceScripts"),jY=da.join(ny,"utility/scripts"),jpe=da.join(jY,et.HDB_RESTART_SCRIPT),QY=da.resolve(ny,"dependencies",`${process.platform}-${process.arch}`,xh.NATS_BINARY_NAME);function JY(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0,...process.env};return ry.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=ry.getEnvCliRootPath()),{name:et.PROCESS_DESCRIPTORS.HDB,script:et.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:e,execArgv:process.execArgv,cwd:ny}}a(JY,"generateMainServerConfig");var Qpe=9930;function Jpe(){bs.initSync(!0);let e=bs.get(et.CONFIG_PARAMS.ROOTPATH),t=da.join(e,"clustering",xh.NATS_CONFIG_FILES.HUB_SERVER),r=da.join(bs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=zY.get(et.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=xh.LOG_LEVEL_FLAGS[bs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==Qpe?"-"+n:""),binFile:QY,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return bs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Tf,i.error_file=Tf),i}a(Jpe,"generateNatsHubServerConfig");var Xpe=9940;function Zpe(){bs.initSync(!0);let e=bs.get(et.CONFIG_PARAMS.ROOTPATH),t=da.join(e,"clustering",xh.NATS_CONFIG_FILES.LEAF_SERVER),r=da.join(bs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=zY.get(et.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=xh.LOG_LEVEL_FLAGS[bs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==Xpe?"-"+n:""),binFile:QY,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return bs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Tf,i.error_file=Tf),i}a(Zpe,"generateNatsLeafServerConfig");function ehe(){bs.initSync();let e=da.join(bs.get(et.CONFIG_PARAMS.LOGGING_ROOT),et.LOG_NAMES.HDB),t={name:et.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,binFile:et.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:zpe,autorestart:!1};return bs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Tf,t.error_file=Tf),t}a(ehe,"generateClusteringUpgradeV4ServiceConfig");function the(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.RESTART_HDB};return ry.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=ry.getEnvCliRootPath()),{...{name:et.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:jY},script:jpe}}a(the,"generateRestart");function rhe(){return{apps:[JY()]}}a(rhe,"generateAllServiceConfigs");XY.exports={generateAllServiceConfigs:rhe,generateMainServerConfig:JY,generateRestart:the,generateNatsHubServerConfig:Jpe,generateNatsLeafServerConfig:Zpe,generateClusteringUpgradeV4ServiceConfig:ehe}});var yf=M((lFe,oW)=>{"use strict";var Lr=(H(),v(z)),cFe=oe(),ma=ty(),sy=_r(),fa=Ct(),Rc=ZY(),uP=me(),bc=J(),nhe=ca(),{startWorker:eW,onMessageFromWorkers:she}=st(),tW=require("fs"),ihe=require("node:path"),ohe=(H(),v(z)),{setTimeout:ahe}=require("node:timers/promises"),{execFile:che,fork:lhe}=require("node:child_process");oW.exports={start:Ac,restart:dhe,kill:hhe,startAllServices:Ehe,startService:nW,restartHdb:fhe,startClusteringProcesses:sW,startClusteringThreads:iW,isHdbRestartRunning:mhe,getHdbPid:phe,cleanupChildrenProcesses:Bh,reloadClustering:ghe,expectedRestartOfChildren:rW};she(e=>{e.type==="restart"&&uP.initSync(!0)});var Eo=[],uhe=10,lP;function Ac(e,t=!1){let r=typeof e.args=="string"?e.args.split(" "):e.args;e.silent=!0,e.detached=!0;let n=e.script?lhe(e.script,r,e):che(e.binFile,r,e);n.name=e.name,n.config=e,n.on("error",(o,c)=>{console.error(o,c)}),n.on("exit",async o=>{let c=Eo.indexOf(n);c>-1&&Eo.splice(c,1),!lP&&o!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<uhe&&(tW.existsSync(ma.getHubConfigPath())?Ac(e):(await ma.generateNatsConfig(!0),Ac(e),await new Promise(l=>setTimeout(l,3e3)),await ma.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ma.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function i(o){let c=uP.get(Lr.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),l=/\[\d+][^\[]+\[(\w+)]/g,u,d=0,f;for(;u=l.exec(o);){if(u.index&&fa.LOG_LEVEL_HIERARCHY[c]>=fa.LOG_LEVEL_HIERARCHY[f||"info"]){let h=f===fa.LOG_LEVELS.ERR||f===fa.LOG_LEVELS.WRN?bc.OUTPUTS.STDERR:bc.OUTPUTS.STDOUT;bc.logCustomLevel(f||"info",h,s,o.slice(d,u.index).trim())}let[m,p]=u;d=u.index+m.length,f=fa.LOG_LEVELS[p]}if(fa.LOG_LEVEL_HIERARCHY[c]>=fa.LOG_LEVEL_HIERARCHY[f||"info"]){let m=f===fa.LOG_LEVELS.ERR||f===fa.LOG_LEVELS.WRN?bc.OUTPUTS.STDERR:bc.OUTPUTS.STDOUT;bc.logCustomLevel(f||"info",m,s,o.toString().slice(d).trim())}}a(i,"extractMessages"),n.stdout.on("data",i),n.stderr.on("data",i),n.unref(),Eo.length===0&&(t||(process.on("exit",Bh),process.on("SIGINT",Bh),process.on("SIGQUIT",Bh),process.on("SIGTERM",Bh))),Eo.push(n)}a(Ac,"start");function Bh(e=!0){if(!lP&&(lP=!0,Eo.length!==0))if(bc.info("Killing child processes..."),Eo.map(t=>t.kill()),e)process.exit(0);else return ahe(2e3)}a(Bh,"cleanupChildrenProcesses");function dhe(e){rW();for(let t of Eo)t.name===e&&t.kill()}a(dhe,"restart");function rW(){for(let e of Eo)e.config&&(e.config.restarts=0)}a(rW,"expectedRestartOfChildren");async function fhe(){await Ac(Rc.generateRestart())}a(fhe,"restartHdb");async function mhe(){let e=await list();for(let t in e)if(e[t].name===Lr.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(mhe,"isHdbRestartRunning");function phe(){let e=uP.getHdbBasePath();if(!e)return;let t=ihe.join(e,ohe.HDB_PID_FILE),r=She(t);if(!(!r||r===process.pid)&&The(r))return r}a(phe,"getHdbPid");function hhe(){for(let e of Eo)e.kill();Eo=[]}a(hhe,"kill");async function Ehe(){await sW(),await iW(),await Ac(Rc.generateAllServiceConfigs())}a(Ehe,"startAllServices");async function nW(e,t=!1){let r;switch(e=e.toLowerCase(),e){case Lr.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Rc.generateMainServerConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Rc.generateNatsIngestServiceConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Rc.generateNatsReplyServiceConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Rc.generateNatsHubServerConfig(),await Ac(r,t),await ma.removeNatsConfig(e);return;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Rc.generateNatsLeafServerConfig(),await Ac(r,t),await ma.removeNatsConfig(e);return;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Rc.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}Ac(r,t)}a(nW,"startService");var _he;async function sW(e=!1){for(let t in Lr.CLUSTERING_PROCESSES){let r=Lr.CLUSTERING_PROCESSES[t];await nW(r,e)}}a(sW,"startClusteringProcesses");async function iW(){_he=eW(Lr.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Lr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await sy.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await sy.updateLocalStreams();let e=await nhe.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Lr.PRE_4_0_0_VERSION){bc.info("Starting clustering upgrade 4.0.0 process"),eW(Lr.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(iW,"startClusteringThreads");async function ghe(){await ma.generateNatsConfig(!0),await sy.reloadNATSHub(),await sy.reloadNATSLeaf(),await ma.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await ma.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(ghe,"reloadClustering");function She(e){try{return Number.parseInt(tW.readFileSync(e,"utf8"),10)}catch{return null}}a(She,"readPidFile");function The(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}a(The,"isProcessRunning")});var mP={};ye(mP,{compactOnStart:()=>yhe,copyDb:()=>fW});async function yhe(){Ic.notify("Running compact on start"),console.log("Running compact on start");let e=(0,dP.get)(F.ROOTPATH),t=new Map,r=ct();(0,fP.updateConfigValue)(F.STORAGE_COMPACTONSTART,!1);try{for(let n in r){if(n==="system"||n.endsWith("-copy"))continue;let s;for(let l in r[n]){s=r[n][l].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,iy.join)(e,"backup",n+".mdb"),o=(0,iy.join)(e,jc,n+"-copy.mdb"),c=0;try{c=await aW(n),console.log("Database",n,"before compact has a total record count of",c)}catch(l){Ic.error("Error getting record count for database",n,l),console.error("Error getting record count for database",n,l)}t.set(n,{dbPath:s,copyDest:o,backupDest:i,recordCount:c}),await fW(n,o),console.log("Backing up",n,"to",i);try{await(0,Xl.move)(s,i,{overwrite:!0})}catch(l){console.log("Error moving database",s,"to",i,l)}}try{Od()}catch(n){Ic.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}for(let[n,{dbPath:s,copyDest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,Xl.move)(i,s,{overwrite:!0}),await(0,Xl.remove)((0,iy.join)(e,jc,`${n}-copy.mdb-lock`));try{Od()}catch(n){Ic.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n),process.exit(0)}}catch(n){Ic.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,fP.updateConfigValue)(F.STORAGE_COMPACTONSTART,!1);for(let[s,{dbPath:i,backupDest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,Xl.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Od(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let o=!0,c=await aW(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let l=`There is a discrepancy between pre and post compact record count for database ${n}.
18
18
  Total record count before compaction: ${i}, total after: ${c}.