harperdb 4.3.0-beta.6 → 4.3.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.
- package/README.md +1 -1
- package/bin/harperdb.js +32 -32
- package/bin/lite.js +19 -19
- package/config/yaml/defaultConfig.yaml +1 -1
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +19 -19
- package/launchServiceScripts/launchNatsReplyService.js +19 -19
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +19 -19
- package/npm-shrinkwrap.json +89 -67
- package/package.json +2 -2
- package/resources/DatabaseTransaction.d.ts +3 -3
- package/server/jobs/jobProcess.js +19 -19
- package/server/threads/threadServer.js +19 -19
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.912a850a.js → main.e02ed83a.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -19
- /package/studio/build-local/static/js/{main.912a850a.js.LICENSE.txt → main.e02ed83a.js.LICENSE.txt} +0 -0
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
"use strict";var Vq=Object.create;var ec=Object.defineProperty;var $q=Object.getOwnPropertyDescriptor;var Yq=Object.getOwnPropertyNames;var Kq=Object.getPrototypeOf,Wq=Object.prototype.hasOwnProperty;var a=(e,t)=>ec(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ye=(e,t)=>{for(var r in t)ec(e,r,{get:t[r],enumerable:!0})},VA=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Yq(t))!Wq.call(e,n)&&n!==r&&ec(e,n,{get:()=>t[n],enumerable:!(s=$q(t,n))||s.enumerable});return e};var x=(e,t,r)=>(r=e!=null?Vq(Kq(e)):{},VA(t||!e||!e.__esModule?ec(r,"default",{value:e,enumerable:!0}):r,e)),se=e=>VA(ec({},"__esModule",{value:!0}),e);var KA=T((pae,YA)=>{var Qq=require("fast-glob"),{statSync:ah,existsSync:ch,readFileSync:zq,writeFileSync:Jq}=require("fs"),{spawnSync:jq,spawn:Xq,execFileSync:mae}=require("child_process"),{isMainThread:Zq}=require("worker_threads"),{join:Wn,relative:$A}=require("path"),{PACKAGE_ROOT:gs}=L(),{tmpdir:eF,platform:tF}=require("os");require("source-map-support").install();var rF=["resources","server","dataLayer","components"],tc="ts-build",uh,sF=__filename.endsWith("tsBuild.js");if(sF){if(Zq){let r;try{ah(Wn(gs,tc)),r=!0}catch{}if(r)for(let s of Qq.sync(rF.map(n=>n+"/**/*.ts"),{cwd:gs})){let n=0,i=0;try{n=ah(Wn(gs,s)).mtimeMs-5e3,i=ah(Wn(gs,tc,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),uh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),uh=!0;if(uh){let s=Wn(gs,"node_modules/.bin/tsc");tF()==="win32"&&(s+=".cmd");let n=jq(s,{cwd:gs});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Wn(eF(),"harperdb-tsc.pid"),o;if(ch(i))try{process.kill(+zq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Xq(s,["--watch"],{cwd:gs,detached:!0,stdio:"ignore"});Jq(i,c.pid.toString()),c.unref()}}}}let e=YA.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(gs)&&!s[0].includes("node_modules")){let i=$A(gs,s[0]),o;i.startsWith(tc)?o=Wn(gs,$A(tc,i)):o=Wn(gs,tc,i);let c=Wn(o,r),u=c+".js";if(ch(u))return u;if(c.includes(".")&&ch(c))return c}return t(r,s,n)}}});var L=T((gae,oO)=>{"use strict";var Xr=require("path"),nF=require("fs"),{relative:Sae,join:Tae}=Xr,{existsSync:iF}=nF;function oF(){let e=__dirname;for(;!iF(Xr.join(e,"package.json"));){let t=Xr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(oF,"getHDBPackageRoot");var Qn=oF(),WA="js",Hl=WA,aF="harperdb-config.yaml",cF="defaultConfig.yaml",uF="hdb",QA=`harperdb.${Hl}`,zA=`customFunctionsServer.${Hl}`,lF=`restartHdb.${Hl}`,_h="HarperDB",Bl="Custom Functions",xl="Clustering Hub",ql="Clustering Leaf",_F="Clustering Ingest Service",dF="Clustering Reply Service",fF="foreground.pid",EF="hdb.pid",hF="data",mF={HDB:_h,CLUSTERING_HUB:xl,CLUSTERING_LEAF:ql,CLUSTERING_INGEST_SERVICE:_F,CLUSTERING_REPLY_SERVICE:dF,CUSTOM_FUNCTIONS:Bl,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"},pF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},SF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},TF={harperdb:_h,"clustering hub":xl,"clustering leaf":ql,"custom functions":Bl,custom_functions:Bl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},gF={CLUSTERING_HUB_PROC_DESCRIPTOR:xl,CLUSTERING_LEAF_PROC_DESCRIPTOR:ql},lh={HDB:Xr.join(Qn,"server/harperdb"),CUSTOM_FUNCTIONS:Xr.join(Qn,"server/customFunctions"),CLUSTERING_HUB:Xr.join(Qn,"server/nats"),CLUSTERING_LEAF:Xr.join(Qn,"server/nats")},RF={HDB:Xr.join(lh.HDB,QA),CUSTOM_FUNCTIONS:Xr.join(lh.CUSTOM_FUNCTIONS,zA)},AF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Xr.join(Qn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Xr.join(Qn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Xr.join(Qn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},OF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},JA="support@harperdb.io",bF="customer-success@harperdb.io",jA=1,NF=4141,XA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",yF="https://www.harperdb.io/product",wF=`For support, please submit a request at ${XA} or contact ${JA}`,ZA=`For license support, please contact ${bF}`,IF="None of the specified records were found.",CF="hash attribute not found",DF=`Your current license only supports ${jA} role. ${ZA}`,LF="Your current license only supports 3 connections to a node.",UF="127.0.0.1",MF=1,PF=/^\.$/,vF=/^\.\.$/,BF="U+002E",HF=/\//g,xF="U+002F",qF=/U\+002F/g,FF=/^U\+002E$/,GF=/^U\+002EU\+002E$/,kF="d",VF=999999,$F="*",YF="--max-old-space-size=",KF="system",WF="__hdb_hash",QF=".harperdb",zF=".hdb",JF="keys",jF="hdb_boot_properties.file",XF=".updateConfig.json",ZF="SIGTSTP",eG=24,tG=6e4,rG=448,sG="blob",nG="trash",iG="database",oG="schema",aG="transactions",cG=".count",uG="id",lG="PROCESS_NAME",eO={SETTINGS_PATH_KEY:"settings_path"},tO=require("lodash"),_G={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},dG={HDB_PATH_KEY:"HDB_INTERNAL_PATH",HDB_AUTH_HEADER:"hdb_auth_header",HDB_USER_DATA_KEY:"hdb_user",CHUNK_SIZE:1e3,MAX_CHARACTER_SIZE:250},fG={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},EG={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"},hG={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},br="hdb_internal:",mG={CREATE_SCHEMA:br+"create_schema",CREATE_TABLE:br+"create_table",CREATE_ATTRIBUTE:br+"create_attribute",ADD_USER:br+"add_user",ALTER_USER:br+"alter_user",DROP_USER:br+"drop_user",HDB_NODES:br+"hdb_nodes",HDB_USERS:br+"hdb_users",HDB_WORKERS:br+"hdb_workers",CATCHUP:br+"catchup",SCHEMA_CATCHUP:br+"schema_catchup",WORKER_ROOM:br+"cluster_workers"},pG={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"},SG="060493.ks",TG=".license",gG={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},X={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},RG={CSV:".csv",JSON:".json"},AG={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},OG={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},rc={};rc[X.INSERT]=X.INSERT;rc[X.UPDATE]=X.UPDATE;rc[X.UPSERT]=X.UPSERT;rc[X.DELETE]=X.DELETE;var He=Object.create(null);He[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;He[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;He[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;He[X.READ_LOG]=X.READ_LOG;He[X.ADD_NODE]=X.ADD_NODE;He[X.LIST_USERS]=X.LIST_USERS;He[X.LIST_ROLES]=X.LIST_ROLES;He[X.USER_INFO]=X.USER_INFO;He[X.SQL]=X.SQL;He[X.GET_JOB]=X.GET_JOB;He[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;He[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;He[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;He[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;He[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;He[X.REMOVE_NODE]=X.REMOVE_NODE;He[X.RESTART]=X.RESTART;He[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;He[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;He[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;He[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;He[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;He[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;He[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;He[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var bG={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},NG={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},rO={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"},yG=tO.invert(rO),wG={CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root"},I={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},sO={settings_path:eO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];sO[t.toLowerCase()]=t}var IG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},CG={csv_file_load:"csv_file_load",csv_data_load:X.CSV_DATA_LOAD,csv_url_load:X.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3"},DG={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"},LG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},UG={VERSION_DEFAULT:"2.2.0"},MG={DEVELOPMENT:8192,DEFAULT:512},PG={IDENTIFY:"identify",AUTHENTICATE:"authenticate",AUTHENTICATE_OK:"authenticated",AUTHENTICATE_FAIL:"authenticate_fail",CONNECTION:"connection",CONNECT:"connect",CATCHUP_REQUEST:"catchup_request",CATCHUP_RESPONSE:"catchup",CONFIRM_MSG:"confirm_msg",ERROR:"error",DISCONNECT:"disconnect",SCHEMA_UPDATE_REQ:"schema_update_request",SCHEMA_UPDATE_RES:"schema_update_response",RECONNECT_ATTEMPT:"reconnect_attempt",CONNECT_ERROR:"connect_error",MESSAGE:"msg",VERSION_MISMATCH:"version_mismatch",DIRECTION_CHANGE:"direction_change"},vG={1e3:"SUCCESSFUL_SHUTDOWN",1001:"CLOSE_GOING_AWAY",1002:"CLOSE_PROTOCOL_ERROR",1003:"CLOSE_UNSUPPORTED",1005:"CLOSE_NO_STATUS",1006:"CLOSE_ABNORMAL",1007:"UNSUPPORTED_PAYLOAD",1008:"POLICY_VIOLATION",1009:"CLOSE_TOO_LARGE",1010:"MANDATORY_EXTENSION",1011:"SERVER_ERROR",1012:"SERVICE_RESTART",1013:"SERVER_BUSY",1014:"BAD_GATEWAY",1015:"HANDSHAKE_FAIL",4141:"LICENSE_LIMIT_REACHED"},BG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},nO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},HG=Symbol("metadata"),xG="__clustering__",qG=Object.values(nO),FG=15984864e5,iO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},GG=tO.invert(iO),kG={GET_CLUSTER_STATUS:"GET_CLUSTER_STATUS",CLUSTER_STATUS_RESPONSE:"CLUSTER_STATUS_RESPONSE",ERROR_RESPONSE:"ERROR",ADD_USER:"ADD_USER",ALTER_USER:"ALTER_USER",DROP_USER:"DROP_USER",HDB_OPERATION:"HDB_OPERATION",ADD_NODE:"ADD_NODE",UPDATE_NODE:"UPDATE_NODE",REMOVE_NODE:"REMOVE_NODE",HDB_USERS_MSG:"HDB_USERS_MSG",HDB_WORKERS:"HDB_WORKERS",HDB_TRANSACTION:"HDB_TRANSACTION"},VG=111,$G=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:Ok.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(wk,"findPs")});var dt=T((Iae,OO)=>{"use strict";var Ik="__dbis__",Ck="__txns__",Dk="__environment_name__",Lk="__dbi_defintion__",Uk={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"},Mk=["__createdtime__","__updatedtime__"],Pk="\uFFFF",AO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},vk=Object.values(AO);OO.exports={AUDIT_STORE_NAME:Ck,INTERNAL_DBIS_NAME:Ik,DBI_DEFINITION_NAME:Lk,SEARCH_TYPES:Uk,TIMESTAMP_NAMES:Mk,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Dk,TRANSACTIONS_DBI_NAMES_ENUM:AO,TRANSACTIONS_DBIS:vk,OVERFLOW_MARKER:Pk}});var Nr=T((Cae,UO)=>{"use strict";var bO=L(),NO=dt(),yO={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},wO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),IO={500:wO("There was an error processing your request."),400:"Invalid request"},Bk=IO[yO.INTERNAL_SERVER_ERROR],Hk={OP_NOT_SUPPORTED_FOR_FS:e=>`${e} is not available for this instance because it uses the File System data store.`,MISSING_VALUE:e=>`${e} is missing.`,INVALID_VALUE:e=>`${e} is invalid.`,NOT_FOUND:e=>`${e} not found.`},xk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},qk={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:e=>`There was an error downloading '${e}'.`,INSERT_JSON_ERR:"There was an error inserting the downloaded JSON data.",INSERT_CSV_ERR:"There was an error inserting the downloaded CSV data.",INVALID_ACTION_PARAM_ERR:e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,INVALID_FILE_EXT_ERR:e=>`Error selecting correct parser - valid file type not found in json - ${e}`,MAX_FILE_SIZE_ERR:(e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:e=>`There was an error downloading '${e}' from AWS.`,WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},Fk={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${NO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${NO.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"},Gk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${bO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${bO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},CO={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"},kk={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},Vk={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},$k={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},Yk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Kk={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},DO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},LO={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},Wk={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."},Qk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},zk={...CO,...qk,...Hk,...kk,...Vk,...$k,...Yk,...Kk,...Gk,...DO,...LO,...Wk,...Qk,...xk};UO.exports={CHECK_LOGS_WRAPPER:wO,HDB_ERROR_MSGS:zk,DEFAULT_ERROR_MSGS:IO,DEFAULT_ERROR_RESP:Bk,HTTP_STATUS_CODES:yO,LMDB_ERRORS_ENUM:Fk,AUTHENTICATION_ERROR_MSGS:CO,VALIDATION_ERROR_MSGS:DO,ITC_ERRORS:LO}});var re=T((Lae,vO)=>{"use strict";var Ho=Nr(),Jk=V(),jk=L(),$l=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,MO),this.statusCode=s||Ho.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Ho.DEFAULT_ERROR_MSGS[s]?Ho.DEFAULT_ERROR_MSGS[s]:Ho.DEFAULT_ERROR_MSGS[Ho.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&Jk[n](i)}},gh=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}},Rh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function MO(e,t,r,s=jk.LOG_LEVELS.ERROR,n=null,i=!1){if(PO(e))return e;let o=new $l(e,t,r,s,n);return i&&delete o.stack,o}a(MO,"handleHDBError");function PO(e){return e.__proto__.constructor.name===$l.name}a(PO,"isHDBError");vO.exports={isHDBError:PO,handleHDBError:MO,ClientError:gh,ServerError:Rh,hdb_errors:Ho}});var Je=T((Mae,kO)=>{"use strict";var dc=L(),Xk=J(),tr=Z(),fc=require("path"),Zk=require("minimist"),BO=require("fs-extra"),HO=require("lodash");tr.initSync();var{CONFIG_PARAMS:zn,DATABASES_PARAM_CONFIG:cc,SYSTEM_SCHEMA_NAME:Yl}=dc,uc,lc,_c;function xO(){if(uc!==void 0)return uc;if(tr.getHdbBasePath()!==void 0)return uc=tr.get(zn.STORAGE_PATH)||fc.join(tr.getHdbBasePath(),dc.DATABASES_DIR_NAME),uc}a(xO,"getBaseSchemaPath");function qO(){if(lc!==void 0)return lc;if(tr.getHdbBasePath()!==void 0)return lc=GO(Yl),lc}a(qO,"getSystemSchemaPath");function FO(){if(_c!==void 0)return _c;if(tr.getHdbBasePath()!==void 0)return _c=tr.get(dc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||fc.join(tr.getHdbBasePath(),dc.TRANSACTIONS_DIR_NAME),_c}a(FO,"getTransactionAuditStoreBasePath");function eV(e,t){let r=tr.get(zn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||fc.join(FO(),e.toString())}a(eV,"getTransactionAuditStorePath");function GO(e,t){e=e.toString(),t=t&&t.toString();let r=tr.get(dc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||fc.join(xO(),e)}a(GO,"getSchemaPath");function tV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,Zk(process.argv));let s=r[zn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!Xk.isObject(s))throw o;i=s}for(let o of i){let c=o[Yl];if(!c)continue;let u=tr.get(zn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[cc.PATH];if(_)return HO.set(u,[Yl,cc.TABLES,t,cc.PATH],_),tr.setProperty(zn.DATABASES,u),_;let l=c?.[cc.PATH];if(l)return HO.set(u,[Yl,cc.PATH],l),tr.setProperty(zn.DATABASES,u),l}}let n=r[zn.STORAGE_PATH.toUpperCase()];if(n){if(!BO.pathExistsSync(n))throw new Error(n+" does not exist");let i=fc.join(n,e);return BO.mkdirsSync(i),tr.setProperty(zn.STORAGE_PATH,n),i}return qO()}a(tV,"initSystemSchemaPaths");function rV(){uc=void 0,lc=void 0,_c=void 0}a(rV,"resetPaths");kO.exports={getBaseSchemaPath:xO,getSystemSchemaPath:qO,getTransactionAuditStorePath:eV,getTransactionAuditStoreBasePath:FO,getSchemaPath:GO,initSystemSchemaPaths:tV,resetPaths:rV}});var yr=T((Hae,WO)=>{"use strict";var sV=Nr().LMDB_ERRORS_ENUM,vae=require("lmdb"),nV=dt(),Bae=require("buffer").Buffer,{OVERFLOW_MARKER:VO,MAX_SEARCH_KEY_LENGTH:Kl}=nV,$O=["number","string","symbol","boolean","bigint"];function iV(e){if(e=e?.primaryStore||e,!e)throw new Error(sV.ENV_REQUIRED)}a(iV,"validateEnv");function oV(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(oV,"stringifyData");function aV(e){return e instanceof Date?e.valueOf():e}a(aV,"convertKeyValueToWrite");function cV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if($O.includes(typeof e))return e.length>Kl?[e.slice(0,Kl)+VO]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if($O.includes(typeof i))i.length>Kl?r.push(i.slice(0,Kl)+VO):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(cV,"getIndexedValues");var Wl=0,YO=0;function KO(){YO=Date.now()-performance.now()}a(KO,"adjustStartTime");KO();var uV=6e4;setInterval(KO,uV).unref();function lV(){let e=performance.now()+YO;return e>Wl?(Wl=e,e):(Wl+=488e-6,Wl)}a(lV,"getNextMonotonicTime");WO.exports={validateEnv:iV,stringifyData:oV,convertKeyValueToWrite:aV,getNextMonotonicTime:lV,getIndexedValues:cV}});var QO,Rs,Ah,Ec=Re(()=>{QO=require("events"),Rs=class extends QO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Ah;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},Ah=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Mi={};Ye(Mi,{server:()=>tt});var zO,tt,rr=Re(()=>{zO=require("../index"),tt={};(0,zO._assignPackageExport)("server",tt)});var Nh={};Ye(Nh,{loadGQLSchema:()=>fV,start:()=>bh,startOnMainThread:()=>dV});function bh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),n)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let K=H(v.type);return K.nullable=!1,K}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let Y={type:v.name?.value};return Object.defineProperty(Y,"location",{value:v.loc.startToken}),Y};a(H,"getProperty");let A=S.name.value,R=[],g={table:null,database:null,properties:R};f.set(A,g);for(let v of S.directives){if(v.name.value==="table"){for(let U of v.arguments)g[U.name.value]=U.value.value;g.schema&&(g.database=g.schema),g.table||(g.table=A),g.audit&&(g.audit=g.audit!=="false"),g.attributes=g.properties,E.push(g)}if(v.name.value==="sealed"&&(g.sealed=!0),v.name.value==="export"){g.export=!0;for(let U of v.arguments)U.name.value==="name"&&(g.export={name:U.value.value})}}let P=!1;for(let v of S.fields){let U=H(v.type);U.name=v.name.value,R.push(U);for(let Y of v.directives)if(Y.name.value==="primaryKey")P?console.warn("Can not define two attributes as a primary key"):(U.isPrimaryKey=!0,P=!0);else if(Y.name.value==="indexed")U.indexed=!0;else if(Y.name.value==="relationship"){let K={};for(let z of Y.arguments)K[z.name.value]=z.value.value;U.relationship=K}else if(Y.name.value==="createdTime")U.assignCreatedTime=!0;else if(Y.name.value==="updatedTime")U.assignUpdatedTime=!0;else if(Y.name.value==="expiresAt")U.expiresAt=!0;else if(Y.name.value==="allow"){let K=U.authorizedRoles=[];for(let z of Y.arguments)z.name.value==="role"&&K.push(z.value.value)}}g.type=A,A==="Query"&&(h=g)}function p(S){let A=f.get(S.type);A?(Object.defineProperty(S,"properties",{value:A.properties}),Object.defineProperty(S,"definition",{value:A})):S.type==="array"?p(S.elements):_V.includes(S.type)||(0,JO.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${n}`)}a(p,"connectPropertyType");for(let S of f.values())for(let A of S.properties)p(A);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Oh.dirname)(s),S.tableClass):i.set((0,Oh.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass))}}var Oh,JO,_V,dV,fV,jO=Re(()=>{Oh=require("path");Ae();JO=x(Ke()),_V=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(bh,"start");dV=bh,fV=bh({ensureTable:ct}).handleFile});async function Ql(e){return EV?(hc||(hc=hV(pV)),(await(await hc).import(e)).namespace):import(e)}async function hV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),hc=new Compartment({console,Math,Date,fetch:mV,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,ZO.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:xt,tables:wr,databases:rt})}};let s=await(0,XO.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),hc}function mV(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 pV(){return{Resource:xt,tables:wr}}var XO,ZO,EV,hc,yh=Re(()=>{As();Ae();XO=require("fs/promises"),ZO=require("path"),EV=!1;a(Ql,"secureImport");a(hV,"getCompartment");a(mV,"secureOnlyFetch");a(pV,"getGlobalVars")});var Ih={};Ye(Ih,{handleFile:()=>SV});async function SV(e,t,r,s){let n=new Map,i=(0,eb.pathToFileURL)(r).toString(),o=await Ql(i);u(o.default)&&s.set((0,wh.dirname)(t),o.default),c(o,(0,wh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?s.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),n}var eb,wh,tb=Re(()=>{eb=require("url");yh();wh=require("path");a(SV,"handleFile")});var Dh={};Ye(Dh,{start:()=>TV});function TV({resources:e}){e.set("login",Ch),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Ch,rb=Re(()=>{As();a(TV,"start");Ch=class extends xt{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var ub={};Ye(ub,{parse:()=>Uh,streamAsJSON:()=>mc,stringify:()=>Pi});function mc(e){return new Lh({value:e})}function sb(e){return console.error(e),JSON.stringify(e.toString())}function nb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Pi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===ab)return cb(e);if(t.resolution)return t.resolution.then(()=>Pi(e));throw t}}function cb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let s=0;s<e.length;s++)s>0&&(r+=","),r+=cb(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+Pi(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Uh(e){return AV.test(e)?gV.parse(e):JSON.parse(e)}var ib,ob,gV,RV,ab,Lh,AV,Mh=Re(()=>{ib=require("stream"),ob=x(require("json-bigint-fixes")),gV=(0,ob.default)({useNativeBigInt:!0}),RV=1e4,ab={};BigInt.prototype.toJSON=function(){throw ab};a(mc,"streamAsJSON");Lh=class extends ib.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),sb)}catch(n){yield sb(n)}else yield Pi(t)}else yield Pi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);nb(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>RV?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 nb(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let s of this.activeIterators)t?s.throw(t):s.return();r()}};a(sb,"handleError");a(nb,"when");a(Pi,"stringify");a(cb,"jsStringify");AV=/-?\d{16,}/;a(Uh,"parse")});var Ab=T((Zae,Rb)=>{"use strict";var Ph=require("recursive-iterator"),OV=require("alasql"),vh=require("clone"),lb=J(),{handleHDBError:_b,hdb_errors:bV}=re(),{HDB_ERROR_MSGS:db,HTTP_STATUS_CODES:fb}=bV,{getDatabases:NV}=(Ae(),se(Fe)),yV=["DISTINCT_ARRAY"],Eb=Symbol("validateTables"),Bh=Symbol("validateTable"),Xae=Symbol("getAllColumns"),hb=Symbol("validateAllColumns"),zl=Symbol("findColumn"),mb=Symbol("validateOrderBy"),pc=Symbol("validateSegment"),Hh=Symbol("validateColumn"),pb=Symbol("setColumnsForTable"),Sb=Symbol("checkColumnsForAsterisk"),Tb=Symbol("validateGroupBy"),gb=Symbol("hasColumns"),xh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Eb](),this[Sb](),this[hb]()}[Eb](){if(this[gb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Bh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Bh](t.table)})}}[gb](){let t=!1,r=new Ph(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Bh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=NV();if(!r[t.databaseid])throw _b(new Error,db.SCHEMA_NOT_FOUND(t.databaseid),fb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw _b(new Error,db.TABLE_NOT_FOUND(t.databaseid,t.tableid),fb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=vh(n);i.table=vh(t),this.attributes.push(i)})}[zl](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[Sb](){let t=new Ph(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[pb](r.tableid)}[pb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new OV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[hb](){this[pc](this.statement.columns,!1),this[pc](this.statement.joins,!1),this[pc](this.statement.where,!1),this[Tb](this.statement.group,!1),this[pc](this.statement.order,!0)}[pc](t,r){if(!t)return;let s=new Ph(t),n=[];for(let{node:i,path:o}of s)!lb.isEmpty(i)&&!lb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[mb](i):n.push(this[Hh](i)));return n}[Tb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&yV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=vh(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[zl](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[zl](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[mb](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[Hh](t)}[Hh](t){let r=this[zl](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};Rb.exports=xh});var bb=T((tce,Ob)=>{"use strict";var qh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Ob.exports=qh});var yb=T((sce,Nb)=>{"use strict";var Fh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Nb.exports=Fh});var Db={};Ye(Db,{HAS_EXPIRATION:()=>Qh,LAST_TIMESTAMP_PLACEHOLDER:()=>gc,LOCAL_TIMESTAMP:()=>wV,METADATA:()=>Sc,NO_TIMESTAMP:()=>kh,PENDING_LOCAL_TIME:()=>zh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Wh,RecordEncoder:()=>Yh,TIMESTAMP_ASSIGN_LAST:()=>CV,TIMESTAMP_ASSIGN_NEW:()=>Ib,TIMESTAMP_ASSIGN_PREVIOUS:()=>Cb,TIMESTAMP_PLACEHOLDER:()=>Jl,TIMESTAMP_RECORD_PREVIOUS:()=>Vh,fromResource:()=>e_,getUpdateRecord:()=>Jh,handleLocalTimeForGets:()=>t_});function LV(){return Tc[0]=Tc[0]^64,IV.getFloat64(0)}function e_(e){Kh=!0;try{return e()}finally{Kh=!1}}function t_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[Sc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[Sc]>=0?c.value:c};let s=e.getRange;e.getRange=function(i){let o=s.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[Sc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let n=e.useReadTransaction();if(n.done(),!n.done.isTracked){let i=n.constructor,o=n.use,c=n.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,vi.push(new WeakRef(this))),!Kh)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<vi.length;u++){let _=vi[u].deref();(!_||_.isDone||_.isCommitted)&&vi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Jh(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?xo=i?.localTime?Vh|Cb:kh:xo=u?i?.localTime?Vh|16384:Ib|16384:kh,l>0&&(c|=Qh),Xl=c,$h=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:xo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(u){let A=_?.user?.username;if(E&&(jl=e.encoder.encode(E)),f&&i?.localTime){let R=i?.localTime,g=r.get(R);if(g){let P=Lt(g).previousLocalTime;return r.put(R,Zl(o,t,s,P,A,d,jl),{ifVersion:p}),S}}r.put(gc,Zl(o,t,s,i?.localTime?1:0,A,d,jl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var wb,Gh,Jl,gc,Wh,wV,Sc,Tc,IV,kh,Ib,CV,Cb,Vh,Qh,zh,DV,jl,xo,Xl,$h,Yh,oce,Kh,vi,qo=Re(()=>{wb=require("msgpackr");Bi();Gh=x(V()),Jl=new Uint8Array([1,1,1,1,4,64,0,0]),gc=new Uint8Array([1,1,1,1,1,0,0,0]),Wh=new Uint8Array([1,1,1,1,3,64,0,0]),wV=Symbol("local-timestamp"),Sc=Symbol("metadata"),Tc=new Uint8Array(8),IV=new DataView(Tc.buffer,0,8),kh=0,Ib=0,CV=1,Cb=3,Vh=4,Qh=16,zh=1,xo=0,Xl=-1,$h=0,Yh=class extends wb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){if(xo||Xl>=0){let i=0,o=xo;o&&(i+=8,xo=0);let c=Xl,u=$h;c>=0&&(i+=2,Xl=-1,u&&(i+=8,$h=0));let _=DV=r.call(this,s,n|2048|i);jl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Jl[4]=o,Jl[5]=o>>8,_.set(Jl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,s,n)}}decode(t,r){let s=r?.start||0,n=r>-1?r:r?.end||t.length,i=t[s],o=0;try{if(i<32&&n>2){let c=s,u;if(i===2){if(t.copy)t.copy(Tc,0,c),c+=8;else for(let d=0;d<8;d++)Tc[d]=t[c++];u=LV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Qh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,n),n-c);return{localTime:u,value:l,[Sc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(LV,"getTimestamp");oce=Map.prototype.get;a(e_,"fromResource");a(t_,"handleLocalTimeForGets");vi=[];setInterval(()=>{for(let e=0;e<vi.length;e++){let t=vi[e].deref();!t||t.isDone||t.isCommitted?vi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(Gh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Gh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Jh,"getUpdateRecord")});var r_=T((cce,Lb)=>{"use strict";var Xh=Z(),Zh=L(),{RecordEncoder:UV}=(qo(),se(Db));Xh.initSync();var MV=Xh.get(Zh.CONFIG_PARAMS.STORAGE_COMPRESSION),PV=Xh.get(Zh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,vV=Zh.UPDATES_PROPERTY,jh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=MV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=PV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:UV},this.alwaysLazyProperty=s=>s===vV)}};Lb.exports=jh});var n_=T((lce,Mb)=>{"use strict";var Fo=Z(),Rc=L();Fo.initSync();var BV=Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Ub=Fo.get(Rc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),HV=Fo.get(Rc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),s_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=BV,this.noFSAccess=!0,Ub!==void 0&&(this.overlappingSync=Ub),this.noReadAhead=HV}};Mb.exports=s_;s_.MAX_DBS=1e4});var We=T((dce,Vb)=>{"use strict";var tm=require("lmdb"),Os=require("fs-extra"),Ir=require("path"),i_=yr(),Bb=V(),sr=Nr().LMDB_ERRORS_ENUM,o_=yb(),rm=r_(),Hb=n_(),Jn=dt(),Pb=L(),{table:xV,resetDatabases:qV}=(Ae(),se(Fe)),vb=Z(),bs=Jn.INTERNAL_DBIS_NAME,xb=Jn.DBI_DEFINITION_NAME,FV="data.mdb",GV="lock.mdb",Ac=".mdb",kV="-lock",em=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=Zr(t,r),this.key_type=this.dbi[Jn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Jn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new tm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function a_(e,t){if(e===void 0)throw new Error(sr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(sr.ENV_NAME_REQUIRED)}a(a_,"pathEnvNameValidation");async function sm(e,t,r=!0){try{await Os.access(e)}catch(s){throw s.code==="ENOENT"?new Error(sr.INVALID_BASE_PATH):s}try{let s=Ir.join(e,t+Ac);return await Os.access(s,Os.constants.R_OK|Os.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Os.access(Ir.join(e,t,FV),Os.constants.R_OK|Os.constants.F_OK),Ir.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(sr.INVALID_ENVIRONMENT)}else throw new Error(sr.INVALID_ENVIRONMENT);throw s}}a(sm,"validateEnvironmentPath");function c_(e,t){if(i_.validateEnv(e),t===void 0)throw new Error(sr.DBI_NAME_REQUIRED)}a(c_,"validateEnvDBIName");async function VV(e,t,r=!1,s=!1){a_(e,t);let n=Ir.basename(e);t=t.toString();let i=vb.get(Pb.CONFIG_PARAMS.DATABASES);i||vb.setProperty(Pb.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await sm(e,t,s),qb(e,t,r)}catch(o){if(o.message===sr.INVALID_ENVIRONMENT){let c=Ir.join(e,t);await Os.mkdirp(s?c:e);let u=new Hb(s?c:c+Ac,!1),_=tm.open(u);_.dbis=Object.create(null);let l=new rm(!1);_.openDB(bs,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=nm(e,t,r);return _[Jn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(VV,"createEnvironment");async function $V(e,t,r,s=!0){a_(e,t),t=t.toString();let n=Ir.join(e,t);return xV({table:t,database:Ir.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a($V,"copyEnvironment");async function qb(e,t,r=!1){a_(e,t),t=t.toString();let s=nm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await sm(e,t),i=Ir.join(e,t+Ac),o=n!=i,c=new Hb(n,o),u=tm.open(c);u.dbis=Object.create(null);let _=Gb(u);for(let l=0;l<_.length;l++)Zr(u,_[l]);return u[Jn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(qb,"openEnvironment");async function YV(e,t,r=!1){a_(e,t),t=t.toString();let s=Ir.join(e,t+Ac),n=await sm(e,t);if(global.lmdb_map!==void 0){let i=nm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Fb(o),delete global.lmdb_map[i]}}await Os.remove(n),await Os.remove(n===s?n+kV:Ir.join(Ir.dirname(n),GV))}a(YV,"deleteEnvironment");async function Fb(e){i_.validateEnv(e);let t=e[Jn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Fb,"closeEnvironment");function nm(e,t,r=!1){let n=`${Ir.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(nm,"getCachedEnvironmentName");function KV(e){i_.validateEnv(e);let t=Object.create(null),r=Zr(e,bs);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==bs)try{t[s]=Object.assign(new o_,n)}catch{Bb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(KV,"listDBIDefinitions");function Gb(e){i_.validateEnv(e);let t=[],r=Zr(e,bs);for(let{key:s}of r.getRange({start:!1}))s!==bs&&t.push(s);return t}a(Gb,"listDBIs");function WV(e,t){let s=Zr(e,bs).getEntry(t),n=new o_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Bb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(WV,"getDBIDefinition");function kb(e,t,r,s=!r){if(c_(e,t),t=t.toString(),t===bs)throw new Error(sr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Zr(e,t)}catch(n){if(n.message===sr.DBI_DOES_NOT_EXIST){let i=new rm(r,s===!0),o=e.openDB(t,i),c=new o_(r===!0,s);return o[xb]=c,Zr(e,bs).putSync(t,c),e.dbis[t]=o,o}throw n}}a(kb,"createDBI");function Zr(e,t){if(c_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==bs?r=WV(e,t):r=new o_,r===void 0)throw new Error(sr.DBI_DOES_NOT_EXIST);let s;try{let n=new rm(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(sr.DBI_DOES_NOT_EXIST):n}return s[xb]=r,e.dbis[t]=s,s}a(Zr,"openDBI");function QV(e,t){c_(e,t),t=t.toString();let r=Zr(e,t),s=r.getStats();return r[Jn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(QV,"statDBI");async function zV(e,t){try{let r=Ir.join(e,t+Ac);return(await Os.stat(r)).size}catch{throw new Error(sr.INVALID_ENVIRONMENT)}}a(zV,"environmentDataSize");function JV(e,t){if(c_(e,t),t=t.toString(),t===bs)throw new Error(sr.CANNOT_DROP_INTERNAL_DBIS_NAME);Zr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Zr(e,bs).removeSync(t)}a(JV,"dropDBI");function jV(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{Zr(e,i)}catch(o){if(o.message===sr.DBI_DOES_NOT_EXIST)kb(e,i,i!==t,i===t),s=!0;else throw o}}s&&qV()}a(jV,"initializeDBIs");Vb.exports={openDBI:Zr,openEnvironment:qb,createEnvironment:VV,listDBIs:Gb,listDBIDefinitions:KV,createDBI:kb,dropDBI:JV,statDBI:QV,deleteEnvironment:YV,initializeDBIs:jV,TransactionCursor:em,environmentDataSize:zV,copyEnvironment:$V,closeEnvironment:Fb}});var Yb=T((Ece,$b)=>{"use strict";var im=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};$b.exports=im});var Wb=T((mce,Kb)=>{"use strict";var om=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};Kb.exports=om});var zb=T((Sce,Qb)=>{"use strict";var am=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};Qb.exports=am});var Go=T((Oce,Xb)=>{"use strict";var XV=We(),ZV=Yb(),e$=Wb(),t$=zb(),Vs=yr(),Oc=Nr().LMDB_ERRORS_ENUM,r$=dt(),mn=L(),s$=J(),n$=require("uuid"),gce=require("lmdb"),{handleHDBError:i$,hdb_errors:o$}=re(),{OVERFLOW_MARKER:Rce,MAX_SEARCH_KEY_LENGTH:Ace}=r$,Jb=Z();Jb.initSync();var u_=Jb.get(mn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),cm=mn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Hi=mn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function a$(e,t,r,s,n=Vs.getNextMonotonicTime()){dm(e,t,r,s),um(e,t,r);let i=new ZV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];jb(_,!0,n);let l=c$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return lm(o,c,s,i,n)}a(a$,"insertRecords");function c$(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][mn.FUNC_VAL],s[o]=c)}let u=Vs.getIndexedValues(c),_=e.dbis[o];if(u){u_&&_.prefetch(u.map(l=>({key:l,value:n})),l_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}u_&&e.dbis[t].prefetch([n],l_),e.dbis[t].put(n,s,s[Hi])})}a(c$,"insertRecord");function u$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(u$,"removeSkippedRecords");function jb(e,t,r){let s=r>0;(s||!Number.isInteger(e[Hi]))&&(e[Hi]=r||(r=Vs.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[cm]))&&(e[cm]=r||Vs.getNextMonotonicTime()):delete e[cm]}a(jb,"setTimestamps");function um(e,t,r){r.indexOf(mn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(mn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(mn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(mn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),XV.initializeDBIs(e,t,r)}a(um,"initializeTransaction");async function l$(e,t,r,s,n=Vs.getNextMonotonicTime()){dm(e,t,r,s),um(e,t,r);let i=new e$,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=_m(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return lm(c,u,s,i,n,o)}a(l$,"updateRecords");async function _$(e,t,r,s,n=Vs.getNextMonotonicTime()){try{dm(e,t,r,s)}catch(u){throw i$(u,u.message,o$.HTTP_STATUS_CODES.BAD_REQUEST)}um(e,t,r);let i=new t$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;s$.isEmpty(_[t])?(l=n$.v4(),_[t]=l):l=_[t];let d=_m(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return lm(o,c,s,i,n)}a(_$,"upsertRecords");async function lm(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||Vs.getNextMonotonicTime(),u$(r,i),s}a(lm,"finalizeWrite");function _m(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(jb(r,!l,o),Number.isInteger(r[Hi])&&_[Hi]>r[Hi])return!1;l&&n.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let A=_[h];if(typeof p=="function"){let g=p([[_]]);Array.isArray(g)&&(p=g[0][mn.FUNC_VAL],r[h]=p)}if(p===A)continue;let R=Vs.getIndexedValues(A);if(R){u_&&S.prefetch(R.map(g=>({key:g,value:s})),l_);for(let g=0,P=R.length;g<P;g++)S.remove(R[g],s)}if(R=Vs.getIndexedValues(p),R){u_&&S.prefetch(R.map(g=>({key:g,value:s})),l_);for(let g=0,P=R.length;g<P;g++)S.put(R[g],s)}}let E=Object.assign({},_,r);c.put(s,E,E[Hi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:_m(e,t,r,s,n,i,o))}a(_m,"updateUpsertRecord");function d$(e,t,r){if(Vs.validateEnv(e),t===void 0)throw new Error(Oc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Oc.WRITE_ATTRIBUTES_REQUIRED):new Error(Oc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(d$,"validateBasic");function dm(e,t,r,s){if(d$(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Oc.RECORDS_REQUIRED):new Error(Oc.RECORDS_MUST_BE_ARRAY)}a(dm,"validateWrite");function l_(){}a(l_,"noop");Xb.exports={insertRecords:a$,updateRecords:l$,upsertRecords:_$}});var xi=T((Nce,f$)=>{f$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var Ys=T((yce,tN)=>{"use strict";var eN=J(),Zb=L(),ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,$s=require("joi"),jn={schema_format:{pattern:ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},E$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(ko).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number(),$s.array()).required(),h$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(ko).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number()),m$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(ko).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number()).required();function p$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>jn.schema_length.maximum?`'${e}' maximum of 250 characters`:ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(p$,"checkValidTable");function S$(e,t){return eN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(S$,"validateSchemaExists");function T$(e,t){let r=t.state.ancestors[0].schema;return eN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(T$,"validateTableExists");function g$(e,t){return e.toLowerCase()===Zb.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Zb.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(g$,"validateSchemaName");tN.exports={common_validators:jn,schema_regex:ko,hdb_schema_table:E$,validateSchemaExists:S$,validateTableExists:T$,validateSchemaName:g$,checkValidTable:p$,hdb_database:h$,hdb_table:m$}});var je=T((Ice,rN)=>{"use strict";var nr=require("validate.js");nr.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||nr.validators.type.checks[t](e)?null:` must be a '${t}' value`};nr.validators.type.checks={Object:function(e){return nr.isObject(e)&&!nr.isArray(e)},Array:nr.isArray,Integer:nr.isInteger,Number:nr.isNumber,String:nr.isString,Date:nr.isDate,Boolean:function(e){return typeof e=="boolean"}};nr.validators.hasValidFileExt=function(e,t){return nr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};rN.exports={validateObject:R$,validateObjectAsync:A$,validateBySchema:O$};function R$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=nr(e,t,{format:"flat"});return r?new Error(r):null}a(R$,"validateObject");async function A$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await nr.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(A$,"validateObjectAsync");function O$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(O$,"validateBySchema")});var __=T((Dce,sN)=>{var{common_validators:Ks}=Ys(),Nc=je(),bc="is required",ft={database:{presence:!1,format:Ks.schema_format,length:Ks.schema_length},schema:{presence:!1,format:Ks.schema_format,length:Ks.schema_length},table:{presence:!0,format:Ks.schema_format,length:Ks.schema_length},attribute:{presence:!0,format:Ks.schema_format,length:Ks.schema_length},hash_attribute:{presence:!0,format:Ks.schema_format,length:Ks.schema_length}};function yc(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(yc,"makeAttributesStrings");function b$(e){return e=yc(e),ft.table.presence=!1,ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(b$,"schema_object");function N$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(N$,"table_object");function y$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,Nc.validateObject(e,ft)}a(y$,"create_table_object");function w$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence={message:bc},ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(w$,"attribute_object");function I$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(I$,"describe_table");function C$(e){if(e){if(!Array.isArray(e))throw new Error("residence must be a string array");if(e.length===0)throw new Error("residence cannot be an empty array");for(let t=0;t<e.length;t++)if(typeof e[t]!="string")throw new Error(`residence must be a string array, item '${e[t]}' is not a string`)}}a(C$,"validateTableResidence");sN.exports={schema_object:b$,create_table_object:y$,table_object:N$,attribute_object:w$,describe_table:I$,validateTableResidence:C$}});var iN=T((Uce,nN)=>{"use strict";var D$=require("uuid"),fm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||D$.v4(),this.schema_table=`${this.schema}.${this.table}`}};nN.exports=fm});var d_=T((Pce,oN)=>{"use strict";var L$=iN(),Em=class extends L${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};oN.exports=Em});var cN=T((Bce,aN)=>{"use strict";aN.exports=M$;var U$="inserted";function M$(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===U$?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(M$,"returnObject")});var f_=T((xce,fN)=>{"use strict";var P$=L(),hm=We(),v$=Go(),{getSystemSchemaPath:B$,getSchemaPath:H$}=Je(),x$=xi(),q$=__(),F$=d_(),G$=cN(),{handleHDBError:uN,hdb_errors:_N}=re(),lN=J(),{HTTP_STATUS_CODES:k$}=_N,mm=x$.hdb_attribute,dN=[];for(let e=0;e<mm.attributes.length;e++)dN.push(mm.attributes[e].attribute);var V$="inserted";fN.exports=$$;async function $$(e){let t=q$.attribute_object(e);if(t)throw uN(new Error,t.message,_N.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&lN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw uN(new Error,r,k$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=lN.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new F$(e.schema,e.table,e.attribute,e.id);try{let i=await hm.openEnvironment(H$(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);hm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await hm.openEnvironment(B$(),P$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await v$.insertRecords(o,mm.hash_attribute,dN,[n]);return G$(V$,c,{records:[n]},u)}catch(i){throw i}}a($$,"lmdbCreateAttribute")});var Sm=T((Fce,hN)=>{var{hdb_table:Y$,hdb_database:EN}=Ys(),K$=je(),pm=require("joi"),W$={undefined:"undefined",null:"null"},Q$=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||W$[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),z$=pm.object({database:EN,schema:EN,table:Y$,records:pm.array().items(pm.object().custom(Q$)).required()});hN.exports=function(e){return K$.validateBySchema(e,z$)}});var wc=T((Vce,pN)=>{"use strict";var pn=J(),mN=V(),kce=Sm(),{getDatabases:J$}=(Ae(),se(Fe)),{ClientError:qi}=re();pN.exports=j$;function j$(e){if(pn.isEmpty(e))throw new qi("invalid update parameters defined.");if(pn.isEmptyOrZeroLength(e.schema))throw new qi("invalid schema specified.");if(pn.isEmptyOrZeroLength(e.table))throw new qi("invalid table specified.");if(!Array.isArray(e.records))throw new qi("records must be an array");let t=J$()[e.schema]?.[e.table];if(pn.isEmpty(t))throw new qi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&pn.isEmptyOrZeroLength(o[r]))throw mN.error("a valid hash attribute must be provided with update record:",o),new qi("a valid hash attribute must be provided with update record, check log for more info");if(!pn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw mN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new qi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!pn.isEmpty(o[r])&&o[r]!==""&&s.has(pn.autoCast(o[r]))&&(o.skip=!0),s.add(pn.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(j$,"insertUpdateValidate")});var Ic=T((Yce,SN)=>{"use strict";var X$=L().OPERATIONS_ENUM,Tm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=X$.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};SN.exports=Tm});var Uc=T((Qce,TN)=>{"use strict";var Wce=Ic(),E_=L(),Rm=J(),gm=V(),Z$=require("uuid"),{handleHDBError:Cc,hdb_errors:e1}=re(),{HDB_ERROR_MSGS:Dc,HTTP_STATUS_CODES:Lc}=e1;TN.exports=t1;function t1(e,t,r){for(let n=0;n<t.length;n++)r1(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];s1(i,r,e.operation)}}a(t1,"processRows");function r1(e){if(Buffer.byteLength(String(e))>E_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Cc(new Error,Dc.ATTR_NAME_LENGTH_ERR(e),Lc.BAD_REQUEST,void 0,void 0,!0);if(Rm.isEmptyOrZeroLength(e)||Rm.isEmpty(e.trim()))throw Cc(new Error,Dc.ATTR_NAME_NULLISH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(r1,"validateAttribute");function s1(e,t,r){if(!e.hasOwnProperty(t)||Rm.isEmptyOrZeroLength(e[t])){if(r===E_.OPERATIONS_ENUM.INSERT||r===E_.OPERATIONS_ENUM.UPSERT){e[t]=Z$.v4();return}throw gm.error("Update transaction aborted due to record with no hash value:",e),Cc(new Error,Dc.RECORD_MISSING_HASH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>E_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw gm.error(e),Cc(new Error,Dc.HASH_VAL_LENGTH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw gm.error(e),Cc(new Error,Dc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(s1,"validateHash")});var RN=T((Jce,gN)=>{"use strict";var Am=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};gN.exports=Am});var bN=T((Xce,ON)=>{"use strict";var Om=We(),n1=V(),AN=Nr().LMDB_ERRORS_ENUM;ON.exports=i1;async function i1(e){try{if(global.lmdb_map!==void 0&&e.operation!==void 0){let t=Object.keys(global.lmdb_map),r;switch(e.operation){case"drop_schema":for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith(`${e.schema}.`)||o.startsWith(`txn.${e.schema}.`))try{await Om.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==AN.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Om.closeEnvironment(global.lmdb_map[s]),await Om.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==AN.ENV_REQUIRED)throw i}break;case"drop_attribute":r=global.lmdb_map[`${e.schema}.${e.table}`],r!==void 0&&typeof r.dbis=="object"&&r.dbis[`${e.attribute}`]!==void 0&&delete r.dbis[`${e.attribute}`];break;default:break}}}catch(t){n1.error(t)}}a(i1,"cleanLMDBMap")});var Sn=T((eue,IN)=>{"use strict";var Mc=require("crypto"),o1=Z(),{CONFIG_PARAMS:a1}=L(),yN="aes-256-cbc",c1=32,u1=16,bm=64,wN=32,l1=bm+wN,NN=new Map;IN.exports={encrypt:_1,decrypt:d1,createNatsTableStreamName:f1};function _1(e){let t=Mc.randomBytes(c1),r=Mc.randomBytes(u1),s=Mc.createCipheriv(yN,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(_1,"encrypt");function d1(e){let t=e.substr(0,bm),r=e.substr(bm,wN),s=e.substr(l1,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Mc.createDecipheriv(yN,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(d1,"decrypt");function f1(e,t){let r=o1.get(a1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=NN.get(r);return s||(s=Mc.createHash("md5").update(r).digest("hex"),NN.set(r,s)),s}a(f1,"createNatsTableStreamName")});var Xn=T((sue,DN)=>{"use strict";var rue=es(),h_=V(),CN=__(),E1=Sn(),m_=J(),{handleHDBError:p_,hdb_errors:h1}=re(),{HDB_ERROR_MSGS:S_,HTTP_STATUS_CODES:Nm}=h1,m1=Z();m1.initSync();var{getDatabases:ym}=(Ae(),se(Fe));DN.exports={describeAll:p1,describeTable:T_,describeSchema:S1};async function p1(e){try{let t=m_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=ym(),i={},o={},c=[],u=e?.exact_count;for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let d=n[l];for(let f in d)try{let E;if(t||s)E=await T_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await T_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){h_.error(E)}}let _={};for(let l in c)t||s?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return h_.error("Got an error in describeAll"),h_.error(t),p_(new Error,S_.DESCRIBE_ALL_ERR)}}a(p1,"describeAll");async function T_(e,t){m_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=CN.describe_table(e);if(i)throw i;let c=ym()[r];if(!c)throw p_(new Error,S_.SCHEMA_NOT_FOUND(e.schema),Nm.NOT_FOUND);let u=c[s];if(!u)throw p_(new Error,S_.TABLE_NOT_FOUND(e.schema,e.table),Nm.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(n){let f={};n.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=E1.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){h_.warn(`unable to stat table dbi due to ${f}`)}return d}a(T_,"descTable");async function S1(e){m_.transformReq(e);let t=CN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=ym()[s];if(!i)throw p_(new Error,S_.SCHEMA_NOT_FOUND(e.schema),Nm.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),m_.isEmpty(u)||u.describe){let _=await T_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(S1,"describeSchema")});var Tn=T((aue,vN)=>{var T1=xi(),{callbackify:UN,promisify:g1}=require("util"),{getDatabases:MN}=(Ae(),se(Fe));vN.exports={setSchemaDataToGlobal:LN,getTableSchema:R1,getSystemSchema:A1,setSchemaDataToGlobalAsync:g1(LN)};var PN=Xn(),iue=UN(PN.describeAll),oue=UN(PN.describeTable);function LN(e){global.hdb_schema=MN(),e&&e()}a(LN,"setSchemaDataToGlobal");function R1(e,t,r){let s=MN()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(R1,"getTableSchema");function A1(){return T1}a(A1,"getSystemSchema")});var Cr=T((uue,qN)=>{"use strict";var R_=Sm(),qt=J(),O1=require("util"),A_=Ns(),b1=Tn(),BN=V(),{handleHDBError:Fi,hdb_errors:N1}=re(),{HTTP_STATUS_CODES:Gi}=N1,y1=O1.promisify(b1.getTableSchema),w1="updated",HN="inserted",xN="upserted";qN.exports={insert:C1,update:D1,upsert:L1,validation:I1,flush:U1};async function I1(e){if(qt.isEmpty(e))throw new Error("invalid update parameters defined.");if(qt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(qt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await y1(e.schema,e.table),r=R_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&qt.isEmptyOrZeroLength(c[s]))throw BN.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!qt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw BN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!qt.isEmpty(c[s])&&c[s]!==""&&n.has(qt.autoCast(c[s]))&&(c.skip=!0),n.add(qt.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(I1,"validation");async function C1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=R_(e);if(t)throw Fi(new Error,t.message,Gi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.createRecords(e);return g_(HN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(C1,"insertData");async function D1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=R_(e);if(t)throw Fi(new Error,t.message,Gi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.updateRecords(e);return qt.isEmpty(s.existing_rows)?g_(w1,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):g_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(D1,"updateData");async function L1(e){if(e.operation!=="upsert")throw Fi(new Error,"invalid operation, must be upsert",Gi.INTERNAL_SERVER_ERROR);let t=R_(e);if(t)throw Fi(new Error,t.message,Gi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.upsertRecords(e);return g_(xN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(L1,"upsertData");function g_(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===HN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===xN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(g_,"returnObject");function U1(e){return qt.transformReq(e),A_.flush(e.schema,e.table)}a(U1,"flush")});var Im=T((_ue,kN)=>{var M1=je(),wm=require("joi"),{hdb_table:P1,hdb_database:FN}=Ys(),GN={schema:FN,database:FN,table:P1},v1={date:wm.date().iso().required()},B1={timestamp:wm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};kN.exports=function(e,t){let r=t==="timestamp"?{...GN,...B1}:{...GN,...v1},s=wm.object(r);return M1.validateBySchema(e,s)}});var YN=T((due,$N)=>{var H1=je(),Cm=require("joi"),{hdb_table:x1,hdb_database:VN}=Ys(),q1=Cm.object({schema:VN,database:VN,table:x1,hash_values:Cm.array().required(),ids:Cm.array()});$N.exports=function(e){return H1.validateBySchema(e,q1)}});var WN=T((fue,KN)=>{"use strict";var Dm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},Lm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},Um=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};KN.exports={InsertObject:Dm,NoSQLSeachObject:Lm,DeleteResponseObject:Um}});var ti=T((hue,XN)=>{"use strict";var zN=Im(),F1=YN(),ki=J(),QN=require("moment"),JN=V(),{promisify:G1,callbackify:k1}=require("util"),Vi=L(),V1=Tn(),Mm=G1(V1.getTableSchema),Pm=Ns(),{DeleteResponseObject:$1}=WN(),{handleHDBError:Zn,hdb_errors:Y1}=re(),{HDB_ERROR_MSGS:O_,HTTP_STATUS_CODES:ei}=Y1,K1="records successfully deleted",W1=k1(jN);XN.exports={delete:W1,deleteRecord:jN,deleteFilesBefore:Q1,deleteAuditLogsBefore:z1};async function Q1(e){let t=zN(e,"date");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(ki.transformReq(e),!QN(e.date,QN.ISO_8601).isValid())throw Zn(new Error,O_.INVALID_DATE,ei.BAD_REQUEST,Vi.LOG_LEVELS.ERROR,O_.INVALID_DATE,!0);let s=ki.checkSchemaTableExist(e.schema,e.table);if(s)throw Zn(new Error,s,ei.NOT_FOUND,Vi.LOG_LEVELS.ERROR,s,!0);let n=await Pm.deleteRecordsBefore(e);if(await Mm(e.schema,e.table),JN.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(Q1,"deleteFilesBefore");async function z1(e){let t=zN(e,"timestamp");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(ki.transformReq(e),isNaN(e.timestamp))throw Zn(new Error,O_.INVALID_VALUE("Timestamp"),ei.BAD_REQUEST,Vi.LOG_LEVELS.ERROR,O_.INVALID_VALUE("Timestamp"),!0);let r=ki.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Vi.LOG_LEVELS.ERROR,r,!0);let s=await Pm.deleteAuditLogsBefore(e);return await Mm(e.schema,e.table),JN.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(z1,"deleteAuditLogsBefore");async function jN(e){e.ids&&(e.hash_values=e.ids);let t=F1(e);if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);ki.transformReq(e);let r=ki.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Vi.LOG_LEVELS.ERROR,r,!0);try{await Mm(e.schema,e.table);let s=await Pm.deleteRecords(e);return ki.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${K1}`),s}catch(s){if(s.message===Vi.SEARCH_NOT_FOUND_MESSAGE){let n=new $1;return n.message=Vi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(jN,"deleteRecord")});var b_=T((pue,ty)=>{var J1=require("crypto"),ZN=9;function j1(e){let t=Z1(ZN),r=ey(e+t);return t+r}a(j1,"createHash");function X1(e,t){let r=e?.substr(0,ZN),s=r+ey(t+r);return e===s}a(X1,"validateHash");function Z1(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(Z1,"generateSalt");function ey(e){return J1.createHash("md5").update(e).digest("hex")}a(ey,"md5");ty.exports={hash:j1,validate:X1}});var sy=T((Tue,ry)=>{var vm=je(),Kt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function eY(e){return Kt.password.presence=!0,Kt.username.presence=!0,Kt.role.presence=!0,Kt.active.presence=!0,vm.validateObject(e,Kt)}a(eY,"addUserValidation");function tY(e){return Kt.password.presence=!1,Kt.username.presence=!0,Kt.role.presence=!1,Kt.active.presence=!1,vm.validateObject(e,Kt)}a(tY,"alterUserValidation");function rY(e){return Kt.password.presence=!1,Kt.username.presence=!0,Kt.role.presence=!1,Kt.active.presence=!1,vm.validateObject(e,Kt)}a(rY,"dropUserValidation");ry.exports={addUserValidation:eY,alterUserValidation:tY,dropUserValidation:rY}});var Ge=T((Aue,iy)=>{"use strict";var{platform:Rue}=require("os"),sY="nats-server.zip",Bm="nats-server",nY=process.platform==="win32"?`${Bm}.exe`:Bm,Hm="HDB",iY=/^[^\s.,*>]+$/,ny="__request__",oY=a(e=>`${e}.${ny}`,"REQUEST_SUBJECT"),aY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},cY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},uY={HUB:"hub.pid",LEAF:"leaf.pid"},lY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},_Y={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Hm,deliver_subject:"__HDB__.WORKQUEUE"},dY={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Hm,deliver_subject:"HDB.SCHEMAQUEUE"},fY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Hm,deliver_subject:"HDB.USERQUEUE"},EY={SUCCESS:"success",ERROR:"error"},hY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},mY={TXN:"txn",MSGID:"msgid"},Vo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},pY={[Vo.ERR]:1,[Vo.WRN]:2,[Vo.INF]:3,[Vo.DBG]:4,[Vo.TRC]:5},SY={debug:"-D",trace:"-DVV"};iy.exports={NATS_SERVER_ZIP:sY,NATS_SERVER_NAME:Bm,NATS_BINARY_NAME:nY,PID_FILES:uY,NATS_CONFIG_FILES:cY,SERVER_SUFFIX:lY,WORK_QUEUE_CONSUMER_NAMES:_Y,SCHEMA_QUEUE_CONSUMER_NAMES:dY,USER_QUEUE_CONSUMER_NAMES:fY,NATS_TERM_CONSTRAINTS_RX:iY,REQUEST_SUFFIX:ny,UPDATE_REMOTE_RESPONSE_STATUSES:EY,CLUSTER_STATUS_STATUSES:hY,REQUEST_SUBJECT:oY,SUBJECT_PREFIXES:mY,MSG_HEADERS:aY,LOG_LEVELS:Vo,LOG_LEVEL_FLAGS:SY,LOG_LEVEL_HIERARCHY:pY}});var ay=T((bue,oy)=>{"use strict";var TY={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
1
|
+
"use strict";var Kq=Object.create;var rc=Object.defineProperty;var Wq=Object.getOwnPropertyDescriptor;var Qq=Object.getOwnPropertyNames;var zq=Object.getPrototypeOf,Jq=Object.prototype.hasOwnProperty;var a=(e,t)=>rc(e,"name",{value:t,configurable:!0});var ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ke=(e,t)=>{for(var r in t)rc(e,r,{get:t[r],enumerable:!0})},YA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Qq(t))!Jq.call(e,s)&&s!==r&&rc(e,s,{get:()=>t[s],enumerable:!(n=Wq(t,s))||n.enumerable});return e};var x=(e,t,r)=>(r=e!=null?Kq(zq(e)):{},YA(t||!e||!e.__esModule?rc(r,"default",{value:e,enumerable:!0}):r,e)),ne=e=>YA(rc({},"__esModule",{value:!0}),e);var QA=T((Rae,WA)=>{var jq=require("fast-glob"),{statSync:uh,existsSync:lh,readFileSync:Xq,writeFileSync:Zq}=require("fs"),{spawnSync:eF,spawn:tF,execFileSync:gae}=require("child_process"),{isMainThread:rF}=require("worker_threads"),{join:Qs,relative:KA}=require("path"),{PACKAGE_ROOT:gn}=U(),{tmpdir:nF,platform:sF}=require("os");require("source-map-support").install();var iF=["resources","server","dataLayer","components"],nc="ts-build",_h,oF=__filename.endsWith("tsBuild.js");if(oF){if(rF){let r;try{uh(Qs(gn,nc)),r=!0}catch{}if(r)for(let n of jq.sync(iF.map(s=>s+"/**/*.ts"),{cwd:gn})){let s=0,i=0;try{s=uh(Qs(gn,n)).mtimeMs-5e3,i=uh(Qs(gn,nc,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),_h=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),_h=!0;if(_h){let n=Qs(gn,"node_modules/.bin/tsc");sF()==="win32"&&(n+=".cmd");let s=eF(n,{cwd:gn});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=Qs(nF(),"harperdb-tsc.pid"),o;if(lh(i))try{process.kill(+Xq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=tF(n,["--watch"],{cwd:gn,detached:!0,stdio:"ignore"});Zq(i,c.pid.toString()),c.unref()}}}}let e=WA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(gn)&&!n[0].includes("node_modules")){let i=KA(gn,n[0]),o;i.startsWith(nc)?o=Qs(gn,KA(nc,i)):o=Qs(gn,nc,i);let c=Qs(o,r),u=c+".js";if(lh(u))return u;if(c.includes(".")&&lh(c))return c}return t(r,n,s)}}});var U=T((bae,cO)=>{"use strict";var Xr=require("path"),aF=require("fs"),{relative:Aae,join:Oae}=Xr,{existsSync:cF}=aF;function uF(){let e=__dirname;for(;!cF(Xr.join(e,"package.json"));){let t=Xr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(uF,"getHDBPackageRoot");var zs=uF(),zA="js",ql=zA,lF="harperdb-config.yaml",_F="defaultConfig.yaml",dF="hdb",JA=`harperdb.${ql}`,jA=`customFunctionsServer.${ql}`,fF=`restartHdb.${ql}`,fh="HarperDB",xl="Custom Functions",Fl="Clustering Hub",Gl="Clustering Leaf",EF="Clustering Ingest Service",hF="Clustering Reply Service",mF="foreground.pid",pF="hdb.pid",SF="data",TF={HDB:fh,CLUSTERING_HUB:Fl,CLUSTERING_LEAF:Gl,CLUSTERING_INGEST_SERVICE:EF,CLUSTERING_REPLY_SERVICE:hF,CUSTOM_FUNCTIONS:xl,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},gF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},RF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},AF={harperdb:fh,"clustering hub":Fl,"clustering leaf":Gl,"custom functions":xl,custom_functions:xl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},OF={CLUSTERING_HUB_PROC_DESCRIPTOR:Fl,CLUSTERING_LEAF_PROC_DESCRIPTOR:Gl},dh={HDB:Xr.join(zs,"server/harperdb"),CUSTOM_FUNCTIONS:Xr.join(zs,"server/customFunctions"),CLUSTERING_HUB:Xr.join(zs,"server/nats"),CLUSTERING_LEAF:Xr.join(zs,"server/nats")},bF={HDB:Xr.join(dh.HDB,JA),CUSTOM_FUNCTIONS:Xr.join(dh.CUSTOM_FUNCTIONS,jA)},NF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Xr.join(zs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Xr.join(zs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Xr.join(zs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},yF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},XA="support@harperdb.io",wF="customer-success@harperdb.io",ZA=1,IF=4141,eO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",CF="https://www.harperdb.io/product",DF=`For support, please submit a request at ${eO} or contact ${XA}`,tO=`For license support, please contact ${wF}`,UF="None of the specified records were found.",LF="hash attribute not found",MF=`Your current license only supports ${ZA} role. ${tO}`,PF="Your current license only supports 3 connections to a node.",vF="127.0.0.1",BF=1,HF=/^\.$/,xF=/^\.\.$/,qF="U+002E",FF=/\//g,GF="U+002F",kF=/U\+002F/g,VF=/^U\+002E$/,$F=/^U\+002EU\+002E$/,YF="d",KF=999999,WF="*",QF="--max-old-space-size=",zF="system",JF="__hdb_hash",jF=".harperdb",XF=".hdb",ZF="keys",eG="hdb_boot_properties.file",tG=".updateConfig.json",rG="SIGTSTP",nG=24,sG=6e4,iG=448,oG="blob",aG="trash",cG="database",uG="schema",lG="transactions",_G=".count",dG="id",fG="PROCESS_NAME",rO={SETTINGS_PATH_KEY:"settings_path"},nO=require("lodash"),EG={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},hG={HDB_PATH_KEY:"HDB_INTERNAL_PATH",HDB_AUTH_HEADER:"hdb_auth_header",HDB_USER_DATA_KEY:"hdb_user",CHUNK_SIZE:1e3,MAX_CHARACTER_SIZE:250},mG={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},pG={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"},SG={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},br="hdb_internal:",TG={CREATE_SCHEMA:br+"create_schema",CREATE_TABLE:br+"create_table",CREATE_ATTRIBUTE:br+"create_attribute",ADD_USER:br+"add_user",ALTER_USER:br+"alter_user",DROP_USER:br+"drop_user",HDB_NODES:br+"hdb_nodes",HDB_USERS:br+"hdb_users",HDB_WORKERS:br+"hdb_workers",CATCHUP:br+"catchup",SCHEMA_CATCHUP:br+"schema_catchup",WORKER_ROOM:br+"cluster_workers"},gG={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"},RG="060493.ks",AG=".license",OG={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},X={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},bG={CSV:".csv",JSON:".json"},NG={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},yG={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},sc={};sc[X.INSERT]=X.INSERT;sc[X.UPDATE]=X.UPDATE;sc[X.UPSERT]=X.UPSERT;sc[X.DELETE]=X.DELETE;var He=Object.create(null);He[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;He[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;He[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;He[X.READ_LOG]=X.READ_LOG;He[X.ADD_NODE]=X.ADD_NODE;He[X.LIST_USERS]=X.LIST_USERS;He[X.LIST_ROLES]=X.LIST_ROLES;He[X.USER_INFO]=X.USER_INFO;He[X.SQL]=X.SQL;He[X.GET_JOB]=X.GET_JOB;He[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;He[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;He[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;He[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;He[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;He[X.REMOVE_NODE]=X.REMOVE_NODE;He[X.RESTART]=X.RESTART;He[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;He[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;He[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;He[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;He[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;He[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;He[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;He[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var wG={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},IG={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},sO={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"},CG=nO.invert(sO),DG={CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root"},I={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},iO={settings_path:rO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];iO[t.toLowerCase()]=t}var UG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},LG={csv_file_load:"csv_file_load",csv_data_load:X.CSV_DATA_LOAD,csv_url_load:X.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3"},MG={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"},PG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},vG={VERSION_DEFAULT:"2.2.0"},BG={DEVELOPMENT:8192,DEFAULT:512},HG={IDENTIFY:"identify",AUTHENTICATE:"authenticate",AUTHENTICATE_OK:"authenticated",AUTHENTICATE_FAIL:"authenticate_fail",CONNECTION:"connection",CONNECT:"connect",CATCHUP_REQUEST:"catchup_request",CATCHUP_RESPONSE:"catchup",CONFIRM_MSG:"confirm_msg",ERROR:"error",DISCONNECT:"disconnect",SCHEMA_UPDATE_REQ:"schema_update_request",SCHEMA_UPDATE_RES:"schema_update_response",RECONNECT_ATTEMPT:"reconnect_attempt",CONNECT_ERROR:"connect_error",MESSAGE:"msg",VERSION_MISMATCH:"version_mismatch",DIRECTION_CHANGE:"direction_change"},xG={1e3:"SUCCESSFUL_SHUTDOWN",1001:"CLOSE_GOING_AWAY",1002:"CLOSE_PROTOCOL_ERROR",1003:"CLOSE_UNSUPPORTED",1005:"CLOSE_NO_STATUS",1006:"CLOSE_ABNORMAL",1007:"UNSUPPORTED_PAYLOAD",1008:"POLICY_VIOLATION",1009:"CLOSE_TOO_LARGE",1010:"MANDATORY_EXTENSION",1011:"SERVER_ERROR",1012:"SERVICE_RESTART",1013:"SERVER_BUSY",1014:"BAD_GATEWAY",1015:"HANDSHAKE_FAIL",4141:"LICENSE_LIMIT_REACHED"},qG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},oO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},FG=Symbol("metadata"),GG="__clustering__",kG=Object.values(oO),VG=15984864e5,aO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},$G=nO.invert(aO),YG={GET_CLUSTER_STATUS:"GET_CLUSTER_STATUS",CLUSTER_STATUS_RESPONSE:"CLUSTER_STATUS_RESPONSE",ERROR_RESPONSE:"ERROR",ADD_USER:"ADD_USER",ALTER_USER:"ALTER_USER",DROP_USER:"DROP_USER",HDB_OPERATION:"HDB_OPERATION",ADD_NODE:"ADD_NODE",UPDATE_NODE:"UPDATE_NODE",REMOVE_NODE:"REMOVE_NODE",HDB_USERS_MSG:"HDB_USERS_MSG",HDB_WORKERS:"HDB_WORKERS",HDB_TRANSACTION:"HDB_TRANSACTION"},KG=111,WG=`\r
|
|
2
|
+
`,QG={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},zG=["*","%"],JG="unauthorized_access",jG="func_val",XG={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},ZG={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},ek={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"},tk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},rk={HTTP:"http"},nk={STOPPED:"stopped",ONLINE:"online"},sk="3.x.x",ik={SUCCESS:"success",FAILURE:"failure"},ok={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};cO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:XA,HDB_SUPPORT_URL:eO,HDB_PRICING_URL:CF,SUPPORT_HELP_MSG:DF,LICENSE_HELP_MSG:tO,HDB_PROC_NAME:JA,HDB_PROC_DESCRIPTOR:fh,CLUSTERING_LEAF_PROC_DESCRIPTOR:Gl,CLUSTERING_HUB_PROC_DESCRIPTOR:Fl,SYSTEM_SCHEMA_NAME:zF,HASH_FOLDER_NAME:JF,HDB_HOME_DIR_NAME:jF,UPDATE_FILE_NAME:tG,LICENSE_KEY_DIR_NAME:ZF,BOOT_PROPS_FILE_NAME:eG,JOB_TYPE_ENUM:LG,JOB_STATUS_ENUM:OG,SYSTEM_TABLE_NAMES:pG,SYSTEM_TABLE_HASH_ATTRIBUTES:SG,OPERATIONS_ENUM:X,VALID_S3_FILE_TYPES:bG,S3_BUCKET_AUTH_KEYS:NG,VALID_SQL_OPS_ENUM:yG,GEO_CONVERSION_ENUM:IG,HDB_SETTINGS_NAMES:sO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:CG,SERVICE_ACTIONS_ENUM:wG,CLUSTER_MESSAGE_TYPE_ENUM:MG,CLUSTER_CONNECTION_DIRECTION_ENUM:PG,CLUSTER_EVENTS_DEFS_ENUM:HG,PERIOD_REGEX:HF,DOUBLE_PERIOD_REGEX:xF,UNICODE_PERIOD:qF,FORWARD_SLASH_REGEX:FF,UNICODE_FORWARD_SLASH:GF,ESCAPED_FORWARD_SLASH_REGEX:kF,ESCAPED_PERIOD_REGEX:VF,ESCAPED_DOUBLE_PERIOD_REGEX:$F,REG_KEY_FILE_NAME:RG,RESTART_TIMEOUT_MS:sG,HDB_FILE_PERMISSIONS:iG,DATABASES_DIR_NAME:cG,LEGACY_DATABASES_DIR_NAME:uG,TRANSACTIONS_DIR_NAME:lG,LIMIT_COUNT_NAME:_G,ID_ATTRIBUTE_STRING:dG,INSERT_MODULE_ENUM:hG,UPGRADE_JSON_FIELD_NAMES_ENUM:mG,RESTART_CODE:rG,RESTART_CODE_NUM:nG,CLUSTER_OPERATIONS:sc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:gG,HDB_INTERNAL_SC_CHANNEL_PREFIX:br,INTERNAL_SC_CHANNELS:TG,CLUSTERING_MESSAGE_TYPES:YG,HDB_FILE_SUFFIX:XF,BLOB_FOLDER_NAME:oG,HDB_TRASH_DIR:aG,ORIGINATOR_SET_VALUE:KG,LICENSE_VALUES:vG,RAM_ALLOCATION_ENUM:BG,TIME_STAMP_NAMES_ENUM:oO,TIME_STAMP_NAMES:kG,PERMS_UPDATE_RELEASE_TIMESTAMP:VG,SEARCH_NOT_FOUND_MESSAGE:UF,SEARCH_ATTRIBUTE_NOT_FOUND:LF,LICENSE_ROLE_DENIED_RESPONSE:MF,LICENSE_MAX_CONNS_REACHED:PF,BASIC_LICENSE_MAX_NON_CU_ROLES:ZA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:IF,VALUE_SEARCH_COMPARATORS:aO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:$G,LICENSE_FILE_NAME:AG,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:xG,NEW_LINE:WG,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:BF,MOMENT_DAYS_TAG:YF,API_TURNOVER_SEC:KF,LOOPBACK:vF,CODE_EXTENSION:ql,WILDCARD_SEARCH_VALUE:WF,NODE_ERROR_CODES:qG,JAVASCRIPT_EXTENSION:zA,PERMS_CRUD_ENUM:QG,UNAUTHORIZED_PERMISSION_NAME:JG,SEARCH_WILDCARDS:zG,FUNC_VAL:jG,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:XG,JWT_ENUM:ZG,CLUSTERING_FLAG:GG,ITC_EVENT_TYPES:ek,CUSTOM_FUNCTION_PROC_NAME:jA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:xl,SERVICES:tk,THREAD_TYPES:rk,MEM_SETTING_KEY:QF,HDB_RESTART_SCRIPT:fF,PROCESS_DESCRIPTORS:TF,SERVICE_SERVERS:bF,SERVICE_SERVERS_CWD:dh,PROCESS_DESCRIPTORS_VALIDATE:AF,LAUNCH_SERVICE_SCRIPTS:NF,LOG_LEVELS:RF,PROCESS_NAME_ENV_PROP:fG,LOG_NAMES:gF,PM2_PROCESS_STATUSES:nk,CONFIG_PARAM_MAP:iO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:lF,HDB_DEFAULT_CONFIG_FILE:_F,ROLE_TYPES_ENUM:yF,BOOT_PROP_PARAMS:rO,INSTALL_PROMPTS:EG,HDB_ROOT_DIR_NAME:dF,CLUSTERING_PROCESSES:OF,FOREGROUND_PID_FILE:mF,PACKAGE_ROOT:zs,PRE_4_0_0_VERSION:sk,DATABASES_PARAM_CONFIG:UG,METADATA_PROPERTY:FG,AUTH_AUDIT_STATUS:ik,AUTH_AUDIT_TYPES:ok,HDB_PID_FILE:pF,DEFAULT_DATABASE_NAME:SF,LEGACY_CONFIG_PARAMS:DG};QA()});var Eh=T((yae,_O)=>{"use strict";var uO=require("minimist");_O.exports=ak;function ak(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=lO(process.env),n=lO(uO(process.argv))):(r=process.env,n=uO(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(ak,"assignCMDENVVariables");function lO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(lO,"objKeysToLowerCase")});var $=T((Iae,Rh)=>{"use strict";var Mi=require("fs-extra"),{workerData:ck,threadId:uk}=require("worker_threads"),hs=require("path"),EO=require("yaml"),hO=require("properties-reader"),At=U(),dO=Eh(),lk=require("os"),{PACKAGE_ROOT:mh}=U(),{_assignPackageExport:_k}=require("../index"),oc={};for(let e in console)oc[e]||(oc[e]=console[e]);var er={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},mO={STDOUT:"stdOut",STDERR:"stdErr"},dk=hs.join(mh,"logs"),fk=hs.join(mh,"config/yaml/",At.HDB_DEFAULT_CONFIG_FILE),Ek=1e4,Es,Vn,Zt,kl,Vl,ac,xo,ic;ic===void 0&&pO();Rh.exports={notify:gO,fatal:RO,error:cc,warn:gh,info:$l,debug:Th,trace:Sh,setLogLevel:Rk,log_level:Zt,loggerWithTag:hk,suppressLogging:mk,initLogSettings:pO,setupConsoleLogging:SO,logCustomLevel:Tk,closeLogFile:ph,getLogFilePath:()=>ac,OUTPUTS:mO,AuthAuditLog:bk};_k("logger",Rh.exports);function pO(e=!1){try{if(ic===void 0||e){ph();let t=gk(),r=dO(["ROOTPATH"]);try{ic=hO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Mi.pathExistsSync(hs.join(r.ROOTPATH,At.HDB_CONFIG_FILE)))throw n}({level:Zt,config_log_path:Vl,to_file:Es,to_stream:Vn}=Ak(r.ROOTPATH?hs.join(r.ROOTPATH,At.HDB_CONFIG_FILE):ic.get("settings_path"))),kl=At.LOG_NAMES.HDB,ac=hs.join(Vl,kl)}}catch(t){if(ic=void 0,t.code===At.NODE_ERROR_CODES.ENOENT){let r=dO(Object.keys(At.CONFIG_PARAM_MAP),!0);for(let o in r){let c=At.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===At.CONFIG_PARAMS.LOGGING_LEVEL){Zt=u;continue}if(c===At.CONFIG_PARAMS.LOGGING_STDSTREAMS){Vn=u;continue}c===At.CONFIG_PARAMS.LOGGING_FILE&&(Es=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=Ok();Es=Es===void 0?s:Es,Es=fO(Es),Vn=Vn===void 0?i:Vn,Vn=fO(Vn),Zt=Zt===void 0?n:Zt,Vl=dk,kl=At.LOG_NAMES.INSTALL,ac=hs.join(Vl,kl);return}throw cc("Error initializing log settings"),cc(t),t}process.env.DEV_MODE&&(Vn=!0),SO()}a(pO,"initLogSettings");var hh=!0;function SO(){Ho("error",cc),Ho("warn",gh),Ho("log",$l),Ho("info",$l),Ho("debug",Th),Ho("trace",Sh)}a(SO,"setupConsoleLogging");function Ho(e,t){console[e]=function(...r){if(hh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return oc[e](...r)}}a(Ho,"logConsole");function hk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(gO),fatal:r(RO),error:r(cc),warn:r(gh),info:r($l),debug:r(Th),trace:r(Sh)};function r(n){return function(...s){return n(t,...s)}}}a(hk,"loggerWithTag");function mk(e){try{hh=!1,e()}finally{hh=!0}}a(mk,"suppressLogging");var pk=ck?.name?.replace(/ /g,"-")||"main";function ms(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||pk+"/"+uk);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
3
|
+
`}a(ms,"createLogRecord");function uc(e){Es&&TO(e),Vn&&process.stdout.write(e)}a(uc,"logStdOut");function Yl(e){Es&&TO(e),Vn&&process.stderr.write(e)}a(Yl,"logStdErr");function TO(e){Sk(),xo?Mi.appendFileSync(xo,e):oc.log(e)}a(TO,"logToFile");function ph(){try{Mi.closeSync(xo)}catch{}xo=null}a(ph,"closeLogFile");function Sk(){if(!xo){try{if(!ac)debugger;xo=Mi.openSync(ac,"a")}catch(e){oc.error(e)}setTimeout(()=>{ph()},Ek).unref()}}a(Sk,"openLogFile");function $l(...e){er[Zt]<=er.info&&uc(ms("info",e))}a($l,"info");function Sh(...e){er[Zt]<=er.trace&&uc(ms("trace",e))}a(Sh,"trace");function cc(...e){er[Zt]<=er.error&&Yl(ms("error",e))}a(cc,"error");function Th(...e){er[Zt]<=er.debug&&uc(ms("debug",e))}a(Th,"debug");function gO(...e){er[Zt]<=er.notify&&uc(ms("notify",e))}a(gO,"notify");function RO(...e){er[Zt]<=er.fatal&&Yl(ms("fatal",e))}a(RO,"fatal");function gh(...e){er[Zt]<=er.warn&&Yl(ms("warn",e))}a(gh,"warn");function Tk(e,t,...r){t===mO.STDERR?Yl(ms(e,r)):uc(ms(e,r))}a(Tk,"logCustomLevel");function gk(){let e;try{e=lk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=hs.join(e,At.HDB_HOME_DIR_NAME,At.BOOT_PROPS_FILE_NAME);return Mi.existsSync(t)||(t=hs.join(mh,"utility/hdb_boot_properties.file")),t}a(gk,"getPropsFilePath");function Rk(e){Zt=e}a(Rk,"setLogLevel");function fO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(fO,"autoCastBoolean");function Ak(e){try{if(e.includes("config/settings.js")){let o=hO(e);return{level:o.get(At.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:hs.dirname(o.get(At.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(At.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(At.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=EO.parseDocument(Mi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===At.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Ak,"getLogConfig");function Ok(){try{let e=EO.parseDocument(Mi.readFileSync(fk,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(Ok,"getDefaultConfig");function bk(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(bk,"AuthAuditLog")});var OO=T((Dae,AO)=>{"use strict";var Nk=require("util"),yk=require("path"),wk=require("child_process"),Ik=Nk.promisify(wk.execFile),Ck=1e3*1e3*10;AO.exports={findPs:Dk};async function Dk(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await Ik("ps",["wwxo",`pid,${r}`],{maxBuffer:Ck});for(let s of n.trim().split(`
|
|
4
|
+
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:yk.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(Dk,"findPs")});var ft=T((Lae,NO)=>{"use strict";var Uk="__dbis__",Lk="__txns__",Mk="__environment_name__",Pk="__dbi_defintion__",vk={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"},Bk=["__createdtime__","__updatedtime__"],Hk="\uFFFF",bO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},xk=Object.values(bO);NO.exports={AUDIT_STORE_NAME:Lk,INTERNAL_DBIS_NAME:Uk,DBI_DEFINITION_NAME:Pk,SEARCH_TYPES:vk,TIMESTAMP_NAMES:Bk,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Mk,TRANSACTIONS_DBI_NAMES_ENUM:bO,TRANSACTIONS_DBIS:xk,OVERFLOW_MARKER:Hk}});var Nr=T((Mae,PO)=>{"use strict";var yO=U(),wO=ft(),IO={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},CO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),DO={500:CO("There was an error processing your request."),400:"Invalid request"},qk=DO[IO.INTERNAL_SERVER_ERROR],Fk={OP_NOT_SUPPORTED_FOR_FS:e=>`${e} is not available for this instance because it uses the File System data store.`,MISSING_VALUE:e=>`${e} is missing.`,INVALID_VALUE:e=>`${e} is invalid.`,NOT_FOUND:e=>`${e} not found.`},Gk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},kk={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:e=>`There was an error downloading '${e}'.`,INSERT_JSON_ERR:"There was an error inserting the downloaded JSON data.",INSERT_CSV_ERR:"There was an error inserting the downloaded CSV data.",INVALID_ACTION_PARAM_ERR:e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,INVALID_FILE_EXT_ERR:e=>`Error selecting correct parser - valid file type not found in json - ${e}`,MAX_FILE_SIZE_ERR:(e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:e=>`There was an error downloading '${e}' from AWS.`,WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},Vk={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${wO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${wO.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"},$k={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${yO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${yO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},UO={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},Yk={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},Kk={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},Wk={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},Qk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},zk={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},LO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},MO={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},Jk={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."},jk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Xk={...UO,...kk,...Fk,...Yk,...Kk,...Wk,...Qk,...zk,...$k,...LO,...MO,...Jk,...jk,...Gk};PO.exports={CHECK_LOGS_WRAPPER:CO,HDB_ERROR_MSGS:Xk,DEFAULT_ERROR_MSGS:DO,DEFAULT_ERROR_RESP:qk,HTTP_STATUS_CODES:IO,LMDB_ERRORS_ENUM:Vk,AUTHENTICATION_ERROR_MSGS:UO,VALIDATION_ERROR_MSGS:LO,ITC_ERRORS:MO}});var re=T((vae,HO)=>{"use strict";var qo=Nr(),Zk=$(),eV=U(),Kl=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,vO),this.statusCode=n||qo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(qo.DEFAULT_ERROR_MSGS[n]?qo.DEFAULT_ERROR_MSGS[n]:qo.DEFAULT_ERROR_MSGS[qo.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&&Zk[s](i)}},Ah=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}},Oh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function vO(e,t,r,n=eV.LOG_LEVELS.ERROR,s=null,i=!1){if(BO(e))return e;let o=new Kl(e,t,r,n,s);return i&&delete o.stack,o}a(vO,"handleHDBError");function BO(e){return e.__proto__.constructor.name===Kl.name}a(BO,"isHDBError");HO.exports={isHDBError:BO,handleHDBError:vO,ClientError:Ah,ServerError:Oh,hdb_errors:qo}});var je=T((Hae,$O)=>{"use strict";var Ec=U(),tV=J(),tr=Z(),hc=require("path"),rV=require("minimist"),xO=require("fs-extra"),qO=require("lodash");tr.initSync();var{CONFIG_PARAMS:Js,DATABASES_PARAM_CONFIG:lc,SYSTEM_SCHEMA_NAME:Wl}=Ec,_c,dc,fc;function FO(){if(_c!==void 0)return _c;if(tr.getHdbBasePath()!==void 0)return _c=tr.get(Js.STORAGE_PATH)||hc.join(tr.getHdbBasePath(),Ec.DATABASES_DIR_NAME),_c}a(FO,"getBaseSchemaPath");function GO(){if(dc!==void 0)return dc;if(tr.getHdbBasePath()!==void 0)return dc=VO(Wl),dc}a(GO,"getSystemSchemaPath");function kO(){if(fc!==void 0)return fc;if(tr.getHdbBasePath()!==void 0)return fc=tr.get(Ec.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||hc.join(tr.getHdbBasePath(),Ec.TRANSACTIONS_DIR_NAME),fc}a(kO,"getTransactionAuditStoreBasePath");function nV(e,t){let r=tr.get(Js.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||hc.join(kO(),e.toString())}a(nV,"getTransactionAuditStorePath");function VO(e,t){e=e.toString(),t=t&&t.toString();let r=tr.get(Ec.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||hc.join(FO(),e)}a(VO,"getSchemaPath");function sV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,rV(process.argv));let n=r[Js.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!tV.isObject(n))throw o;i=n}for(let o of i){let c=o[Wl];if(!c)continue;let u=tr.get(Js.DATABASES);u=u??{};let _=c?.tables?.[t]?.[lc.PATH];if(_)return qO.set(u,[Wl,lc.TABLES,t,lc.PATH],_),tr.setProperty(Js.DATABASES,u),_;let l=c?.[lc.PATH];if(l)return qO.set(u,[Wl,lc.PATH],l),tr.setProperty(Js.DATABASES,u),l}}let s=r[Js.STORAGE_PATH.toUpperCase()];if(s){if(!xO.pathExistsSync(s))throw new Error(s+" does not exist");let i=hc.join(s,e);return xO.mkdirsSync(i),tr.setProperty(Js.STORAGE_PATH,s),i}return GO()}a(sV,"initSystemSchemaPaths");function iV(){_c=void 0,dc=void 0,fc=void 0}a(iV,"resetPaths");$O.exports={getBaseSchemaPath:FO,getSystemSchemaPath:GO,getTransactionAuditStorePath:nV,getTransactionAuditStoreBasePath:kO,getSchemaPath:VO,initSystemSchemaPaths:sV,resetPaths:iV}});var yr=T((Gae,zO)=>{"use strict";var oV=Nr().LMDB_ERRORS_ENUM,qae=require("lmdb"),aV=ft(),Fae=require("buffer").Buffer,{OVERFLOW_MARKER:YO,MAX_SEARCH_KEY_LENGTH:Ql}=aV,KO=["number","string","symbol","boolean","bigint"];function cV(e){if(e=e?.primaryStore||e,!e)throw new Error(oV.ENV_REQUIRED)}a(cV,"validateEnv");function uV(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(uV,"stringifyData");function lV(e){return e instanceof Date?e.valueOf():e}a(lV,"convertKeyValueToWrite");function _V(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(KO.includes(typeof e))return e.length>Ql?[e.slice(0,Ql)+YO]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(KO.includes(typeof i))i.length>Ql?r.push(i.slice(0,Ql)+YO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(_V,"getIndexedValues");var zl=0,WO=0;function QO(){WO=Date.now()-performance.now()}a(QO,"adjustStartTime");QO();var dV=6e4;setInterval(QO,dV).unref();function fV(){let e=performance.now()+WO;return e>zl?(zl=e,e):(zl+=488e-6,zl)}a(fV,"getNextMonotonicTime");zO.exports={validateEnv:cV,stringifyData:uV,convertKeyValueToWrite:lV,getNextMonotonicTime:fV,getIndexedValues:_V}});var JO,Rn,bh,mc=ge(()=>{JO=require("events"),Rn=class extends JO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new bh;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},bh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Pi={};Ke(Pi,{server:()=>rt});var jO,rt,rr=ge(()=>{jO=require("../index"),rt={};(0,jO._assignPackageExport)("server",rt)});var wh={};Ke(wh,{loadGQLSchema:()=>mV,start:()=>yh,startOnMainThread:()=>hV});function yh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(P){if(P.kind==="NonNullType"){let W=H(P.type);return W.nullable=!1,W}if(P.kind==="ListType")return{type:"array",elements:H(P.type)};let K={type:P.name?.value};return Object.defineProperty(K,"location",{value:P.loc.startToken}),K};a(H,"getProperty");let g=S.name.value,A=[],R={table:null,database:null,properties:A};f.set(g,R);for(let P of S.directives){if(P.name.value==="table"){for(let M of P.arguments)R[M.name.value]=M.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=g),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(P.name.value==="sealed"&&(R.sealed=!0),P.name.value==="export"){R.export=!0;for(let M of P.arguments)M.name.value==="name"&&(R.export={name:M.value.value})}}let v=!1;for(let P of S.fields){let M=H(P.type);M.name=P.name.value,A.push(M);for(let K of P.directives)if(K.name.value==="primaryKey")v?console.warn("Can not define two attributes as a primary key"):(M.isPrimaryKey=!0,v=!0);else if(K.name.value==="indexed")M.indexed=!0;else if(K.name.value==="relationship"){let W={};for(let V of K.arguments)W[V.name.value]=V.value.value;M.relationship=W}else if(K.name.value==="createdTime")M.assignCreatedTime=!0;else if(K.name.value==="updatedTime")M.assignUpdatedTime=!0;else if(K.name.value==="expiresAt")M.expiresAt=!0;else if(K.name.value==="allow"){let W=M.authorizedRoles=[];for(let V of K.arguments)V.name.value==="role"&&W.push(V.value.value)}}R.type=g,g==="Query"&&(h=R)}function p(S){let g=f.get(S.type);g?(Object.defineProperty(S,"properties",{value:g.properties}),Object.defineProperty(S,"definition",{value:g})):S.type==="array"?p(S.elements):EV.includes(S.type)||(0,XO.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of f.values())for(let g of S.properties)p(g);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Nh.dirname)(n),S.tableClass):i.set((0,Nh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Nh,XO,EV,hV,mV,ZO=ge(()=>{Nh=require("path");Re();XO=x(We()),EV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(yh,"start");hV=yh,mV=yh({ensureTable:ut}).handleFile});async function Jl(e){return pV?(pc||(pc=SV(gV)),(await(await pc).import(e)).namespace):import(e)}async function SV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),pc=new Compartment({console,Math,Date,fetch:TV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,tb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:xt,tables:wr,databases:nt})}};let n=await(0,eb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),pc}function TV(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 gV(){return{Resource:xt,tables:wr}}var eb,tb,pV,pc,Ih=ge(()=>{An();Re();eb=require("fs/promises"),tb=require("path"),pV=!1;a(Jl,"secureImport");a(SV,"getCompartment");a(TV,"secureOnlyFetch");a(gV,"getGlobalVars")});var Dh={};Ke(Dh,{handleFile:()=>RV});async function RV(e,t,r,n){let s=new Map,i=(0,rb.pathToFileURL)(r).toString(),o=await Jl(i);u(o.default)&&n.set((0,Ch.dirname)(t),o.default),c(o,(0,Ch.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var rb,Ch,nb=ge(()=>{rb=require("url");Ih();Ch=require("path");a(RV,"handleFile")});var Lh={};Ke(Lh,{start:()=>AV});function AV({resources:e}){e.set("login",Uh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Uh,sb=ge(()=>{An();a(AV,"start");Uh=class extends xt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var _b={};Ke(_b,{parse:()=>Ph,streamAsJSON:()=>Sc,stringify:()=>vi});function Sc(e){return new Mh({value:e})}function ib(e){return console.error(e),JSON.stringify(e.toString())}function ob(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function vi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===ub)return lb(e);if(t.resolution)return t.resolution.then(()=>vi(e));throw t}}function lb(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+=lb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+vi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Ph(e){return NV.test(e)?OV.parse(e):JSON.parse(e)}var ab,cb,OV,bV,ub,Mh,NV,vh=ge(()=>{ab=require("stream"),cb=x(require("json-bigint-fixes")),OV=(0,cb.default)({useNativeBigInt:!0}),bV=1e4,ub={};BigInt.prototype.toJSON=function(){throw ub};a(Sc,"streamAsJSON");Mh=class extends ab.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),ib)}catch(s){yield ib(s)}else yield vi(t)}else yield vi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);ob(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>bV?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 ob(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(ib,"handleError");a(ob,"when");a(vi,"stringify");a(lb,"jsStringify");NV=/-?\d{16,}/;a(Ph,"parse")});var bb=T((nce,Ob)=>{"use strict";var Bh=require("recursive-iterator"),yV=require("alasql"),Hh=require("clone"),db=J(),{handleHDBError:fb,hdb_errors:wV}=re(),{HDB_ERROR_MSGS:Eb,HTTP_STATUS_CODES:hb}=wV,{getDatabases:IV}=(Re(),ne(Fe)),CV=["DISTINCT_ARRAY"],mb=Symbol("validateTables"),xh=Symbol("validateTable"),rce=Symbol("getAllColumns"),pb=Symbol("validateAllColumns"),jl=Symbol("findColumn"),Sb=Symbol("validateOrderBy"),Tc=Symbol("validateSegment"),qh=Symbol("validateColumn"),Tb=Symbol("setColumnsForTable"),gb=Symbol("checkColumnsForAsterisk"),Rb=Symbol("validateGroupBy"),Ab=Symbol("hasColumns"),Fh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[mb](),this[gb](),this[pb]()}[mb](){if(this[Ab]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[xh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[xh](t.table)})}}[Ab](){let t=!1,r=new Bh(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[xh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=IV();if(!r[t.databaseid])throw fb(new Error,Eb.SCHEMA_NOT_FOUND(t.databaseid),hb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw fb(new Error,Eb.TABLE_NOT_FOUND(t.databaseid,t.tableid),hb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=Hh(s);i.table=Hh(t),this.attributes.push(i)})}[jl](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[gb](){let t=new Bh(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Tb](r.tableid)}[Tb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new yV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[pb](){this[Tc](this.statement.columns,!1),this[Tc](this.statement.joins,!1),this[Tc](this.statement.where,!1),this[Rb](this.statement.group,!1),this[Tc](this.statement.order,!0)}[Tc](t,r){if(!t)return;let n=new Bh(t),s=[];for(let{node:i,path:o}of n)!db.isEmpty(i)&&!db.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Sb](i):s.push(this[qh](i)));return s}[Rb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&CV.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=Hh(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[jl](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[jl](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[Sb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[qh](t)}[qh](t){let r=this[jl](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Ob.exports=Fh});var yb=T((ice,Nb)=>{"use strict";var Gh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Nb.exports=Gh});var Ib=T((ace,wb)=>{"use strict";var kh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};wb.exports=kh});var Lb={};Ke(Lb,{HAS_EXPIRATION:()=>Jh,LAST_TIMESTAMP_PLACEHOLDER:()=>Ac,LOCAL_TIMESTAMP:()=>DV,METADATA:()=>gc,NO_TIMESTAMP:()=>$h,PENDING_LOCAL_TIME:()=>jh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>zh,RecordEncoder:()=>Wh,TIMESTAMP_ASSIGN_LAST:()=>LV,TIMESTAMP_ASSIGN_NEW:()=>Db,TIMESTAMP_ASSIGN_PREVIOUS:()=>Ub,TIMESTAMP_PLACEHOLDER:()=>Xl,TIMESTAMP_RECORD_PREVIOUS:()=>Yh,fromResource:()=>r_,getUpdateRecord:()=>Xh,handleLocalTimeForGets:()=>n_});function PV(){return Rc[0]=Rc[0]^64,UV.getFloat64(0)}function r_(e){Qh=!0;try{return e()}finally{Qh=!1}}function n_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[gc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[gc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[gc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,Bi.push(new WeakRef(this))),!Qh)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Bi.length;u++){let _=Bi[u].deref();(!_||_.isDone||_.isCommitted)&&Bi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Xh(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Fo=i?.localTime?Yh|Ub:$h:Fo=u?i?.localTime?Yh|16384:Db|16384:$h,l>0&&(c|=Jh),e_=c,Kh=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Fo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let g=_?.user?.username;if(E&&(Zl=e.encoder.encode(E)),f&&i?.localTime){let A=i?.localTime,R=r.get(A);if(R){let v=Ut(R).previousLocalTime;return r.put(A,t_(o,t,n,v,g,d,Zl),{ifVersion:p}),S}}r.put(Ac,t_(o,t,n,i?.localTime?1:0,g,d,Zl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Cb,Vh,Xl,Ac,zh,DV,gc,Rc,UV,$h,Db,LV,Ub,Yh,Jh,jh,MV,Zl,Fo,e_,Kh,Wh,lce,Qh,Bi,Go=ge(()=>{Cb=require("msgpackr");Hi();Vh=x($()),Xl=new Uint8Array([1,1,1,1,4,64,0,0]),Ac=new Uint8Array([1,1,1,1,1,0,0,0]),zh=new Uint8Array([1,1,1,1,3,64,0,0]),DV=Symbol("local-timestamp"),gc=Symbol("metadata"),Rc=new Uint8Array(8),UV=new DataView(Rc.buffer,0,8),$h=0,Db=0,LV=1,Ub=3,Yh=4,Jh=16,jh=1,Fo=0,e_=-1,Kh=0,Wh=class extends Cb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(Fo||e_>=0){let i=0,o=Fo;o&&(i+=8,Fo=0);let c=e_,u=Kh;c>=0&&(i+=2,e_=-1,u&&(i+=8,Kh=0));let _=MV=r.call(this,n,s|2048|i);Zl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Xl[4]=o,Xl[5]=o>>8,_.set(Xl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(Rc,0,c),c+=8;else for(let d=0;d<8;d++)Rc[d]=t[c++];u=PV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Jh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[gc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(PV,"getTimestamp");lce=Map.prototype.get;a(r_,"fromResource");a(n_,"handleLocalTimeForGets");Bi=[];setInterval(()=>{for(let e=0;e<Bi.length;e++){let t=Bi[e].deref();!t||t.isDone||t.isCommitted?Bi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(Vh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Vh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Xh,"getUpdateRecord")});var s_=T((dce,Mb)=>{"use strict";var em=Z(),tm=U(),{RecordEncoder:vV}=(Go(),ne(Lb));em.initSync();var BV=em.get(tm.CONFIG_PARAMS.STORAGE_COMPRESSION),HV=em.get(tm.CONFIG_PARAMS.STORAGE_CACHING)!==!1,xV=tm.UPDATES_PROPERTY,Zh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=BV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=HV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:vV},this.alwaysLazyProperty=n=>n===xV)}};Mb.exports=Zh});var o_=T((Ece,vb)=>{"use strict";var ko=Z(),Oc=U();ko.initSync();var qV=ko.get(Oc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||ko.get(Oc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||ko.get(Oc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Pb=ko.get(Oc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),FV=ko.get(Oc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),i_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=qV,this.noFSAccess=!0,Pb!==void 0&&(this.overlappingSync=Pb),this.noReadAhead=FV}};vb.exports=i_;i_.MAX_DBS=1e4});var Qe=T((mce,Yb)=>{"use strict";var nm=require("lmdb"),On=require("fs-extra"),Ir=require("path"),a_=yr(),xb=$(),nr=Nr().LMDB_ERRORS_ENUM,c_=Ib(),sm=s_(),qb=o_(),js=ft(),Bb=U(),{table:GV,resetDatabases:kV}=(Re(),ne(Fe)),Hb=Z(),bn=js.INTERNAL_DBIS_NAME,Fb=js.DBI_DEFINITION_NAME,VV="data.mdb",$V="lock.mdb",bc=".mdb",YV="-lock",rm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=Zr(t,r),this.key_type=this.dbi[js.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[js.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new nm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function u_(e,t){if(e===void 0)throw new Error(nr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(nr.ENV_NAME_REQUIRED)}a(u_,"pathEnvNameValidation");async function im(e,t,r=!0){try{await On.access(e)}catch(n){throw n.code==="ENOENT"?new Error(nr.INVALID_BASE_PATH):n}try{let n=Ir.join(e,t+bc);return await On.access(n,On.constants.R_OK|On.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await On.access(Ir.join(e,t,VV),On.constants.R_OK|On.constants.F_OK),Ir.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(nr.INVALID_ENVIRONMENT)}else throw new Error(nr.INVALID_ENVIRONMENT);throw n}}a(im,"validateEnvironmentPath");function l_(e,t){if(a_.validateEnv(e),t===void 0)throw new Error(nr.DBI_NAME_REQUIRED)}a(l_,"validateEnvDBIName");async function KV(e,t,r=!1,n=!1){u_(e,t);let s=Ir.basename(e);t=t.toString();let i=Hb.get(Bb.CONFIG_PARAMS.DATABASES);i||Hb.setProperty(Bb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await im(e,t,n),Gb(e,t,r)}catch(o){if(o.message===nr.INVALID_ENVIRONMENT){let c=Ir.join(e,t);await On.mkdirp(n?c:e);let u=new qb(n?c:c+bc,!1),_=nm.open(u);_.dbis=Object.create(null);let l=new sm(!1);_.openDB(bn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=om(e,t,r);return _[js.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(KV,"createEnvironment");async function WV(e,t,r,n=!0){u_(e,t),t=t.toString();let s=Ir.join(e,t);return GV({table:t,database:Ir.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(WV,"copyEnvironment");async function Gb(e,t,r=!1){u_(e,t),t=t.toString();let n=om(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await im(e,t),i=Ir.join(e,t+bc),o=s!=i,c=new qb(s,o),u=nm.open(c);u.dbis=Object.create(null);let _=Vb(u);for(let l=0;l<_.length;l++)Zr(u,_[l]);return u[js.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(Gb,"openEnvironment");async function QV(e,t,r=!1){u_(e,t),t=t.toString();let n=Ir.join(e,t+bc),s=await im(e,t);if(global.lmdb_map!==void 0){let i=om(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await kb(o),delete global.lmdb_map[i]}}await On.remove(s),await On.remove(s===n?s+YV:Ir.join(Ir.dirname(s),$V))}a(QV,"deleteEnvironment");async function kb(e){a_.validateEnv(e);let t=e[js.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(kb,"closeEnvironment");function om(e,t,r=!1){let s=`${Ir.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(om,"getCachedEnvironmentName");function zV(e){a_.validateEnv(e);let t=Object.create(null),r=Zr(e,bn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==bn)try{t[n]=Object.assign(new c_,s)}catch{xb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(zV,"listDBIDefinitions");function Vb(e){a_.validateEnv(e);let t=[],r=Zr(e,bn);for(let{key:n}of r.getRange({start:!1}))n!==bn&&t.push(n);return t}a(Vb,"listDBIs");function JV(e,t){let n=Zr(e,bn).getEntry(t),s=new c_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{xb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(JV,"getDBIDefinition");function $b(e,t,r,n=!r){if(l_(e,t),t=t.toString(),t===bn)throw new Error(nr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Zr(e,t)}catch(s){if(s.message===nr.DBI_DOES_NOT_EXIST){let i=new sm(r,n===!0),o=e.openDB(t,i),c=new c_(r===!0,n);return o[Fb]=c,Zr(e,bn).putSync(t,c),e.dbis[t]=o,o}throw s}}a($b,"createDBI");function Zr(e,t){if(l_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==bn?r=JV(e,t):r=new c_,r===void 0)throw new Error(nr.DBI_DOES_NOT_EXIST);let n;try{let s=new sm(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(nr.DBI_DOES_NOT_EXIST):s}return n[Fb]=r,e.dbis[t]=n,n}a(Zr,"openDBI");function jV(e,t){l_(e,t),t=t.toString();let r=Zr(e,t),n=r.getStats();return r[js.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(jV,"statDBI");async function XV(e,t){try{let r=Ir.join(e,t+bc);return(await On.stat(r)).size}catch{throw new Error(nr.INVALID_ENVIRONMENT)}}a(XV,"environmentDataSize");function ZV(e,t){if(l_(e,t),t=t.toString(),t===bn)throw new Error(nr.CANNOT_DROP_INTERNAL_DBIS_NAME);Zr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Zr(e,bn).removeSync(t)}a(ZV,"dropDBI");function e$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{Zr(e,i)}catch(o){if(o.message===nr.DBI_DOES_NOT_EXIST)$b(e,i,i!==t,i===t),n=!0;else throw o}}n&&kV()}a(e$,"initializeDBIs");Yb.exports={openDBI:Zr,openEnvironment:Gb,createEnvironment:KV,listDBIs:Vb,listDBIDefinitions:zV,createDBI:$b,dropDBI:ZV,statDBI:jV,deleteEnvironment:QV,initializeDBIs:e$,TransactionCursor:rm,environmentDataSize:XV,copyEnvironment:WV,closeEnvironment:kb}});var Wb=T((Sce,Kb)=>{"use strict";var am=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Kb.exports=am});var zb=T((gce,Qb)=>{"use strict";var cm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Qb.exports=cm});var jb=T((Ace,Jb)=>{"use strict";var um=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Jb.exports=um});var Vo=T((wce,eN)=>{"use strict";var t$=Qe(),r$=Wb(),n$=zb(),s$=jb(),$n=yr(),Nc=Nr().LMDB_ERRORS_ENUM,i$=ft(),ps=U(),o$=J(),a$=require("uuid"),bce=require("lmdb"),{handleHDBError:c$,hdb_errors:u$}=re(),{OVERFLOW_MARKER:Nce,MAX_SEARCH_KEY_LENGTH:yce}=i$,Xb=Z();Xb.initSync();var __=Xb.get(ps.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),lm=ps.TIME_STAMP_NAMES_ENUM.CREATED_TIME,xi=ps.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function l$(e,t,r,n,s=$n.getNextMonotonicTime()){Em(e,t,r,n),_m(e,t,r);let i=new r$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Zb(_,!0,s);let l=_$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return dm(o,c,n,i,s)}a(l$,"insertRecords");function _$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][ps.FUNC_VAL],n[o]=c)}let u=$n.getIndexedValues(c),_=e.dbis[o];if(u){__&&_.prefetch(u.map(l=>({key:l,value:s})),d_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}__&&e.dbis[t].prefetch([s],d_),e.dbis[t].put(s,n,n[xi])})}a(_$,"insertRecord");function d$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(d$,"removeSkippedRecords");function Zb(e,t,r){let n=r>0;(n||!Number.isInteger(e[xi]))&&(e[xi]=r||(r=$n.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[lm]))&&(e[lm]=r||$n.getNextMonotonicTime()):delete e[lm]}a(Zb,"setTimestamps");function _m(e,t,r){r.indexOf(ps.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(ps.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(ps.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(ps.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),t$.initializeDBIs(e,t,r)}a(_m,"initializeTransaction");async function f$(e,t,r,n,s=$n.getNextMonotonicTime()){Em(e,t,r,n),_m(e,t,r);let i=new n$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=fm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return dm(c,u,n,i,s,o)}a(f$,"updateRecords");async function E$(e,t,r,n,s=$n.getNextMonotonicTime()){try{Em(e,t,r,n)}catch(u){throw c$(u,u.message,u$.HTTP_STATUS_CODES.BAD_REQUEST)}_m(e,t,r);let i=new s$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;o$.isEmpty(_[t])?(l=a$.v4(),_[t]=l):l=_[t];let d=fm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return dm(o,c,n,i,s)}a(E$,"upsertRecords");async function dm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||$n.getNextMonotonicTime(),d$(r,i),n}a(dm,"finalizeWrite");function fm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Zb(r,!l,o),Number.isInteger(r[xi])&&_[xi]>r[xi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let g=_[h];if(typeof p=="function"){let R=p([[_]]);Array.isArray(R)&&(p=R[0][ps.FUNC_VAL],r[h]=p)}if(p===g)continue;let A=$n.getIndexedValues(g);if(A){__&&S.prefetch(A.map(R=>({key:R,value:n})),d_);for(let R=0,v=A.length;R<v;R++)S.remove(A[R],n)}if(A=$n.getIndexedValues(p),A){__&&S.prefetch(A.map(R=>({key:R,value:n})),d_);for(let R=0,v=A.length;R<v;R++)S.put(A[R],n)}}let E=Object.assign({},_,r);c.put(n,E,E[xi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:fm(e,t,r,n,s,i,o))}a(fm,"updateUpsertRecord");function h$(e,t,r){if($n.validateEnv(e),t===void 0)throw new Error(Nc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Nc.WRITE_ATTRIBUTES_REQUIRED):new Error(Nc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(h$,"validateBasic");function Em(e,t,r,n){if(h$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Nc.RECORDS_REQUIRED):new Error(Nc.RECORDS_MUST_BE_ARRAY)}a(Em,"validateWrite");function d_(){}a(d_,"noop");eN.exports={insertRecords:l$,updateRecords:f$,upsertRecords:E$}});var qi=T((Cce,m$)=>{m$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var Kn=T((Dce,nN)=>{"use strict";var rN=J(),tN=U(),$o=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Yn=require("joi"),Xs={schema_format:{pattern:$o,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},p$=Yn.alternatives(Yn.string().min(1).max(Xs.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+Xs.schema_format.message}),Yn.number(),Yn.array()).required(),S$=Yn.alternatives(Yn.string().min(1).max(Xs.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+Xs.schema_format.message}),Yn.number()),T$=Yn.alternatives(Yn.string().min(1).max(Xs.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+Xs.schema_format.message}),Yn.number()).required();function g$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Xs.schema_length.maximum?`'${e}' maximum of 250 characters`:$o.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(g$,"checkValidTable");function R$(e,t){return rN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(R$,"validateSchemaExists");function A$(e,t){let r=t.state.ancestors[0].schema;return rN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(A$,"validateTableExists");function O$(e,t){return e.toLowerCase()===tN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${tN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(O$,"validateSchemaName");nN.exports={common_validators:Xs,schema_regex:$o,hdb_schema_table:p$,validateSchemaExists:R$,validateTableExists:A$,validateSchemaName:O$,checkValidTable:g$,hdb_database:S$,hdb_table:T$}});var Xe=T((Lce,sN)=>{"use strict";var sr=require("validate.js");sr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||sr.validators.type.checks[t](e)?null:` must be a '${t}' value`};sr.validators.type.checks={Object:function(e){return sr.isObject(e)&&!sr.isArray(e)},Array:sr.isArray,Integer:sr.isInteger,Number:sr.isNumber,String:sr.isString,Date:sr.isDate,Boolean:function(e){return typeof e=="boolean"}};sr.validators.hasValidFileExt=function(e,t){return sr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};sN.exports={validateObject:b$,validateObjectAsync:N$,validateBySchema:y$};function b$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=sr(e,t,{format:"flat"});return r?new Error(r):null}a(b$,"validateObject");async function N$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await sr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(N$,"validateObjectAsync");function y$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(y$,"validateBySchema")});var f_=T((Pce,iN)=>{var{common_validators:Wn}=Kn(),wc=Xe(),yc="is required",Et={database:{presence:!1,format:Wn.schema_format,length:Wn.schema_length},schema:{presence:!1,format:Wn.schema_format,length:Wn.schema_length},table:{presence:!0,format:Wn.schema_format,length:Wn.schema_length},attribute:{presence:!0,format:Wn.schema_format,length:Wn.schema_length},hash_attribute:{presence:!0,format:Wn.schema_format,length:Wn.schema_length}};function Ic(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(Ic,"makeAttributesStrings");function w$(e){return e=Ic(e),Et.table.presence=!1,Et.attribute.presence=!1,Et.hash_attribute.presence=!1,wc.validateObject(e,Et)}a(w$,"schema_object");function I$(e){return e=Ic(e),Et.table.presence={message:yc},Et.attribute.presence=!1,Et.hash_attribute.presence=!1,wc.validateObject(e,Et)}a(I$,"table_object");function C$(e){return e=Ic(e),Et.table.presence={message:yc},Et.attribute.presence=!1,wc.validateObject(e,Et)}a(C$,"create_table_object");function D$(e){return e=Ic(e),Et.table.presence={message:yc},Et.attribute.presence={message:yc},Et.hash_attribute.presence=!1,wc.validateObject(e,Et)}a(D$,"attribute_object");function U$(e){return e=Ic(e),Et.table.presence={message:yc},Et.attribute.presence=!1,Et.hash_attribute.presence=!1,wc.validateObject(e,Et)}a(U$,"describe_table");function L$(e){if(e){if(!Array.isArray(e))throw new Error("residence must be a string array");if(e.length===0)throw new Error("residence cannot be an empty array");for(let t=0;t<e.length;t++)if(typeof e[t]!="string")throw new Error(`residence must be a string array, item '${e[t]}' is not a string`)}}a(L$,"validateTableResidence");iN.exports={schema_object:w$,create_table_object:C$,table_object:I$,attribute_object:D$,describe_table:U$,validateTableResidence:L$}});var aN=T((Bce,oN)=>{"use strict";var M$=require("uuid"),hm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||M$.v4(),this.schema_table=`${this.schema}.${this.table}`}};oN.exports=hm});var E_=T((xce,cN)=>{"use strict";var P$=aN(),mm=class extends P${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};cN.exports=mm});var lN=T((Fce,uN)=>{"use strict";uN.exports=B$;var v$="inserted";function B$(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===v$?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(B$,"returnObject")});var h_=T((kce,hN)=>{"use strict";var H$=U(),pm=Qe(),x$=Vo(),{getSystemSchemaPath:q$,getSchemaPath:F$}=je(),G$=qi(),k$=f_(),V$=E_(),$$=lN(),{handleHDBError:_N,hdb_errors:fN}=re(),dN=J(),{HTTP_STATUS_CODES:Y$}=fN,Sm=G$.hdb_attribute,EN=[];for(let e=0;e<Sm.attributes.length;e++)EN.push(Sm.attributes[e].attribute);var K$="inserted";hN.exports=W$;async function W$(e){let t=k$.attribute_object(e);if(t)throw _N(new Error,t.message,fN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&dN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw _N(new Error,r,Y$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=dN.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new V$(e.schema,e.table,e.attribute,e.id);try{let i=await pm.openEnvironment(F$(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);pm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await pm.openEnvironment(q$(),H$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await x$.insertRecords(o,Sm.hash_attribute,EN,[s]);return $$(K$,c,{records:[s]},u)}catch(i){throw i}}a(W$,"lmdbCreateAttribute")});var gm=T(($ce,pN)=>{var{hdb_table:Q$,hdb_database:mN}=Kn(),z$=Xe(),Tm=require("joi"),J$={undefined:"undefined",null:"null"},j$=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||J$[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),X$=Tm.object({database:mN,schema:mN,table:Q$,records:Tm.array().items(Tm.object().custom(j$)).required()});pN.exports=function(e){return z$.validateBySchema(e,X$)}});var Cc=T((Wce,TN)=>{"use strict";var Ss=J(),SN=$(),Kce=gm(),{getDatabases:Z$}=(Re(),ne(Fe)),{ClientError:Fi}=re();TN.exports=e1;function e1(e){if(Ss.isEmpty(e))throw new Fi("invalid update parameters defined.");if(Ss.isEmptyOrZeroLength(e.schema))throw new Fi("invalid schema specified.");if(Ss.isEmptyOrZeroLength(e.table))throw new Fi("invalid table specified.");if(!Array.isArray(e.records))throw new Fi("records must be an array");let t=Z$()[e.schema]?.[e.table];if(Ss.isEmpty(t))throw new Fi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Ss.isEmptyOrZeroLength(o[r]))throw SN.error("a valid hash attribute must be provided with update record:",o),new Fi("a valid hash attribute must be provided with update record, check log for more info");if(!Ss.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw SN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Fi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ss.isEmpty(o[r])&&o[r]!==""&&n.has(Ss.autoCast(o[r]))&&(o.skip=!0),n.add(Ss.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(e1,"insertUpdateValidate")});var Dc=T((zce,gN)=>{"use strict";var t1=U().OPERATIONS_ENUM,Rm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=t1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};gN.exports=Rm});var Pc=T((Xce,RN)=>{"use strict";var jce=Dc(),m_=U(),Om=J(),Am=$(),r1=require("uuid"),{handleHDBError:Uc,hdb_errors:n1}=re(),{HDB_ERROR_MSGS:Lc,HTTP_STATUS_CODES:Mc}=n1;RN.exports=s1;function s1(e,t,r){for(let s=0;s<t.length;s++)i1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];o1(i,r,e.operation)}}a(s1,"processRows");function i1(e){if(Buffer.byteLength(String(e))>m_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Uc(new Error,Lc.ATTR_NAME_LENGTH_ERR(e),Mc.BAD_REQUEST,void 0,void 0,!0);if(Om.isEmptyOrZeroLength(e)||Om.isEmpty(e.trim()))throw Uc(new Error,Lc.ATTR_NAME_NULLISH_ERR,Mc.BAD_REQUEST,void 0,void 0,!0)}a(i1,"validateAttribute");function o1(e,t,r){if(!e.hasOwnProperty(t)||Om.isEmptyOrZeroLength(e[t])){if(r===m_.OPERATIONS_ENUM.INSERT||r===m_.OPERATIONS_ENUM.UPSERT){e[t]=r1.v4();return}throw Am.error("Update transaction aborted due to record with no hash value:",e),Uc(new Error,Lc.RECORD_MISSING_HASH_ERR,Mc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>m_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Am.error(e),Uc(new Error,Lc.HASH_VAL_LENGTH_ERR,Mc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Am.error(e),Uc(new Error,Lc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Mc.BAD_REQUEST,void 0,void 0,!0)}a(o1,"validateHash")});var ON=T((eue,AN)=>{"use strict";var bm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};AN.exports=bm});var yN=T((rue,NN)=>{"use strict";var Nm=Qe(),a1=$(),bN=Nr().LMDB_ERRORS_ENUM;NN.exports=c1;async function c1(e){try{if(global.lmdb_map!==void 0&&e.operation!==void 0){let t=Object.keys(global.lmdb_map),r;switch(e.operation){case"drop_schema":for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith(`${e.schema}.`)||o.startsWith(`txn.${e.schema}.`))try{await Nm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==bN.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await Nm.closeEnvironment(global.lmdb_map[n]),await Nm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==bN.ENV_REQUIRED)throw i}break;case"drop_attribute":r=global.lmdb_map[`${e.schema}.${e.table}`],r!==void 0&&typeof r.dbis=="object"&&r.dbis[`${e.attribute}`]!==void 0&&delete r.dbis[`${e.attribute}`];break;default:break}}}catch(t){a1.error(t)}}a(c1,"cleanLMDBMap")});var Ts=T((sue,DN)=>{"use strict";var vc=require("crypto"),u1=Z(),{CONFIG_PARAMS:l1}=U(),IN="aes-256-cbc",_1=32,d1=16,ym=64,CN=32,f1=ym+CN,wN=new Map;DN.exports={encrypt:E1,decrypt:h1,createNatsTableStreamName:m1};function E1(e){let t=vc.randomBytes(_1),r=vc.randomBytes(d1),n=vc.createCipheriv(IN,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(E1,"encrypt");function h1(e){let t=e.substr(0,ym),r=e.substr(ym,CN),n=e.substr(f1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=vc.createDecipheriv(IN,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(h1,"decrypt");function m1(e,t){let r=u1.get(l1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=wN.get(r);return n||(n=vc.createHash("md5").update(r).digest("hex"),wN.set(r,n)),n}a(m1,"createNatsTableStreamName")});var Zs=T((aue,LN)=>{"use strict";var oue=en(),p_=$(),UN=f_(),p1=Ts(),S_=J(),{handleHDBError:T_,hdb_errors:S1}=re(),{HDB_ERROR_MSGS:g_,HTTP_STATUS_CODES:wm}=S1,T1=Z();T1.initSync();var{getDatabases:Im}=(Re(),ne(Fe));LN.exports={describeAll:g1,describeTable:R_,describeSchema:R1};async function g1(e){try{let t=S_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Im(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await R_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await R_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){p_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return p_.error("Got an error in describeAll"),p_.error(t),T_(new Error,g_.DESCRIBE_ALL_ERR)}}a(g1,"describeAll");async function R_(e,t){S_.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=UN.describe_table(e);if(i)throw i;let c=Im()[r];if(!c)throw T_(new Error,g_.SCHEMA_NOT_FOUND(e.schema),wm.NOT_FOUND);let u=c[n];if(!u)throw T_(new Error,g_.TABLE_NOT_FOUND(e.schema,e.table),wm.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=p1.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){p_.warn(`unable to stat table dbi due to ${f}`)}return d}a(R_,"descTable");async function R1(e){S_.transformReq(e);let t=UN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Im()[n];if(!i)throw T_(new Error,g_.SCHEMA_NOT_FOUND(e.schema),wm.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),S_.isEmpty(u)||u.describe){let _=await R_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(R1,"describeSchema")});var gs=T((_ue,HN)=>{var A1=qi(),{callbackify:PN,promisify:O1}=require("util"),{getDatabases:vN}=(Re(),ne(Fe));HN.exports={setSchemaDataToGlobal:MN,getTableSchema:b1,getSystemSchema:N1,setSchemaDataToGlobalAsync:O1(MN)};var BN=Zs(),uue=PN(BN.describeAll),lue=PN(BN.describeTable);function MN(e){global.hdb_schema=vN(),e&&e()}a(MN,"setSchemaDataToGlobal");function b1(e,t,r){let n=vN()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(b1,"getTableSchema");function N1(){return A1}a(N1,"getSystemSchema")});var Cr=T((fue,GN)=>{"use strict";var O_=gm(),qt=J(),y1=require("util"),b_=Nn(),w1=gs(),xN=$(),{handleHDBError:Gi,hdb_errors:I1}=re(),{HTTP_STATUS_CODES:ki}=I1,C1=y1.promisify(w1.getTableSchema),D1="updated",qN="inserted",FN="upserted";GN.exports={insert:L1,update:M1,upsert:P1,validation:U1,flush:v1};async function U1(e){if(qt.isEmpty(e))throw new Error("invalid update parameters defined.");if(qt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(qt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await C1(e.schema,e.table),r=O_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&qt.isEmptyOrZeroLength(c[n]))throw xN.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!qt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw xN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!qt.isEmpty(c[n])&&c[n]!==""&&s.has(qt.autoCast(c[n]))&&(c.skip=!0),s.add(qt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(U1,"validation");async function L1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=O_(e);if(t)throw Gi(new Error,t.message,ki.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Gi(new Error,r,ki.BAD_REQUEST);let n=await b_.createRecords(e);return A_(qN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(L1,"insertData");async function M1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=O_(e);if(t)throw Gi(new Error,t.message,ki.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Gi(new Error,r,ki.BAD_REQUEST);let n=await b_.updateRecords(e);return qt.isEmpty(n.existing_rows)?A_(D1,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):A_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(M1,"updateData");async function P1(e){if(e.operation!=="upsert")throw Gi(new Error,"invalid operation, must be upsert",ki.INTERNAL_SERVER_ERROR);let t=O_(e);if(t)throw Gi(new Error,t.message,ki.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Gi(new Error,r,ki.BAD_REQUEST);let n=await b_.upsertRecords(e);return A_(FN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(P1,"upsertData");function A_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===qN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===FN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(A_,"returnObject");function v1(e){return qt.transformReq(e),b_.flush(e.schema,e.table)}a(v1,"flush")});var Dm=T((hue,$N)=>{var B1=Xe(),Cm=require("joi"),{hdb_table:H1,hdb_database:kN}=Kn(),VN={schema:kN,database:kN,table:H1},x1={date:Cm.date().iso().required()},q1={timestamp:Cm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};$N.exports=function(e,t){let r=t==="timestamp"?{...VN,...q1}:{...VN,...x1},n=Cm.object(r);return B1.validateBySchema(e,n)}});var WN=T((mue,KN)=>{var F1=Xe(),Um=require("joi"),{hdb_table:G1,hdb_database:YN}=Kn(),k1=Um.object({schema:YN,database:YN,table:G1,hash_values:Um.array().required(),ids:Um.array()});KN.exports=function(e){return F1.validateBySchema(e,k1)}});var zN=T((pue,QN)=>{"use strict";var Lm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Mm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Pm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};QN.exports={InsertObject:Lm,NoSQLSeachObject:Mm,DeleteResponseObject:Pm}});var ri=T((Tue,ey)=>{"use strict";var jN=Dm(),V1=WN(),Vi=J(),JN=require("moment"),XN=$(),{promisify:$1,callbackify:Y1}=require("util"),$i=U(),K1=gs(),vm=$1(K1.getTableSchema),Bm=Nn(),{DeleteResponseObject:W1}=zN(),{handleHDBError:ei,hdb_errors:Q1}=re(),{HDB_ERROR_MSGS:N_,HTTP_STATUS_CODES:ti}=Q1,z1="records successfully deleted",J1=Y1(ZN);ey.exports={delete:J1,deleteRecord:ZN,deleteFilesBefore:j1,deleteAuditLogsBefore:X1};async function j1(e){let t=jN(e,"date");if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);if(Vi.transformReq(e),!JN(e.date,JN.ISO_8601).isValid())throw ei(new Error,N_.INVALID_DATE,ti.BAD_REQUEST,$i.LOG_LEVELS.ERROR,N_.INVALID_DATE,!0);let n=Vi.checkSchemaTableExist(e.schema,e.table);if(n)throw ei(new Error,n,ti.NOT_FOUND,$i.LOG_LEVELS.ERROR,n,!0);let s=await Bm.deleteRecordsBefore(e);if(await vm(e.schema,e.table),XN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(j1,"deleteFilesBefore");async function X1(e){let t=jN(e,"timestamp");if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);if(Vi.transformReq(e),isNaN(e.timestamp))throw ei(new Error,N_.INVALID_VALUE("Timestamp"),ti.BAD_REQUEST,$i.LOG_LEVELS.ERROR,N_.INVALID_VALUE("Timestamp"),!0);let r=Vi.checkSchemaTableExist(e.schema,e.table);if(r)throw ei(new Error,r,ti.NOT_FOUND,$i.LOG_LEVELS.ERROR,r,!0);let n=await Bm.deleteAuditLogsBefore(e);return await vm(e.schema,e.table),XN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(X1,"deleteAuditLogsBefore");async function ZN(e){e.ids&&(e.hash_values=e.ids);let t=V1(e);if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);Vi.transformReq(e);let r=Vi.checkSchemaTableExist(e.schema,e.table);if(r)throw ei(new Error,r,ti.NOT_FOUND,$i.LOG_LEVELS.ERROR,r,!0);try{await vm(e.schema,e.table);let n=await Bm.deleteRecords(e);return Vi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${z1}`),n}catch(n){if(n.message===$i.SEARCH_NOT_FOUND_MESSAGE){let s=new W1;return s.message=$i.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(ZN,"deleteRecord")});var y_=T((Rue,ny)=>{var Z1=require("crypto"),ty=9;function eY(e){let t=rY(ty),r=ry(e+t);return t+r}a(eY,"createHash");function tY(e,t){let r=e?.substr(0,ty),n=r+ry(t+r);return e===n}a(tY,"validateHash");function rY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(rY,"generateSalt");function ry(e){return Z1.createHash("md5").update(e).digest("hex")}a(ry,"md5");ny.exports={hash:eY,validate:tY}});var iy=T((Oue,sy)=>{var Hm=Xe(),Kt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function nY(e){return Kt.password.presence=!0,Kt.username.presence=!0,Kt.role.presence=!0,Kt.active.presence=!0,Hm.validateObject(e,Kt)}a(nY,"addUserValidation");function sY(e){return Kt.password.presence=!1,Kt.username.presence=!0,Kt.role.presence=!1,Kt.active.presence=!1,Hm.validateObject(e,Kt)}a(sY,"alterUserValidation");function iY(e){return Kt.password.presence=!1,Kt.username.presence=!0,Kt.role.presence=!1,Kt.active.presence=!1,Hm.validateObject(e,Kt)}a(iY,"dropUserValidation");sy.exports={addUserValidation:nY,alterUserValidation:sY,dropUserValidation:iY}});var Ge=T((yue,ay)=>{"use strict";var{platform:Nue}=require("os"),oY="nats-server.zip",xm="nats-server",aY=process.platform==="win32"?`${xm}.exe`:xm,qm="HDB",cY=/^[^\s.,*>]+$/,oy="__request__",uY=a(e=>`${e}.${oy}`,"REQUEST_SUBJECT"),lY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},_Y={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},dY={HUB:"hub.pid",LEAF:"leaf.pid"},fY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},EY={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:qm,deliver_subject:"__HDB__.WORKQUEUE"},hY={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:qm,deliver_subject:"HDB.SCHEMAQUEUE"},mY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:qm,deliver_subject:"HDB.USERQUEUE"},pY={SUCCESS:"success",ERROR:"error"},SY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},TY={TXN:"txn",MSGID:"msgid"},Yo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},gY={[Yo.ERR]:1,[Yo.WRN]:2,[Yo.INF]:3,[Yo.DBG]:4,[Yo.TRC]:5},RY={debug:"-D",trace:"-DVV"};ay.exports={NATS_SERVER_ZIP:oY,NATS_SERVER_NAME:xm,NATS_BINARY_NAME:aY,PID_FILES:dY,NATS_CONFIG_FILES:_Y,SERVER_SUFFIX:fY,WORK_QUEUE_CONSUMER_NAMES:EY,SCHEMA_QUEUE_CONSUMER_NAMES:hY,USER_QUEUE_CONSUMER_NAMES:mY,NATS_TERM_CONSTRAINTS_RX:cY,REQUEST_SUFFIX:oy,UPDATE_REMOTE_RESPONSE_STATUSES:pY,CLUSTER_STATUS_STATUSES:SY,REQUEST_SUBJECT:uY,SUBJECT_PREFIXES:TY,MSG_HEADERS:lY,LOG_LEVELS:Yo,LOG_LEVEL_FLAGS:RY,LOG_LEVEL_HIERARCHY:gY}});var uy=T((Iue,cy)=>{"use strict";var AY={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
5
5
|
`),cert:"-----BEGIN CERTIFICATE-----\rMIIDXDCCAkSgAwIBAgIFNTE4MzQwDQYJKoZIhvcNAQELBQAwXTEXMBUGA1UEAxMO\rSGFycGVyREIsIEluYy4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UE\rBxMGRGVudmVyMRcwFQYDVQQKEw5IYXJwZXJEQiwgSW5jLjAeFw0yMjAzMTEyMzAz\rNDlaFw0yNzAzMTAyMzAzNDlaMF0xFzAVBgNVBAMTDkhhcnBlckRCLCBJbmMuMQsw\rCQYDVQQGEwJVUzELMAkGA1UECBMCQ08xDzANBgNVBAcTBkRlbnZlcjEXMBUGA1UE\rChMOSGFycGVyREIsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\rAQCsEUlBF8WImS78rCFXVKyntxfrW++4qZ3hGnoD2MHZAuDHyeP/5eGnaE9GQhKc\r4DwG4DGvh0wP2zIYnBfiQ3L2ZtnlDR9ZkKIQYGlVxTUn6T43krhK5nZKqDF43Yg3\rZEvO3cbJBjiKZx0eA2/toehdSsTAHHQx5gTDcggNe2tgoJHYPwi9YF/AxSBZrbgb\ryWlYgtYDmF32ytHP03GUCIdKOFuBPsHTGu4SkdEIdLIqO9oglW1YFH5qZ6NiwApW\rsP+GCuqOwDXXbdjr75iq9Tq/CDrjGFLaTPmvd2Q0qG/BtaCll0ghpG+yIHvt/iQs\rajS+LxEWAnVlGMaDdFErbDUtAgMBAAGjIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYD\rVR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4IBAQASR4YW/rPK7PNArHVe9zzM\rb0rKNX/2T9/0nybRhmE/+hdlSgliTAeebmwkUS2APckmekYt/q2ZY2NS65Fo/jjp\rG8TJrtcF4h+ylVqUp0ZXQLFtIsr7r2JZA7hJ6njW6G4DHSZ0gxtECLi4CBlTjzm5\rNmnmIDObvGRTuqmcdAZmXeObbta/He2XIzietukPAYX062pNM+G5XT5UM1eG/Vlp\rN86vjhpyI+ffKy+C60SJqxmKM3ydgN7oLscE7+2wLPN25XqN4W99OwGsp5dTdu/f\r5lPtFayXdJ55e/sNQKmGN+UGLrL05c2MWgjb8U/LFilnupUianceoeSERZmVjzKX\r-----END CERTIFICATE-----\r".replace(/\r/g,`\r
|
|
6
|
-
`)},gY="certificate.pem",RY="privateKey.pem",AY="ca.pem";oy.exports={CERTIFICATE_VALUES:TY,CERTIFICATE_PEM_NAME:gY,PRIVATEKEY_PEM_NAME:RY,CA_PEM_NAME:AY}});var qm=T((yue,dy)=>{"use strict";var _y=require("fs-extra"),ie=require("joi"),OY=require("os"),{boolean:Ne,string:ir,number:At,array:xm}=ie.types(),{totalmem:cy}=require("os"),$i=require("path"),bY=V(),N_=J(),Nue=ay(),uy=L(),NY=je(),ly="log",yY="components",wY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",IY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",CY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",DY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",LY="rootPath config parameter is undefined",UY="clustering.enabled config parameter is undefined",Yi=At.min(0).required(),y_=xm.items({host:ir.required(),port:Yi}).empty(null),Ws;dy.exports={configValidator:MY,routesValidator:qY,route_constraints:y_};function MY(e){if(Ws=e.rootPath,N_.isEmpty(Ws))throw LY;let t=Ne.required(),r=At.min(0).max(1e3).empty(null).default(xY),s=ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Pc),n=ir.optional().empty(null),i=ir.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ie.string().empty(null).default(Pc),c=ie.custom(vY).empty(null).default(Pc),u=e.clustering?.enabled;if(N_.isEmpty(u))throw UY;let _;return u===!0?_=ie.object({enabled:t,hubServer:ie.object({cluster:ie.object({name:ie.required().empty(null),network:ie.object({port:Yi,routes:y_}).required()}).required(),leafNodes:ie.object({network:ie.object({port:Yi}).required()}).required(),network:ie.object({port:Yi}).required()}).required(),leafServer:ie.object({network:ie.object({port:Yi,routes:y_}).required(),streams:ie.object({maxAge:At.min(120).allow(null).optional(),maxBytes:At.min(1).allow(null).optional(),maxMsgs:At.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ie.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Ne.optional(),databaseLevel:Ne.optional(),tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ne.required(),verify:Ne.optional()}),user:ir.optional().empty(null)}).required():_=ie.object({enabled:t,tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ne.required()})}).required(),ie.object({authentication:ie.object({authorizeLocal:Ne,cacheTTL:At.required(),enableSessions:Ne}),analytics:ie.object({aggregatePeriod:At}),componentsRoot:s.optional(),clustering:_,localStudio:ie.object({enabled:t}).required(),logging:ie.object({auditAuthEvents:ie.object({logFailed:Ne,logSuccessful:Ne}),file:Ne.required(),level:ie.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ie.object({enabled:Ne.optional(),compress:Ne.optional(),interval:ir.custom(HY).optional().empty(null),maxSize:ir.custom(BY).optional().empty(null),path:ir.optional().empty(null).default(Pc)}).required(),root:s,stdStreams:Ne.required(),auditLog:Ne.required()}).required(),operationsApi:ie.object({network:ie.object({cors:Ne.optional(),corsAccessList:xm.optional(),headersTimeout:At.min(1).optional(),keepAliveTimeout:At.min(1).optional(),port:At.optional().empty(null),domainSocket:ie.optional().empty("hdb/operations-server").default(Pc),securePort:At.optional().empty(null),timeout:At.min(1).optional()}).optional(),tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ie.object({network:ie.object({port:Yi,securePort:Yi,mtls:ie.alternatives([Ne.optional(),ie.object({user:ir.optional(),certificateAuthority:n,required:Ne.optional()})])}).required(),webSocket:Ne.optional(),requireAuthentication:Ne.optional()}),http:ie.object({compressionThreshold:At.optional(),cors:Ne.optional(),corsAccessList:xm.optional(),headersTimeout:At.min(1).optional(),port:At.min(0).optional().empty(null),securePort:At.min(0).optional().empty(null),mtls:ie.alternatives([Ne.optional(),ie.object({user:ir.optional(),certificateAuthority:n,required:Ne.optional()})])}).required(),threads:ie.alternatives(r.optional(),ie.object({count:r.optional(),debug:ie.alternatives(Ne.optional(),ie.object({startingPort:At.min(1).optional(),host:ir.optional(),waitForDebugger:Ne.optional()})),maxHeapMemory:At.min(0).optional()})),storage:ie.object({writeAsync:Ne.required(),overlappingSync:Ne.optional(),caching:Ne.optional(),compression:Ne.optional(),noReadAhead:Ne.optional(),path:c,prefetchWrites:Ne.optional()}).required(),ignoreScripts:Ne.optional(),tls:ie.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:ir.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(MY,"configValidator");function PY(e){return _y.existsSync(e)?null:`Specified path ${e} does not exist.`}a(PY,"doesPathExist");function vY(e,t){ie.assert(e,ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=PY(e);if(r)return t.message(r)}a(vY,"validatePath");function BY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(wY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(CY):e}a(BY,"validateRotationMaxSize");function HY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(IY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(DY):e}a(HY,"validateRotationInterval");function xY(e,t){let r=t.state.path.join("."),s=OY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||cy();return i=Math.round(Math.min(i,cy())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),bY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(xY,"setDefaultThreads");function Pc(e,t){let r=t.state.path.join(".");if(!N_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(N_.isEmpty(Ws))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return $i.join(Ws,yY);case"logging.root":return $i.join(Ws,ly);case"clustering.leafServer.streams.path":return $i.join(Ws,"clustering","leaf");case"storage.path":let s=$i.join(Ws,uy.LEGACY_DATABASES_DIR_NAME);return _y.existsSync(s)?s:$i.join(Ws,uy.DATABASES_DIR_NAME);case"logging.rotation.path":return $i.join(Ws,ly);case"operationsApi.network.domainSocket":return r==null?null:$i.join(Ws,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Pc,"setDefaultRoot");function qY(e){let t=ie.object({routes:y_});return NY.validateBySchema({routes:e},t)}a(qY,"routesValidator")});var Ur=T((Cue,Ry)=>{"use strict";var Lr=L(),Ut=J(),Ot=V(),{configValidator:FY,routesValidator:fy}=qm(),or=require("fs-extra"),GY=require("yaml"),ys=require("path"),kY=require("is-number"),hy=require("properties-reader"),VY=require("lodash"),{handleHDBError:$Y}=re(),{HTTP_STATUS_CODES:YY,HDB_ERROR_MSGS:w_}=Nr(),Iue=require("minimist"),{server:KY}=(rr(),se(Mi)),{DATABASES_PARAM_CONFIG:vc,CONFIG_PARAMS:Dr,CONFIG_PARAM_MAP:ws}=Lr,WY="Unable to get config value because config is uninitialized",QY="Config successfully initialized",zY="Error backing up config file",JY="Empty parameter sent to getConfigValue",my=ys.join(Lr.PACKAGE_ROOT,"config","yaml",Lr.HDB_DEFAULT_CONFIG_FILE),jY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ey={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"},I_,bt,C_;Ry.exports={createConfigFile:XY,getDefaultConfig:ZY,getConfigValue:Sy,initConfig:Gm,flattenConfig:$o,updateConfigValue:Ty,updateConfigObject:tK,getConfiguration:nK,setConfiguration:iK,readConfigFile:Vm,getClusteringRoutes:oK,initOldConfig:gy,getConfigFromFile:aK,getConfigFilePath:Ki,addConfig:cK,deleteConfigFromFile:uK,getConfigObj:lK};function XY(e){let t=ri(my);I_=$o(t.toJSON());let r;for(let o in e){let c=ws[o.toLowerCase()];if(c===Dr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=Fm(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){Ot.error(l)}}}r&&py(t,r),km(t);let s=t.toJSON();bt=$o(s);let n=t.getIn(["rootPath"]),i=ys.join(n,Lr.HDB_CONFIG_FILE);or.createFileSync(i),or.writeFileSync(i,String(t)),Ot.trace(`Config file written to ${i}`)}a(XY,"createConfigFile");function py(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!Ut.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(vc.TABLES))for(let i in s[n][vc.TABLES])for(let o in s[n][vc.TABLES][i]){let c=s[n][vc.TABLES][i][o],u=[Dr.DATABASES,n,vc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Dr.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){Ot.error("Error parsing schemas CLI/env config arguments",s)}}a(py,"setSchemasConfig");function ZY(e){if(I_===void 0){let r=ri(my);I_=$o(r.toJSON())}let t=ws[e.toLowerCase()];if(t!==void 0)return I_[t.toLowerCase()]}a(ZY,"getDefaultConfig");function Sy(e){if(e==null){Ot.error(JY);return}if(bt===void 0){Ot.trace(WY);return}let t=ws[e.toLowerCase()];if(t!==void 0)return bt[t.toLowerCase()]}a(Sy,"getConfigValue");function Ki(e=Ut.getPropsFilePath()){let t=Ut.getEnvCliRootPath();return t?ys.join(t,Lr.HDB_CONFIG_FILE):hy(e).get(Lr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ki,"getConfigFilePath");function Gm(e=!1){if(bt===void 0||e){let t;if(!Ut.noBootFile()){t=Ut.getPropsFilePath();try{or.accessSync(t,or.constants.F_OK|or.constants.R_OK)}catch(i){throw Ot.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ki(t),s;if(r.includes("config/settings.js"))try{gy(r);return}catch(i){if(i.code!==Lr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ri(r)}catch(i){if(i.code===Lr.NODE_ERROR_CODES.ENOENT){Ot.trace(`HarperDB config file not found at ${r}.
|
|
7
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw Ot.error(i),new Error(`Error reading HarperDB config file at ${r}`)}eK(s,r),km(s);let n=s.toJSON();if(KY.config=n,bt=$o(n),bt.logging_rotation_rotate)for(let i in Ey)bt[i]&&Ot.error(`Config ${Ey[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Ot.trace(QY)}}a(Gm,"initConfig");function eK(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],ys.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],ys.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],ys.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(Ot.trace("Updating config file with missing config params"),or.writeFileSync(t,String(e)))}a(eK,"checkForUpdatedConfig");function km(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t?.http?.threads&&(t.threads=t?.http?.threads);let r=FY(t);if(r.error)throw w_.CONFIG_VALIDATION(r.error.message);typeof r.value.threads=="object"?e.setIn(["threads","count"],r.value.threads.count):e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(km,"validateConfig");function tK(e,t){bt===void 0&&(bt={});let r=ws[e.toLowerCase()];if(r===void 0){Ot.trace(`Unable to update config object because config param '${e}' does not exist`);return}bt[r.toLowerCase()]=t}a(tK,"updateConfigObject");function Ty(e,t,r=void 0,s=!1,n=!1,i=!1){bt===void 0&&Gm();let o=Sy(ws.hdb_root),c=ys.join(o,Lr.HDB_CONFIG_FILE),u=ri(c),_;if(r===void 0&&e.toLowerCase()===Dr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=ws[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Fm(f,t);u.setIn([...E],h)}else for(let f in r){let E=ws[f.toLowerCase()];if(E===Dr.HTTP_SECUREPORT&&r[f]===bt[Dr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Dr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===bt[Dr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Dr.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Lr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=Fm(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(A){Ot.error(A)}}}_&&py(u,_),km(u);let l=u.getIn(["rootPath"]),d=ys.join(l,Lr.HDB_CONFIG_FILE);s===!0&&rK(c,l),or.writeFileSync(d,String(u)),n&&(bt=$o(u.toJSON())),Ot.trace(`Config parameter: ${e} updated with value: ${t}`)}a(Ty,"updateConfigValue");function rK(e,t){try{let r=ys.join(t,"backup",`${Lr.HDB_CONFIG_FILE}.bak`);or.copySync(e,r),Ot.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Ot.error(zY),Ot.error(r)}}a(rK,"backupConfigFile");var sK=["databases"];function $o(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),C_=e,r(e);function r(s){let n={};for(let i in s)if(s.hasOwnProperty(i)){if(typeof s[i]=="object"&&s[i]!==null&&!Array.isArray(s[i])&&!sK.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Dr[u.toUpperCase()]&&ws[u]&&(n[ws[u].toLowerCase()]=o[c]),n[u]=o[c]}}s[i]!==void 0&&(n[i.toLowerCase()]=s[i])}return n}a(r,"squashObj")}a($o,"flattenConfig");function Fm(e,t){if(e===Dr.CLUSTERING_NODENAME||e===Dr.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(kY(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Ut.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return Ut.autoCast(t)}a(Fm,"castConfigValue");function nK(){let e=Ut.getPropsFilePath(),t=Ki(e);return ri(t).toJSON()}a(nK,"getConfiguration");async function iK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return Ty(void 0,void 0,n,!0),jY}catch(i){throw typeof i=="string"||i instanceof String?$Y(i,i,YY.BAD_REQUEST,void 0,void 0,!0):i}}a(iK,"setConfiguration");function Vm(){let e=Ut.getPropsFilePath();try{or.accessSync(e,or.constants.F_OK|or.constants.R_OK)}catch(s){if(!Ut.noBootFile())throw Ot.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ki(e);return ri(t).toJSON()}a(Vm,"readConfigFile");function ri(e){return GY.parseDocument(or.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ri,"parseYamlDoc");function oK(){let e=Vm(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Ut.isEmptyOrZeroLength(t)?[]:t;let r=fy(t);if(r)throw w_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Ut.isEmptyOrZeroLength(s)?[]:s;let n=fy(s);if(n)throw w_.CONFIG_VALIDATION(n.message);if(!Ut.isEmptyOrZeroLength(s)&&!Ut.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!Ut.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw w_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(oK,"getClusteringRoutes");function gy(e){let t=hy(e);bt={};for(let r in ws){let s=t.get(r.toUpperCase());if(Ut.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=ws[r].toLowerCase();n===Dr.LOGGING_ROOT?bt[n]=ys.dirname(s):bt[n]=s}return bt}a(gy,"initOldConfig");function aK(e){let t=Vm();return VY.get(t,e.replaceAll("_","."))}a(aK,"getConfigFromFile");async function cK(e,t){let r=ri(Ki());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await or.writeFile(Ki(),String(r))}a(cK,"addConfig");function uK(e){let t=Ki(Ut.getPropsFilePath()),r=ri(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=ys.join(s,Lr.HDB_CONFIG_FILE);or.writeFileSync(n,String(r))}a(uK,"deleteConfigFromFile");function lK(){return C_||(Gm(),C_)}a(lK,"getConfigObj")});var Oy=T((Lue,Ay)=>{"use strict";var D_=L(),L_=class{static{a(this,"BaseLicense")}constructor(t=0,r=D_.RAM_ALLOCATION_ENUM.DEFAULT,s=D_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},$m=class extends L_{static{a(this,"ExtendedLicense")}constructor(t=0,r=D_.RAM_ALLOCATION_ENUM.DEFAULT,s=D_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};Ay.exports={BaseLicense:L_,ExtendedLicense:$m}});var Wi=T((Mue,Cy)=>{"use strict";var Ko=require("fs-extra"),Ny=b_(),yy=require("crypto"),_K=require("moment"),dK=require("uuid").v4,Wt=V(),Km=require("path"),fK=J(),si=L(),{totalmem:by}=require("os"),EK=Oy().ExtendedLicense,Yo="invalid license key format",hK="061183",mK="mofi25",pK="aes-256-cbc",SK=16,TK=32,wy=Z();wy.initSync();var Ym;Cy.exports={validateLicense:Iy,generateFingerPrint:RK,licenseSearch:zm,getLicense:bK,checkMemoryLimit:NK};function Wm(){return Km.join(wy.getHdbBasePath(),si.LICENSE_KEY_DIR_NAME,si.LICENSE_FILE_NAME)}a(Wm,"getLicenseDirPath");function gK(){let e=Wm();return Km.join(e,si.LICENSE_FILE_NAME)}a(gK,"getLicenseFilePath");function Qm(){let e=Wm();return Km.join(e,si.REG_KEY_FILE_NAME)}a(Qm,"getFingerPrintFilePath");async function RK(){let e=Qm();try{return await Ko.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await AK();throw Wt.error(`Error writing fingerprint file to ${e}`),Wt.error(t),new Error("There was an error generating the fingerprint")}}a(RK,"generateFingerPrint");async function AK(){let e=dK(),t=Ny.hash(e),r=Qm();try{await Ko.mkdirp(Wm()),await Ko.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Wt.error(`Error writing fingerprint file to ${r}`),Wt.error(s),new Error("There was an error generating the fingerprint")}return t}a(AK,"writeFingerprint");function Iy(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:si.RAM_ALLOCATION_ENUM.DEFAULT,version:si.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Wt.error("empty license key passed to validate."),r;let s=Qm(),n=!1;try{n=Ko.statSync(s)}catch(i){Wt.error(i)}if(n){let i;try{i=Ko.readFileSync(s,"utf8")}catch{Wt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(mK),c=o[1];c=Buffer.concat([Buffer.from(c)],SK);let u=Buffer.concat([Buffer.from(i)],TK),_=yy.createDecipheriv(pK,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=OK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Yo),Wt.error(Yo),new Error(Yo)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(Yo),Wt.error(Yo),new Error(Yo)}else r.exp_date=l;r.exp_date<_K().valueOf()&&(r.valid_date=!1),Ny.validate(o[1],`${hK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||Wt.error("Invalid licence"),r}a(Iy,"validateLicense");function OK(e,t){try{let r=yy.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Wt.warn("Check old license failed")}}a(OK,"checkOldLicense");function zm(){let e=new EK,t=[];try{t=Ko.readFileSync(gK(),"utf-8").split(si.NEW_LINE)}catch(r){r.code==="ENOENT"?Wt.info("no license file found"):Wt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(fK.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=Iy(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){Wt.error("There was an error parsing the license string."),Wt.error(n),e.ram_allocation=si.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Ym=e,e}a(zm,"licenseSearch");async function bK(){return Ym||await zm(),Ym}a(bK,"getLicense");function NK(){let e=zm().ram_allocation,t=process.constrainedMemory?.()||by();if(t=Math.round(Math.min(t,by())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(NK,"checkMemoryLimit")});var ts=T((xue,Yy)=>{"use strict";var My="username is required",Py="nothing to update, must supply active, role or password to update",vy="password cannot be an empty string",By="If role is specified, it cannot be empty.",Hy="active must be true or false";Yy.exports={addUser:PK,alterUser:vK,dropUser:HK,getSuperUser:GK,userInfo:xK,listUsers:M_,listUsersExternal:qK,setUsersToGlobal:Qo,findAndValidateUser:Vy,getClusterUser:kK,USERNAME_REQUIRED:My,ALTERUSER_NOTHING_TO_UPDATE:Py,EMPTY_PASSWORD:vy,EMPTY_ROLE:By,ACTIVE_BOOLEAN:Hy};var xy=Cr(),yK=ti(),Xm=b_(),qy=sy(),Fy=es(),Zm=gn(),Mr=J(),Gy=require("validate.js"),Te=V(),{promisify:wK}=require("util"),ep=Sn(),Dy=L(),Ly=Ge(),IK=Ur(),vue=Z(),Bue=Wi(),CK=xi(),{table:Hue}=(Ae(),se(Fe)),{handleHDBError:Qs,hdb_errors:DK}=re(),{HTTP_STATUS_CODES:zs,AUTHENTICATION_ERROR_MSGS:Jm,HDB_ERROR_MSGS:Wo}=DK,{UserEventMsg:tp}=Is(),jm=require("lodash"),{server:rp}=(rr(),se(Mi)),LK=V();rp.getUser=(e,t)=>Vy(e,t,t!=null);var ky={username:!0,active:!0,role:!0,password:!0},Uy=new Map,U_=Fy.searchByValue,UK=Fy.searchByHash,MK=wK(yK.delete);async function PK(e){let t=Gy.cleanAttributes(e,ky),r=qy.addUserValidation(t);if(r)throw Qs(new Error,r.message,zs.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await U_(s),n=n&&Array.from(n)}catch(u){throw Te.error("There was an error searching for a role in add user"),Te.error(u),u}if(!n||n.length<1)throw Qs(new Error,Wo.ROLE_NAME_NOT_FOUND(t.role),zs.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw Qs(new Error,Wo.DUP_ROLES_FOUND(t.role),zs.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=ep.encrypt(t.password)),t.password=Xm.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await xy.insert(i)}catch(u){throw Te.error("There was an error searching for a user."),Te.error(u),u}Te.debug(o);try{await Qo()}catch(u){throw Te.error("Got an error setting users to global"),Te.error(u),u}if(o.skipped_hashes.length===1)throw Qs(new Error,Wo.USER_ALREADY_EXISTS(t.username),zs.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],Zm.signalUserChange(new tp(process.pid)),`${c.username} successfully added`}a(PK,"addUser");async function vK(e){let t=Gy.cleanAttributes(e,ky);if(Mr.isEmptyOrZeroLength(t.username))throw new Error(My);if(Mr.isEmptyOrZeroLength(t.password)&&Mr.isEmptyOrZeroLength(t.role)&&Mr.isEmptyOrZeroLength(t.active))throw new Error(Py);if(!Mr.isEmpty(t.password)&&Mr.isEmptyOrZeroLength(t.password.trim()))throw new Error(vy);if(!Mr.isEmpty(t.active)&&!Mr.isBoolean(t.active))throw new Error(Hy);let r=BK(t.username);if(!Mr.isEmpty(t.password)&&!Mr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=ep.encrypt(t.password)),t.password=Xm.hash(t.password)),t.role==="")throw new Error(By);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await U_(i)||[])}catch(c){throw Te.error("Got an error searching for a role."),Te.error(c),c}if(!o||o.length===0){let c=Wo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Te.error(c),Qs(new Error,c,zs.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Wo.ALTER_USER_DUP_ROLES(t.role);throw Te.error(c),Qs(new Error,c,zs.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await xy.update(s)}catch(i){throw Te.error("Error during update."),Te.error(i),i}try{await Qo()}catch(i){throw Te.error("Got an error setting users to global"),Te.error(i),i}return Zm.signalUserChange(new tp(process.pid)),n}a(vK,"alterUser");function BK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(BK,"isClusterUser");async function HK(e){try{let t=qy.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Mr.isEmpty(global.hdb_users.get(e.username)))throw Qs(new Error,Wo.USER_NOT_EXIST(e.username),zs.NOT_FOUND,void 0,void 0,!0);let s;try{s=await MK(r)}catch(n){throw Te.error("Got an error deleting a user."),Te.error(n),n}Te.debug(s);try{await Qo()}catch(n){throw Te.error("Got an error setting users to global."),Te.error(n),n}return Zm.signalUserChange(new tp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(HK,"dropUser");async function xK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=jm.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await UK(r)}catch(n){throw Te.error("Got an error searching for a role."),Te.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Te.error(r),r}return t}a(xK,"userInfo");async function qK(){let e;try{e=await M_()}catch(t){throw Te.error("Got an error listing users."),Te.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(qK,"listUsersExternal");async function M_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await U_(e)}catch(o){throw Te.error("Got an error searching for roles."),Te.error(o),o}let r={};for(let o of t)r[o.id]=jm.cloneDeep(o);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await U_(s)}catch(o){throw Te.error("Got an error searching for users."),Te.error(o),o}let i=new Map;for(let o of n)o=jm.cloneDeep(o),o.role=r[o.role],FK(o.role),i.set(o.username,o);return i}catch(e){throw Te.error("got an error listing users"),Te.error(e),Mr.errorizeMessage(e)}return null}a(M_,"listUsers");function FK(e){try{if(!e){Te.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(CK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Te.error("Got an error trying to set system permissions."),Te.error(t)}}a(FK,"appendSystemTablesToRole");async function Qo(){try{let e=await M_();global.hdb_users=e}catch(e){throw Te.error(e),e}}a(Qo,"setUsersToGlobal");async function Vy(e,t,r=!0){global.hdb_users||await Qo();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw Qs(new Error,Jm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw Qs(new Error,Jm.USER_INACTIVE,zs.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(Uy.get(t)===s.password)return n;if(Xm.validate(s.password,t))Uy.set(t,s.password);else throw Qs(new Error,Jm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}return n}a(Vy,"findAndValidateUser");async function GK(){global.hdb_users||await Qo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(GK,"getSuperUser");async function kK(){let e=await M_(),t=IK.getConfigFromFile(Dy.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Mr.isEmpty(r)&&r?.role?.role===Dy.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=ep.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+Ly.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+Ly.SERVER_SUFFIX.ADMIN,r}a(kK,"getClusterUser");var $y=[];rp.invalidateUser=function(e){for(let t of $y)try{t(e)}catch(r){LK.error("Error invalidating user",r)}};rp.onInvalidatedUser=function(e){$y.push(e)}});var Hc=T((kue,zy)=>{"use strict";var Qi=V(),Pr=L(),VK=bN(),Fue=Tn(),Gue=Xn(),$K=ts(),{validateEvent:Ky}=Is(),Bc=Ns(),YK=require("process"),{resetDatabases:KK}=(Ae(),se(Fe)),WK={[Pr.ITC_EVENT_TYPES.SCHEMA]:QK,[Pr.ITC_EVENT_TYPES.USER]:Qy};async function QK(e){let t=Ky(e);if(t){Qi.error(t);return}Qi.trace("ITC schemaHandler received schema event:",e),await VK(e.message),await zK(e.message)}a(QK,"schemaHandler");async function zK(e){try{Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=KK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Qi.error(t)}}a(zK,"syncSchemaMetadata");var Wy=[];async function Qy(e){try{try{Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Qi.warn(r)}let t=Ky(e);if(t){Qi.error(t);return}Qi.trace(`ITC userHandler ${Pr.HDB_ITC_CLIENT_PREFIX}${YK.pid} received user event:`,e),await $K.setUsersToGlobal();for(let r of Wy)r()}catch(t){Qi.error(t)}}a(Qy,"userHandler");Qy.addListener=function(e){Wy.push(e)};zy.exports=WK});var Is=T((Que,jy)=>{"use strict";var $ue=V(),sp=J(),JK=L(),{ITC_ERRORS:xc}=Nr(),{parentPort:Yue,threadId:jK,isMainThread:XK,workerData:Kue}=require("worker_threads"),{onMessageFromWorkers:ZK,broadcast:Wue,broadcastWithAcknowledgement:eW}=Ke();jy.exports={sendItcEvent:tW,validateEvent:Jy,SchemaEventMsg:rW,UserEventMsg:sW};var P_;ZK(async(e,t)=>{P_=P_||Hc(),Jy(e),P_[e.type]&&await P_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function tW(e){return!XK&&e.message&&(e.message.originator=jK),eW(e)}a(tW,"sendItcEvent");function Jy(e){if(typeof e!="object")return xc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||sp.isEmpty(e.type))return xc.MISSING_TYPE;if(!e.hasOwnProperty("message")||sp.isEmpty(e.message))return xc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||sp.isEmpty(e.message.originator))return xc.MISSING_ORIGIN;if(JK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return xc.INVALID_EVENT(e.type)}a(Jy,"validateEvent");function rW(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(rW,"SchemaEventMsg");function sW(e){this.originator=e}a(sW,"UserEventMsg")});var gn=T((jue,tw)=>{"use strict";var Xy=L(),Jue=J(),v_=V(),Zy=RN(),zo,{sendItcEvent:ew}=Is();function nW(e){try{v_.trace("signalSchemaChange called with message:",e),zo=zo||Hc();let t=new Zy(Xy.ITC_EVENT_TYPES.SCHEMA,e);return zo.schema(t),ew(t)}catch(t){v_.error(t)}}a(nW,"signalSchemaChange");function iW(e){try{v_.trace("signalUserChange called with message:",e),zo=zo||Hc();let t=new Zy(Xy.ITC_EVENT_TYPES.USER,e);return zo.user(t),ew(t)}catch(t){v_.error(t)}}a(iW,"signalUserChange");tw.exports={signalSchemaChange:nW,signalUserChange:iW}});var B_=T((Zue,sw)=>{"use strict";var rw=J(),oW=L(),aW=V(),cW=f_(),uW=d_(),lW=gn(),{SchemaEventMsg:_W}=Is(),dW="already exists in";sw.exports=fW;async function fW(e,t,r){if(rw.isEmptyOrZeroLength(r))return r;let s=[];rw.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await EW(e,t.schema,t.name,i)})),n}a(fW,"lmdbCheckForNewAttributes");async function EW(e,t,r,s){let n=new uW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await hW(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(dW))aW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(EW,"createNewAttribute");async function hW(e){let t;return t=await cW(e),lW.signalSchemaChange(new _W(process.pid,oW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(hW,"createAttribute")});var Jo=T((tle,nw)=>{"use strict";var np=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};nw.exports=np});var ow=T((sle,iw)=>{"use strict";var mW=Jo(),pW=L().OPERATIONS_ENUM,ip=class extends mW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(pW.INSERT,r,s,n,i),this.records=t}};iw.exports=ip});var cw=T((ile,aw)=>{"use strict";var SW=Jo(),TW=L().OPERATIONS_ENUM,op=class extends SW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(TW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};aw.exports=op});var lw=T((ale,uw)=>{"use strict";var gW=Jo(),RW=L().OPERATIONS_ENUM,ap=class extends gW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(RW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};uw.exports=ap});var dw=T((ule,_w)=>{"use strict";var AW=Jo(),OW=L().OPERATIONS_ENUM,cp=class extends AW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(OW.DELETE,s,n,t,i),this.original_records=r}};_w.exports=cp});var qc=T((dle,mw)=>{"use strict";var _le=require("path"),fw=We(),bW=ow(),NW=cw(),yW=lw(),wW=dw(),jo=dt(),Ew=J(),{CONFIG_PARAMS:IW}=L(),hw=Z();hw.initSync();var H_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:CW}=Je();mw.exports=DW;async function DW(e,t){if(hw.get(IW.LOGGING_AUDITLOG)===!1)return;let r=CW(e.schema,e.table),s=await fw.openEnvironment(r,e.table,!0),n=LW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){fw.initializeDBIs(s,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,jo.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),Ew.isEmpty(n.user_name)||s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(DW,"writeTransaction");function LW(e,t){let r=Ew.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===H_.INSERT)return new bW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.UPDATE)return new NW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.UPSERT)return new yW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.DELETE)return new wW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(LW,"createTransactionObject")});var up=T((hle,pw)=>{"use strict";var UW=wc(),Ele=Ic(),Fc=L(),MW=Uc(),PW=Go().insertRecords,vW=We(),BW=V(),HW=B_(),{getSchemaPath:xW}=Je(),qW=qc();pw.exports=FW;async function FW(e){try{let{schema_table:t,attributes:r}=UW(e);MW(e,r,t.hash_attribute),e.schema!==Fc.SYSTEM_SCHEMA_NAME&&(r.includes(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await HW(e.hdb_auth_header,t,r),n=xW(e.schema,e.table),i=await vW.openEnvironment(n,e.table),o=await PW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await qW(e,o)}catch(c){BW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(FW,"lmdbCreateRecords")});var gw=T((ple,Tw)=>{"use strict";var Sw=L(),GW=up(),kW=Ic(),VW=require("fs-extra"),{getSchemaPath:$W}=Je();Tw.exports=YW;async function YW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new kW(Sw.SYSTEM_SCHEMA_NAME,Sw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await GW(r),await VW.mkdirp($W(e.schema))}a(YW,"lmdbCreateSchema")});var Aw=T((Tle,Rw)=>{"use strict";var lp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};Rw.exports=lp});var yw=T((ble,Nw)=>{"use strict";var Ow=We(),_p=yr(),dp=Nr().LMDB_ERRORS_ENUM,KW=dt(),bw=V(),Rle=J(),WW=require("lmdb"),QW=Aw(),zW=L(),{OVERFLOW_MARKER:Ale,MAX_SEARCH_KEY_LENGTH:Ole}=KW,JW=zW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function jW(e,t,r,s){if(_p.validateEnv(e),t===void 0)throw new Error(dp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(dp.IDS_REQUIRED):new Error(dp.IDS_MUST_BE_ITERABLE);try{let n=Ow.listDBIs(e);Ow.initializeDBIs(e,t,n);let i=new QW,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||s&&h[JW]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,WW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let A=n[S];if(!h.hasOwnProperty(A)||A===t)continue;let R=e.dbis[A],g=h[A];if(g!=null)try{let P=_p.getIndexedValues(g);if(P)for(let H=0,v=P.length;H<v;H++)R.remove(P[H],o)}catch{bw.warn(`cannot delete from attribute: ${A}, ${g}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){bw.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=_p.getNextMonotonicTime(),i}catch(n){throw n}}a(jW,"deleteRecords");Nw.exports={deleteRecords:jW}});var Gc=T((yle,Iw)=>{"use strict";var Xo=J(),XW=yw(),ZW=We(),{getSchemaPath:eQ}=Je(),tQ=qc(),rQ=V();Iw.exports=sQ;async function sQ(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Xo.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Xo.isEmptyOrZeroLength(e.hash_values)&&!Xo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Xo.isEmpty(u)||e.hash_values.push(u)}}if(Xo.isEmptyOrZeroLength(e.hash_values))return ww([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Xo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[s]:e.hash_values[c]}}let n=eQ(e.schema,e.table),i=await ZW.openEnvironment(n,e.table),o=await XW.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await tQ(e,o)}catch(c){rQ.error(`unable to write transaction due to ${c.message}`)}return ww(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(sQ,"lmdbDeleteRecords");function ww(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(ww,"createDeleteResponse")});var Ep=T((Cle,Cw)=>{"use strict";var nQ=L(),Ile=yr();function fp(e,t){let r=Object.create(null);if(t.length===1&&nQ.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(fp,"parseRow");function iQ(e,t,r,s){let n=fp(r,e);s.push(n)}a(iQ,"searchAll");function oQ(e,t,r,s){let n=fp(r,e);s[t]=n}a(oQ,"searchAllToMap");function aQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(aQ,"iterateDBI");function zi(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(zi,"pushResults");function cQ(e,t,r,s,n,i){t.toString().endsWith(e)&&zi(t,r,s,n,i)}a(cQ,"endsWith");function uQ(e,t,r,s,n,i){t.toString().includes(e)&&zi(t,r,s,n,i)}a(uQ,"contains");function lQ(e,t,r,s,n,i){t>e&&zi(t,r,s,n,i)}a(lQ,"greaterThanCompare");function _Q(e,t,r,s,n,i){t>=e&&zi(t,r,s,n,i)}a(_Q,"greaterThanEqualCompare");function dQ(e,t,r,s,n,i){t<e&&zi(t,r,s,n,i)}a(dQ,"lessThanCompare");function fQ(e,t,r,s,n,i){t<=e&&zi(t,r,s,n,i)}a(fQ,"lessThanEqualCompare");Cw.exports={parseRow:fp,searchAll:iQ,searchAllToMap:oQ,iterateDBI:aQ,endsWith:cQ,contains:uQ,greaterThanCompare:lQ,greaterThanEqualCompare:_Q,lessThanCompare:dQ,lessThanEqualCompare:fQ,pushResults:zi}});var Zo=T((Ple,Bw)=>{"use strict";var ni=We(),Lle=V(),vr=yr(),x_=dt(),ut=Nr().LMDB_ERRORS_ENUM,Ule=J(),EQ=L(),q_=Ep(),{parseRow:hQ}=q_,Mle=require("lmdb"),{OVERFLOW_MARKER:Dw,MAX_SEARCH_KEY_LENGTH:mQ}=x_;function Lw(e,t,r,s=!1,n=void 0,i=void 0){return Ji(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(Lw,"iterateFullIndex");function kc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Ji(e,t,r,(l,d,f,E)=>{let R={transaction:l,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(R.values=!1,d.getRange(R).map(g=>({value:g}))):d.getRange(R)})}a(kc,"iterateRangeBetween");function Ji(e,t,r,s){let n=e.database||e,i=ni.openDBI(n,r);i[x_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ni.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Ji,"setupTransaction");function Uw(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(Dw)){if(!n)if(r)n=ni.openDBI(e,r);else{let u=ni.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=ni.openDBI(e,u[_]),!n[x_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(Uw,"getOverflowCheck");function pQ(e,t,r,s=!1,n=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);return Ji(e,t,t,(o,c,u)=>(F_(r),r=Vc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>hQ(_.value,r))))}a(pQ,"searchAll");function SQ(e,t,r,s=!1,n=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);F_(r),r=Vc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of Lw(e,t,t,s,n,i))o.set(c,q_.parseRow(u,r));return o}a(SQ,"searchAllToMap");function TQ(e,t,r=!1,s=void 0,n=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=Lw(e,void 0,t,r,s,n),c=o.transaction,u=Uw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(TQ,"iterateDBI");function gQ(e,t){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);return ni.statDBI(e,t).entryCount}a(gQ,"countAll");function RQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Ji(e,t,r,(c,u,_,l)=>(s=vr.convertKeyValueToWrite(s),l===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(RQ,"equals");function AQ(e,t,r){return ii(e,t,r),ni.openDBI(e,t).getValuesCount(r)}a(AQ,"count");function OQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Ji(e,null,r,(c,u)=>{s=vr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(OQ,"startsWith");function bQ(e,t,r,s,n=!1,i=void 0,o=void 0){return Mw(e,t,r,s,n,i,o,!0)}a(bQ,"endsWith");function Mw(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ii(e,r,s),Ji(e,null,r,(u,_,l,d)=>{let f=Uw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(E=>{let h=E.toString();return h.endsWith(Dw)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(s):S.includes(s))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(s):h.includes(s))?_[x_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(Mw,"contains");function NQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),kc(e,t,r,s,u,n,i,o,!0,!1)}a(NQ,"greaterThan");function yQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),kc(e,t,r,s,u,n,i,o,!1,!1)}a(yQ,"greaterThanEqual");function wQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),kc(e,t,r,u,s,n,i,o,!1,!0)}a(wQ,"lessThan");function IQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),kc(e,t,r,u,s,n,i,o,!1,!1)}a(IQ,"lessThanEqual");function CQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(vr.validateEnv(e),r===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ut.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ut.END_VALUE_REQUIRED);if(s=vr.convertKeyValueToWrite(s),n=vr.convertKeyValueToWrite(n),s>n)throw new Error(ut.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return kc(e,t,r,s,n,i,o,c)}a(CQ,"between");function DQ(e,t,r,s){vr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(F_(r),r=Vc(n,r),s===void 0)throw new Error(ut.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=q_.parseRow(c,r)),o}a(DQ,"searchByHash");function LQ(e,t,r){vr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ut.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(LQ,"checkHashExists");function UQ(e,t,r,s,n=[]){return vw(e,t,r,s,n),Pw(e,t,r,s,n).map(i=>i[1])}a(UQ,"batchSearchByHash");function MQ(e,t,r,s,n=[]){vw(e,t,r,s,n);let i=new Map;for(let[o,c]of Pw(e,t,r,s,n))i.set(o,c);return i}a(MQ,"batchSearchByHashToMap");function Pw(e,t,r,s,n=[]){return Ji(e,t,t,(i,o,c)=>{r=Vc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,q_.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(Pw,"batchHashSearch");function vw(e,t,r,s,n){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(F_(r),s==null)throw new Error(ut.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ut.IDS_MUST_BE_ITERABLE)}a(vw,"initializeBatchSearchByHash");function F_(e){if(!Array.isArray(e))throw e===void 0?new Error(ut.FETCH_ATTRIBUTES_REQUIRED):new Error(ut.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(F_,"validateFetchAttributes");function ii(e,t,r){if(vr.validateEnv(e),t===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ut.SEARCH_VALUE_REQUIRED);if(r?.length>mQ)throw new Error(ut.SEARCH_VALUE_TOO_LARGE)}a(ii,"validateComparisonFunctions");function Vc(e,t){return t.length===1&&EQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ni.listDBIs(e)),t}a(Vc,"setGetWholeRowAttributes");Bw.exports={searchAll:pQ,searchAllToMap:SQ,count:AQ,countAll:gQ,equals:RQ,startsWith:OQ,endsWith:bQ,contains:Mw,searchByHash:DQ,setGetWholeRowAttributes:Vc,batchSearchByHash:UQ,batchSearchByHashToMap:MQ,checkHashExists:LQ,iterateDBI:TQ,greaterThan:NQ,greaterThanEqual:yQ,lessThan:wQ,lessThanEqual:IQ,between:CQ}});var ea=T((Ble,Gw)=>{var Hw=require("lodash"),xw=je(),fe=require("joi"),PQ=J(),{hdb_schema_table:$c,checkValidTable:qw,hdb_table:Fw,hdb_database:G_}=Ys(),{handleHDBError:vQ,hdb_errors:BQ}=re(),{getDatabases:HQ}=(Ae(),se(Fe)),{HTTP_STATUS_CODES:xQ}=BQ,qQ=fe.object({database:G_,schema:G_,table:Fw,search_attribute:$c,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives($c,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),FQ=fe.object({database:G_,schema:G_,table:Fw,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives($c,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives($c,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives($c,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});Gw.exports=function(e,t){let r=null;switch(t){case"value":r=xw.validateBySchema(e,qQ);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(qw("database",e.schema)),i(qw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),n&&(r=new Error(n.trim()));break;case"conditions":r=xw.validateBySchema(e,FQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=PQ.checkGlobalSchemaTable(e.schema,e.table);if(n)return vQ(new Error,n,xQ.NOT_FOUND);let o=HQ()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=Hw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!Hw.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var hp=T((xle,kw)=>{"use strict";var GQ=We(),kQ=ea(),{getSchemaPath:VQ}=Je();kw.exports=$Q;function $Q(e){let t=kQ(e,"hashes");if(t)throw t;let r=VQ(e.schema,e.table);return GQ.openEnvironment(r,e.table)}a($Q,"initialize")});var mp=T((Fle,Vw)=>{"use strict";var YQ=Zo(),KQ=hp();Vw.exports=WQ;async function WQ(e){let t=await KQ(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return YQ.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(WQ,"lmdbGetDataByHash")});var ta=T((kle,$w)=>{"use strict";var pp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};$w.exports=pp});var Kw=T((Yle,Yw)=>{"use strict";var $le=ta(),QQ=Zo(),zQ=hp();Yw.exports=JQ;async function JQ(e){let t=await zQ(e),r=global.hdb_schema[e.schema][e.table];return QQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(JQ,"lmdbSearchByHash")});var Js=T((Wle,Ww)=>{"use strict";var Sp=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};Ww.exports=Sp});var k_=T((zle,Zw)=>{"use strict";var Qt=Zo(),jQ=We(),XQ=J(),Ee=dt(),ji=L(),ZQ=xi(),Qw=Nr().LMDB_ERRORS_ENUM,{getSchemaPath:ez}=Je(),Rn=ji.SEARCH_WILDCARDS;async function tz(e,t,r){let s;e.schema===ji.SYSTEM_SCHEMA_NAME?s=ZQ[e.table]:s=global.hdb_schema[e.schema][e.table];let n=Xw(e,s.hash_attribute,r,t);return Jw(e,n,s.hash_attribute,r)}a(tz,"prepSearch");async function Jw(e,t,r,s){let n=ez(e.schema,e.table),i=await jQ.openEnvironment(n,e.table),o=jw(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(rz(e,r)===!1){let l=e.search_attribute;if(l===r)return s?zw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?zw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?Qt.batchSearchByHashToMap(c,r,e.get_attributes,_):Qt.batchSearchByHash(c,r,e.get_attributes,_)}a(Jw,"executeSearch");function jw(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:n=Qt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:n=Qt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:n=Qt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:n=Qt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Qt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Qt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Qt.searchAll(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Qt.searchAllToMap(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:n=Qt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:n=Qt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Qt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:n=Qt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:n=Qt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(jw,"searchByType");function zw(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(zw,"createMapFromIterable");function rz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(rz,"checkToFetchMore");function Xw(e,t,r,s){if(XQ.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Rn.indexOf(n)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(Rn[0])<0&&n.indexOf(Rn[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(Rn.indexOf(i)>=0&&Rn.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(Rn.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(Rn.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(n.includes(Rn[0])||n.includes(Rn[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(Qw.UNKNOWN_SEARCH_TYPE)}else switch(s){case ji.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case ji.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case ji.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case ji.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case ji.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Qw.UNKNOWN_SEARCH_TYPE)}}a(Xw,"createSearchTypeFromSearchObject");Zw.exports={executeSearch:Jw,createSearchTypeFromSearchObject:Xw,prepSearch:tz,searchByType:jw}});var tI=T((Xle,eI)=>{"use strict";var jle=Js(),sz=ea(),nz=J(),iz=L(),oz=k_();eI.exports=az;function az(e,t){if(!nz.isEmpty(t)&&iz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=sz(e,"value");if(s)throw s;return oz.prepSearch(e,t,!0)}a(az,"lmdbGetDataByValue")});var Yc=T((t_e,rI)=>{"use strict";var e_e=Js(),cz=ea(),uz=J(),lz=L(),_z=k_();rI.exports=dz;async function dz(e,t){if(!uz.isEmpty(t)&&lz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=cz(e,"value");if(s)throw s;return _z.prepSearch(e,t,!1)}a(dz,"lmdbSearchByValue")});var nI=T((n_e,sI)=>{"use strict";var s_e=dt(),Tp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},gp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Rp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};sI.exports={SearchByConditionsObject:Tp,SearchCondition:gp,SortAttribute:Rp}});var uI=T((c_e,cI)=>{"use strict";var o_e=nI().SearchByConditionsObject,fz=Js(),Ez=ea(),Ap=Zo(),V_=dt(),{Resource:a_e}=(As(),se(Op)),aI=k_(),hz=Ep(),mz=require("lodash"),{getSchemaPath:pz}=Je(),iI=We(),{handleHDBError:Sz,hdb_errors:Tz}=re(),{HTTP_STATUS_CODES:gz}=Tz,Rz=1e8;cI.exports=Az;async function Az(e){let t=Ez(e,"conditions");if(t)throw Sz(t,t.message,gz.BAD_REQUEST,void 0,void 0,!0);e.operator=e.operator?e.operator.toLowerCase():void 0,e.offset=Number.isInteger(e.offset)?e.offset:0;let r=pz(e.schema,e.table),s=await iI.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)iI.openDBI(s,_.search_attribute);let i=mz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===V_.SEARCH_TYPES.EQUALS?_.estimated_count=Ap.count(s,_.search_attribute,_.search_value):l===V_.SEARCH_TYPES.CONTAINS||l===V_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Rz}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await oI(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=s.dbis[n.hash_attribute],l=i.slice(1).map(aI.filterByType),d=l.length,f=Ap.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>hz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await oI(o,e,f,n.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Ap.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Az,"lmdbSearchByConditions");async function oI(e,t,r,s){let n=new fz(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===V_.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,aI.searchByType(e,n,i,s).map(o=>o.value)}a(oI,"executeConditionSearch")});var ra=T((l_e,lI)=>{"use strict";var Oz=L().OPERATIONS_ENUM,bp=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=Oz.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};lI.exports=bp});var Np=T((d_e,SI)=>{"use strict";var EI=Js(),hI=ra(),mI=Yc(),pI=Gc(),ar=L(),_I=J(),dI=We(),{getTransactionAuditStorePath:bz,getSchemaPath:Nz}=Je(),fI=V();SI.exports=yz;async function yz(e){try{if(_I.isEmpty(global.hdb_schema[e.schema])||_I.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await wz(e),await Iz(e);let t=Nz(e.schema,e.table);try{await dI.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")fI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=bz(e.schema,e.table);await dI.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")fI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(yz,"lmdbDropTable");async function wz(e){let t=new EI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await mI(t)),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new hI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await pI(n)}a(wz,"deleteAttributesFromSystem");async function Iz(e){let t=new EI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await mI(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new hI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await pI(n)}catch(i){throw i}}a(Iz,"dropTableFromSystem")});var gI=T((E_e,TI)=>{"use strict";var Cz=require("fs-extra"),Dz=Js(),Lz=ta(),Uz=ra(),Mz=Np(),Pz=Gc(),vz=mp(),Bz=Yc(),An=L(),{getSchemaPath:Hz}=Je(),{handleHDBError:xz,hdb_errors:qz}=re(),{HDB_ERROR_MSGS:Fz,HTTP_STATUS_CODES:Gz}=qz;TI.exports=kz;async function kz(e){let t;try{t=await Vz(e.schema);let r=new Dz(An.SYSTEM_SCHEMA_NAME,An.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,An.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[An.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await Bz(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await Mz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new Uz(An.SYSTEM_SCHEMA_NAME,An.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Pz(n);let i=Hz(t);await Cz.remove(i)}catch(r){throw r}}a(kz,"lmdbDropSchema");async function Vz(e){let t=new Lz(An.SYSTEM_SCHEMA_NAME,An.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[An.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await vz(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw xz(new Error,Fz.SCHEMA_NOT_FOUND(e),Gz.NOT_FOUND,void 0,void 0,!0);return s}a(Vz,"validateDropSchema")});var $_=T((m_e,RI)=>{"use strict";var yp=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};RI.exports=yp});var OI=T((T_e,AI)=>{"use strict";var $z=require("fs-extra"),Y_=We(),{getTransactionAuditStorePath:Yz}=Je(),wp=dt(),S_e=$_();AI.exports=Kz;async function Kz(e){let t;try{let r=Yz(e.schema,e.table);await $z.mkdirp(r),t=await Y_.createEnvironment(r,e.table,!0)}catch(r){throw r.message=`unable to create transactions audit environment for ${e.schema}.${e.table} due to: ${r.message}`,r}try{Y_.createDBI(t,wp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Y_.createDBI(t,wp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Y_.createDBI(t,wp.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(Kz,"createTransactionsAuditEnvironment")});var wI=T((R_e,yI)=>{"use strict";var Ip=L(),bI=We(),Wz=Go(),{getSystemSchemaPath:Qz,getSchemaPath:zz}=Je(),Jz=xi(),jz=f_(),Cp=d_(),Xz=V(),Zz=OI(),Lp=Jz.hdb_table,NI=[];for(let e=0;e<Lp.attributes.length;e++)NI.push(Lp.attributes[e].attribute);yI.exports=eJ;async function eJ(e,t){let r=zz(t.schema,t.table),s=new Cp(t.schema,t.table,Ip.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Cp(t.schema,t.table,Ip.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Cp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await bI.createEnvironment(r,t.table),e!==void 0){let o=await bI.openEnvironment(Qz(),Ip.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Wz.insertRecords(o,Lp.hash_attribute,NI,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Dp(s),await Dp(n),await Dp(i)}await Zz(t)}catch(o){throw o}}a(eJ,"lmdbCreateTable");async function Dp(e){try{await jz(e)}catch(t){Xz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Dp,"createAttribute")});var CI=T((O_e,II)=>{"use strict";var tJ=wc(),rJ=Uc(),sJ=B_(),Kc=L(),nJ=Go().updateRecords,iJ=We(),{getSchemaPath:oJ}=Je(),aJ=qc(),cJ=V();II.exports=uJ;async function uJ(e){try{let{schema_table:t,attributes:r}=tJ(e);rJ(e,r,t.hash_attribute),e.schema!==Kc.SYSTEM_SCHEMA_NAME&&(r.includes(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await sJ(e.hdb_auth_header,t,r),n=oJ(e.schema,e.table),i=await iJ.openEnvironment(n,e.table),o=await nJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await aJ(e,o)}catch(c){cJ.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(uJ,"lmdbUpdateRecords")});var LI=T((N_e,DI)=>{"use strict";var lJ=L().OPERATIONS_ENUM,Up=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=lJ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};DI.exports=Up});var MI=T((I_e,UI)=>{"use strict";var w_e=LI(),_J=wc(),dJ=Uc(),fJ=B_(),Wc=L(),EJ=Go().upsertRecords,hJ=We(),{getSchemaPath:mJ}=Je(),pJ=qc(),SJ=V(),{handleHDBError:TJ,hdb_errors:gJ}=re();UI.exports=RJ;async function RJ(e){let t;try{t=_J(e)}catch(u){throw TJ(u,u.message,gJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;dJ(e,s,r.hash_attribute),e.schema!==Wc.SYSTEM_SCHEMA_NAME&&(s.includes(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await fJ(e.hdb_auth_header,r,s),i=mJ(e.schema,e.table),o=await hJ.openEnvironment(i,e.table),c=await EJ(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await pJ(e,c)}catch(u){SJ.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(RJ,"lmdbUpsertRecords")});var vI=T((D_e,PI)=>{"use strict";var Mp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};PI.exports=Mp});var HI=T((U_e,BI)=>{"use strict";var Pp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};BI.exports=Pp});var FI=T((v_e,qI)=>{"use strict";var vp=We(),{getTransactionAuditStorePath:AJ}=Je(),P_e=vI(),Qc=dt(),OJ=J(),xI=HI(),bJ=require("util").promisify,NJ=bJ(setTimeout),yJ=1e4,wJ=100;qI.exports=IJ;async function IJ(e){let t=AJ(e.schema,e.table),r=await vp.openEnvironment(t,e.table,!0),s=vp.listDBIs(r);vp.initializeDBIs(r,Qc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new xI;do n=await CJ(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await NJ(wJ);while(n.transactions_deleted>0);return i}a(IJ,"deleteAuditLogsBefore");async function CJ(e,t){let r=new xI;try{let s=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[Qc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];OJ.isEmpty(c)||(n=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>yJ)break}return await n,r}catch(s){throw s}}a(CJ,"deleteTransactions")});var kI=T((H_e,GI)=>{"use strict";var Bp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};GI.exports=Bp});var $I=T((F_e,VI)=>{"use strict";var DJ=Js(),LJ=ra(),q_e=kI(),js=L(),UJ=J(),Hp=We(),MJ=xi(),PJ=Yc(),vJ=Gc(),{getSchemaPath:BJ}=Je();VI.exports=HJ;async function HJ(e,t=!0){let r;e.schema===js.SYSTEM_SCHEMA_NAME?r=MJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await qJ(e),n=BJ(e.schema,e.table),i=await Hp.openEnvironment(n,e.table);return t===!0&&await xJ(e,i,r.hash_attribute),Hp.dropDBI(i,e.attribute),s}a(HJ,"lmdbDropAttribute");async function xJ(e,t,r){let s=Hp.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);n=t.dbis[r].put(o,_,u)}await n}a(xJ,"removeAttributeFromAllObjects");async function qJ(e){let t=new DJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await PJ(t)).filter(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(UJ.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new LJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return vJ(i)}a(qJ,"dropAttributeFromSystem")});var JI=T((V_e,zI)=>{"use strict";var xp=We(),sa=dt(),k_e=yr(),qp=L(),YI=J(),{getTransactionAuditStorePath:FJ}=Je(),GJ=Zo(),K_=Jo(),kJ=V();zI.exports=VJ;async function VJ(e){let t=FJ(e.schema,e.table),r=await xp.openEnvironment(t,e.table,!0),s=xp.listDBIs(r);xp.initializeDBIs(r,sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return KI(r,e.search_values);case qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,YJ(r,e.search_values,n);case qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return $J(r,e.search_values);default:return KI(r)}}a(VJ,"readAuditLog");function KI(e,t=[0,Date.now()]){YI.isEmpty(t[0])&&(t[0]=0),YI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new K_,n))}a(KI,"searchTransactionsByTimestamp");function $J(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[sa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,QI(e,i))}return Object.fromEntries(r)}a($J,"searchTransactionsByUsername");function YJ(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=GJ.equals(e,sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,sa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);s.has(f)?s.get(f).push(_.toString()):s.set(f,[_.toString()])}}let n=Array.from(s.keys()),i=QI(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);WI(u,"records",r,l,o),WI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(YJ,"searchTransactionsByHashValues");function WI(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let _=n.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new K_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new K_(e.operation,e.user_name,i,void 0);_[t]=[c],n.set(u,[_])}}}a(WI,"loopRecords");function QI(e,t){let r=[];try{let s=e.dbis[sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new K_,i);r.push(o)}}catch(i){kJ.warn(i)}return r}catch(s){throw s}}a(QI,"batchSearchTransactions")});var XI=T((W_e,jI)=>{"use strict";var{getSchemaPath:Y_e}=Je(),K_e=We(),{database:KJ}=(Ae(),se(Fe));jI.exports={writeTransaction:WJ};async function WJ(e,t,r){return KJ({database:e,table:t}).transaction(r)}a(WJ,"writeTransaction")});var rC=T((z_e,tC)=>{"use strict";var{getSchemaPath:ZI}=Je(),eC=We();tC.exports={flush:QJ,resetReadTxn:zJ};async function QJ(e,t){return(await eC.openEnvironment(ZI(e,t),t.toString())).flushed}a(QJ,"flush");async function zJ(e,t){try{(await eC.openEnvironment(ZI(e,t),t.toString())).resetReadTxn()}catch{}}a(zJ,"resetReadTxn")});var oC=T((j_e,iC)=>{"use strict";var{Readable:JJ}=require("stream"),{getDatabases:jJ}=(Ae(),se(Fe)),{readSync:XJ,openSync:ZJ,createReadStream:sC}=require("fs"),{open:e2}=require("lmdb"),nC=r_(),t2=n_(),{AUDIT_STORE_OPTIONS:r2}=(Bi(),se(aC)),{INTERNAL_DBIS_NAME:s2,AUDIT_STORE_NAME:n2}=dt();iC.exports=o2;var Fp=32768,i2=100;async function o2(e){let t=e.database||e.schema||"data",r=jJ()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let _=r[n[0]];if(!_)throw new Error(`Can not find table ${n[0]}`);let l=_.dbisDB,d=e2({noSync:!0,maxDbs:t2.MAX_DBS}),f,E=d.openDB(s2,new nC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(R,g){g.encoding="binary",g.encoder=void 0;let P=d.openDB(R,g),H=l.openDB(R,g);for(let{key:v,version:U,value:Y}of H.getRange({transaction:h,versions:H.useVersions}))f=P.put(v,Y,U),p++%i2===0&&(await new Promise(K=>setTimeout(K,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:g}of l.getRange({transaction:h,start:!1}))if(n.some(P=>R.startsWith?.(P+"/"))){E.put(R,g);let[,P]=R.split("/"),H=!P,v=new nC(!H,H);await S(R,v)}e.include_audit&&await S(n2,Object.assign({},r2)),await f;let A=sC(d.path);return A.headers=u(),A.on("close",()=>{h.done(),d.close()}),A}let o=r[Object.keys(r)[0]].primaryStore,c=ZJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(Fp);XJ(c,_,0,Fp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=sC(null,{fd:c,start:Fp}),f=new JJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",s),_}}a(o2,"getBackup")});var lC=T((Z_e,uC)=>{"use strict";var a2=V(),{handleHDBError:c2}=re(),u2=bb(),l2=f_(),_2=up(),d2=gw(),f2=Gc(),E2=mp(),h2=Kw(),m2=tI(),p2=Yc(),S2=uI(),T2=gI(),g2=wI(),R2=CI(),A2=MI(),O2=FI(),b2=Np(),N2=$I(),y2=JI(),w2=XI(),cC=rC(),I2=oC(),Gp=class extends u2{static{a(this,"LMDBBridge")}async searchByConditions(t){return S2(t)}async getDataByHash(t){return await E2(t)}async searchByHash(t){return await h2(t)}async getDataByValue(t,r){return await m2(t,r)}async searchByValue(t){return await p2(t)}async createSchema(t){return await d2(t)}async dropSchema(t){return await T2(t)}async createTable(t,r){return await g2(t,r)}async dropTable(t){return await b2(t)}async createAttribute(t){return await l2(t)}async createRecords(t){return await _2(t)}async updateRecords(t){return await R2(t)}async upsertRecords(t){try{return await A2(t)}catch(r){throw c2(r,null,null,a2.ERR,r)}}async deleteRecords(t){return await f2(t)}async dropAttribute(t){return await N2(t)}async deleteAuditLogsBefore(t){return await O2(t)}async readAuditLog(t){return await y2(t)}writeTransaction(t,r,s){return w2.writeTransaction(t,r,s)}flush(t,r){return cC.flush(t,r)}resetReadTxn(t,r){return cC.resetReadTxn(t,r)}getBackup(t){return I2(t)}};uC.exports=Gp});function U2(){L2=setInterval(function(){for(let e of kp)if(e.stale){let t=e[Oe]?.url;_C.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},D2).unref()}var Vp,_C,C2,kp,Xi,W_,D2,L2,$p=Re(()=>{Vp=x(yr()),_C=x(V());As();qo();C2=100,kp=new Set,Xi=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===0)return this.readTxnsUsed=1,e_(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),kp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),e_(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(kp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(this.open===2)throw new Error("Can not use a transaction that is no longer open");if(this.open===1){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,Vp.getNextMonotonicTime)());let s=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let A=S();E?E.push?E.push(A):E=[E,A]:E=A}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}s||this.doneReadTxn(),this.open=t?.letItLinger?1:2;let n,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,s)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){s>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);n=n||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<C2>>s?u():n=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),n)return n.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=s+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=2,this.writes=[]}},W_=class extends Xi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Vp.getNextMonotonicTime)())}getReadTxn(){}},D2=3e4;a(U2,"startMonitoringTxns");U2()});function Xe(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===0&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let s=e.transaction=new Xi;e.timestamp&&(s.timestamp=e.timestamp),s[Oe]=e,e.resourceCache||(e.resourceCache=[]);let n;try{if(n=t(s),n?.then)return n.then(i,o)}catch(c){o(c)}return i(n);function i(c){let u=s.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var dC,Zi=Re(()=>{dC=require("../index");As();$p();a(Xe,"transaction");(0,dC._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var RC={};Ye(RC,{ResourceBridge:()=>Wp});function Qp({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function EC(e,t){let r=Xs(e),s=Qp(e,r);if(!r)throw new Cs.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user},o;Xe(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:n,select:s},i);return l=l&&z_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function Xs(e){let t=e.database||e.schema||P2,r=Ds()[t];if(!r)throw(0,Cs.handleHDBError)(new Error,M2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function hC(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*mC(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var pC,Q_,Cs,SC,TC,Ls,Yp,Kp,gC,M2,P2,v2,B2,fC,Wp,AC=Re(()=>{"use strict";pC=x(lC()),Q_=x(ea()),Cs=x(re());Ae();SC=x(wc()),TC=x(Uc()),Ls=x(L()),Yp=x(gn()),Kp=x(Is()),gC=x(J());Zi();J_();({HDB_ERROR_MSGS:M2}=Cs.hdb_errors),P2="data",v2=1e4,B2=10,Wp=class extends pC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),fC=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,Q_.default)(t,"conditions");if(r)throw(0,Cs.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=Xs(t);if(!s)throw new Cs.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Qp(t,s),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Cs.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ct({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await Xs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Xs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(o,c,u),await new Promise(_=>setImmediate(_));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Xs(t).dropTable()}createSchema(t){return zc({database:t.schema,table:null}),Yp.signalSchemaChange(new Kp.SchemaEventMsg(process.pid,Ls.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await zp(t.schema),Yp.signalSchemaChange(new Kp.SchemaEventMsg(process.pid,Ls.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,fC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,SC.default)(t);(0,TC.default)(t,s,r.primaryKey);let n,i=Ds()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Xe(o,async c=>{if(!i.schemaDefined){n=[];for(let l of s)i.attributes.find(f=>f.name==l)||n.push(l);n.length>0&&await i.addAttributes(n.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=z_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:_}})}async deleteRecords(t){let r=Ds()[t.schema][t.table],s={user:t.hdb_user};return Xe(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return hC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Ds()[t.schema][t.table];if(!r.createdTimeProperty)throw new Cs.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Ls.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,gC.async_set_timeout)(B2),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%v2===0&&await _();return u.length>0&&await _(),n?hC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,Q_.default)(t,"hashes");if(r)throw r;return EC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of EC(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Ls.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let s=(0,Q_.default)(t,"value");if(s)throw s;let n=Xs(t);if(!n)throw new Cs.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Ls.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Qp(t,n)})}async getDataByValue(t,r){let s=new Map,n=Xs(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){Xs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Xs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Xs(t),s={};switch(t.search_type){case Ls.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case Ls.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of mC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return mC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Qp,"getSelect");a(EC,"getRecords");a(Xs,"getTable");a(hC,"createDeleteResponse");a(mC,"groupRecordsInHistory")});var Ns=T((hde,OC)=>{"use strict";var{ResourceBridge:H2}=(AC(),se(RC)),x2=Z();x2.initSync();var j_;function q2(){return j_||(j_=new H2,j_)}a(q2,"getBridge");OC.exports=q2()});var wC=T((pde,yC)=>{"use strict";var bC=require("lodash"),Jc=require("mathjs"),F2=require("jsonata"),NC=J();yC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?bC.uniqWith(e,bC.isEqual):e,searchJSON:G2,mad:jc.bind(null,Jc.mad),mean:jc.bind(null,Jc.mean),mode:jc.bind(null,Jc.mode),prod:jc.bind(null,Jc.prod),median:jc.bind(null,Jc.median)};function jc(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(jc,"aggregateFunction");function G2(e,t){if(typeof e!="string"||e.length===0)throw new Error("search json expression must be a non-empty string");let r="__"+e+"__";if(NC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),NC.isEmpty(this.__ala__.res[r])){let s=F2(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(G2,"searchJSON")});var CC=T((Tde,IC)=>{"use strict";var Et=require("moment"),Jp="YYYY-MM-DDTHH:mm:ss.SSSZZ";Et.suppressDeprecationWarnings=!0;IC.exports={current_date:()=>Et().utc().format("YYYY-MM-DD"),current_time:()=>Et().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Et(e).utc().format("YYYY");case"month":return Et(e).utc().format("MM");case"day":return Et(e).utc().format("DD");case"hour":return Et(e).utc().format("HH");case"minute":return Et(e).utc().format("mm");case"second":return Et(e).utc().format("ss");case"millisecond":return Et(e).utc().format("SSS");default:break}},date:e=>Et(e).utc().format(Jp),date_format:(e,t)=>Et(e).utc().format(t),date_add:(e,t,r)=>Et(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Et(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=Et(e).utc(),n=Et(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>Et().utc().valueOf(),get_server_time:()=>Et().format(Jp),offset_utc:(e,t)=>Et(e).utc().utcOffset(t).format(Jp)}});var MC=T((gde,UC)=>{"use strict";var k2=require("@turf/area"),V2=require("@turf/length"),$2=require("@turf/circle"),Y2=require("@turf/difference"),K2=require("@turf/distance"),W2=require("@turf/boolean-contains"),Q2=require("@turf/boolean-equal"),z2=require("@turf/boolean-disjoint"),J2=require("@turf/helpers"),DC=L(),pe=J(),On=V();UC.exports={geoArea:j2,geoLength:X2,geoCircle:Z2,geoDifference:e4,geoDistance:LC,geoNear:t4,geoContains:r4,geoEqual:s4,geoCrosses:n4,geoConvert:i4};function j2(e){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return k2.default(e)}catch(t){return On.trace(t,e),NaN}}a(j2,"geoArea");function X2(e,t){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return V2.default(e,{units:t||"kilometers"})}catch(r){return On.trace(r,e),NaN}}a(X2,"geoLength");function Z2(e,t,r){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return $2.default(e,t,{units:r||"kilometers"})}catch(s){return On.trace(s,e,t),NaN}}a(Z2,"geoCircle");function e4(e,t){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return Y2(e,t)}catch(r){return On.trace(r,e,t),NaN}}a(e4,"geoDifference");function LC(e,t,r){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return K2.default(e,t,{units:r||"kilometers"})}catch(s){return On.trace(s,e,t),NaN}}a(LC,"geoDistance");function t4(e,t,r,s){if(pe.isEmpty(e)||pe.isEmpty(t))return!1;if(pe.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return LC(e,t,s)<=r}catch(n){return On.trace(n,e,t),!1}}a(t4,"geoNear");function r4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return W2.default(e,t)}catch(r){return On.trace(r,e,t),!1}}a(r4,"geoContains");function s4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return Q2.default(e,t)}catch(r){return On.trace(r,e,t),!1}}a(s4,"geoEqual");function n4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return!z2.default(e,t)}catch(r){return On.trace(r,e,t),!1}}a(n4,"geoCrosses");function i4(e,t,r){if(pe.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(pe.isEmpty(t))throw new Error("geo_type is required");if(pe.isEmpty(DC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(DC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=pe.autoCastJSON(e)),J2[t](e,r)}a(i4,"geoConvert")});var X_=T((Ade,PC)=>{var eo=wC(),Br=CC(),Zs=MC();PC.exports=e=>{e.aggr.mad=e.aggr.MAD=eo.mad,e.aggr.mean=e.aggr.MEAN=eo.mean,e.aggr.mode=e.aggr.MODE=eo.mode,e.aggr.prod=e.aggr.PROD=eo.prod,e.aggr.median=e.aggr.MEDIAN=eo.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=eo.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=eo.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Br.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Br.current_time,e.fn.extract=e.fn.EXTRACT=Br.extract,e.fn.date=e.fn.DATE=Br.date,e.fn.date_format=e.fn.DATE_FORMAT=Br.date_format,e.fn.date_add=e.fn.DATE_ADD=Br.date_add,e.fn.date_sub=e.fn.DATE_SUB=Br.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Br.date_diff,e.fn.now=e.fn.NOW=Br.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Br.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Br.get_server_time,e.fn.getdate=e.fn.GETDATE=Br.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Br.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=Zs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Zs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Zs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Zs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Zs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Zs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Zs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Zs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Zs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Zs.geoNear}});var xC=T((Ode,HC)=>{"use strict";var Xc=require("lodash"),cr=require("alasql");cr.options.cache=!1;var o4=X_(),vC=require("clone"),Z_=require("recursive-iterator"),_e=V(),Ce=J(),na=Ns(),a4=L(),{hdb_errors:c4}=re(),{getDatabases:BC}=(Ae(),se(Fe)),u4="IS NULL",Us="There was a problem performing this search. Please check the logs and try again.";o4(cr);var jp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw _e.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),Ce.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(s))return _e.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw _e.error("Error thrown from checkEmptySQL in SQLSearch class method search."),_e.error(s),new Error(Us)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw _e.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),_e.error(s),new Error(Us)}if(Object.keys(this.data).length===0)return _e.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw _e.error("Error thrown from processJoins in SQLSearch class method search."),_e.error(s),new Error(Us)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw _e.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),_e.error(s),new Error(Us)}try{return t=await this._finalSQL(),t}catch(s){throw _e.error("Error thrown from finalSQL in SQLSearch class method search."),_e.error(s),new Error(Us)}}_getColumns(){let t=new Z_(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(vC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Xc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=BC()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){_e.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Z_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let s=Ce.autoCast(r.right.value);[!0,!1].indexOf(s)>=0&&(r.right=new cr.yy.LogicValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=Ce.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new cr.yy.LogicValue({value:i}):s instanceof cr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new cr.yy.NumValue({value:i}))});if(t){_e.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Z_(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(a4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ce.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ce.isEmptyOrZeroLength(r.left.columnid)||Ce.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(Ce.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!Ce.isEmpty(r.right.value)||!Ce.isEmpty(r.left.value)?s.add(Ce.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)s.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Xc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(Ce.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);Ce.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&!Ce.isEmptyOrZeroLength(this.columns.columns))return t;if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await cr.promise(r)}catch(r){throw _e.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),_e.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let s=this._findColumn(r);s&&this.fetch_attributes.push(vC(s))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(Ce.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(u4)>-1&&this.tables.forEach(n=>{let i={columnid:BC()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Xc.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,_=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!Ce.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await na.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(Us)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await na.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(Us)}else if(!Ce.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await na.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...s[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]):(this.data[i].__merged_data[p]=[...s[i]],this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(Us)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await na.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(Us)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof cr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new cr.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new cr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let n=t.is_func?new cr.yy.FuncValue:new cr.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,n);f=await cr.promise(h,t),t=null}catch(E){throw _e.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),_e.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=Xc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,A=p.length;S<A;S++){let R=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[R]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Z_(this.columns);for(let{node:i}of n)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&s.push(o)}}s=Xc.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw _e.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),_e.error(i),new Error(Us)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await na.getDataByHash(c),_=n.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=n.columns[h],S=E[p]===void 0?null:E[p];this.data[s].__merged_data[f].push(S)}}}}catch(r){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getData."),_e.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let s;try{let n=this._buildSQL();_e.trace(`Final SQL: ${n}`),s=await cr.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),_e.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw _e.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),_e.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return _e.error(c4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),_e.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;s=s.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;s=s.replace(u,_)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await na.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw _e.error("There was an error when processing this SQL operation. Check your logs"),_e.error(o),new Error(Us)}}return Object.values(Object.values(this.data)[0].__merged_data)}};HC.exports=jp});var es=T((Nde,qC)=>{"use strict";var l4=Ab();qC.exports={searchByConditions:d4,searchByHash:f4,searchByValue:E4,search:h4};var Xp=Ns(),{transformReq:Zp}=J(),_4=xC();async function d4(e){return Zp(e),Xp.searchByConditions(e)}a(d4,"searchByConditions");async function f4(e){Zp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Xp.searchByHash(e))r&&t.push(r);return t}a(f4,"searchByHash");async function E4(e){Zp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Xp.searchByValue(e))t.push(r);return t}a(E4,"searchByValue");function h4(e,t){try{let r=new l4(e);r.validate(),new _4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(h4,"search")});var ed=T((wde,FC)=>{"use strict";var m4=Ns();FC.exports={writeTransaction:p4};function p4(e,t,r){return m4.writeTransaction(e,t,r)}a(p4,"writeTransaction")});var $C=T((Dde,VC)=>{"use strict";var S4=es(),T4=Tn(),GC=V(),g4=Cr(),Cde=ed(),R4=require("clone"),tS=require("alasql"),A4=X_(),kC=require("util"),O4=kC.promisify(T4.getTableSchema),b4=kC.promisify(S4.search),N4=L(),eS=J();A4(tS);VC.exports={update:w4};var y4="There was a problem performing this update. Please check the logs and try again.";async function w4({statement:e,hdb_user:t}){let r=await O4(e.table.databaseid,e.table.tableid),s=I4(e.columns);eS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=R4(n),c=eS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=tS.parse(u).statements[0],l=await b4(_),d=C4(s,l);return D4(o,d,t)}a(w4,"update");function I4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=tS.compile(`SELECT ${r.expression.toString()} AS [${N4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw GC.error(t),new Error(y4)}}a(I4,"createUpdateRecord");function C4(e,t){return eS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(C4,"buildUpdateRecords");async function D4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await g4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){GC.error(`Error delete new_attributes from update response: ${i}`)}return n}a(D4,"updateRecords")});var KC=T((Pde,YC)=>{var L4=require("alasql"),U4=es(),M4=V(),P4=Ns(),sS=require("util"),rS=J(),v4=L(),B4=Tn(),Ude=ed(),Mde=Cr(),H4="record",x4="successfully deleted",q4=sS.callbackify(V4),F4=sS.promisify(U4.search),G4=sS.promisify(B4.getTableSchema);YC.exports={convertDelete:q4};function k4(e){return`${e.deleted_hashes.length} ${H4}${e.deleted_hashes.length===1?"":"s"} ${x4}`}a(k4,"generateReturnMessage");async function V4({statement:e,hdb_user:t}){let r=await G4(e.table.databaseid,e.table.tableid);rS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=rS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=L4.parse(o).statements[0],u={operation:v4.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await F4(c);let _=await P4.deleteRecords(u);return rS.isEmptyOrZeroLength(_.message)&&(_.message=k4(_)),delete _.txn_time,_}catch(_){throw M4.error(_),_.hdb_code?_.message:_}}a(V4,"convertDelete")});var jC=T((Bde,JC)=>{"use strict";var $4=Xn(),{hdb_errors:WC}=re(),{getDatabases:QC}=(Ae(),se(Fe));JC.exports={checkSchemaExists:zC,checkSchemaTableExists:Y4,schema_describe:$4};async function zC(e){if(!QC()[e])return WC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(zC,"checkSchemaExists");async function Y4(e,t){let r=await zC(e);if(r)return r;if(!QC()[e][t])return WC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Y4,"checkSchemaTableExists")});var Zc=T((xde,K4)=>{K4.exports={name:"harperdb",version:"4.3.0-beta.6",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.10.0-beta.2",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.3.3","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var su={};Ye(su,{addAnalyticsListener:()=>ru,recordAction:()=>Hr,recordActionBinary:()=>rs,setAnalyticsEnabled:()=>W4});function W4(e){aD=e}function Hr(e,t,r,s,n){if(!aD)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);let o=sd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:s,type:n},sd.set(i,o)}td||Q4()}function rs(e,t,r,s,n){Hr(!!e,t,r,s,n)}function ru(e){lD.push(e)}function Q4(){td=performance.now(),setTimeout(async()=>{let e=performance.now()-td;td=0;let t=[],r={time:Date.now(),period:e,threadId:to.threadId,metrics:t};for(let[n,i]of sd){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of _D){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await dD()}let s=process.memoryUsage();t.push({metric:"memory",threadId:to.threadId,byThread:!0,...s});for(let n of lD)n(t);sd=new Map,to.parentPort?to.parentPort.postMessage({type:uD,report:r}):hD({report:r})},cD).unref()}async function z4(e,t=6e4){let r=oS(),s=fD(),n;for(let h of s.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){n=h.value.time;break}if(Date.now()-t<n)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:n||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:A}=p;for(let R of S||[]){let{path:g,method:P,type:H,metric:v,count:U,total:Y,distribution:K,threads:z,...ne}=R;U||(U=1);let me=v+(g?"-"+g:"");P!==void 0&&(me+="-"+P),H!==void 0&&(me+="-"+H);let ce=o.get(me);if(ce){if(ce.threads){let le=ce.threads[A];if(le)ce=le;else{ce.threads[A]=Object.assign({},ne);continue}}ce.count||(ce.count=1);let xe=ce.count;for(let le in ne){let Dt=ne[le];typeof Dt=="number"&&(ce[le]=(ce[le]*xe+Dt*U)/(xe+U))}ce.count+=U,Y>=0&&(ce.total+=Y,ce.ratio=ce.total/ce.count)}else ce=Object.assign({period:t},R),delete ce.distribution,o.set(me,ce),ce.byThread&&(ce.threads=[],ce.threads[A]=Object.assign({},ne),u.push(ce));if(K){K=K.map(le=>typeof le=="number"?{value:le,count:1}:le);let xe=c.get(me);xe?xe.push(...K):c.set(me,K)}}await dD()}for(let h of u){let{path:p,method:S,type:A,metric:R,count:g,total:P,distribution:H,threads:v,...U}=h;v=v.filter(Y=>Y);for(let Y in U){if(typeof h[Y]!="number")continue;let K=0;for(let z of v){let ne=z[Y];typeof ne=="number"&&(K+=ne)}h[Y]=K}h.count=v.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((le,Dt)=>le.value>Dt.value?1:-1);let A=S.count-1,R=[],g=0,P=0,H;for(let le of _D){let Dt=A*le;for(;g<Dt;)H=p[P++],g+=H.count,P===1&&g--;let Ul=p[P>1?P-2:0];H||(H=p[0]),R.push(H.value-(H.value-Ul.value)*(g-Dt)/H.count)}let[v,U,Y,K,z,ne,me,ce,xe]=R;Object.assign(S,{p1:v,p10:U,p25:Y,median:K,p75:z,p90:ne,p95:me,p99:ce,p999:xe})}let l;for(let[h,p]of o)p.id=(0,rd.getNextMonotonicTime)(),p.time=_,s.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||s.primaryStore.put(p.id,p)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,rd.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-XC,active:E-ZC,time:d,...process.memoryUsage()};s.primaryStore.put(h,p,{append:!0}).then(S=>{S||s.primaryStore.put(h,p)})}XC=f,ZC=E}async function eD(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function oS(){return tD||(tD=ct({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function fD(){return rD||(rD=ct({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function X4(){ED=!0;let e=(0,tu.get)(iS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await z4(cD,e),await eD(oS(),J4),await eD(fD(),j4)},Math.min(e/2,2147483647)).unref()}function hD(e,t){let r=e.report;r.threadId=t?.threadId||to.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(sD+=s.mean*s.count);r.totalBytesProcessed=sD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(nD.get(t))}),nD.set(t,t.performance.eventLoopUtilization())),r.id=(0,rd.getNextMonotonicTime)(),oS().primaryStore.put(r.id,r),ED||X4(),Z4&&(mD=t3(r))}async function t3(e){if(await mD,!oi){let r=(0,eu.dirname)((0,oD.getLogFilePath)());try{oi=await(0,nS.open)((0,eu.join)(r,"analytics.log"),"r+")}catch{oi=await(0,nS.open)((0,eu.join)(r,"analytics.log"),"w+")}}let t=(await oi.stat()).size;if(t>e3){let r=Buffer.alloc(t);await oi.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await oi.write(r,{position:0}),await oi.truncate(r.length),t=r.length}await oi.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var
|
|
6
|
+
`)},OY="certificate.pem",bY="privateKey.pem",NY="ca.pem";cy.exports={CERTIFICATE_VALUES:AY,CERTIFICATE_PEM_NAME:OY,PRIVATEKEY_PEM_NAME:bY,CA_PEM_NAME:NY}});var Gm=T((Due,Ey)=>{"use strict";var fy=require("fs-extra"),se=require("joi"),yY=require("os"),{boolean:Ne,string:ir,number:Ot,array:Fm}=se.types(),{totalmem:ly}=require("os"),Yi=require("path"),wY=$(),w_=J(),Cue=uy(),_y=U(),IY=Xe(),dy="log",CY="components",DY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",UY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",LY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",MY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",PY="rootPath config parameter is undefined",vY="clustering.enabled config parameter is undefined",Ki=Ot.min(0).required(),I_=Fm.items({host:ir.required(),port:Ki}).empty(null),Qn;Ey.exports={configValidator:BY,routesValidator:kY,route_constraints:I_};function BY(e){if(Qn=e.rootPath,w_.isEmpty(Qn))throw PY;let t=Ne.required(),r=Ot.min(0).max(1e3).empty(null).default(GY),n=ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Bc),s=ir.optional().empty(null),i=ir.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=se.string().empty(null).default(Bc),c=se.custom(xY).empty(null).default(Bc),u=e.clustering?.enabled;if(w_.isEmpty(u))throw vY;let _;return u===!0?_=se.object({enabled:t,hubServer:se.object({cluster:se.object({name:se.required().empty(null),network:se.object({port:Ki,routes:I_}).required()}).required(),leafNodes:se.object({network:se.object({port:Ki}).required()}).required(),network:se.object({port:Ki}).required()}).required(),leafServer:se.object({network:se.object({port:Ki,routes:I_}).required(),streams:se.object({maxAge:Ot.min(120).allow(null).optional(),maxBytes:Ot.min(1).allow(null).optional(),maxMsgs:Ot.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:se.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Ne.optional(),databaseLevel:Ne.optional(),tls:se.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:Ne.required(),verify:Ne.optional()}),user:ir.optional().empty(null)}).required():_=se.object({enabled:t,tls:se.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:Ne.required()})}).required(),se.object({authentication:se.object({authorizeLocal:Ne,cacheTTL:Ot.required(),enableSessions:Ne}),analytics:se.object({aggregatePeriod:Ot}),componentsRoot:n.optional(),clustering:_,localStudio:se.object({enabled:t}).required(),logging:se.object({auditAuthEvents:se.object({logFailed:Ne,logSuccessful:Ne}),file:Ne.required(),level:se.valid("notify","fatal","error","warn","info","debug","trace"),rotation:se.object({enabled:Ne.optional(),compress:Ne.optional(),interval:ir.custom(FY).optional().empty(null),maxSize:ir.custom(qY).optional().empty(null),path:ir.optional().empty(null).default(Bc)}).required(),root:n,stdStreams:Ne.required(),auditLog:Ne.required()}).required(),operationsApi:se.object({network:se.object({cors:Ne.optional(),corsAccessList:Fm.optional(),headersTimeout:Ot.min(1).optional(),keepAliveTimeout:Ot.min(1).optional(),port:Ot.optional().empty(null),domainSocket:se.optional().empty("hdb/operations-server").default(Bc),securePort:Ot.optional().empty(null),timeout:Ot.min(1).optional()}).optional(),tls:se.object({certificate:s,certificateAuthority:s,privateKey:s})}).required(),rootPath:ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:se.object({network:se.object({port:Ki,securePort:Ki,mtls:se.alternatives([Ne.optional(),se.object({user:ir.optional(),certificateAuthority:s,required:Ne.optional()})])}).required(),webSocket:Ne.optional(),requireAuthentication:Ne.optional()}),http:se.object({compressionThreshold:Ot.optional(),cors:Ne.optional(),corsAccessList:Fm.optional(),headersTimeout:Ot.min(1).optional(),port:Ot.min(0).optional().empty(null),securePort:Ot.min(0).optional().empty(null),mtls:se.alternatives([Ne.optional(),se.object({user:ir.optional(),certificateAuthority:s,required:Ne.optional()})])}).required(),threads:se.alternatives(r.optional(),se.object({count:r.optional(),debug:se.alternatives(Ne.optional(),se.object({startingPort:Ot.min(1).optional(),host:ir.optional(),waitForDebugger:Ne.optional()})),maxHeapMemory:Ot.min(0).optional()})),storage:se.object({writeAsync:Ne.required(),overlappingSync:Ne.optional(),caching:Ne.optional(),compression:Ne.optional(),noReadAhead:Ne.optional(),path:c,prefetchWrites:Ne.optional()}).required(),ignoreScripts:Ne.optional(),tls:se.object({certificate:s.optional(),certificateAuthority:s.optional(),privateKey:s.optional(),ciphers:ir.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(BY,"configValidator");function HY(e){return fy.existsSync(e)?null:`Specified path ${e} does not exist.`}a(HY,"doesPathExist");function xY(e,t){se.assert(e,ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=HY(e);if(r)return t.message(r)}a(xY,"validatePath");function qY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(DY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(LY):e}a(qY,"validateRotationMaxSize");function FY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(UY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(MY):e}a(FY,"validateRotationInterval");function GY(e,t){let r=t.state.path.join("."),n=yY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||ly();return i=Math.round(Math.min(i,ly())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),wY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(GY,"setDefaultThreads");function Bc(e,t){let r=t.state.path.join(".");if(!w_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(w_.isEmpty(Qn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Yi.join(Qn,CY);case"logging.root":return Yi.join(Qn,dy);case"clustering.leafServer.streams.path":return Yi.join(Qn,"clustering","leaf");case"storage.path":let n=Yi.join(Qn,_y.LEGACY_DATABASES_DIR_NAME);return fy.existsSync(n)?n:Yi.join(Qn,_y.DATABASES_DIR_NAME);case"logging.rotation.path":return Yi.join(Qn,dy);case"operationsApi.network.domainSocket":return r==null?null:Yi.join(Qn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Bc,"setDefaultRoot");function kY(e){let t=se.object({routes:I_});return IY.validateBySchema({routes:e},t)}a(kY,"routesValidator")});var Lr=T((Mue,Oy)=>{"use strict";var Ur=U(),Lt=J(),bt=$(),{configValidator:VY,routesValidator:hy}=Gm(),or=require("fs-extra"),$Y=require("yaml"),yn=require("path"),YY=require("is-number"),py=require("properties-reader"),KY=require("lodash"),{handleHDBError:WY}=re(),{HTTP_STATUS_CODES:QY,HDB_ERROR_MSGS:C_}=Nr(),Lue=require("minimist"),{server:zY}=(rr(),ne(Pi)),{DATABASES_PARAM_CONFIG:Hc,CONFIG_PARAMS:Dr,CONFIG_PARAM_MAP:wn}=Ur,JY="Unable to get config value because config is uninitialized",jY="Config successfully initialized",XY="Error backing up config file",ZY="Empty parameter sent to getConfigValue",Sy=yn.join(Ur.PACKAGE_ROOT,"config","yaml",Ur.HDB_DEFAULT_CONFIG_FILE),eK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",my={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"},D_,Nt,U_;Oy.exports={createConfigFile:tK,getDefaultConfig:rK,getConfigValue:gy,initConfig:Vm,flattenConfig:Ko,updateConfigValue:Ry,updateConfigObject:sK,getConfiguration:aK,setConfiguration:cK,readConfigFile:Ym,getClusteringRoutes:uK,initOldConfig:Ay,getConfigFromFile:lK,getConfigFilePath:Wi,addConfig:_K,deleteConfigFromFile:dK,getConfigObj:fK};function tK(e){let t=ni(Sy);D_=Ko(t.toJSON());let r;for(let o in e){let c=wn[o.toLowerCase()];if(c===Dr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=km(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&Ty(t,r),$m(t);let n=t.toJSON();Nt=Ko(n);let s=t.getIn(["rootPath"]),i=yn.join(s,Ur.HDB_CONFIG_FILE);or.createFileSync(i),or.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(tK,"createConfigFile");function Ty(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Lt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Hc.TABLES))for(let i in n[s][Hc.TABLES])for(let o in n[s][Hc.TABLES][i]){let c=n[s][Hc.TABLES][i][o],u=[Dr.DATABASES,s,Hc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Dr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){bt.error("Error parsing schemas CLI/env config arguments",n)}}a(Ty,"setSchemasConfig");function rK(e){if(D_===void 0){let r=ni(Sy);D_=Ko(r.toJSON())}let t=wn[e.toLowerCase()];if(t!==void 0)return D_[t.toLowerCase()]}a(rK,"getDefaultConfig");function gy(e){if(e==null){bt.error(ZY);return}if(Nt===void 0){bt.trace(JY);return}let t=wn[e.toLowerCase()];if(t!==void 0)return Nt[t.toLowerCase()]}a(gy,"getConfigValue");function Wi(e=Lt.getPropsFilePath()){let t=Lt.getEnvCliRootPath();return t?yn.join(t,Ur.HDB_CONFIG_FILE):py(e).get(Ur.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Wi,"getConfigFilePath");function Vm(e=!1){if(Nt===void 0||e){let t;if(!Lt.noBootFile()){t=Lt.getPropsFilePath();try{or.accessSync(t,or.constants.F_OK|or.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Wi(t),n;if(r.includes("config/settings.js"))try{Ay(r);return}catch(i){if(i.code!==Ur.NODE_ERROR_CODES.ENOENT)throw i}try{n=ni(r)}catch(i){if(i.code===Ur.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}nK(n,r),$m(n);let s=n.toJSON();if(zY.config=s,Nt=Ko(s),Nt.logging_rotation_rotate)for(let i in my)Nt[i]&&bt.error(`Config ${my[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(jY)}}a(Vm,"initConfig");function nK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],yn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],yn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],yn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),n&&(bt.trace("Updating config file with missing config params"),or.writeFileSync(t,String(e)))}a(nK,"checkForUpdatedConfig");function $m(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t?.http?.threads&&(t.threads=t?.http?.threads);let r=VY(t);if(r.error)throw C_.CONFIG_VALIDATION(r.error.message);typeof r.value.threads=="object"?e.setIn(["threads","count"],r.value.threads.count):e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a($m,"validateConfig");function sK(e,t){Nt===void 0&&(Nt={});let r=wn[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Nt[r.toLowerCase()]=t}a(sK,"updateConfigObject");function Ry(e,t,r=void 0,n=!1,s=!1,i=!1){Nt===void 0&&Vm();let o=gy(wn.hdb_root),c=yn.join(o,Ur.HDB_CONFIG_FILE),u=ni(c),_;if(r===void 0&&e.toLowerCase()===Dr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=wn[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=km(f,t);u.setIn([...E],h)}else for(let f in r){let E=wn[f.toLowerCase()];if(E===Dr.HTTP_SECUREPORT&&r[f]===Nt[Dr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Dr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===Nt[Dr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Dr.DATABASES){_=r[f];continue}if(E?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Ur.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=km(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(g){bt.error(g)}}}_&&Ty(u,_),$m(u);let l=u.getIn(["rootPath"]),d=yn.join(l,Ur.HDB_CONFIG_FILE);n===!0&&iK(c,l),or.writeFileSync(d,String(u)),s&&(Nt=Ko(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(Ry,"updateConfigValue");function iK(e,t){try{let r=yn.join(t,"backup",`${Ur.HDB_CONFIG_FILE}.bak`);or.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(XY),bt.error(r)}}a(iK,"backupConfigFile");var oK=["databases"];function Ko(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),U_=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])&&!oK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Dr[u.toUpperCase()]&&wn[u]&&(s[wn[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Ko,"flattenConfig");function km(e,t){if(e===Dr.CLUSTERING_NODENAME||e===Dr.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(YY(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Lt.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 Lt.autoCast(t)}a(km,"castConfigValue");function aK(){let e=Lt.getPropsFilePath(),t=Wi(e);return ni(t).toJSON()}a(aK,"getConfiguration");async function cK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return Ry(void 0,void 0,s,!0),eK}catch(i){throw typeof i=="string"||i instanceof String?WY(i,i,QY.BAD_REQUEST,void 0,void 0,!0):i}}a(cK,"setConfiguration");function Ym(){let e=Lt.getPropsFilePath();try{or.accessSync(e,or.constants.F_OK|or.constants.R_OK)}catch(n){if(!Lt.noBootFile())throw bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Wi(e);return ni(t).toJSON()}a(Ym,"readConfigFile");function ni(e){return $Y.parseDocument(or.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ni,"parseYamlDoc");function uK(){let e=Ym(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Lt.isEmptyOrZeroLength(t)?[]:t;let r=hy(t);if(r)throw C_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Lt.isEmptyOrZeroLength(n)?[]:n;let s=hy(n);if(s)throw C_.CONFIG_VALIDATION(s.message);if(!Lt.isEmptyOrZeroLength(n)&&!Lt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Lt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw C_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(uK,"getClusteringRoutes");function Ay(e){let t=py(e);Nt={};for(let r in wn){let n=t.get(r.toUpperCase());if(Lt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=wn[r].toLowerCase();s===Dr.LOGGING_ROOT?Nt[s]=yn.dirname(n):Nt[s]=n}return Nt}a(Ay,"initOldConfig");function lK(e){let t=Ym();return KY.get(t,e.replaceAll("_","."))}a(lK,"getConfigFromFile");async function _K(e,t){let r=ni(Wi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await or.writeFile(Wi(),String(r))}a(_K,"addConfig");function dK(e){let t=Wi(Lt.getPropsFilePath()),r=ni(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=yn.join(n,Ur.HDB_CONFIG_FILE);or.writeFileSync(s,String(r))}a(dK,"deleteConfigFromFile");function fK(){return U_||(Vm(),U_)}a(fK,"getConfigObj")});var Ny=T((vue,by)=>{"use strict";var L_=U(),M_=class{static{a(this,"BaseLicense")}constructor(t=0,r=L_.RAM_ALLOCATION_ENUM.DEFAULT,n=L_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},Km=class extends M_{static{a(this,"ExtendedLicense")}constructor(t=0,r=L_.RAM_ALLOCATION_ENUM.DEFAULT,n=L_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};by.exports={BaseLicense:M_,ExtendedLicense:Km}});var Qi=T((Hue,Uy)=>{"use strict";var Qo=require("fs-extra"),wy=y_(),Iy=require("crypto"),EK=require("moment"),hK=require("uuid").v4,Wt=$(),Qm=require("path"),mK=J(),si=U(),{totalmem:yy}=require("os"),pK=Ny().ExtendedLicense,Wo="invalid license key format",SK="061183",TK="mofi25",gK="aes-256-cbc",RK=16,AK=32,Cy=Z();Cy.initSync();var Wm;Uy.exports={validateLicense:Dy,generateFingerPrint:bK,licenseSearch:jm,getLicense:wK,checkMemoryLimit:IK};function zm(){return Qm.join(Cy.getHdbBasePath(),si.LICENSE_KEY_DIR_NAME,si.LICENSE_FILE_NAME)}a(zm,"getLicenseDirPath");function OK(){let e=zm();return Qm.join(e,si.LICENSE_FILE_NAME)}a(OK,"getLicenseFilePath");function Jm(){let e=zm();return Qm.join(e,si.REG_KEY_FILE_NAME)}a(Jm,"getFingerPrintFilePath");async function bK(){let e=Jm();try{return await Qo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await NK();throw Wt.error(`Error writing fingerprint file to ${e}`),Wt.error(t),new Error("There was an error generating the fingerprint")}}a(bK,"generateFingerPrint");async function NK(){let e=hK(),t=wy.hash(e),r=Jm();try{await Qo.mkdirp(zm()),await Qo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Wt.error(`Error writing fingerprint file to ${r}`),Wt.error(n),new Error("There was an error generating the fingerprint")}return t}a(NK,"writeFingerprint");function Dy(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:si.RAM_ALLOCATION_ENUM.DEFAULT,version:si.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Wt.error("empty license key passed to validate."),r;let n=Jm(),s=!1;try{s=Qo.statSync(n)}catch(i){Wt.error(i)}if(s){let i;try{i=Qo.readFileSync(n,"utf8")}catch{Wt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(TK),c=o[1];c=Buffer.concat([Buffer.from(c)],RK);let u=Buffer.concat([Buffer.from(i)],AK),_=Iy.createDecipheriv(gK,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=yK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Wo),Wt.error(Wo),new Error(Wo)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(Wo),Wt.error(Wo),new Error(Wo)}else r.exp_date=l;r.exp_date<EK().valueOf()&&(r.valid_date=!1),wy.validate(o[1],`${SK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||Wt.error("Invalid licence"),r}a(Dy,"validateLicense");function yK(e,t){try{let r=Iy.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Wt.warn("Check old license failed")}}a(yK,"checkOldLicense");function jm(){let e=new pK,t=[];try{t=Qo.readFileSync(OK(),"utf-8").split(si.NEW_LINE)}catch(r){r.code==="ENOENT"?Wt.info("no license file found"):Wt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(mK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=Dy(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){Wt.error("There was an error parsing the license string."),Wt.error(s),e.ram_allocation=si.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Wm=e,e}a(jm,"licenseSearch");async function wK(){return Wm||await jm(),Wm}a(wK,"getLicense");function IK(){let e=jm().ram_allocation,t=process.constrainedMemory?.()||yy();if(t=Math.round(Math.min(t,yy())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(IK,"checkMemoryLimit")});var tn=T((kue,Wy)=>{"use strict";var vy="username is required",By="nothing to update, must supply active, role or password to update",Hy="password cannot be an empty string",xy="If role is specified, it cannot be empty.",qy="active must be true or false";Wy.exports={addUser:HK,alterUser:xK,dropUser:FK,getSuperUser:$K,userInfo:GK,listUsers:v_,listUsersExternal:kK,setUsersToGlobal:Jo,findAndValidateUser:Yy,getClusterUser:YK,USERNAME_REQUIRED:vy,ALTERUSER_NOTHING_TO_UPDATE:By,EMPTY_PASSWORD:Hy,EMPTY_ROLE:xy,ACTIVE_BOOLEAN:qy};var Fy=Cr(),CK=ri(),ep=y_(),Gy=iy(),ky=en(),tp=Rs(),Mr=J(),Vy=require("validate.js"),Se=$(),{promisify:DK}=require("util"),rp=Ts(),Ly=U(),My=Ge(),UK=Lr(),que=Z(),Fue=Qi(),LK=qi(),{table:Gue}=(Re(),ne(Fe)),{handleHDBError:zn,hdb_errors:MK}=re(),{HTTP_STATUS_CODES:Jn,AUTHENTICATION_ERROR_MSGS:Xm,HDB_ERROR_MSGS:zo}=MK,{UserEventMsg:np}=In(),Zm=require("lodash"),{server:sp}=(rr(),ne(Pi)),PK=$();sp.getUser=(e,t)=>Yy(e,t,t!=null);var $y={username:!0,active:!0,role:!0,password:!0},Py=new Map,P_=ky.searchByValue,vK=ky.searchByHash,BK=DK(CK.delete);async function HK(e){let t=Vy.cleanAttributes(e,$y),r=Gy.addUserValidation(t);if(r)throw zn(new Error,r.message,Jn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await P_(n),s=s&&Array.from(s)}catch(u){throw Se.error("There was an error searching for a role in add user"),Se.error(u),u}if(!s||s.length<1)throw zn(new Error,zo.ROLE_NAME_NOT_FOUND(t.role),Jn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw zn(new Error,zo.DUP_ROLES_FOUND(t.role),Jn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=rp.encrypt(t.password)),t.password=ep.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await Fy.insert(i)}catch(u){throw Se.error("There was an error searching for a user."),Se.error(u),u}Se.debug(o);try{await Jo()}catch(u){throw Se.error("Got an error setting users to global"),Se.error(u),u}if(o.skipped_hashes.length===1)throw zn(new Error,zo.USER_ALREADY_EXISTS(t.username),Jn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],tp.signalUserChange(new np(process.pid)),`${c.username} successfully added`}a(HK,"addUser");async function xK(e){let t=Vy.cleanAttributes(e,$y);if(Mr.isEmptyOrZeroLength(t.username))throw new Error(vy);if(Mr.isEmptyOrZeroLength(t.password)&&Mr.isEmptyOrZeroLength(t.role)&&Mr.isEmptyOrZeroLength(t.active))throw new Error(By);if(!Mr.isEmpty(t.password)&&Mr.isEmptyOrZeroLength(t.password.trim()))throw new Error(Hy);if(!Mr.isEmpty(t.active)&&!Mr.isBoolean(t.active))throw new Error(qy);let r=qK(t.username);if(!Mr.isEmpty(t.password)&&!Mr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=rp.encrypt(t.password)),t.password=ep.hash(t.password)),t.role==="")throw new Error(xy);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await P_(i)||[])}catch(c){throw Se.error("Got an error searching for a role."),Se.error(c),c}if(!o||o.length===0){let c=zo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Se.error(c),zn(new Error,c,Jn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=zo.ALTER_USER_DUP_ROLES(t.role);throw Se.error(c),zn(new Error,c,Jn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await Fy.update(n)}catch(i){throw Se.error("Error during update."),Se.error(i),i}try{await Jo()}catch(i){throw Se.error("Got an error setting users to global"),Se.error(i),i}return tp.signalUserChange(new np(process.pid)),s}a(xK,"alterUser");function qK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(qK,"isClusterUser");async function FK(e){try{let t=Gy.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Mr.isEmpty(global.hdb_users.get(e.username)))throw zn(new Error,zo.USER_NOT_EXIST(e.username),Jn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await BK(r)}catch(s){throw Se.error("Got an error deleting a user."),Se.error(s),s}Se.debug(n);try{await Jo()}catch(s){throw Se.error("Got an error setting users to global."),Se.error(s),s}return tp.signalUserChange(new np(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(FK,"dropUser");async function GK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Zm.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await vK(r)}catch(s){throw Se.error("Got an error searching for a role."),Se.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Se.error(r),r}return t}a(GK,"userInfo");async function kK(){let e;try{e=await v_()}catch(t){throw Se.error("Got an error listing users."),Se.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(kK,"listUsersExternal");async function v_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await P_(e)}catch(o){throw Se.error("Got an error searching for roles."),Se.error(o),o}let r={};for(let o of t)r[o.id]=Zm.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await P_(n)}catch(o){throw Se.error("Got an error searching for users."),Se.error(o),o}let i=new Map;for(let o of s)o=Zm.cloneDeep(o),o.role=r[o.role],VK(o.role),i.set(o.username,o);return i}catch(e){throw Se.error("got an error listing users"),Se.error(e),Mr.errorizeMessage(e)}return null}a(v_,"listUsers");function VK(e){try{if(!e){Se.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(LK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Se.error("Got an error trying to set system permissions."),Se.error(t)}}a(VK,"appendSystemTablesToRole");async function Jo(){try{let e=await v_();global.hdb_users=e}catch(e){throw Se.error(e),e}}a(Jo,"setUsersToGlobal");async function Yy(e,t,r=!0){global.hdb_users||await Jo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw zn(new Error,Xm.GENERIC_AUTH_FAIL,Jn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw zn(new Error,Xm.USER_INACTIVE,Jn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(Py.get(t)===n.password)return s;if(ep.validate(n.password,t))Py.set(t,n.password);else throw zn(new Error,Xm.GENERIC_AUTH_FAIL,Jn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(Yy,"findAndValidateUser");async function $K(){global.hdb_users||await Jo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a($K,"getSuperUser");async function YK(){let e=await v_(),t=UK.getConfigFromFile(Ly.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Mr.isEmpty(r)&&r?.role?.role===Ly.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=rp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+My.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+My.SERVER_SUFFIX.ADMIN,r}a(YK,"getClusterUser");var Ky=[];sp.invalidateUser=function(e){for(let t of Ky)try{t(e)}catch(r){PK.error("Error invalidating user",r)}};sp.onInvalidatedUser=function(e){Ky.push(e)}});var qc=T((Kue,jy)=>{"use strict";var zi=$(),Pr=U(),KK=yN(),$ue=gs(),Yue=Zs(),WK=tn(),{validateEvent:Qy}=In(),xc=Nn(),QK=require("process"),{resetDatabases:zK}=(Re(),ne(Fe)),JK={[Pr.ITC_EVENT_TYPES.SCHEMA]:jK,[Pr.ITC_EVENT_TYPES.USER]:Jy};async function jK(e){let t=Qy(e);if(t){zi.error(t);return}zi.trace("ITC schemaHandler received schema event:",e),await KK(e.message),await XK(e.message)}a(jK,"schemaHandler");async function XK(e){try{xc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),xc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),xc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=zK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){zi.error(t)}}a(XK,"syncSchemaMetadata");var zy=[];async function Jy(e){try{try{xc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),xc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){zi.warn(r)}let t=Qy(e);if(t){zi.error(t);return}zi.trace(`ITC userHandler ${Pr.HDB_ITC_CLIENT_PREFIX}${QK.pid} received user event:`,e),await WK.setUsersToGlobal();for(let r of zy)r()}catch(t){zi.error(t)}}a(Jy,"userHandler");Jy.addListener=function(e){zy.push(e)};jy.exports=JK});var In=T((Xue,Zy)=>{"use strict";var Que=$(),ip=J(),ZK=U(),{ITC_ERRORS:Fc}=Nr(),{parentPort:zue,threadId:eW,isMainThread:tW,workerData:Jue}=require("worker_threads"),{onMessageFromWorkers:rW,broadcast:jue,broadcastWithAcknowledgement:nW}=We();Zy.exports={sendItcEvent:sW,validateEvent:Xy,SchemaEventMsg:iW,UserEventMsg:oW};var B_;rW(async(e,t)=>{B_=B_||qc(),Xy(e),B_[e.type]&&await B_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function sW(e){return!tW&&e.message&&(e.message.originator=eW),nW(e)}a(sW,"sendItcEvent");function Xy(e){if(typeof e!="object")return Fc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||ip.isEmpty(e.type))return Fc.MISSING_TYPE;if(!e.hasOwnProperty("message")||ip.isEmpty(e.message))return Fc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||ip.isEmpty(e.message.originator))return Fc.MISSING_ORIGIN;if(ZK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Fc.INVALID_EVENT(e.type)}a(Xy,"validateEvent");function iW(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(iW,"SchemaEventMsg");function oW(e){this.originator=e}a(oW,"UserEventMsg")});var Rs=T((tle,nw)=>{"use strict";var ew=U(),ele=J(),H_=$(),tw=ON(),jo,{sendItcEvent:rw}=In();function aW(e){try{H_.trace("signalSchemaChange called with message:",e),jo=jo||qc();let t=new tw(ew.ITC_EVENT_TYPES.SCHEMA,e);return jo.schema(t),rw(t)}catch(t){H_.error(t)}}a(aW,"signalSchemaChange");function cW(e){try{H_.trace("signalUserChange called with message:",e),jo=jo||qc();let t=new tw(ew.ITC_EVENT_TYPES.USER,e);return jo.user(t),rw(t)}catch(t){H_.error(t)}}a(cW,"signalUserChange");nw.exports={signalSchemaChange:aW,signalUserChange:cW}});var x_=T((nle,iw)=>{"use strict";var sw=J(),uW=U(),lW=$(),_W=h_(),dW=E_(),fW=Rs(),{SchemaEventMsg:EW}=In(),hW="already exists in";iw.exports=mW;async function mW(e,t,r){if(sw.isEmptyOrZeroLength(r))return r;let n=[];sw.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await pW(e,t.schema,t.name,i)})),s}a(mW,"lmdbCheckForNewAttributes");async function pW(e,t,r,n){let s=new dW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await SW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(hW))lW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(pW,"createNewAttribute");async function SW(e){let t;return t=await _W(e),fW.signalSchemaChange(new EW(process.pid,uW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(SW,"createAttribute")});var Xo=T((ile,ow)=>{"use strict";var op=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};ow.exports=op});var cw=T((ale,aw)=>{"use strict";var TW=Xo(),gW=U().OPERATIONS_ENUM,ap=class extends TW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(gW.INSERT,r,n,s,i),this.records=t}};aw.exports=ap});var lw=T((ule,uw)=>{"use strict";var RW=Xo(),AW=U().OPERATIONS_ENUM,cp=class extends RW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(AW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};uw.exports=cp});var dw=T((_le,_w)=>{"use strict";var OW=Xo(),bW=U().OPERATIONS_ENUM,up=class extends OW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(bW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};_w.exports=up});var Ew=T((fle,fw)=>{"use strict";var NW=Xo(),yW=U().OPERATIONS_ENUM,lp=class extends NW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(yW.DELETE,n,s,t,i),this.original_records=r}};fw.exports=lp});var Gc=T((mle,Sw)=>{"use strict";var hle=require("path"),hw=Qe(),wW=cw(),IW=lw(),CW=dw(),DW=Ew(),Zo=ft(),mw=J(),{CONFIG_PARAMS:UW}=U(),pw=Z();pw.initSync();var q_=U().OPERATIONS_ENUM,{getTransactionAuditStorePath:LW}=je();Sw.exports=MW;async function MW(e,t){if(pw.get(UW.LOGGING_AUDITLOG)===!1)return;let r=LW(e.schema,e.table),n=await hw.openEnvironment(r,e.table,!0),s=PW(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){hw.initializeDBIs(n,Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Zo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),mw.isEmpty(s.user_name)||n.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(MW,"writeTransaction");function PW(e,t){let r=mw.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===q_.INSERT)return new wW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.UPDATE)return new IW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.UPSERT)return new CW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.DELETE)return new DW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(PW,"createTransactionObject")});var _p=T((Tle,Tw)=>{"use strict";var vW=Cc(),Sle=Dc(),kc=U(),BW=Pc(),HW=Vo().insertRecords,xW=Qe(),qW=$(),FW=x_(),{getSchemaPath:GW}=je(),kW=Gc();Tw.exports=VW;async function VW(e){try{let{schema_table:t,attributes:r}=vW(e);BW(e,r,t.hash_attribute),e.schema!==kc.SYSTEM_SCHEMA_NAME&&(r.includes(kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await FW(e.hdb_auth_header,t,r),s=GW(e.schema,e.table),i=await xW.openEnvironment(s,e.table),o=await HW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await kW(e,o)}catch(c){qW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(VW,"lmdbCreateRecords")});var Aw=T((Rle,Rw)=>{"use strict";var gw=U(),$W=_p(),YW=Dc(),KW=require("fs-extra"),{getSchemaPath:WW}=je();Rw.exports=QW;async function QW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new YW(gw.SYSTEM_SCHEMA_NAME,gw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await $W(r),await KW.mkdirp(WW(e.schema))}a(QW,"lmdbCreateSchema")});var bw=T((Ole,Ow)=>{"use strict";var dp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};Ow.exports=dp});var Iw=T((Ile,ww)=>{"use strict";var Nw=Qe(),fp=yr(),Ep=Nr().LMDB_ERRORS_ENUM,zW=ft(),yw=$(),Nle=J(),JW=require("lmdb"),jW=bw(),XW=U(),{OVERFLOW_MARKER:yle,MAX_SEARCH_KEY_LENGTH:wle}=zW,ZW=XW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function eQ(e,t,r,n){if(fp.validateEnv(e),t===void 0)throw new Error(Ep.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Ep.IDS_REQUIRED):new Error(Ep.IDS_MUST_BE_ITERABLE);try{let s=Nw.listDBIs(e);Nw.initializeDBIs(e,t,s);let i=new jW,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||n&&h[ZW]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,JW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let g=s[S];if(!h.hasOwnProperty(g)||g===t)continue;let A=e.dbis[g],R=h[g];if(R!=null)try{let v=fp.getIndexedValues(R);if(v)for(let H=0,P=v.length;H<P;H++)A.remove(v[H],o)}catch{yw.warn(`cannot delete from attribute: ${g}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){yw.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=fp.getNextMonotonicTime(),i}catch(s){throw s}}a(eQ,"deleteRecords");ww.exports={deleteRecords:eQ}});var Vc=T((Dle,Dw)=>{"use strict";var ea=J(),tQ=Iw(),rQ=Qe(),{getSchemaPath:nQ}=je(),sQ=Gc(),iQ=$();Dw.exports=oQ;async function oQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ea.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ea.isEmptyOrZeroLength(e.hash_values)&&!ea.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ea.isEmpty(u)||e.hash_values.push(u)}}if(ea.isEmptyOrZeroLength(e.hash_values))return Cw([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ea.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=nQ(e.schema,e.table),i=await rQ.openEnvironment(s,e.table),o=await tQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await sQ(e,o)}catch(c){iQ.error(`unable to write transaction due to ${c.message}`)}return Cw(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(oQ,"lmdbDeleteRecords");function Cw(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(Cw,"createDeleteResponse")});var mp=T((Mle,Uw)=>{"use strict";var aQ=U(),Lle=yr();function hp(e,t){let r=Object.create(null);if(t.length===1&&aQ.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(hp,"parseRow");function cQ(e,t,r,n){let s=hp(r,e);n.push(s)}a(cQ,"searchAll");function uQ(e,t,r,n){let s=hp(r,e);n[t]=s}a(uQ,"searchAllToMap");function lQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(lQ,"iterateDBI");function Ji(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Ji,"pushResults");function _Q(e,t,r,n,s,i){t.toString().endsWith(e)&&Ji(t,r,n,s,i)}a(_Q,"endsWith");function dQ(e,t,r,n,s,i){t.toString().includes(e)&&Ji(t,r,n,s,i)}a(dQ,"contains");function fQ(e,t,r,n,s,i){t>e&&Ji(t,r,n,s,i)}a(fQ,"greaterThanCompare");function EQ(e,t,r,n,s,i){t>=e&&Ji(t,r,n,s,i)}a(EQ,"greaterThanEqualCompare");function hQ(e,t,r,n,s,i){t<e&&Ji(t,r,n,s,i)}a(hQ,"lessThanCompare");function mQ(e,t,r,n,s,i){t<=e&&Ji(t,r,n,s,i)}a(mQ,"lessThanEqualCompare");Uw.exports={parseRow:hp,searchAll:cQ,searchAllToMap:uQ,iterateDBI:lQ,endsWith:_Q,contains:dQ,greaterThanCompare:fQ,greaterThanEqualCompare:EQ,lessThanCompare:hQ,lessThanEqualCompare:mQ,pushResults:Ji}});var ta=T((xle,xw)=>{"use strict";var ii=Qe(),vle=$(),vr=yr(),F_=ft(),lt=Nr().LMDB_ERRORS_ENUM,Ble=J(),pQ=U(),G_=mp(),{parseRow:SQ}=G_,Hle=require("lmdb"),{OVERFLOW_MARKER:Lw,MAX_SEARCH_KEY_LENGTH:TQ}=F_;function Mw(e,t,r,n=!1,s=void 0,i=void 0){return ji(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(Mw,"iterateFullIndex");function $c(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return ji(e,t,r,(l,d,f,E)=>{let A={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(A.values=!1,d.getRange(A).map(R=>({value:R}))):d.getRange(A)})}a($c,"iterateRangeBetween");function ji(e,t,r,n){let s=e.database||e,i=ii.openDBI(s,r);i[F_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ii.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(ji,"setupTransaction");function Pw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(Lw)){if(!s)if(r)s=ii.openDBI(e,r);else{let u=ii.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ii.openDBI(e,u[_]),!s[F_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(Pw,"getOverflowCheck");function gQ(e,t,r,n=!1,s=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return ji(e,t,t,(o,c,u)=>(k_(r),r=Yc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>SQ(_.value,r))))}a(gQ,"searchAll");function RQ(e,t,r,n=!1,s=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);k_(r),r=Yc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of Mw(e,t,t,n,s,i))o.set(c,G_.parseRow(u,r));return o}a(RQ,"searchAllToMap");function AQ(e,t,r=!1,n=void 0,s=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=Mw(e,void 0,t,r,n,s),c=o.transaction,u=Pw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(AQ,"iterateDBI");function OQ(e,t){if(vr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return ii.statDBI(e,t).entryCount}a(OQ,"countAll");function bQ(e,t,r,n,s=!1,i=void 0,o=void 0){return oi(e,r,n),ji(e,t,r,(c,u,_,l)=>(n=vr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(bQ,"equals");function NQ(e,t,r){return oi(e,t,r),ii.openDBI(e,t).getValuesCount(r)}a(NQ,"count");function yQ(e,t,r,n,s=!1,i=void 0,o=void 0){return oi(e,r,n),ji(e,null,r,(c,u)=>{n=vr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(yQ,"startsWith");function wQ(e,t,r,n,s=!1,i=void 0,o=void 0){return vw(e,t,r,n,s,i,o,!0)}a(wQ,"endsWith");function vw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return oi(e,r,n),ji(e,null,r,(u,_,l,d)=>{let f=Pw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(Lw)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[F_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(vw,"contains");function IQ(e,t,r,n,s=!1,i=void 0,o=void 0){oi(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),$c(e,t,r,n,u,s,i,o,!0,!1)}a(IQ,"greaterThan");function CQ(e,t,r,n,s=!1,i=void 0,o=void 0){oi(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),$c(e,t,r,n,u,s,i,o,!1,!1)}a(CQ,"greaterThanEqual");function DQ(e,t,r,n,s=!1,i=void 0,o=void 0){oi(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),$c(e,t,r,u,n,s,i,o,!1,!0)}a(DQ,"lessThan");function UQ(e,t,r,n,s=!1,i=void 0,o=void 0){oi(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),$c(e,t,r,u,n,s,i,o,!1,!1)}a(UQ,"lessThanEqual");function LQ(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(vr.validateEnv(e),r===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(lt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(lt.END_VALUE_REQUIRED);if(n=vr.convertKeyValueToWrite(n),s=vr.convertKeyValueToWrite(s),n>s)throw new Error(lt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return $c(e,t,r,n,s,i,o,c)}a(LQ,"between");function MQ(e,t,r,n){vr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(k_(r),r=Yc(s,r),n===void 0)throw new Error(lt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=G_.parseRow(c,r)),o}a(MQ,"searchByHash");function PQ(e,t,r){vr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(PQ,"checkHashExists");function vQ(e,t,r,n,s=[]){return Hw(e,t,r,n,s),Bw(e,t,r,n,s).map(i=>i[1])}a(vQ,"batchSearchByHash");function BQ(e,t,r,n,s=[]){Hw(e,t,r,n,s);let i=new Map;for(let[o,c]of Bw(e,t,r,n,s))i.set(o,c);return i}a(BQ,"batchSearchByHashToMap");function Bw(e,t,r,n,s=[]){return ji(e,t,t,(i,o,c)=>{r=Yc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,G_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(Bw,"batchHashSearch");function Hw(e,t,r,n,s){if(vr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(k_(r),n==null)throw new Error(lt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(lt.IDS_MUST_BE_ITERABLE)}a(Hw,"initializeBatchSearchByHash");function k_(e){if(!Array.isArray(e))throw e===void 0?new Error(lt.FETCH_ATTRIBUTES_REQUIRED):new Error(lt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(k_,"validateFetchAttributes");function oi(e,t,r){if(vr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.SEARCH_VALUE_REQUIRED);if(r?.length>TQ)throw new Error(lt.SEARCH_VALUE_TOO_LARGE)}a(oi,"validateComparisonFunctions");function Yc(e,t){return t.length===1&&pQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ii.listDBIs(e)),t}a(Yc,"setGetWholeRowAttributes");xw.exports={searchAll:gQ,searchAllToMap:RQ,count:NQ,countAll:OQ,equals:bQ,startsWith:yQ,endsWith:wQ,contains:vw,searchByHash:MQ,setGetWholeRowAttributes:Yc,batchSearchByHash:vQ,batchSearchByHashToMap:BQ,checkHashExists:PQ,iterateDBI:AQ,greaterThan:IQ,greaterThanEqual:CQ,lessThan:DQ,lessThanEqual:UQ,between:LQ}});var ra=T((Fle,Vw)=>{var qw=require("lodash"),Fw=Xe(),fe=require("joi"),HQ=J(),{hdb_schema_table:Kc,checkValidTable:Gw,hdb_table:kw,hdb_database:V_}=Kn(),{handleHDBError:xQ,hdb_errors:qQ}=re(),{getDatabases:FQ}=(Re(),ne(Fe)),{HTTP_STATUS_CODES:GQ}=qQ,kQ=fe.object({database:V_,schema:V_,table:kw,search_attribute:Kc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(Kc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),VQ=fe.object({database:V_,schema:V_,table:kw,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives(Kc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(Kc,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives(Kc,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});Vw.exports=function(e,t){let r=null;switch(t){case"value":r=Fw.validateBySchema(e,kQ);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(Gw("database",e.schema)),i(Gw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=Fw.validateBySchema(e,VQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=HQ.checkGlobalSchemaTable(e.schema,e.table);if(s)return xQ(new Error,s,GQ.NOT_FOUND);let o=FQ()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=qw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!qw.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var pp=T((kle,$w)=>{"use strict";var $Q=Qe(),YQ=ra(),{getSchemaPath:KQ}=je();$w.exports=WQ;function WQ(e){let t=YQ(e,"hashes");if(t)throw t;let r=KQ(e.schema,e.table);return $Q.openEnvironment(r,e.table)}a(WQ,"initialize")});var Sp=T(($le,Yw)=>{"use strict";var QQ=ta(),zQ=pp();Yw.exports=JQ;async function JQ(e){let t=await zQ(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return QQ.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(JQ,"lmdbGetDataByHash")});var na=T((Kle,Kw)=>{"use strict";var Tp=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};Kw.exports=Tp});var Qw=T((zle,Ww)=>{"use strict";var Qle=na(),jQ=ta(),XQ=pp();Ww.exports=ZQ;async function ZQ(e){let t=await XQ(e),r=global.hdb_schema[e.schema][e.table];return jQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(ZQ,"lmdbSearchByHash")});var jn=T((jle,zw)=>{"use strict";var gp=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};zw.exports=gp});var $_=T((Zle,tI)=>{"use strict";var Qt=ta(),ez=Qe(),tz=J(),Ee=ft(),Xi=U(),rz=qi(),Jw=Nr().LMDB_ERRORS_ENUM,{getSchemaPath:nz}=je(),As=Xi.SEARCH_WILDCARDS;async function sz(e,t,r){let n;e.schema===Xi.SYSTEM_SCHEMA_NAME?n=rz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=eI(e,n.hash_attribute,r,t);return Xw(e,s,n.hash_attribute,r)}a(sz,"prepSearch");async function Xw(e,t,r,n){let s=nz(e.schema,e.table),i=await ez.openEnvironment(s,e.table),o=Zw(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(iz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?jw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?jw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Qt.batchSearchByHashToMap(c,r,e.get_attributes,_):Qt.batchSearchByHash(c,r,e.get_attributes,_)}a(Xw,"executeSearch");function Zw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=Qt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=Qt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=Qt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=Qt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Qt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Qt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Qt.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Qt.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=Qt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=Qt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Qt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=Qt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=Qt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Zw,"searchByType");function jw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(jw,"createMapFromIterable");function iz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(iz,"checkToFetchMore");function eI(e,t,r,n){if(tz.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),As.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(As[0])<0&&s.indexOf(As[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(As.indexOf(i)>=0&&As.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(As.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(As.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(As[0])||s.includes(As[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(Jw.UNKNOWN_SEARCH_TYPE)}else switch(n){case Xi.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case Xi.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case Xi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case Xi.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case Xi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Jw.UNKNOWN_SEARCH_TYPE)}}a(eI,"createSearchTypeFromSearchObject");tI.exports={executeSearch:Xw,createSearchTypeFromSearchObject:eI,prepSearch:sz,searchByType:Zw}});var nI=T((r_e,rI)=>{"use strict";var t_e=jn(),oz=ra(),az=J(),cz=U(),uz=$_();rI.exports=lz;function lz(e,t){if(!az.isEmpty(t)&&cz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=oz(e,"value");if(n)throw n;return uz.prepSearch(e,t,!0)}a(lz,"lmdbGetDataByValue")});var Wc=T((i_e,sI)=>{"use strict";var s_e=jn(),_z=ra(),dz=J(),fz=U(),Ez=$_();sI.exports=hz;async function hz(e,t){if(!dz.isEmpty(t)&&fz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=_z(e,"value");if(n)throw n;return Ez.prepSearch(e,t,!1)}a(hz,"lmdbSearchByValue")});var oI=T((c_e,iI)=>{"use strict";var a_e=ft(),Rp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},Ap=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Op=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};iI.exports={SearchByConditionsObject:Rp,SearchCondition:Ap,SortAttribute:Op}});var _I=T((d_e,lI)=>{"use strict";var l_e=oI().SearchByConditionsObject,mz=jn(),pz=ra(),bp=ta(),Y_=ft(),{Resource:__e}=(An(),ne(Np)),uI=$_(),Sz=mp(),Tz=require("lodash"),{getSchemaPath:gz}=je(),aI=Qe(),{handleHDBError:Rz,hdb_errors:Az}=re(),{HTTP_STATUS_CODES:Oz}=Az,bz=1e8;lI.exports=Nz;async function Nz(e){let t=pz(e,"conditions");if(t)throw Rz(t,t.message,Oz.BAD_REQUEST,void 0,void 0,!0);e.operator=e.operator?e.operator.toLowerCase():void 0,e.offset=Number.isInteger(e.offset)?e.offset:0;let r=gz(e.schema,e.table),n=await aI.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)aI.openDBI(n,_.search_attribute);let i=Tz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===Y_.SEARCH_TYPES.EQUALS?_.estimated_count=bp.count(n,_.search_attribute,_.search_value):l===Y_.SEARCH_TYPES.CONTAINS||l===Y_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=bz}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await cI(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(uI.filterByType),d=l.length,f=bp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>Sz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await cI(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=bp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Nz,"lmdbSearchByConditions");async function cI(e,t,r,n){let s=new mz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===Y_.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,uI.searchByType(e,s,i,n).map(o=>o.value)}a(cI,"executeConditionSearch")});var sa=T((E_e,dI)=>{"use strict";var yz=U().OPERATIONS_ENUM,yp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=yz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};dI.exports=yp});var wp=T((m_e,gI)=>{"use strict";var mI=jn(),pI=sa(),SI=Wc(),TI=Vc(),ar=U(),fI=J(),EI=Qe(),{getTransactionAuditStorePath:wz,getSchemaPath:Iz}=je(),hI=$();gI.exports=Cz;async function Cz(e){try{if(fI.isEmpty(global.hdb_schema[e.schema])||fI.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await Dz(e),await Uz(e);let t=Iz(e.schema,e.table);try{await EI.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")hI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=wz(e.schema,e.table);await EI.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")hI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Cz,"lmdbDropTable");async function Dz(e){let t=new mI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await SI(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new pI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await TI(s)}a(Dz,"deleteAttributesFromSystem");async function Uz(e){let t=new mI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await SI(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new pI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await TI(s)}catch(i){throw i}}a(Uz,"dropTableFromSystem")});var AI=T((S_e,RI)=>{"use strict";var Lz=require("fs-extra"),Mz=jn(),Pz=na(),vz=sa(),Bz=wp(),Hz=Vc(),xz=Sp(),qz=Wc(),Os=U(),{getSchemaPath:Fz}=je(),{handleHDBError:Gz,hdb_errors:kz}=re(),{HDB_ERROR_MSGS:Vz,HTTP_STATUS_CODES:$z}=kz;RI.exports=Yz;async function Yz(e){let t;try{t=await Kz(e.schema);let r=new Mz(Os.SYSTEM_SCHEMA_NAME,Os.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await qz(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await Bz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new vz(Os.SYSTEM_SCHEMA_NAME,Os.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Hz(s);let i=Fz(t);await Lz.remove(i)}catch(r){throw r}}a(Yz,"lmdbDropSchema");async function Kz(e){let t=new Pz(Os.SYSTEM_SCHEMA_NAME,Os.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await xz(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw Gz(new Error,Vz.SCHEMA_NOT_FOUND(e),$z.NOT_FOUND,void 0,void 0,!0);return n}a(Kz,"validateDropSchema")});var K_=T((g_e,OI)=>{"use strict";var Ip=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};OI.exports=Ip});var NI=T((O_e,bI)=>{"use strict";var Wz=require("fs-extra"),W_=Qe(),{getTransactionAuditStorePath:Qz}=je(),Cp=ft(),A_e=K_();bI.exports=zz;async function zz(e){let t;try{let r=Qz(e.schema,e.table);await Wz.mkdirp(r),t=await W_.createEnvironment(r,e.table,!0)}catch(r){throw r.message=`unable to create transactions audit environment for ${e.schema}.${e.table} due to: ${r.message}`,r}try{W_.createDBI(t,Cp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),W_.createDBI(t,Cp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),W_.createDBI(t,Cp.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(zz,"createTransactionsAuditEnvironment")});var CI=T((N_e,II)=>{"use strict";var Dp=U(),yI=Qe(),Jz=Vo(),{getSystemSchemaPath:jz,getSchemaPath:Xz}=je(),Zz=qi(),eJ=h_(),Up=E_(),tJ=$(),rJ=NI(),Mp=Zz.hdb_table,wI=[];for(let e=0;e<Mp.attributes.length;e++)wI.push(Mp.attributes[e].attribute);II.exports=nJ;async function nJ(e,t){let r=Xz(t.schema,t.table),n=new Up(t.schema,t.table,Dp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Up(t.schema,t.table,Dp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Up(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await yI.createEnvironment(r,t.table),e!==void 0){let o=await yI.openEnvironment(jz(),Dp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Jz.insertRecords(o,Mp.hash_attribute,wI,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Lp(n),await Lp(s),await Lp(i)}await rJ(t)}catch(o){throw o}}a(nJ,"lmdbCreateTable");async function Lp(e){try{await eJ(e)}catch(t){tJ.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Lp,"createAttribute")});var UI=T((w_e,DI)=>{"use strict";var sJ=Cc(),iJ=Pc(),oJ=x_(),Qc=U(),aJ=Vo().updateRecords,cJ=Qe(),{getSchemaPath:uJ}=je(),lJ=Gc(),_J=$();DI.exports=dJ;async function dJ(e){try{let{schema_table:t,attributes:r}=sJ(e);iJ(e,r,t.hash_attribute),e.schema!==Qc.SYSTEM_SCHEMA_NAME&&(r.includes(Qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await oJ(e.hdb_auth_header,t,r),s=uJ(e.schema,e.table),i=await cJ.openEnvironment(s,e.table),o=await aJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await lJ(e,o)}catch(c){_J.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(dJ,"lmdbUpdateRecords")});var MI=T((C_e,LI)=>{"use strict";var fJ=U().OPERATIONS_ENUM,Pp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=fJ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};LI.exports=Pp});var vI=T((L_e,PI)=>{"use strict";var U_e=MI(),EJ=Cc(),hJ=Pc(),mJ=x_(),zc=U(),pJ=Vo().upsertRecords,SJ=Qe(),{getSchemaPath:TJ}=je(),gJ=Gc(),RJ=$(),{handleHDBError:AJ,hdb_errors:OJ}=re();PI.exports=bJ;async function bJ(e){let t;try{t=EJ(e)}catch(u){throw AJ(u,u.message,OJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;hJ(e,n,r.hash_attribute),e.schema!==zc.SYSTEM_SCHEMA_NAME&&(n.includes(zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await mJ(e.hdb_auth_header,r,n),i=TJ(e.schema,e.table),o=await SJ.openEnvironment(i,e.table),c=await pJ(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await gJ(e,c)}catch(u){RJ.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(bJ,"lmdbUpsertRecords")});var HI=T((P_e,BI)=>{"use strict";var vp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};BI.exports=vp});var qI=T((B_e,xI)=>{"use strict";var Bp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};xI.exports=Bp});var kI=T((q_e,GI)=>{"use strict";var Hp=Qe(),{getTransactionAuditStorePath:NJ}=je(),x_e=HI(),Jc=ft(),yJ=J(),FI=qI(),wJ=require("util").promisify,IJ=wJ(setTimeout),CJ=1e4,DJ=100;GI.exports=UJ;async function UJ(e){let t=NJ(e.schema,e.table),r=await Hp.openEnvironment(t,e.table,!0),n=Hp.listDBIs(r);Hp.initializeDBIs(r,Jc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new FI;do s=await LJ(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await IJ(DJ);while(s.transactions_deleted>0);return i}a(UJ,"deleteAuditLogsBefore");async function LJ(e,t){let r=new FI;try{let n=e.dbis[Jc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[Jc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];yJ.isEmpty(c)||(s=e.dbis[Jc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[Jc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>CJ)break}return await s,r}catch(n){throw n}}a(LJ,"deleteTransactions")});var $I=T((G_e,VI)=>{"use strict";var xp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};VI.exports=xp});var KI=T(($_e,YI)=>{"use strict";var MJ=jn(),PJ=sa(),V_e=$I(),Xn=U(),vJ=J(),qp=Qe(),BJ=qi(),HJ=Wc(),xJ=Vc(),{getSchemaPath:qJ}=je();YI.exports=FJ;async function FJ(e,t=!0){let r;e.schema===Xn.SYSTEM_SCHEMA_NAME?r=BJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await kJ(e),s=qJ(e.schema,e.table),i=await qp.openEnvironment(s,e.table);return t===!0&&await GJ(e,i,r.hash_attribute),qp.dropDBI(i,e.attribute),n}a(FJ,"lmdbDropAttribute");async function GJ(e,t,r){let n=qp.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(GJ,"removeAttributeFromAllObjects");async function kJ(e){let t=new MJ(Xn.SYSTEM_SCHEMA_NAME,Xn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Xn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Xn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Xn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await HJ(t)).filter(o=>o[Xn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(vJ.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[Xn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new PJ(Xn.SYSTEM_SCHEMA_NAME,Xn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return xJ(i)}a(kJ,"dropAttributeFromSystem")});var XI=T((W_e,jI)=>{"use strict";var Fp=Qe(),ia=ft(),K_e=yr(),Gp=U(),WI=J(),{getTransactionAuditStorePath:VJ}=je(),$J=ta(),Q_=Xo(),YJ=$();jI.exports=KJ;async function KJ(e){let t=VJ(e.schema,e.table),r=await Fp.openEnvironment(t,e.table,!0),n=Fp.listDBIs(r);Fp.initializeDBIs(r,ia.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case Gp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return QI(r,e.search_values);case Gp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,QJ(r,e.search_values,s);case Gp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return WJ(r,e.search_values);default:return QI(r)}}a(KJ,"readAuditLog");function QI(e,t=[0,Date.now()]){WI.isEmpty(t[0])&&(t[0]=0),WI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[ia.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new Q_,s))}a(QI,"searchTransactionsByTimestamp");function WJ(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[ia.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,JI(e,i))}return Object.fromEntries(r)}a(WJ,"searchTransactionsByUsername");function QJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=$J.equals(e,ia.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ia.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=JI(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);zI(u,"records",r,l,o),zI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(QJ,"searchTransactionsByHashValues");function zI(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new Q_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new Q_(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(zI,"loopRecords");function JI(e,t){let r=[];try{let n=e.dbis[ia.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new Q_,i);r.push(o)}}catch(i){YJ.warn(i)}return r}catch(n){throw n}}a(JI,"batchSearchTransactions")});var eC=T((j_e,ZI)=>{"use strict";var{getSchemaPath:z_e}=je(),J_e=Qe(),{database:zJ}=(Re(),ne(Fe));ZI.exports={writeTransaction:JJ};async function JJ(e,t,r){return zJ({database:e,table:t}).transaction(r)}a(JJ,"writeTransaction")});var sC=T((Z_e,nC)=>{"use strict";var{getSchemaPath:tC}=je(),rC=Qe();nC.exports={flush:jJ,resetReadTxn:XJ};async function jJ(e,t){return(await rC.openEnvironment(tC(e,t),t.toString())).flushed}a(jJ,"flush");async function XJ(e,t){try{(await rC.openEnvironment(tC(e,t),t.toString())).resetReadTxn()}catch{}}a(XJ,"resetReadTxn")});var cC=T((tde,aC)=>{"use strict";var{Readable:ZJ}=require("stream"),{getDatabases:e2}=(Re(),ne(Fe)),{readSync:t2,openSync:r2,createReadStream:iC}=require("fs"),{open:n2}=require("lmdb"),oC=s_(),s2=o_(),{AUDIT_STORE_OPTIONS:i2}=(Hi(),ne(uC)),{INTERNAL_DBIS_NAME:o2,AUDIT_STORE_NAME:a2}=ft();aC.exports=u2;var kp=32768,c2=100;async function u2(e){let t=e.database||e.schema||"data",r=e2()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=n2({noSync:!0,maxDbs:s2.MAX_DBS}),f,E=d.openDB(o2,new oC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(A,R){R.encoding="binary",R.encoder=void 0;let v=d.openDB(A,R),H=l.openDB(A,R);for(let{key:P,version:M,value:K}of H.getRange({transaction:h,versions:H.useVersions}))f=v.put(P,K,M),p++%c2===0&&(await new Promise(W=>setTimeout(W,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:R}of l.getRange({transaction:h,start:!1}))if(s.some(v=>A.startsWith?.(v+"/"))){E.put(A,R);let[,v]=A.split("/"),H=!v,P=new oC(!H,H);await S(A,P)}e.include_audit&&await S(a2,Object.assign({},i2)),await f;let g=iC(d.path);return g.headers=u(),g.on("close",()=>{h.done(),d.close()}),g}let o=r[Object.keys(r)[0]].primaryStore,c=r2(o.path);return o.transaction(()=>{let _=Buffer.alloc(kp);t2(c,_,0,kp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=iC(null,{fd:c,start:kp}),f=new ZJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(u2,"getBackup")});var dC=T((nde,_C)=>{"use strict";var l2=$(),{handleHDBError:_2}=re(),d2=yb(),f2=h_(),E2=_p(),h2=Aw(),m2=Vc(),p2=Sp(),S2=Qw(),T2=nI(),g2=Wc(),R2=_I(),A2=AI(),O2=CI(),b2=UI(),N2=vI(),y2=kI(),w2=wp(),I2=KI(),C2=XI(),D2=eC(),lC=sC(),U2=cC(),Vp=class extends d2{static{a(this,"LMDBBridge")}async searchByConditions(t){return R2(t)}async getDataByHash(t){return await p2(t)}async searchByHash(t){return await S2(t)}async getDataByValue(t,r){return await T2(t,r)}async searchByValue(t){return await g2(t)}async createSchema(t){return await h2(t)}async dropSchema(t){return await A2(t)}async createTable(t,r){return await O2(t,r)}async dropTable(t){return await w2(t)}async createAttribute(t){return await f2(t)}async createRecords(t){return await E2(t)}async updateRecords(t){return await b2(t)}async upsertRecords(t){try{return await N2(t)}catch(r){throw _2(r,null,null,l2.ERR,r)}}async deleteRecords(t){return await m2(t)}async dropAttribute(t){return await I2(t)}async deleteAuditLogsBefore(t){return await y2(t)}async readAuditLog(t){return await C2(t)}writeTransaction(t,r,n){return D2.writeTransaction(t,r,n)}flush(t,r){return lC.flush(t,r)}resetReadTxn(t,r){return lC.resetReadTxn(t,r)}getBackup(t){return U2(t)}};_C.exports=Vp});function B2(){v2=setInterval(function(){for(let e of $p)if(e.stale){let t=e[Ae]?.url;hC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},P2).unref()}var Yp,EC,hC,L2,$p,M2,jc,fC,Zi,z_,P2,v2,Kp=ge(()=>{Yp=x(yr()),EC=x(re()),hC=x($());An();Go();L2=100,$p=new Set,M2=25e3,Zi=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,r_(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),$p.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),r_(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&($p.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(jc&&performance.now()-fC>M2)throw new EC.ServerError("Outstanding write transactions have too long of queue, please try again later",503);if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,Yp.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let g=S();E?E.push?E.push(g):E=[E,g]:E=g}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<L2>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return jc||(jc=s,fC=performance.now(),jc.then(()=>{jc=null})),s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},z_=class extends Zi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Yp.getNextMonotonicTime)())}getReadTxn(){}},P2=3e4;a(B2,"startMonitoringTxns");B2()});function Ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Zi;e.timestamp&&(n.timestamp=e.timestamp),n[Ae]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var mC,eo=ge(()=>{mC=require("../index");An();Kp();a(Ze,"transaction");(0,mC._assignPackageExport)("transaction",Ze);Ze.commit=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ze.abort=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var NC={};Ke(NC,{ResourceBridge:()=>zp});function Jp({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function SC(e,t){let r=Zn(e),n=Jp(e,r);if(!r)throw new Cn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&j_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function Zn(e){let t=e.database||e.schema||x2,r=Dn()[t];if(!r)throw(0,Cn.handleHDBError)(new Error,H2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function TC(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*gC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var RC,J_,Cn,AC,OC,Un,Wp,Qp,bC,H2,x2,q2,F2,pC,zp,yC=ge(()=>{"use strict";RC=x(dC()),J_=x(ra()),Cn=x(re());Re();AC=x(Cc()),OC=x(Pc()),Un=x(U()),Wp=x(Rs()),Qp=x(In()),bC=x(J());eo();X_();({HDB_ERROR_MSGS:H2}=Cn.hdb_errors),x2="data",q2=1e4,F2=10,zp=class extends RC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),pC=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,J_.default)(t,"conditions");if(r)throw(0,Cn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=Zn(t);if(!n)throw new Cn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Jp(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Cn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ut({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await Zn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Zn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Zn(t).dropTable()}createSchema(t){return Xc({database:t.schema,table:null}),Wp.signalSchemaChange(new Qp.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await jp(t.schema),Wp.signalSchemaChange(new Qp.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,pC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,AC.default)(t);(0,OC.default)(t,n,r.primaryKey);let s,i=Dn()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=j_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=Dn()[t.schema][t.table],n={user:t.hdb_user};return Ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return TC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=Dn()[t.schema][t.table];if(!r.createdTimeProperty)throw new Cn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,bC.async_set_timeout)(F2),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%q2===0&&await _();return u.length>0&&await _(),s?TC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,J_.default)(t,"hashes");if(r)throw r;return SC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of SC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,J_.default)(t,"value");if(n)throw n;let s=Zn(t);if(!s)throw new Cn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Un.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Jp(t,s)})}async getDataByValue(t,r){let n=new Map,s=Zn(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){Zn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Zn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Zn(t),n={};switch(t.search_type){case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of gC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return gC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Jp,"getSelect");a(SC,"getRecords");a(Zn,"getTable");a(TC,"createDeleteResponse");a(gC,"groupRecordsInHistory")});var Nn=T((Tde,wC)=>{"use strict";var{ResourceBridge:G2}=(yC(),ne(NC)),k2=Z();k2.initSync();var Z_;function V2(){return Z_||(Z_=new G2,Z_)}a(V2,"getBridge");wC.exports=V2()});var UC=T((Rde,DC)=>{"use strict";var IC=require("lodash"),Zc=require("mathjs"),$2=require("jsonata"),CC=J();DC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?IC.uniqWith(e,IC.isEqual):e,searchJSON:Y2,mad:eu.bind(null,Zc.mad),mean:eu.bind(null,Zc.mean),mode:eu.bind(null,Zc.mode),prod:eu.bind(null,Zc.prod),median:eu.bind(null,Zc.median)};function eu(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(eu,"aggregateFunction");function Y2(e,t){if(typeof e!="string"||e.length===0)throw new Error("search json expression must be a non-empty string");let r="__"+e+"__";if(CC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),CC.isEmpty(this.__ala__.res[r])){let n=$2(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(Y2,"searchJSON")});var MC=T((Ode,LC)=>{"use strict";var ht=require("moment"),Xp="YYYY-MM-DDTHH:mm:ss.SSSZZ";ht.suppressDeprecationWarnings=!0;LC.exports={current_date:()=>ht().utc().format("YYYY-MM-DD"),current_time:()=>ht().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return ht(e).utc().format("YYYY");case"month":return ht(e).utc().format("MM");case"day":return ht(e).utc().format("DD");case"hour":return ht(e).utc().format("HH");case"minute":return ht(e).utc().format("mm");case"second":return ht(e).utc().format("ss");case"millisecond":return ht(e).utc().format("SSS");default:break}},date:e=>ht(e).utc().format(Xp),date_format:(e,t)=>ht(e).utc().format(t),date_add:(e,t,r)=>ht(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>ht(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=ht(e).utc(),s=ht(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>ht().utc().valueOf(),get_server_time:()=>ht().format(Xp),offset_utc:(e,t)=>ht(e).utc().utcOffset(t).format(Xp)}});var HC=T((bde,BC)=>{"use strict";var K2=require("@turf/area"),W2=require("@turf/length"),Q2=require("@turf/circle"),z2=require("@turf/difference"),J2=require("@turf/distance"),j2=require("@turf/boolean-contains"),X2=require("@turf/boolean-equal"),Z2=require("@turf/boolean-disjoint"),e4=require("@turf/helpers"),PC=U(),me=J(),bs=$();BC.exports={geoArea:t4,geoLength:r4,geoCircle:n4,geoDifference:s4,geoDistance:vC,geoNear:i4,geoContains:o4,geoEqual:a4,geoCrosses:c4,geoConvert:u4};function t4(e){if(me.isEmpty(e))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e));try{return K2.default(e)}catch(t){return bs.trace(t,e),NaN}}a(t4,"geoArea");function r4(e,t){if(me.isEmpty(e))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e));try{return W2.default(e,{units:t||"kilometers"})}catch(r){return bs.trace(r,e),NaN}}a(r4,"geoLength");function n4(e,t,r){if(me.isEmpty(e))return NaN;if(me.isEmpty(t))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e));try{return Q2.default(e,t,{units:r||"kilometers"})}catch(n){return bs.trace(n,e,t),NaN}}a(n4,"geoCircle");function s4(e,t){if(me.isEmpty(e))return NaN;if(me.isEmpty(t))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return z2(e,t)}catch(r){return bs.trace(r,e,t),NaN}}a(s4,"geoDifference");function vC(e,t,r){if(me.isEmpty(e))return NaN;if(me.isEmpty(t))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return J2.default(e,t,{units:r||"kilometers"})}catch(n){return bs.trace(n,e,t),NaN}}a(vC,"geoDistance");function i4(e,t,r,n){if(me.isEmpty(e)||me.isEmpty(t))return!1;if(me.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return vC(e,t,n)<=r}catch(s){return bs.trace(s,e,t),!1}}a(i4,"geoNear");function o4(e,t){if(me.isEmpty(e)||me.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return j2.default(e,t)}catch(r){return bs.trace(r,e,t),!1}}a(o4,"geoContains");function a4(e,t){if(me.isEmpty(e)||me.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return X2.default(e,t)}catch(r){return bs.trace(r,e,t),!1}}a(a4,"geoEqual");function c4(e,t){if(me.isEmpty(e)||me.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return!Z2.default(e,t)}catch(r){return bs.trace(r,e,t),!1}}a(c4,"geoCrosses");function u4(e,t,r){if(me.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(me.isEmpty(t))throw new Error("geo_type is required");if(me.isEmpty(PC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(PC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=me.autoCastJSON(e)),e4[t](e,r)}a(u4,"geoConvert")});var ed=T((yde,xC)=>{var to=UC(),Br=MC(),es=HC();xC.exports=e=>{e.aggr.mad=e.aggr.MAD=to.mad,e.aggr.mean=e.aggr.MEAN=to.mean,e.aggr.mode=e.aggr.MODE=to.mode,e.aggr.prod=e.aggr.PROD=to.prod,e.aggr.median=e.aggr.MEDIAN=to.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=to.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=to.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Br.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Br.current_time,e.fn.extract=e.fn.EXTRACT=Br.extract,e.fn.date=e.fn.DATE=Br.date,e.fn.date_format=e.fn.DATE_FORMAT=Br.date_format,e.fn.date_add=e.fn.DATE_ADD=Br.date_add,e.fn.date_sub=e.fn.DATE_SUB=Br.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Br.date_diff,e.fn.now=e.fn.NOW=Br.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Br.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Br.get_server_time,e.fn.getdate=e.fn.GETDATE=Br.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Br.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=es.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=es.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=es.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=es.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=es.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=es.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=es.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=es.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=es.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=es.geoNear}});var kC=T((wde,GC)=>{"use strict";var tu=require("lodash"),cr=require("alasql");cr.options.cache=!1;var l4=ed(),qC=require("clone"),td=require("recursive-iterator"),le=$(),Ce=J(),oa=Nn(),_4=U(),{hdb_errors:d4}=re(),{getDatabases:FC}=(Re(),ne(Fe)),f4="IS NULL",Ln="There was a problem performing this search. Please check the logs and try again.";l4(cr);var Zp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw le.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),Ce.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(n))return le.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(n),new Error(Ln)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(n),new Error(Ln)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(n),new Error(Ln)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(n),new Error(Ln)}try{return t=await this._finalSQL(),t}catch(n){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(n),new Error(Ln)}}_getColumns(){let t=new td(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(qC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=tu.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=FC()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new td(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let n=Ce.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new cr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Ce.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new cr.yy.LogicValue({value:i}):n instanceof cr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new cr.yy.NumValue({value:i}))});if(t){le.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new td(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(_4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ce.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ce.isEmptyOrZeroLength(r.left.columnid)||Ce.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(Ce.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!Ce.isEmpty(r.right.value)||!Ce.isEmpty(r.left.value)?n.add(Ce.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&tu.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(Ce.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Ce.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&!Ce.isEmptyOrZeroLength(this.columns.columns))return t;if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await cr.promise(r)}catch(r){throw le.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),le.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(qC(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(Ce.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(f4)>-1&&this.tables.forEach(s=>{let i={columnid:FC()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=tu.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!Ce.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await oa.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Ln)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await oa.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Ln)}else if(!Ce.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await oa.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(Ln)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await oa.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(Ln)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof cr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new cr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new cr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new cr.yy.FuncValue:new cr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await cr.promise(h,t),t=null}catch(E){throw le.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),le.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=tu.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,g=p.length;S<g;S++){let A=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[A]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new td(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=tu.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(Ln)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await oa.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=s.columns[h],S=E[p]===void 0?null:E[p];this.data[n].__merged_data[f].push(S)}}}}catch(r){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getData."),le.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();le.trace(`Final SQL: ${s}`),n=await cr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),le.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return le.error(d4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),le.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await oa.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(Ln)}}return Object.values(Object.values(this.data)[0].__merged_data)}};GC.exports=Zp});var en=T((Cde,VC)=>{"use strict";var E4=bb();VC.exports={searchByConditions:m4,searchByHash:p4,searchByValue:S4,search:T4};var eS=Nn(),{transformReq:tS}=J(),h4=kC();async function m4(e){return tS(e),eS.searchByConditions(e)}a(m4,"searchByConditions");async function p4(e){tS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of eS.searchByHash(e))r&&t.push(r);return t}a(p4,"searchByHash");async function S4(e){tS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of eS.searchByValue(e))t.push(r);return t}a(S4,"searchByValue");function T4(e,t){try{let r=new E4(e);r.validate(),new h4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(T4,"search")});var rd=T((Ude,$C)=>{"use strict";var g4=Nn();$C.exports={writeTransaction:R4};function R4(e,t,r){return g4.writeTransaction(e,t,r)}a(R4,"writeTransaction")});var QC=T((Pde,WC)=>{"use strict";var A4=en(),O4=gs(),YC=$(),b4=Cr(),Mde=rd(),N4=require("clone"),nS=require("alasql"),y4=ed(),KC=require("util"),w4=KC.promisify(O4.getTableSchema),I4=KC.promisify(A4.search),C4=U(),rS=J();y4(nS);WC.exports={update:U4};var D4="There was a problem performing this update. Please check the logs and try again.";async function U4({statement:e,hdb_user:t}){let r=await w4(e.table.databaseid,e.table.tableid),n=L4(e.columns);rS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=N4(s),c=rS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=nS.parse(u).statements[0],l=await I4(_),d=M4(n,l);return P4(o,d,t)}a(U4,"update");function L4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=nS.compile(`SELECT ${r.expression.toString()} AS [${C4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw YC.error(t),new Error(D4)}}a(L4,"createUpdateRecord");function M4(e,t){return rS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(M4,"buildUpdateRecords");async function P4(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await b4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){YC.error(`Error delete new_attributes from update response: ${i}`)}return s}a(P4,"updateRecords")});var JC=T((xde,zC)=>{var v4=require("alasql"),B4=en(),H4=$(),x4=Nn(),iS=require("util"),sS=J(),q4=U(),F4=gs(),Bde=rd(),Hde=Cr(),G4="record",k4="successfully deleted",V4=iS.callbackify(W4),$4=iS.promisify(B4.search),Y4=iS.promisify(F4.getTableSchema);zC.exports={convertDelete:V4};function K4(e){return`${e.deleted_hashes.length} ${G4}${e.deleted_hashes.length===1?"":"s"} ${k4}`}a(K4,"generateReturnMessage");async function W4({statement:e,hdb_user:t}){let r=await Y4(e.table.databaseid,e.table.tableid);sS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=sS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=v4.parse(o).statements[0],u={operation:q4.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await $4(c);let _=await x4.deleteRecords(u);return sS.isEmptyOrZeroLength(_.message)&&(_.message=K4(_)),delete _.txn_time,_}catch(_){throw H4.error(_),_.hdb_code?_.message:_}}a(W4,"convertDelete")});var tD=T((Fde,eD)=>{"use strict";var Q4=Zs(),{hdb_errors:jC}=re(),{getDatabases:XC}=(Re(),ne(Fe));eD.exports={checkSchemaExists:ZC,checkSchemaTableExists:z4,schema_describe:Q4};async function ZC(e){if(!XC()[e])return jC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(ZC,"checkSchemaExists");async function z4(e,t){let r=await ZC(e);if(r)return r;if(!XC()[e][t])return jC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(z4,"checkSchemaTableExists")});var ru=T((kde,J4)=>{J4.exports={name:"harperdb",version:"4.3.0-beta.7",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.10.0-beta.3",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.3.3","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var au={};Ke(au,{addAnalyticsListener:()=>ou,recordAction:()=>Hr,recordActionBinary:()=>rn,setAnalyticsEnabled:()=>j4});function j4(e){lD=e}function Hr(e,t,r,n,s){if(!lD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=id.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},id.set(i,o)}nd||X4()}function rn(e,t,r,n,s){Hr(!!e,t,r,n,s)}function ou(e){fD.push(e)}function X4(){nd=performance.now(),setTimeout(async()=>{let e=performance.now()-nd;nd=0;let t=[],r={time:Date.now(),period:e,threadId:ro.threadId,metrics:t};for(let[s,i]of id){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of ED){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await hD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:ro.threadId,byThread:!0,...n});for(let s of fD)s(t);id=new Map,ro.parentPort?ro.parentPort.postMessage({type:dD,report:r}):SD({report:r})},_D).unref()}async function Z4(e,t=6e4){let r=cS(),n=mD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let g=performance.now();g-S>5e3&&(0,nu.warn)("Unusually high event queue latency on the main thread of "+Math.round(g-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let g=performance.now();g-S>5e3&&(0,nu.warn)("Unusually high task queue latency on the main thread of "+Math.round(g-S)+"ms"),p(g-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:g,threadId:A}=S;for(let R of g||[]){let{path:v,method:H,type:P,metric:M,count:K,total:W,distribution:V,threads:ce,...de}=R;K||(K=1);let xe=M+(v?"-"+v:"");H!==void 0&&(xe+="-"+H),P!==void 0&&(xe+="-"+P);let ae=c.get(xe);if(ae){if(ae.threads){let $e=ae.threads[A];if($e)ae=$e;else{ae.threads[A]=Object.assign({},de);continue}}ae.count||(ae.count=1);let Oe=ae.count;for(let $e in de){let Fn=de[$e];typeof Fn=="number"&&(ae[$e]=(ae[$e]*Oe+Fn*K)/(Oe+K))}ae.count+=K,W>=0&&(ae.total+=W,ae.ratio=ae.total/ae.count)}else ae=Object.assign({period:t},R),delete ae.distribution,c.set(xe,ae),ae.byThread&&(ae.threads=[],ae.threads[A]=Object.assign({},de),_.push(ae));if(V){V=V.map($e=>typeof $e=="number"?{value:$e,count:1}:$e);let Oe=u.get(xe);Oe?Oe.push(...V):u.set(xe,V)}}await hD()}for(let p of _){let{path:S,method:g,type:A,metric:R,count:v,total:H,distribution:P,threads:M,...K}=p;M=M.filter(W=>W);for(let W in K){if(typeof p[W]!="number")continue;let V=0;for(let ce of M){let de=ce[W];typeof de=="number"&&(V+=de)}p[W]=V}p.count=M.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let g=c.get(p);S.sort(($e,Fn)=>$e.value>Fn.value?1:-1);let A=g.count-1,R=[],v=0,H=0,P;for(let $e of ED){let Fn=A*$e;for(;v<Fn;)P=S[H++],v+=P.count,H===1&&v--;let vo=S[H>1?H-2:0];P||(P=S[0]),R.push(P.value-(P.value-vo.value)*(v-Fn)/P.count)}let[M,K,W,V,ce,de,xe,ae,Oe]=R;Object.assign(g,{p1:M,p10:K,p25:W,median:V,p75:ce,p90:de,p95:xe,p99:ae,p999:Oe})}let d;for(let[p,S]of c)S.id=(0,sd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(g=>{g||n.primaryStore.put(S.id,S)}),d=!0;let f=Date.now(),{idle:E,active:h}=performance.eventLoopUtilization();if(d||h*10>E){let p=(0,sd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:E-rD,active:h-nD,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(g=>{g||n.primaryStore.put(p,S)})}rD=E,nD=h}async function sD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function cS(){return iD||(iD=ut({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function mD(){return oD||(oD=ut({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function r3(){pD=!0;let e=(0,iu.get)(aS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await Z4(_D,e),await sD(cS(),e3),await sD(mD(),t3)},Math.min(e/2,2147483647)).unref()}function SD(e,t){let r=e.report;r.threadId=t?.threadId||ro.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(aD+=n.mean*n.count);r.totalBytesProcessed=aD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(cD.get(t))}),cD.set(t,t.performance.eventLoopUtilization())),r.id=(0,sd.getNextMonotonicTime)(),cS().primaryStore.put(r.id,r),pD||r3(),n3&&(TD=i3(r))}async function i3(e){if(await TD,!ai){let r=(0,su.dirname)((0,nu.getLogFilePath)());try{ai=await(0,oS.open)((0,su.join)(r,"analytics.log"),"r+")}catch{ai=await(0,oS.open)((0,su.join)(r,"analytics.log"),"w+")}}let t=(await ai.stat()).size;if(t>s3){let r=Buffer.alloc(t);await ai.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ai.write(r,{position:0}),await ai.truncate(r.length),t=r.length}await ai.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var ro,uD,nu,su,oS,sd,iu,aS,id,lD,nd,_D,dD,fD,ED,rD,nD,hD,e3,t3,iD,oD,pD,aD,cD,n3,TD,ai,s3,Ns=ge(()=>{ro=require("worker_threads"),uD=x(We());Re();nu=x($()),su=require("path"),oS=require("fs/promises"),sd=x(yr()),iu=x(Z()),aS=x(U());rr();(0,iu.initSync)();id=new Map,lD=(0,iu.get)(aS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(j4,"setAnalyticsEnabled");a(Hr,"recordAction");rt.recordAnalytics=Hr;a(rn,"recordActionBinary");nd=0,_D=1e3,dD="analytics-report",fD=[];a(ou,"addAnalyticsListener");ED=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(X4,"sendAnalytics");a(Z4,"aggregation");rD=0,nD=0,hD=a(()=>new Promise(setImmediate),"rest");a(sD,"cleanup");e3=36e5,t3=31536e6;a(cS,"getRawAnalyticsTable");a(mD,"getAnalyticsTable");(0,uD.setChildListenerByType)(dD,SD);a(r3,"startScheduledTasks");aD=0,cD=new Map,n3=!1;a(SD,"recordAnalytics");s3=1e6;a(i3,"logAnalytics")});var st=T((rfe,qD)=>{"use strict";var Ft=Z();Ft.initSync();var o3=require("fs-extra"),a3=require("semver"),lu=require("path"),{monotonicFactory:c3}=require("ulidx"),RD=c3(),u3=require("util"),AD=require("child_process"),l3=u3.promisify(AD.exec),_3=AD.spawn,ye=Ge(),Pe=U(),dS=J(),xr=$(),od=Ts(),d3=rd(),cu=Lr(),{onMessageByType:f3}=We(),{isMainThread:E3}=require("worker_threads"),{Encoder:h3,decode:fS}=require("msgpackr"),OD=new h3,{isEmpty:oo}=dS,bD=tn(),m3=48*36e11,p3=5e9;E3&&f3(Pe.ITC_EVENT_TYPES.RESTART,()=>{nn=void 0,io=void 0});var{connect:S3,StorageType:ND,RetentionPolicy:yD,AckPolicy:ad,DeliverPolicy:cd,DiscardPolicy:T3,NatsConnection:Xde,JetStreamManager:Zde,JetStreamClient:efe,StringCodec:tfe,JSONCodec:g3,createInbox:ES,headers:R3,ErrorCode:gD}=require("nats"),{PACKAGE_ROOT:A3}=U(),O3=ru(),{recordAction:b3}=(Ns(),ne(au)),wD=g3(),N3="clustering",y3=O3.engines[ye.NATS_SERVER_NAME],w3=lu.join(A3,"dependencies"),_S=lu.join(w3,`${process.platform}-${process.arch}`,ye.NATS_BINARY_NAME),uS,lS,uu,no,so;qD.exports={runCommand:ID,checkNATSServerInstalled:I3,createConnection:hS,getConnection:ud,getJetStreamManager:_u,getJetStream:DD,getNATSReferences:ur,getServerList:D3,createLocalStream:mS,listStreams:UD,deleteLocalStream:U3,getServerConfig:du,listRemoteStreams:L3,viewStream:M3,viewStreamIterator:P3,publishToStream:v3,createWorkQueueStream:B3,addSourceToWorkStream:MD,request:x3,removeSourceFromWorkStream:vD,reloadNATS:pS,reloadNATSHub:q3,reloadNATSLeaf:F3,extractServerName:PD,requestErrorHandler:G3,updateWorkStream:k3,createLocalTableStream:HD,createTableStreams:V3,purgeTableStream:xD,purgeSchemaTableStreams:$3,getStreamInfo:Y3,updateLocalStreams:W3,closeConnection:C3,getJsmServerName:fu,addNatsMsgHeader:LD,updateIngestStreamConsumer:H3,clearClientCache:CD};async function ID(e,t=void 0){let{stdout:r,stderr:n}=await l3(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(ND,"runCommand");async function b3(){try{await r3.access(uS)}catch{return!1}let e=await ND(`${uS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return s3.eq(t,A3)}a(b3,"checkNATSServerInstalled");async function fS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await RD.getClusterUser();if(io(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}xr.trace("create nats connection called");let i=await E3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),xr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&xr.error("Error with Nats client connection, connection closed",o),yD()}),i}a(fS,"createConnection");function yD(){ss=void 0,ro=void 0,so=void 0,no=void 0}a(yD,"clearClientCache");async function N3(){ss&&(await ss.drain(),ss=void 0,ro=void 0,so=void 0,no=void 0)}a(N3,"closeConnection");var ss,no;async function ad(){return no||(no=fS(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),ss=await no),ss||no}a(ad,"getConnection");async function au(){if(ro)return ro;io(ss)&&await ad();let{domain:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(io(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ro=await ss.jetstreamManager({domain:e,timeout:6e4}),ro}a(au,"getJetStreamManager");async function wD(){if(so)return so;io(ss)&&await ad();let{domain:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(io(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return so=ss.jetstream({domain:e,timeout:6e4}),so}a(wD,"getJetStream");async function ur(){let e=ss||await ad(),t=ro||await au(),r=so||await wD();return{connection:e,jsm:t,js:r}}a(ur,"getNATSReferences");async function y3(e){let t=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await RD.getClusterUser(),n=await fS(t,r,s),i=dS(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=bD.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await lS.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(y3,"getServerList");async function ES(e,t){let{jsm:r}=await ur(),s=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:AD.File,retention:OD.Limits,subjects:t,discard:h3.Old,max_msgs:n,max_bytes:i,max_age:s})}a(ES,"createLocalStream");async function ID(){let{jsm:e}=await ur(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(ID,"listStreams");async function w3(e){let{jsm:t}=await ur();await t.streams.delete(e)}a(w3,"deleteLocalStream");async function I3(e){let{connection:t}=await ur(),r=[],s=dS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(bD.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(I3,"listRemoteStreams");async function C3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ur(),i=SD(),o={durable_name:i,ack_policy:id.Explicit};t&&(o.deliver_policy=od.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=_S(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(ye.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(C3,"viewStream");async function*D3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ur(),i=SD(),o={durable_name:i,ack_policy:id.Explicit};t&&(o.deliver_policy=od.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=_S(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(ye.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(D3,"viewStreamIterator");async function L3(e,t,r,s){xr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=CD(s,r);let{js:n}=await ur(),i=await uu(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:gD.encode(s);try{xr.trace(`publishToStream publishing to subject: ${o}`),g3(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return MD(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){xr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await ES(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(L3,"publishToStream");function CD(e,t){t===void 0&&(t=p3());let r=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(ye.MSG_HEADERS.ORIGIN)&&r&&t.append(ye.MSG_HEADERS.ORIGIN,r),t}a(CD,"addNatsMsgHeader");function cu(e){e=e.toLowerCase();let t=ou.join(Ft.get(Pe.CONFIG_PARAMS.ROOTPATH),R3);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return io(cS)&&(cS={port:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.HUB,config_file:ye.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:ou.join(t,ye.PID_FILES.HUB),hdb_nats_path:t}),cS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return io(aS)&&(aS={port:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,config_file:ye.NATS_CONFIG_FILES.LEAF_SERVER,domain:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,pid_file_path:ou.join(t,ye.PID_FILES.LEAF),hdb_nats_path:t}),aS;xr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(cu,"getServerConfig");async function U3(e){let{jsm:t}=await ur(),r=await uu();try{await t.streams.add({name:e.stream_name,storage:AD.File,retention:OD.Limits,max_age:d3,max_bytes:f3,subjects:[`${ye.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:id.Explicit,durable_name:e.durable_name,deliver_policy:od.All,max_ack_pending:1e4});else throw s}}a(U3,"createWorkQueueStream");async function M3(){let{jsm:e}=await ur();(await e.consumers.info(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(xr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name),xr.info("Adding pull consumer to ingest stream"),await e.consumers.add(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:id.Explicit,durable_name:ye.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:od.All,max_ack_pending:1e4}))}a(M3,"updateIngestStreamConsumer");async function DD(e,t,r){let{jsm:s}=await ur(),n=await s.streams.info(t),i=LD(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=nd.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let p=0,S=n.config.sources.length;p<S;p++)if(d=n.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await s.streams.purge(t,{filter:p}),n.config.sources.splice(f,1),await s.streams.update(t,n.config)}let h={name:_,opt_start_time:o,filter_subject:`${ye.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(DD,"addSourceToWorkStream");function LD(e){return e.split(".")[1]}a(LD,"extractServerName");async function UD(e,t,r){let{jsm:s}=await ur(),{schema:n,table:i}=r,o=`txn.${n}.${i}.${e}`;await s.streams.purge(t,{filter:o});let c=nd.createNatsTableStreamName(n,i),u=await s.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await s.streams.update(t,u.config)}a(UD,"removeSourceFromWorkStream");async function P3(e,t,r=6e4,s=dS()){if(!lS.isObject(t))throw new Error("data param must be an object");let n=gD.encode(t),{connection:i}=await ur(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return _S(c.data)}a(P3,"request");function hS(e){return new Promise(async(t,r)=>{let s=a3(uS,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(hS,"reloadNATS");async function v3(){let{pid_file_path:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await hS(e)}a(v3,"reloadNATSHub");async function B3(){let{pid_file_path:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await hS(e)}a(B3,"reloadNATSLeaf");function H3(e,t,r){let s;switch(e.code){case pD.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case pD.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(H3,"requestErrorHandler");async function x3(e,t){let r=t+ye.SERVER_SUFFIX.LEAF;await MD(async()=>{e.subscribe===!0?await DD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await UD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(x3,"updateWorkStream");function MD(e){return c3.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(MD,"exclusiveLock");async function PD(e,t){let r=nd.createNatsTableStreamName(e,t),s=await uu(),n=k3(e,t,s);await ES(r,[n])}a(PD,"createLocalTableStream");async function q3(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await PD(s,n)}}a(q3,"createTableStreams");async function vD(e,t,r=!1){if(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=nd.createNatsTableStreamName(e,t),{jsm:n}=await ur();r?await n.streams.purge(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name):await n.streams.purge(s)}catch(s){if(s.message==="stream not found")xr.warn(s);else throw s}}a(vD,"purgeTableStream");async function F3(e,t){if(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await vD(e,t[r])}a(F3,"purgeSchemaTableStreams");async function G3(e){return(await au()).streams.info(e)}a(G3,"getStreamInfo");function k3(e,t,r){return`${ye.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(k3,"createSubjectName");async function uu(){if(iu)return iu;if(iu=(await au())?.nc?.info?.server_name,iu===void 0)throw new Error("Unable to get jetstream manager server name");return iu}a(uu,"getJsmServerName");async function V3(){let e=await au(),t=await uu(),r=await ID();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=$3(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");xr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}await e.streams.update(n.name,n)}}}a(V3,"updateLocalStreams");function $3(e){let{config:t}=e,r=!1;if(t.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a($3,"updateStreamLimits")});var lu=T((tfe,FD)=>{"use strict";var ia=__(),oa=jC(),Y3=V(),K3=require("uuid").v4,efe=require("clone"),ud=gn(),aa=L(),W3=require("util"),ai=Ns(),{handleHDBError:lr,hdb_errors:Q3}=re(),{HDB_ERROR_MSGS:cd,HTTP_STATUS_CODES:_r}=Q3,{SchemaEventMsg:ld}=Is(),HD=st(),{getDatabases:z3}=(Ae(),se(Fe)),{transformReq:ca}=J();FD.exports={createSchema:J3,createSchemaStructure:xD,createTable:j3,createTableStructure:qD,createAttribute:rj,dropSchema:X3,dropTable:Z3,dropAttribute:ej,getBackup:sj};async function J3(e){let t=await xD(e);return ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema)),t}a(J3,"createSchema");async function xD(e){let t=ia.schema_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(ca(e),!await oa.checkSchemaExists(e.schema))throw lr(new Error,cd.SCHEMA_EXISTS_ERR(e.schema),_r.BAD_REQUEST,aa.LOG_LEVELS.ERROR,cd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ai.createSchema(e),`database '${e.schema}' successfully created`}a(xD,"createSchemaStructure");async function j3(e){return ca(e),e.hash_attribute=e.primary_key??e.hash_attribute,await qD(e)}a(j3,"createTable");async function qD(e){let t=ia.create_table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(ia.validateTableResidence(e.residence),!await oa.checkSchemaTableExists(e.schema,e.table))throw lr(new Error,cd.TABLE_EXISTS_ERR(e.schema,e.table),_r.BAD_REQUEST,aa.LOG_LEVELS.ERROR,cd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:K3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await ai.createTable(s,e);else throw lr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",_r.BAD_REQUEST);else await ai.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(qD,"createTableStructure");async function X3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ia.schema_object(e),s=t??r;if(s)throw lr(s,s.message,_r.BAD_REQUEST,void 0,void 0,!0);ca(e);let n=await oa.checkSchemaExists(e.schema);if(n)throw lr(new Error,n,_r.NOT_FOUND,aa.LOG_LEVELS.ERROR,n,!0);let i=await oa.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ai.dropSchema(e),ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema)),await HD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(X3,"dropSchema");async function Z3(e){let t=ia.table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);ca(e);let r=await oa.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,aa.LOG_LEVELS.ERROR,r,!0);return await ai.dropTable(e),await HD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Z3,"dropTable");async function ej(e){let t=ia.attribute_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);ca(e);let r=await oa.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,aa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw lr(new Error,"You cannot drop a hash attribute",_r.BAD_REQUEST,void 0,void 0,!0);if(aa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw lr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,_r.BAD_REQUEST,void 0,void 0,!0);try{return await ai.dropAttribute(e),tj(e),ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw Y3.error(`Got an error deleting attribute ${W3.inspect(e)}.`),s}}a(ej,"dropAttribute");function tj(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(tj,"dropAttributeFromGlobal");async function rj(e){ca(e);let t=z3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw lr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,_r.BAD_REQUEST,void 0,void 0,!0);return await ai.createAttribute(e),ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(rj,"createAttribute");function sj(e){return ai.getBackup(e)}a(sj,"getBackup")});var kD=T((sfe,GD)=>{"use strict";var{OPERATIONS_ENUM:nj}=L(),mS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=nj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};GD.exports=mS});var pS=T((ofe,WD)=>{"use strict";var ij=Ns(),ife=kD(),_d=J(),dd=L(),oj=Z(),{handleHDBError:VD,hdb_errors:aj}=re(),{HDB_ERROR_MSGS:$D,HTTP_STATUS_CODES:YD}=aj,cj=Object.values(dd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),KD="To use this operation audit log must be enabled in harperdb-config.yaml";WD.exports=uj;async function uj(e){if(_d.isEmpty(e.schema))throw new Error($D.SCHEMA_REQUIRED_ERR);if(_d.isEmpty(e.table))throw new Error($D.TABLE_REQUIRED_ERR);if(!oj.get(dd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw VD(new Error,KD,YD.BAD_REQUEST,dd.LOG_LEVELS.ERROR,KD,!0);let t=_d.checkSchemaTableExist(e.schema,e.table);if(t)throw VD(new Error,t,YD.NOT_FOUND,dd.LOG_LEVELS.ERROR,t,!0);if(!_d.isEmpty(e.search_type)&&cj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await ij.readAuditLog(e)}a(uj,"readAuditLog")});var zD=T((cfe,QD)=>{"use strict";var{OPERATIONS_ENUM:lj}=L(),SS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=lj.GET_BACKUP,this.schema=t,this.table=r}};QD.exports=SS});var XD=T((dfe,jD)=>{"use strict";var _j=Ns(),lfe=zD(),TS=J(),dj=L(),_fe=Z(),{handleHDBError:fj,hdb_errors:Ej}=re(),{HDB_ERROR_MSGS:JD,HTTP_STATUS_CODES:hj}=Ej;jD.exports=mj;async function mj(e){if(TS.isEmpty(e.schema))throw new Error(JD.SCHEMA_REQUIRED_ERR);if(TS.isEmpty(e.table))throw new Error(JD.TABLE_REQUIRED_ERR);let t=TS.checkSchemaTableExist(e.schema,e.table);if(t)throw fj(new Error,t,hj.NOT_FOUND,dj.LOG_LEVELS.ERROR,t,!0);return await _j.getBackup(read_audit_log_object)}a(mj,"getBackup")});var nL=T((Efe,sL)=>{var ci=require("validate.js"),eL=je(),ua=L(),{handleHDBError:pj,hdb_errors:Sj}=re(),{HDB_ERROR_MSGS:lt,HTTP_STATUS_CODES:Tj}=Sj,gS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),gj={STRUCTURE_USER:"structure_user"},ZD=Object.values(ua.ROLE_TYPES_ENUM),Rj="attribute_permissions",Aj="attribute_name",{PERMS_CRUD_ENUM:la}=ua,Oj=[Rj,...Object.values(la)],tL=[la.READ,la.INSERT,la.UPDATE],bj=[Aj,...tL];function Nj(e){let t=gS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,rL(e,t)}a(Nj,"addRoleValidation");function yj(e){let t=gS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,rL(e,t)}a(yj,"alterRoleValidation");function wj(e){let t=gS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,eL.validateObject(e,t)}a(wj,"dropRoleValidation");var Ij=["operation","role","id","permission","hdb_user","hdb_auth_header"];function rL(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)Ij.includes(s[o])||n.push(s[o]);n.length>0&&ht(lt.INVALID_ROLE_JSON_KEYS(n),r);let i=eL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{ht(o,r)}),e.permission){let o=Cj(e);o&&ht(o,r),ZD.forEach(c=>{e.permission[c]&&!ci.isBoolean(e.permission[c])&&ht(lt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(ZD.indexOf(o)<0){if(o===gj.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||ht(lt.SCHEMA_NOT_FOUND(d),r)}continue}ht(lt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){ht(lt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){ht(lt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{Oj.includes(l)||ht(lt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(la).forEach(l=>{ci.isDefined(_[l])?ci.isBoolean(_[l])||ht(lt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):ht(lt.TABLE_PERM_MISSING(l),r,o,u)}),ci.isDefined(_.attribute_permissions)){if(!ci.isArray(_.attribute_permissions)){ht(lt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{ht(lt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(p=>{!bj.includes(p)&&p!==la.DELETE&&ht(lt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ci.isDefined(E.attribute_name)){ht(lt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){ht(lt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}tL.forEach(p=>{ci.isDefined(E[p])?ci.isBoolean(E[p])||ht(lt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):ht(lt.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;ht(lt.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return Dj(r)}a(rL,"customValidate");sL.exports={addRoleValidation:Nj,alterRoleValidation:yj,dropRoleValidation:wj};function Cj(e){let{operation:t,permission:r}=e;if(t===ua.OPERATIONS_ENUM.ADD_ROLE||t===ua.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return lt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ua.ROLE_TYPES_ENUM.SUPER_USER:ua.ROLE_TYPES_ENUM.CLUSTER_USER;return lt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Cj,"validateNoSUPerms");function Dj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:lt.ROLE_PERMS_ERROR,...e};return pj(new Error,s,Tj.BAD_REQUEST)}else return null}a(Dj,"generateRolePermResponse");function ht(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(ht,"addPermError")});var yS=T((mfe,cL)=>{"use strict";var iL=Cr(),oL=es(),Lj=ti(),AS=nL(),OS=gn(),Uj=require("uuid").v4,Mj=require("util"),fd=L(),Pj=J(),bS=oL.searchByValue,vj=oL.searchByHash,Bj=Mj.promisify(Lj.delete),Hj=Js(),xj=ta(),{hdb_errors:qj,handleHDBError:oo}=re(),{HDB_ERROR_MSGS:aL,HTTP_STATUS_CODES:_u}=qj,{UserEventMsg:NS}=Is();cL.exports={addRole:Fj,alterRole:Gj,dropRole:kj,listRoles:Vj};function RS(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(RS,"scrubRoleDetails");async function Fj(e){let t=AS.addRoleValidation(e);if(t)throw t;e=RS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await bS(r)||[])}catch(i){throw oo(i)}if(s&&s.length>0)throw oo(new Error,aL.ROLE_ALREADY_EXISTS(e.role),_u.CONFLICT,void 0,void 0,!0);e.id||(e.id=Uj());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await iL.insert(n),OS.signalUserChange(new NS(process.pid)),e=RS(e),e}a(Fj,"addRole");async function Gj(e){let t=AS.alterRoleValidation(e);if(t)throw t;e=RS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await iL.update(r)}catch(n){throw oo(n)}if(s&&s?.message==="updated 0 of 1 records")throw oo(new Error,"Invalid role id",_u.BAD_REQUEST,void 0,void 0,!0);return await OS.signalUserChange(new NS(process.pid)),e}a(Gj,"alterRole");async function kj(e){let t=AS.dropRoleValidation(e);if(t)throw oo(new Error,t,_u.BAD_REQUEST,void 0,void 0,!0);let r=new xj(fd.SYSTEM_SCHEMA_NAME,fd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await vj(r));if(s.length===0)throw oo(new Error,aL.ROLE_NOT_FOUND,_u.NOT_FOUND,void 0,void 0,!0);let n=new Hj(fd.SYSTEM_SCHEMA_NAME,fd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await bS(n)),o=!1;if(Pj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw oo(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,_u.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Bj(c),OS.signalUserChange(new NS(process.pid)),`${s[0].role} successfully deleted`}a(kj,"dropRole");async function Vj(){return bS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Vj,"listRoles")});var dL=T((Sfe,_L)=>{"use strict";var $j=Z(),ui=require("joi"),Yj=je(),uL=require("moment"),Kj=require("fs-extra"),wS=require("path"),Wj=require("lodash"),du=L(),{LOG_LEVELS:ao}=L(),Qj="YYYY-MM-DD hh:mm:ss",zj=wS.resolve(__dirname,"../logs");_L.exports=function(e){return Yj.validateBySchema(e,Jj)};var Jj=ui.object({from:ui.custom(lL),until:ui.custom(lL),level:ui.valid(ao.NOTIFY,ao.FATAL,ao.ERROR,ao.WARN,ao.INFO,ao.DEBUG,ao.TRACE),order:ui.valid("asc","desc"),limit:ui.number().min(1),start:ui.number().min(0),log_name:ui.custom(jj)});function lL(e,t){if(uL(e,uL.ISO_8601).format(Qj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(lL,"validateDatetime");function jj(e,t){if(Wj.invert(du.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=$j.get(du.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?du.LOG_NAMES.HDB:e,i=n===du.LOG_NAMES.INSTALL?wS.join(zj,du.LOG_NAMES.INSTALL):wS.join(s,n);return Kj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(jj,"validateReadLogPath")});var CS=T((gfe,EL)=>{"use strict";var Ed=L(),Xj=V(),Zj=Z(),eX=dL(),IS=require("path"),fL=require("fs-extra"),{once:tX}=require("events"),{handleHDBError:rX,hdb_errors:sX}=re(),{PACKAGE_ROOT:nX}=L(),iX=IS.join(nX,"logs"),oX=1e3,aX=200;EL.exports=cX;async function cX(e){let t=eX(e);if(t)throw rX(t,t.message,sX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Zj.get(Ed.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?Ed.LOG_NAMES.HDB:e.log_name,n=s===Ed.LOG_NAMES.INSTALL?IS.join(iX,Ed.LOG_NAMES.INSTALL):IS.join(r,s),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?oX:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(fL.statSync(n).size-(h+5)*aX,0));let S=fL.createReadStream(n,{start:p});S.on("error",v=>{Xj.error(v)});let A=0,R=[],g="",P;S.on("data",v=>{let U=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=g+v;let Y=0,K;for(;(K=U.exec(v))&&!S.destroyed;){P&&(P.message=v.slice(Y,K.index),H(P));let[z,ne,me]=K,ce=me.split("] ["),xe=ce[0],le=ce[1];ce.splice(0,2),P={timestamp:ne,thread:xe,level:le,tags:ce,message:""},Y=K.index+z.length}g=v.slice(Y)}),S.on("end",v=>{S.destroyed||P&&(P.message=g.trim(),H(P))}),S.resume();function H(v){let U,Y,K;switch(!0){case(i&&c&&_):U=new Date(v.timestamp),Y=new Date(u),K=new Date(l),v.level===o&&U>=Y&&U<=K&&A<E?A++:v.level===o&&U>=Y&&U<=K&&(li(v,f,R),A++,A===h&&S.destroy());break;case(i&&c):U=new Date(v.timestamp),Y=new Date(u),v.level===o&&U>=Y&&A<E?A++:v.level===o&&U>=Y&&(li(v,f,R),A++,A===h&&S.destroy());break;case(i&&_):U=new Date(v.timestamp),K=new Date(l),v.level===o&&U<=K&&A<E?A++:v.level===o&&U<=K&&(li(v,f,R),A++,A===h&&S.destroy());break;case(c&&_):U=new Date(v.timestamp),Y=new Date(u),K=new Date(l),U>=Y&&U<=K&&A<E?A++:U>=Y&&U<=K&&(li(v,f,R),A++,A===h&&S.destroy());break;case i:v.level===o&&A<E?A++:v.level===o&&(li(v,f,R),A++,A===h&&S.destroy());break;case c:U=new Date(v.timestamp),Y=new Date(u),U>=Y&&A<E?A++:U>=Y&&A>=E&&(li(v,f,R),A++,A===h&&S.destroy());break;case _:U=new Date(v.timestamp),K=new Date(l),U<=K&&A<E?A++:U<=K&&A>=E&&(li(v,f,R),A++,A===h&&S.destroy());break;default:A<E?A++:(li(v,f,R),A++,A===h&&S.destroy())}}return a(H,"onLogMessage"),await tX(S,"close"),R}a(cX,"readLog");function li(e,t,r){t==="desc"?uX(e,r):t==="asc"?lX(e,r):r.push(e)}a(li,"pushLineToResult");function uX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(uX,"insertDescending");function lX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(lX,"insertAscending")});var hd=T((Nfe,SL)=>{"use strict";var DS=require("joi"),{string:fu,boolean:hL,date:_X}=DS.types(),dX=je(),{validateSchemaExists:Afe,validateTableExists:Ofe,validateSchemaName:bfe}=Ys(),fX=L(),EX=Ge(),mL=Z();mL.initSync();var hX=fu.invalid(mL.get(fX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(EX.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),pL={operation:fu.valid("add_node","update_node","set_node_replication"),node_name:hX,subscriptions:DS.array().items({table:fu.optional(),schema:fu.optional(),database:fu.optional(),subscribe:hL.required(),publish:hL.required().custom(pX),start_time:_X.iso()}).min(1).required()};function mX(e){return dX.validateBySchema(e,DS.object(pL))}a(mX,"addUpdateNodeValidator");function pX(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(pX,"checkForFalsy");SL.exports={addUpdateNodeValidator:mX,validation_schema:pL}});var gL=T((wfe,TL)=>{var SX=je(),TX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};TL.exports=function(e){return SX.validateObject(e,TX)}});var md=T((Ife,RL)=>{"use strict";var gX=L().OPERATIONS_ENUM,LS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=gX.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};RL.exports=LS});var OL=T((Dfe,AL)=>{"use strict";var RX={OPERATION:"operation",REFRESH:"refresh"},US=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},MS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};AL.exports={JWTTokens:US,TOKEN_TYPE_ENUM:RX,JWTRSAKeys:MS}});var mu=T((Ufe,wL)=>{"use strict";var hu=require("jsonwebtoken"),PS=require("fs-extra"),vS=J(),ns=L(),{handleHDBError:dr,hdb_errors:AX}=re(),{HTTP_STATUS_CODES:fr,AUTHENTICATION_ERROR_MSGS:Er}=AX,Eu=V(),bL=b_(),xS=ts(),OX=Cr().update,bX=md(),NX=gn(),{UserEventMsg:yX}=Is(),_i=Z();_i.initSync();var BS=require("path"),{JWTTokens:wX,JWTRSAKeys:IX,TOKEN_TYPE_ENUM:pd}=OL(),CX=_i.get(ns.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?_i.get(ns.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",DX=_i.get(ns.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?_i.get(ns.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Sd="RS256",HS;wL.exports={createTokens:LX,validateOperationToken:MX,refreshOperationToken:UX,validateRefreshToken:yL};async function LX(e){if(vS.isEmpty(e)||typeof e!="object")throw dr(new Error,Er.INVALID_AUTH_OBJECT,fr.BAD_REQUEST,void 0,void 0,!0);if(vS.isEmpty(e.username))throw dr(new Error,Er.USERNAME_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);if(vS.isEmpty(e.password))throw dr(new Error,Er.PASSWORD_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await xS.findAndValidateUser(e.username,e.password),!t)throw dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Eu.error(f),dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Td(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await NL(i,r.private_key,r.passphrase),c=await hu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:DX,algorithm:Sd,subject:pd.REFRESH}),u=bL.hash(c),_=new bX(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await OX(_)}catch(f){Eu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw dr(new Error,Er.REFRESH_TOKEN_SAVE_FAILED,fr.INTERNAL_SERVER_ERROR);return NX.signalUserChange(new yX(process.pid)),new wX(o,c)}a(LX,"createTokens");async function NL(e,t,r){return await hu.sign(e,{key:t,passphrase:r},{expiresIn:CX,algorithm:Sd,subject:pd.OPERATION})}a(NL,"signOperationToken");async function Td(){if(HS===void 0)try{let e=BS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PASSPHRASE_NAME),t=BS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=BS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await PS.readFile(e)).toString(),n=(await PS.readFile(t)).toString(),i=(await PS.readFile(r)).toString();HS=new IX(i,n,s)}catch(e){throw Eu.error(e),dr(new Error,Er.NO_ENCRYPTION_KEYS,fr.INTERNAL_SERVER_ERROR)}return HS}a(Td,"getJWTRSAKeys");async function UX(e){if(!e)throw dr(new Error,Er.INVALID_BODY,fr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw dr(new Error,Er.REFRESH_TOKEN_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);await yL(e.refresh_token);let t=await Td(),r=await hu.decode(e.refresh_token);return{operation_token:await NL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(UX,"refreshOperationToken");async function MX(e){try{let t=await Td(),r=await hu.verify(e,t.public_key,{algorithms:Sd,subject:pd.OPERATION});return await xS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Eu.warn(t),t.name&&t.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}}a(MX,"validateOperationToken");async function yL(e){let t;try{let r=await Td(),s=await hu.verify(e,r.public_key,{algorithms:Sd,subject:pd.REFRESH});t=await xS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Eu.warn(r),r.name&&r.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}if(!bL.validate(t.refresh_token,e))throw dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED);return t}a(yL,"validateRefreshToken")});var qS=T((vfe,DL)=>{"use strict";var PX=gL(),_a=require("passport"),vX=require("passport-local").Strategy,BX=require("passport-http").BasicStrategy,HX=require("util"),xX=ts(),CL=HX.callbackify(xX.findAndValidateUser),Pfe=Nr(),qX=L(),IL=mu();_a.use(new vX(function(e,t,r){CL(e,t,r)}));_a.use(new BX(function(e,t,r){CL(e,t,r)}));_a.serializeUser(function(e,t){t(null,e)});_a.deserializeUser(function(e,t){t(null,e)});function FX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),s){case"Basic":_a.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===qX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?IL.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):IL.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:_a.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(FX,"authorize");function GX(e,t){let r=PX(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n?.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(GX,"checkPermissions");DL.exports={authorize:FX,checkPermissions:GX}});var di=T((Hfe,LL)=>{"use strict";var FS=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},GS=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};LL.exports={Node:FS,NodeSubscription:GS}});var ML=T((qfe,UL)=>{"use strict";var kX=L().OPERATIONS_ENUM,kS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=kX.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};UL.exports=kS});var pu=T((Gfe,PL)=>{"use strict";var VS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},$S=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,o,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};PL.exports={RemotePayloadObject:VS,RemotePayloadSubscription:$S}});var BL=T((Vfe,vL)=>{"use strict";var YS=class{static{a(this,"TableSizeObject")}constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};vL.exports=YS});var qL=T((Qfe,xL)=>{"use strict";var VX=BL(),Yfe=dt(),HL=We(),$X=V(),{getSchemaPath:Kfe,getTransactionAuditStorePath:Wfe}=Je(),{getDatabases:YX}=(Ae(),se(Fe));xL.exports=KX;async function KX(e){let t=new VX;try{let r=YX()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await HL.environmentDataSize(schema_path,e.name),o=await HL.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=n.entryCount}catch(r){$X.warn(`unable to stat table dbi due to ${r}`)}return t}a(KX,"lmdbGetTableSize")});var GL=T((Jfe,FL)=>{"use strict";var KS=class{static{a(this,"SystemInformationObject")}constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};FL.exports=KS});var da=T((eEe,YL)=>{"use strict";var WX=require("fs-extra"),QX=require("path"),zt=require("systeminformation"),fi=V(),zX=st(),WS=Ge(),Rd=L(),JX=qL(),$L=Xn(),{getThreadInfo:kL}=Ke(),sT=Z();sT.initSync();var jX=GL(),{openEnvironment:Xfe}=We(),{getSchemaPath:Zfe}=Je(),{database:XX}=(Ae(),se(Fe)),gd;YL.exports={getHDBProcessInfo:jS,getNetworkInfo:ZS,getDiskInfo:XS,getMemoryInfo:JS,getCPUInfo:zS,getTimeInfo:QS,getSystemInformation:eT,systemInformation:ZX,getTableSize:tT,getMetrics:rT};function QS(){return zt.time()}a(QS,"getTimeInfo");async function zS(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await zt.cpu();l.cpu_speed=await zt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:A,...R}=await zt.currentLoad();return R.cpus=[],A.forEach(g=>{let{raw_load:P,raw_load_idle:H,raw_load_irq:v,raw_load_nice:U,raw_load_system:Y,raw_load_user:K,...z}=g;R.cpus.push(z)}),l.current_load=R,l}catch(e){return fi.error(`error in getCPUInfo: ${e}`),{}}}a(zS,"getCPUInfo");async function JS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await zt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return fi.error(`error in getMemoryInfo: ${e}`),{}}}a(JS,"getMemoryInfo");async function jS(){let e={core:[],clustering:[]};try{let t=await zt.processes(),r;try{r=Number.parseInt(await WX.readFile(QX.join(sT.get(Rd.CONFIG_PARAMS.ROOTPATH),Rd.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Rd.NODE_ERROR_CODES.ENOENT)fi.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return fi.error(`error in getHDBProcessInfo: ${t}`),e}}a(jS,"getHDBProcessInfo");async function XS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await zt.fsStats();return e.read_write=_,e.size=await zt.fsSize(),e}catch(t){return fi.error(`error in getDiskInfo: ${t}`),e}}a(XS,"getDiskInfo");async function ZS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await zt.networkInterfaceDefault(),e.latency=await zt.inetChecksite("google.com"),(await zt.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=s;e.interfaces.push(f)}),(await zt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return fi.error(`error in getNetworkInfo: ${t}`),e}}a(ZS,"getNetworkInfo");async function eT(){if(gd!==void 0)return gd;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await zt.osInfo();e=c;let u=await zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,gd=e,gd}catch(t){return fi.error(`error in getSystemInformation: ${t}`),e}}a(eT,"getSystemInformation");async function tT(){let e=[],t=await $L.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await JX(s));return e}a(tT,"getTableSize");async function rT(){let e=await $L.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=XX({database:r,table:n}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),s[n]=o}catch(i){fi.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(rT,"getMetrics");async function VL(){if(sT.get(Rd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await zX.getNATSReferences(),r=await t.streams.info(WS.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(WS.WORK_QUEUE_CONSUMER_NAMES.stream_name,WS.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.sources&&(n.ingest.stream.sources=r.sources),n}}a(VL,"getNatsStreamInfo");async function ZX(e){let t=new jX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await eT(),t.time=QS(),t.cpu=await zS(),t.memory=await JS(),t.disk=await XS(),t.network=await ZS(),t.harperdb_processes=await jS(),t.table_size=await tT(),t.metrics=await rT(),t.threads=await kL(),t.replication=await VL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await eT();break;case"time":t.time=QS();break;case"cpu":t.cpu=await zS();break;case"memory":t.memory=await JS();break;case"disk":t.disk=await XS();break;case"network":t.network=await ZS();break;case"harperdb_processes":t.harperdb_processes=await jS();break;case"table_size":t.table_size=await tT();break;case"database_metrics":case"metrics":t.metrics=await rT();break;case"threads":t.threads=await kL();break;case"replication":t.replication=await VL();break;default:break}return t}a(ZX,"systemInformation")});var Od=T((rEe,KL)=>{"use strict";KL.exports={version:eZ,printVersion:tZ};var Ad=Zc();function eZ(){if(Ad)return Ad.version}a(eZ,"version");function tZ(){Ad&&console.log(`HarperDB Version ${Ad.version}`)}a(tZ,"printVersion")});var is=T((oEe,JL)=>{"use strict";var rZ=Cr(),nT=J(),sZ=require("util"),co=L(),WL=Z();WL.initSync();var nZ=qS(),QL=es(),{Node:nEe,NodeSubscription:iEe}=di(),iZ=ta(),oZ=ML(),{RemotePayloadObject:aZ,RemotePayloadSubscription:cZ}=pu(),{handleHDBError:uZ,hdb_errors:lZ}=re(),{HTTP_STATUS_CODES:_Z,HDB_ERROR_MSGS:dZ}=lZ,fZ=Js(),EZ=da(),hZ=Od(),{getDatabases:mZ}=(Ae(),se(Fe)),pZ=sZ.promisify(nZ.authorize),SZ=QL.searchByHash,TZ=QL.searchByValue;JL.exports={authHeaderToUser:gZ,isEmpty:RZ,getNodeRecord:AZ,upsertNodeRecord:OZ,buildNodePayloads:bZ,checkClusteringEnabled:NZ,getAllNodeRecords:yZ,getSystemInfo:wZ,reverseSubscription:zL};async function gZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await pZ(t,null),e}a(gZ,"authHeaderToUser");function RZ(e){return e==null}a(RZ,"isEmpty");async function AZ(e){let t=new iZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return SZ(t)}a(AZ,"getNodeRecord");async function OZ(e){let t=new oZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return rZ.upsert(t)}a(OZ,"upsertNodeRecord");function zL(e){if(nT.isEmpty(e.subscribe)||nT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(zL,"reverseSubscription");function bZ(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=nT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=zL(c),E=mZ()[u]?.[_],h=new cZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new aZ(r,t,n,s)}a(bZ,"buildNodePayloads");function NZ(){if(!WL.get(co.CONFIG_PARAMS.CLUSTERING_ENABLED))throw uZ(new Error,dZ.CLUSTERING_NOT_ENABLED,_Z.BAD_REQUEST,void 0,void 0,!0)}a(NZ,"checkClusteringEnabled");async function yZ(){let e=new fZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await TZ(e))}a(yZ,"getAllNodeRecords");async function wZ(){let e=await EZ.getSystemInformation();return{hdb_version:hZ.version(),node_version:e.node_version,platform:e.platform}}a(wZ,"getSystemInfo")});var iT=T((cEe,nU)=>{"use strict";var bd=st(),jL=J(),XL=Ge(),ZL=L(),Nd=V(),eU=lu(),IZ=$_(),{RemotePayloadObject:CZ}=pu(),{handleHDBError:tU,hdb_errors:DZ}=re(),{HTTP_STATUS_CODES:rU}=DZ,{NodeSubscription:sU}=di();nU.exports=LZ;async function LZ(e,t){let r;try{r=await bd.request(`${t}.${XL.REQUEST_SUFFIX}`,new CZ(ZL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Nd.trace("Response from remote describe all request:",r)}catch(o){Nd.error(`addNode received error from describe all request to remote node: ${o}`);let c=bd.requestErrorHandler(o,"add_node",t);throw tU(new Error,c,rU.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===XL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw tU(new Error,o,rU.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===ZL.SYSTEM_SCHEMA_NAME){await bd.createLocalTableStream(u,c);let h=new sU(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=jL.doesSchemaExist(u),l=s[u]!==void 0,d=c?jL.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(Nd.trace(`addNode creating schema: ${u}`),await eU.createSchema({operation:"create_schema",schema:u})),!d&&f){Nd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new IZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await eU.createTable(h)}await bd.createLocalTableStream(u,c);let E=new sU(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(LZ,"reviewSubscriptions")});var Id=T((lEe,aU)=>{"use strict";var{handleHDBError:yd,hdb_errors:UZ}=re(),{HTTP_STATUS_CODES:wd}=UZ,{addUpdateNodeValidator:MZ}=hd(),Su=V(),oU=L(),iU=Ge(),PZ=J(),oT=st(),Tu=is(),vZ=Z(),BZ=iT(),{Node:HZ,NodeSubscription:xZ}=di(),{broadcast:qZ}=Ke(),FZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",GZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",kZ=vZ.get(oU.CONFIG_PARAMS.CLUSTERING_NODENAME);aU.exports=VZ;async function VZ(e,t=!1){Su.trace("addNode called with:",e),Tu.checkClusteringEnabled();let r=MZ(e);if(r)throw yd(r,r.message,wd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Tu.getNodeRecord(s);if(!PZ.isEmptyOrZeroLength(d))throw yd(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,wd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await BZ(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=FZ,o;let c=Tu.buildNodePayloads(n,kZ,oU.OPERATIONS_ENUM.ADD_NODE,await Tu.getSystemInfo());Su.trace("addNode sending remote payload:",c);let u;try{u=await oT.request(`${s}.${iU.REQUEST_SUFFIX}`,c)}catch(d){Su.error(`addNode received error from request: ${d}`);let f=oT.requestErrorHandler(d,"add_node",s);throw yd(new Error,f,wd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===iU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw yd(new Error,d,wd.INTERNAL_SERVER_ERROR,"error",d)}Su.trace(u);let _=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];Su.trace("Add node updating work stream for node:",s,"subscriptions:",E),await oT.updateWorkStream(E,s),n[d].start_time===void 0&&delete n[d].start_time,_.push(new xZ(E.schema,E.table,E.publish,E.subscribe))}let l=new HZ(s,_,u.system_info);return await Tu.upsertNodeRecord(l),qZ({type:"nats_update"}),i.length>0?o.message=GZ:o.message=`Successfully added '${s}' to manifest`,o}a(VZ,"addNode")});var lT=T((fEe,lU)=>{"use strict";var{handleHDBError:aT,hdb_errors:$Z}=re(),{HTTP_STATUS_CODES:cT}=$Z,{addUpdateNodeValidator:YZ}=hd(),gu=V(),uU=L(),cU=Ge(),dEe=J(),uT=st(),Ru=is(),KZ=Z(),{cloneDeep:WZ}=require("lodash"),QZ=iT(),{Node:zZ,NodeSubscription:JZ}=di(),{broadcast:jZ}=Ke(),XZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",ZZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",e5=KZ.get(uU.CONFIG_PARAMS.CLUSTERING_NODENAME);lU.exports=t5;async function t5(e){gu.trace("updateNode called with:",e),Ru.checkClusteringEnabled();let t=YZ(e);if(t)throw aT(t,t.message,cT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await Ru.getNodeRecord(r);n.length>0&&(s=WZ(n));let{added:i,skipped:o}=await QZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=XZ,c;let u=Ru.buildNodePayloads(i,e5,uU.OPERATIONS_ENUM.UPDATE_NODE,await Ru.getSystemInfo());gu.trace("updateNode sending remote payload:",u);let _;try{_=await uT.request(`${r}.${cU.REQUEST_SUFFIX}`,u)}catch(l){gu.error(`updateNode received error from request: ${l}`);let d=uT.requestErrorHandler(l,"update_node",r);throw aT(new Error,d,cT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===cU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw aT(new Error,l,cT.INTERNAL_SERVER_ERROR,"error",l)}gu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];gu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await uT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return s||(s=[new zZ(r,[],_.system_info)]),await r5(s[0],i,_.system_info),o.length>0?c.message=ZZ:c.message=`Successfully updated '${r}'`,c}a(t5,"updateNode");async function r5(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=s.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new JZ(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Ru.upsertNodeRecord(s),jZ({type:"nats_update"})}a(r5,"updateNodeTable")});var hU=T((hEe,EU)=>{"use strict";var fU=require("joi"),{string:_U}=fU.types(),s5=je(),dU=L(),n5=Z(),i5=Ge();EU.exports=o5;function o5(e){let t=_U.invalid(n5.get(dU.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(i5.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=fU.object({operation:_U.valid(dU.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return s5.validateBySchema(e,r)}a(o5,"removeNodeValidator")});var Dd=T((pEe,RU)=>{"use strict";var{handleHDBError:mU,hdb_errors:a5}=re(),{HTTP_STATUS_CODES:pU}=a5,c5=hU(),Au=V(),SU=is(),u5=J(),Cd=L(),TU=Ge(),gU=st(),l5=Z(),{RemotePayloadObject:_5}=pu(),{NodeSubscription:d5}=di(),f5=ra(),E5=ti(),{broadcast:h5}=Ke(),m5=l5.get(Cd.CONFIG_PARAMS.CLUSTERING_NODENAME);RU.exports=p5;async function p5(e){Au.trace("removeNode called with:",e),SU.checkClusteringEnabled();let t=c5(e);if(t)throw mU(t,t.message,pU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await SU.getNodeRecord(r);if(u5.isEmptyOrZeroLength(s))throw mU(new Error,`Node '${r}' was not found.`,pU.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new _5(Cd.OPERATIONS_ENUM.REMOVE_NODE,m5,[]),i,o=!1;try{i=await gU.request(`${r}.${TU.REQUEST_SUFFIX}`,n),Au.trace("Remove node reply from remote node:",r,i)}catch(u){Au.error("removeNode received error from request:",u),o=!0}for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];Au.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new d5(l.schema,l.table,!1,!1);await gU.updateWorkStream(d,r)}let c=new f5(Cd.SYSTEM_SCHEMA_NAME,Cd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await E5.deleteRecord(c),h5({type:"nats_update"}),i?.status===TU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Au.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(p5,"removeNode")});var bU=T((TEe,OU)=>{"use strict";var AU=require("joi"),{string:S5,array:T5}=AU.types(),g5=je(),R5=hd();OU.exports=A5;function A5(e){let t=AU.object({operation:S5.valid("configure_cluster").required(),connections:T5.items(R5.validation_schema).required()});return g5.validateBySchema(e,t)}a(A5,"configureClusterValidator")});var _T=T((REe,CU)=>{"use strict";var O5=L(),Ld=V(),b5=J(),N5=Dd(),y5=Id(),NU=is(),w5=bU(),{handleHDBError:yU,hdb_errors:I5}=re(),{HTTP_STATUS_CODES:wU}=I5,C5="Configure cluster complete.",D5="Failed to configure the cluster. Check the logs for more details.",L5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";CU.exports=U5;async function U5(e){Ld.trace("configure cluster called with:",e),NU.checkClusteringEnabled();let t=w5(e);if(t)throw yU(t,t.message,wU.BAD_REQUEST,void 0,void 0,!0);let r=await NU.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(IU(N5,{operation:O5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let n=await Promise.allSettled(s);Ld.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(IU(y5,E,E.node_name))}let c=await Promise.allSettled(i);Ld.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=n.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(Ld.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let p=h?.value?.result;typeof p=="string"&&p.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(b5.isEmptyOrZeroLength(u))return{message:C5,connections:_};if(l)return{message:L5,failed_nodes:u,connections:_};throw yU(new Error,D5,wU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(U5,"configureCluster");async function IU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(IU,"functionWrapper")});var LU=T((OEe,DU)=>{"use strict";var Ud=require("joi"),M5=je(),{validateSchemaExists:P5,validateTableExists:v5,validateSchemaName:B5}=Ys(),H5=Ud.object({operation:Ud.string().valid("purge_stream"),schema:Ud.string().custom(P5).custom(B5).required(),table:Ud.string().custom(v5).required()});function x5(e){return M5.validateBySchema(e,H5)}a(x5,"purgeStreamValidator");DU.exports=x5});var dT=T((NEe,UU)=>{"use strict";var{handleHDBError:q5,hdb_errors:F5}=re(),{HTTP_STATUS_CODES:G5}=F5,k5=LU(),V5=st(),$5=is();UU.exports=Y5;async function Y5(e){if(e.purge_ingest!==!0){let n=k5(e);if(n)throw q5(n,n.message,G5.BAD_REQUEST,void 0,void 0,!0)}$5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await V5.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(Y5,"purgeStream")});var hT=T((wEe,xU)=>{"use strict";var ET=is(),K5=st(),vU=Z(),Md=L(),uo=Ge(),W5=J(),fT=V(),{RemotePayloadObject:Q5}=pu(),{ErrorCode:MU}=require("nats"),PU=vU.get(Md.CONFIG_PARAMS.CLUSTERING_ENABLED),BU=vU.get(Md.CONFIG_PARAMS.CLUSTERING_NODENAME);xU.exports={clusterStatus:z5,buildNodeStatus:HU};async function z5(){let e={node_name:BU,is_enabled:PU,connections:[]};if(!PU)return e;let t=await ET.getAllNodeRecords();if(W5.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(HU(t[s],e.connections));return await Promise.allSettled(r),e}a(z5,"clusterStatus");async function HU(e,t){let r=e.name,s=new Q5(Md.OPERATIONS_ENUM.CLUSTER_STATUS,BU,void 0,await ET.getSystemInfo()),n,i,o=uo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await K5.request(uo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===uo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=uo.CLUSTER_STATUS_STATUSES.CLOSED,fT.error(`Error getting node status from ${r} `,n))}catch(u){fT.warn(`Error getting node status from ${r}`,u),u.code===MU.NoResponders?o=uo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===MU.Timeout?o=uo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=uo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new J5(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Md.PRE_4_0_0_VERSION&&await ET.upsertNodeRecord(u)}catch(u){fT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(HU,"buildNodeStatus");function J5(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(J5,"NodeStatusObject")});var pT=T((CEe,qU)=>{"use strict";var{handleHDBError:j5,hdb_errors:X5}=re(),{HTTP_STATUS_CODES:Z5}=X5,e8=st(),t8=is(),mT=J(),Pd=require("joi"),r8=je(),s8=2e3,n8=Pd.object({timeout:Pd.number().min(1),connected_nodes:Pd.boolean(),routes:Pd.boolean()});qU.exports=i8;async function i8(e){t8.checkClusteringEnabled();let t=r8.validateBySchema(e,n8);if(t)throw j5(t,t.message,Z5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||mT.autoCastBoolean(s),o=n===void 0||mT.autoCastBoolean(n),c={nodes:[]},u=await e8.getServerList(r??s8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:mT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(i8,"clusterNetwork")});var VU=T((LEe,kU)=>{"use strict";var ST=require("joi"),FU=je(),{route_constraints:GU}=qm();kU.exports={setRoutesValidator:o8,deleteRoutesValidator:a8};function o8(e){let t=ST.object({server:ST.valid("hub","leaf").required(),routes:GU.required()});return FU.validateBySchema(e,t)}a(o8,"setRoutesValidator");function a8(e){let t=ST.object({routes:GU.required()});return FU.validateBySchema(e,t)}a(a8,"deleteRoutesValidator")});var gT=T((MEe,WU)=>{"use strict";var lo=Ur(),TT=J(),vd=L(),$U=VU(),{handleHDBError:YU,hdb_errors:c8}=re(),{HTTP_STATUS_CODES:KU}=c8,u8="cluster routes successfully set",l8="cluster routes successfully deleted";WU.exports={setRoutes:_8,getRoutes:d8,deleteRoutes:f8};function _8(e){let t=$U.setRoutesValidator(e);if(t)throw YU(t,t.message,KU.BAD_REQUEST,void 0,void 0,!0);let r=lo.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=TT.autoCast(_.port);let l=s.some(f=>f.host===_.host&&f.port===_.port),d=n.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(s.push(_),o.push(_))}return e.server==="hub"?lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:u8,set:o,skipped:i}}a(_8,"setRoutes");function d8(){let e=lo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(d8,"getRoutes");function f8(e){let t=$U.deleteRoutesValidator(e);if(t)throw YU(t,t.message,KU.BAD_REQUEST,void 0,void 0,!0);let r=lo.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=TT.isEmptyOrZeroLength(s)?null:s,lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=TT.isEmptyOrZeroLength(n)?null:n,lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:l8,deleted:i,skipped:o}}a(f8,"deleteRoutes")});var zU=T((vEe,QU)=>{"use strict";var Ou=require("alasql"),_o=require("recursive-iterator"),Ms=V(),E8=J(),bu=L(),RT=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,m8(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>bu.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!bu.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][bu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=h8(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!bu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Ou.yy.Column({columnid:_});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function h8(e){return e.filter(t=>t[bu.PERMS_CRUD_ENUM.READ])}a(h8,"filterReadRestrictedAttrs");function m8(e,t,r,s,n){p8(e,t,r,s,n)}a(m8,"interpretAST");function Nu(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(Nu,"addSchemaTableToMap");function p8(e,t,r,s,n){if(!e){Ms.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Ou.yy.Insert?R8(e,t,r):e instanceof Ou.yy.Select?S8(e,t,r,s,n):e instanceof Ou.yy.Update?T8(e,t,r):e instanceof Ou.yy.Delete?g8(e,t,r):Ms.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(p8,"getRecordAttributesAST");function S8(e,t,r,s,n){if(!e){Ms.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(E8.isEmptyOrZeroLength(i)){Ms.error("No schema specified");return}e.from.forEach(c=>{Nu(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Nu(c.table,t,r,s,n)});let o=new _o(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Ms.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new _o(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Ms.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new _o(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Ms.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new _o(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Ms.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(S8,"getSelectAttributes");function T8(e,t,r){if(!e){Ms.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new _o(e.columns),n=e.table.databaseid;Nu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&AT(e.table.tableid,n,i.columnid,t,r)}a(T8,"getUpdateAttributes");function g8(e,t,r){if(!e){Ms.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new _o(e.where),n=e.table.databaseid;Nu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&AT(e.table.tableid,n,i.columnid,t,r)}a(g8,"getDeleteAttributes");function R8(e,t,r){if(!e){Ms.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new _o(e.columns),n=e.into.databaseid;Nu(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&AT(e.into.tableid,n,i.columnid,t,r)}a(R8,"getInsertAttributes");function AT(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(AT,"pushAttribute");QU.exports=RT});var NT=T((HEe,ZU)=>{var Bd=Wi(),JU=require("chalk"),qr=V(),jU=require("prompt"),{promisify:A8}=require("util"),OT=L(),O8=require("fs-extra"),b8=require("path"),N8=J(),y8=Od(),XU=Z();XU.initSync();var w8=require("moment"),I8=A8(jU.get),C8=b8.join(XU.getHdbBasePath(),OT.LICENSE_KEY_DIR_NAME,OT.LICENSE_FILE_NAME,OT.LICENSE_FILE_NAME);ZU.exports={getFingerprint:L8,setLicense:D8,parseLicense:bT,register:U8,getRegistrationInfo:P8};async function D8(e){if(e&&e.key&&e.company){try{qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await bT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw qr.error(r),qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(D8,"setLicense");async function L8(){let e={};try{e=await Bd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw qr.error(r),qr.error(t),new Error(r)}return e}a(L8,"getFingerprint");async function bT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");qr.info("Validating license input...");let r=Bd.validateLicense(e,t);if(qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{qr.info("writing license to disk"),await O8.writeFile(C8,JSON.stringify({license_key:e,company:t}))}catch(s){throw qr.error("Failed to write License"),s}return"Registration successful."}a(bT,"parseLicense");async function U8(){let e=await M8();return bT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(U8,"register");async function M8(){let e=await Bd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:JU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:JU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{jU.start()}catch(s){qr.error(s)}let r;try{r=await I8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(M8,"promptForRegistration");async function P8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Bd.getLicense()}catch(r){throw qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(N8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=y8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=w8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(P8,"getRegistrationInfo")});var tM=T((qEe,eM)=>{"use strict";var v8=Ge(),yT=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+v8.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};eM.exports=yT});var nM=T((GEe,sM)=>{"use strict";var rM=Ge(),wT=class{static{a(this,"LeafConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+rM.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+rM.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};sM.exports=wT});var oM=T((VEe,iM)=>{"use strict";var IT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};iM.exports=IT});var cM=T((YEe,aM)=>{"use strict";var B8=Ge(),CT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+B8.SERVER_SUFFIX.ADMIN,this.password=r}};aM.exports=CT});var UT=T((WEe,_M)=>{"use strict";var fa=require("path"),qd=require("fs-extra"),H8=tM(),x8=nM(),q8=oM(),F8=cM(),DT=ts(),ha=J(),hr=Ur(),xd=L(),yu=Ge(),{CONFIG_PARAMS:_t}=xd,wu=V(),Iu=Z(),uM=Sn(),LT=st(),Ea="clustering",G8=1e4,lM=5;_M.exports={generateNatsConfig:V8,removeNatsConfig:$8,getHubConfigPath:k8};function k8(){let e=Iu.get(_t.ROOTPATH);return fa.join(e,Ea,yu.NATS_CONFIG_FILES.HUB_SERVER)}a(k8,"getHubConfigPath");async function V8(e=!1,t=void 0){Iu.initSync();let r=Iu.get(_t.ROOTPATH),s=fa.join(r,Ea,yu.PID_FILES.HUB),n=fa.join(r,Ea,yu.PID_FILES.LEAF),i=hr.getConfigFromFile(_t.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=fa.join(r,Ea,yu.NATS_CONFIG_FILES.HUB_SERVER),c=fa.join(r,Ea,yu.NATS_CONFIG_FILES.LEAF_SERVER),u=hr.getConfigFromFile(_t.CLUSTERING_TLS_CERTIFICATE),_=hr.getConfigFromFile(_t.CLUSTERING_TLS_PRIVATEKEY),l=hr.getConfigFromFile(_t.CLUSTERING_TLS_CERT_AUTH),d=hr.getConfigFromFile(_t.CLUSTERING_TLS_INSECURE),f=hr.getConfigFromFile(_t.CLUSTERING_TLS_VERIFY),E=hr.getConfigFromFile(_t.CLUSTERING_NODENAME),h=hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await LT.checkNATSServerInstalled()||Fd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await DT.listUsers(),S=hr.getConfigFromFile(_t.CLUSTERING_USER),A=await DT.getClusterUser();(ha.isEmpty(A)||A.active!==!0)&&Fd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Hd(_t.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Hd(_t.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Hd(_t.CLUSTERING_HUBSERVER_NETWORK_PORT),await Hd(_t.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],g=[];for(let[z,ne]of p.entries())ne.role.role===xd.ROLE_TYPES_ENUM.CLUSTER_USER&&ne.active&&(R.push(new F8(ne.username,uM.decrypt(ne.hash))),g.push(new q8(ne.username,uM.decrypt(ne.hash))));let P=[],{hub_routes:H}=hr.getClusteringRoutes();if(!ha.isEmptyOrZeroLength(H))for(let z of H)P.push(`tls://${A.sys_name_encoded}:${A.uri_encoded_d_hash}@${z.host}:${z.port}`);let v=new H8(hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_CLUSTER_NAME),hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),P,R,g);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=ha.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===xd.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await qd.writeJson(o,v),wu.trace(`Hub server config written to ${o}`));let U=`tls://${A.sys_name_encoded}:${A.uri_encoded_d_hash}@0.0.0.0:${h}`,Y=`tls://${A.uri_encoded_name}:${A.uri_encoded_d_hash}@0.0.0.0:${h}`,K=new x8(hr.getConfigFromFile(_t.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[U],[Y],R,g,u,_,l,d);l==null&&delete K.tls.ca_file,(t===void 0||t===xd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await qd.writeJson(c,K),wu.trace(`Leaf server config written to ${c}`))}a(V8,"generateNatsConfig");async function Hd(e){let t=Iu.get(e);return ha.isEmpty(t)&&Fd(`port undefined for '${e}'`),await ha.isPortTaken(t)&&Fd(`'${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(Hd,"isPortAvailable");function Fd(e){let t=`Error generating clustering config: ${e}`;wu.error(t),console.error(t),process.exit(1)}a(Fd,"generateNatsConfigError");async function $8(e){let{port:t,config_file:r}=LT.getServerConfig(e),{username:s,decrypt_hash:n}=await DT.getClusterUser(),i=0,o=2e3;for(;i<lM;){try{let _=await LT.createConnection(t,s,n,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){wu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=lM)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await ha.async_set_timeout(o*(i*2))}let c="0".repeat(G8),u=fa.join(Iu.get(_t.ROOTPATH),Ea,r);await qd.writeFile(u,c),await qd.remove(u),wu.notify(e,"started.")}a($8,"removeNatsConfig")});var pM=T((zEe,mM)=>{"use strict";var Fr=Z(),Y8=Wi(),he=L(),Cu=Ge(),Nn=require("path"),{PACKAGE_ROOT:kd}=L(),dM=Z(),Gd=J(),ma="/dev/null",K8=Nn.join(kd,"launchServiceScripts"),fM=Nn.join(kd,"utility/scripts"),W8=Nn.join(fM,he.HDB_RESTART_SCRIPT),EM=Nn.resolve(kd,"dependencies",`${process.platform}-${process.arch}`,Cu.NATS_BINARY_NAME);function hM(){let t=Y8.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,s={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Gd.noBootFile()&&(s[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Gd.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:kd}}a(hM,"generateMainServerConfig");var Q8=9930;function z8(){Fr.initSync(!0);let e=Fr.get(he.CONFIG_PARAMS.ROOTPATH),t=Nn.join(e,"clustering",Cu.NATS_CONFIG_FILES.HUB_SERVER),r=Nn.join(Fr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=dM.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=Cu.LOG_LEVEL_FLAGS[Fr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==Q8?"-"+s:""),script:EM,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ma,i.error_file=ma),i}a(z8,"generateNatsHubServerConfig");var J8=9940;function j8(){Fr.initSync(!0);let e=Fr.get(he.CONFIG_PARAMS.ROOTPATH),t=Nn.join(e,"clustering",Cu.NATS_CONFIG_FILES.LEAF_SERVER),r=Nn.join(Fr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=dM.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=Cu.LOG_LEVEL_FLAGS[Fr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==J8?"-"+s:""),script:EM,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ma,i.error_file=ma),i}a(j8,"generateNatsLeafServerConfig");function X8(){Fr.initSync();let e=Nn.join(Fr.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:K8,autorestart:!1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ma,t.error_file=ma),t}a(X8,"generateClusteringUpgradeV4ServiceConfig");function Z8(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return Gd.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Gd.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:fM},script:W8}}a(Z8,"generateRestart");function e6(){return{apps:[hM()]}}a(e6,"generateAllServiceConfigs");mM.exports={generateAllServiceConfigs:e6,generateMainServerConfig:hM,generateRestart:Z8,generateNatsHubServerConfig:z8,generateNatsLeafServerConfig:j8,generateClusteringUpgradeV4ServiceConfig:X8}});var LM=T((XEe,DM)=>{"use strict";var ve=L(),t6=J(),yn=UT(),Du=st(),en=Ge(),Ei=pM(),Vd=Z(),hi=V(),r6=is(),{startWorker:SM,onMessageFromWorkers:s6}=Ke(),n6=da(),jEe=require("util"),i6=require("child_process"),o6=require("fs"),{execFile:a6}=i6,we;DM.exports={enterPM2Mode:c6,start:mi,stop:MT,reload:gM,restart:RM,list:PT,describe:OM,connect:wn,kill:f6,startAllServices:E6,startService:vT,getUniqueServicesList:bM,restartAllServices:h6,isServiceRegistered:NM,reloadStopStart:yM,restartHdb:AM,deleteProcess:_6,startClusteringProcesses:IM,startClusteringThreads:CM,isHdbRestartRunning:d6,isClusteringRunning:p6,stopClustering:m6,reloadClustering:S6};var Lu=!1;s6(e=>{e.type==="restart"&&Vd.initSync(!0)});function c6(){Lu=!0}a(c6,"enterPM2Mode");function wn(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,s)=>{hi.setupConsoleLogging(),r&&t(r),e(s)})})}a(wn,"connect");var mr,u6=10,TM;function mi(e,t=!1){if(Lu)return l6(e);let r=a6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=mr.indexOf(r);o>-1&&mr.splice(o,1),!TM&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<u6&&(o6.existsSync(yn.getHubConfigPath())?mi(e):(await yn.generateNatsConfig(!0),mi(e),await new Promise(c=>setTimeout(c,3e3)),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=Vd.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&en.LOG_LEVEL_HIERARCHY[o]>=en.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===en.LOG_LEVELS.ERR||l===en.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=en.LOG_LEVELS[f]}if(en.LOG_LEVEL_HIERARCHY[o]>=en.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===en.LOG_LEVELS.ERR||l===en.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),mr=[],!mr&&!t){let i=a(()=>{TM=!0,mr&&(mr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}mr.push(r)}a(mi,"start");function l6(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.start(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(l6,"startWithPM2");function MT(e){if(!Lu){for(let t of mr||[])t.name===e&&(mr.splice(mr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.stop(e,async(s,n)=>{s&&(we.disconnect(),r(s)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(s)),we.disconnect(),t(o)})})})}a(MT,"stop");function gM(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.reload(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(gM,"reload");function RM(e){if(!Lu)for(let t of mr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.restart(e,(s,n)=>{we.disconnect(),t(n)})})}a(RM,"restart");function _6(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.delete(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(_6,"deleteProcess");async function AM(){await mi(Ei.generateRestart())}a(AM,"restartHdb");async function d6(){let e=await PT();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(d6,"isHdbRestartRunning");function PT(){return new Promise(async(e,t)=>{try{await wn()}catch(r){t(r)}we.list((r,s)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(s)})})}a(PT,"list");function OM(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.describe(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(OM,"describe");function f6(){if(!Lu){for(let e of mr||[])e.kill();mr=[];return}return new Promise(async(e,t)=>{try{await wn()}catch(r){t(r)}we.killDaemon((r,s)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(s)})})}a(f6,"kill");async function E6(){try{await IM(),await CM(),await mi(Ei.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(E6,"startAllServices");async function vT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ei.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ei.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ei.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ei.generateNatsHubServerConfig(),await mi(r,t),await yn.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ei.generateNatsLeafServerConfig(),await mi(r,t),await yn.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ei.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await mi(r)}catch(r){throw we?.disconnect(),r}}a(vT,"startService");async function bM(){try{let e=await PT(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(bM,"getUniqueServicesList");async function h6(e=[]){try{let t=!1,r=await bM();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await RM(o))}t&&await yM(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(h6,"restartAllServices");async function NM(e){if(mr?.find(r=>r.name===e))return!0;let t=await n6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(NM,"isServiceRegistered");async function yM(e){let t=Vd.get(ve.CONFIG_PARAMS.THREADS_COUNT)??Vd.get(ve.CONFIG_PARAMS.THREADS),r=await OM(e),s=t6.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await MT(e),await vT(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await AM():await gM(e)}a(yM,"reloadStopStart");var wM;async function IM(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await vT(r,e)}}a(IM,"startClusteringProcesses");async function CM(){wM=SM(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Du.createWorkQueueStream(en.WORK_QUEUE_CONSUMER_NAMES),await Du.updateIngestStreamConsumer(),await Du.updateLocalStreams();let e=await r6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){hi.info("Starting clustering upgrade 4.0.0 process"),SM(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(CM,"startClusteringThreads");async function m6(){for(let e in ve.CLUSTERING_PROCESSES)if(e!==ve.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ve.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await wM.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await MT(t)}}a(m6,"stopClustering");async function p6(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await NM(t)===!1)return!1}return!0}a(p6,"isClusteringRunning");async function S6(){await yn.generateNatsConfig(!0),await Du.reloadNATSHub(),await Du.reloadNATSLeaf(),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(S6,"reloadClustering")});var Wd=T((ehe,xM)=>{"use strict";var T6=require("minimist"),{isMainThread:xT,parentPort:PM}=require("worker_threads"),nt=L(),{PROCESS_DESCRIPTORS_VALIDATE:Uu}=nt,tn=V(),qT=J(),$d=UT(),pa=st(),BT=Ge(),vM=Ur(),rn=LM(),UM=da(),g6=dh(),{restartWorkers:Yd,onMessageByType:R6}=Ke(),{handleHDBError:A6,hdb_errors:O6}=re(),{HTTP_STATUS_CODES:b6}=O6,Kd=Z();Kd.initSync();var Mu=`Restarting HarperDB. This may take up to ${nt.RESTART_TIMEOUT_MS/1e3} seconds.`,N6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",MM="Clustering is not enabled so cannot be restarted",y6="Invalid service",Sa,os;xM.exports={restart:BM,restartService:FT};xT&&R6(nt.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?FT({service:e.workerType}):BM({operation:"restart"})});async function BM(e){os=Object.keys(e).length===0,Sa=await rn.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR);let t=T6(process.argv);if(t.service){await FT(t);return}if(os&&!Sa){console.error(N6);return}if(os&&console.log(Mu),Sa){rn.enterPM2Mode(),tn.notify(Mu);let r=g6(Object.keys(nt.CONFIG_PARAM_MAP),!0);return qT.isEmptyOrZeroLength(Object.keys(r))||vM.updateConfigValue(void 0,void 0,r,!0,!0),I6(),Mu}return xT?(tn.notify(Mu),setTimeout(()=>{Yd()},50)):PM.postMessage({type:nt.ITC_EVENT_TYPES.RESTART}),Mu}a(BM,"restart");async function FT(e){let{service:t}=e;if(nt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw A6(new Error,y6,b6.BAD_REQUEST,void 0,void 0,!0);if(Sa=await rn.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR),!xT)return PM.postMessage({type:nt.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Uu.clustering:if(!Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=MM;break}os&&console.log("Restarting clustering"),tn.notify("Restarting clustering"),await HM();break;case Uu.clustering_config:case Uu["clustering config"]:if(!Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=MM;break}os&&console.log("Restarting clustering_config"),tn.notify("Restarting clustering_config"),await rn.reloadClustering();break;case"custom_functions":case"custom functions":case Uu.harperdb:case Uu.http_workers:if(os&&!Sa){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}os&&console.log("Restarting http_workers"),tn.notify("Restarting http_workers"),os?await rn.restart(nt.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Yd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(tn.error(r),os&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(FT,"restartService");async function w6(){await pa.publishToStream(`${BT.SUBJECT_PREFIXES.TXN}.${BT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,BT.WORK_QUEUE_CONSUMER_NAMES.stream_name,pa.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(w6,"postDummyNatsMsg");async function I6(){await HM(),await rn.restart(nt.HDB_PROC_DESCRIPTOR),await qT.async_set_timeout(2e3),Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await HT(),os&&(await pa.closeConnection(),process.exit(0))}a(I6,"restartPM2Mode");async function HM(){if(!vM.getConfigFromFile(nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await UM.getHDBProcessInfo()).clustering.length===0)tn.trace("Clustering not running, restart will start clustering services"),await $d.generateNatsConfig(!0),await rn.startClusteringProcesses(),await rn.startClusteringThreads(),await HT(),os&&await pa.closeConnection();else{await w6(),await $d.generateNatsConfig(!0),Sa?(tn.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await rn.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await rn.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await UM.getHDBProcessInfo()).clustering.forEach(n=>{tn.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await qT.async_set_timeout(3e3),await HT(),await pa.updateLocalStreams(),os&&await pa.closeConnection(),tn.trace("Restart clustering restarting ingest and reply service threads");let t=Yd(nt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Yd(nt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(HM,"restartClustering");async function HT(){await $d.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await $d.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(HT,"removeNatsConfig")});var zM=T((she,QM)=>{"use strict";var rhe=require("lodash"),pr=L(),{handleHDBError:qM,hdb_errors:C6}=re(),{HDB_ERROR_MSGS:D6,HTTP_STATUS_CODES:L6}=C6,GT=V();QM.exports={getRolePermissions:M6};var fo=Object.create(null),U6=a(e=>({key:e,perms:{}}),"perms_template_obj"),VM=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),$M=a((e=!1,t=!1,r=!1,s=!1)=>({[pr.PERMS_CRUD_ENUM.READ]:e,[pr.PERMS_CRUD_ENUM.INSERT]:t,[pr.PERMS_CRUD_ENUM.UPDATE]:r,[pr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),kT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...$M(t,r,s,n)}),"table_perms_template"),FM=a((e,t=$M())=>({attribute_name:e,describe:WM(t),[Pu]:t[Pu],[VT]:t[VT],[$T]:t[$T]}),"attr_perms_template"),GM=a((e,t=!1)=>({attribute_name:e,describe:t,[Pu]:t}),"timestamp_attr_perms_template"),{READ:Pu,INSERT:VT,UPDATE:$T}=pr.PERMS_CRUD_ENUM,YM=Object.values(pr.PERMS_CRUD_ENUM),KM=[Pu,VT,$T];function M6(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[pr.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(fo[t]&&fo[t].key===s)return fo[t].perms;let n=P6(e,r);return fo[t]?fo[t].key=s:fo[t]=U6(s),fo[t].perms=n,n}catch(r){if(!e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<pr.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw GT.error(s),GT.debug(r),qM(new Error,D6.OUTDATED_PERMS_TRANSLATION_ERROR,L6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
-
${r.stack}`;throw GT.error(s),qM(new Error)}}}a(M6,"getRolePermissions");function P6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[pr.SYSTEM_SCHEMA_NAME]=s[pr.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=v6(t[i]);return}r[i]=VM(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],u=t[i][o],_=B6(c,u);r[i].describe||YM.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=kT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=kT()})}),r}a(P6,"translateRolePermissions");function v6(e){let t=VM(!0);return Object.keys(e).forEach(r=>{t.tables[r]=kT(!0,!0,!0,!0,!0)}),t}a(v6,"createStructureUserPermissions");function B6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return pr.TIME_STAMP_NAMES.includes(d)&&(f=GM(d,l[Pu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=FM(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=WM(l),n.attribute_permissions.push(l),c||H6(l,u)}else if(_!==o){let l;pr.TIME_STAMP_NAMES.includes(_)?l=GM(_):l=FM(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=kM(n),n}else return e.describe=kM(e),e}a(B6,"getTableAttrPerms");function kM(e){return YM.filter(t=>e[t]).length>0}a(kM,"getSchemaTableDescribePerm");function WM(e){return KM.filter(t=>e[t]).length>0}a(WM,"getAttributeDescribePerm");function H6(e,t){KM.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(H6,"checkForHashPerms")});var JM={};Ye(JM,{Resources:()=>Qd,keyArrayToString:()=>Ta,resetResources:()=>x6,resources:()=>pi});function x6(){return pi=new Qd}function Ta(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Qd,pi,vu=Re(()=>{Zi();Qd=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!n)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return n=this.get(o),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(t[0]!=="/"&&(t="/"+t),n.relativeURL=t)),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return Xe(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(x6,"resetResources");a(Ta,"keyArrayToString")});var jM={};Ye(jM,{Headers:()=>Si,appendHeader:()=>YT});function YT(e,t,r,s){if(e.append)e.append(t,r,s);else if(e.set){let n=e.get(t);if(n)if(s)r=(typeof n=="string"?n:n.join(", "))+", "+r;else if(typeof n=="string")r=[n,r];else{n.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var Si,Bu=Re(()=>{Si=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase();if(!super.has(s))return super.set(s,[t,r])}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];if(s)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(YT,"appendHeader")});var Hu={};Ye(Hu,{authentication:()=>iP,bypassAuth:()=>Y6,login:()=>W6,logout:()=>Q6,start:()=>K6});function Y6(){nP=!0}async function iP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?k6?G6:[]:F6?q6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Si([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return zd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),zd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(zd){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(E);if(h>=0){let p=n.indexOf(";",h),S=n.indexOf("=",h);u=n.slice(S+1,p===-1?n.length:p),_=await ZM.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new jd.AuthAuditLog(E,h,Gt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Gt.AUTH_AUDIT_STATUS.SUCCESS?XM.notify(S):XM.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let E=e.mtlsConfig.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=e.peerCertificate.subject.CN),e.user=await tt.getUser(E,null,null))}let d;if(!e.user)if(s){if(d=Eo.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await tt.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Jd.validateOperationToken)(h)}catch(A){if(A.message==="invalid token")try{return await(0,Jd.validateRefreshToken)(h),c({status:-1})}catch{throw A}}break}}catch(A){return $6&&(Eo.get(h)||(Eo.set(h,h),l(p,Gt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ti({error:A.message},e)})}Eo.set(s,d),V6&&l(d.username,Gt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await tt.getUser(_.user,null,e):(nP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,tP.getSuperUser)());zd&&(e.session.update=function(E){if(!u){u=(0,rP.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):f?.headers?.set&&f.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,ZM.put(E)},e.login=async function(E,h){e.user=await tt.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&pi.loginPath?(f.status=302,f.headers.set("Location",pi.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new Si);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function K6({server:e,port:t}){e.request(iP,{port:t||"all"}),eP||(eP=!0,setInterval(()=>{Eo=new Map},as.get(Gt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),sP.user.addListener(()=>{Eo=new Map}))}async function W6(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function Q6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var tP,Jd,rP,as,Gt,jd,sP,XM,q6,F6,G6,k6,ZM,zd,nP,V6,$6,Eo,eP,Xd=Re(()=>{tP=x(ts());rr();vu();Jd=x(mu());Ae();rP=require("uuid"),as=x(Z()),Gt=x(L()),jd=x(V()),sP=x(Hc());Bu();ga();XM=(0,jd.loggerWithTag)("auth-event");as.initSync();q6=as.get(Gt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),F6=as.get(Gt.CONFIG_PARAMS.HTTP_CORS),G6=as.get(Gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),k6=as.get(Gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),ZM=ct({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),zd=as.get(Gt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,nP=as.get(Gt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,V6=as.get(Gt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,$6=as.get(Gt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Eo=new Map;tt.onInvalidatedUser(()=>{Eo=new Map});a(Y6,"bypassAuth");a(iP,"authentication");a(K6,"start");a(W6,"login");a(Q6,"logout")});var dP=T((Ehe,_P)=>{"use strict";var Ie=require("joi"),oP=require("fs-extra"),aP=require("path"),Cn=je(),cP=Z(),uP=L(),lP=V(),{hdb_errors:z6}=re(),{HDB_ERROR_MSGS:Jt}=z6,In=/^[a-zA-Z0-9-_]+$/;_P.exports={getDropCustomFunctionValidator:j6,setCustomFunctionValidator:X6,addComponentValidator:r9,dropCustomFunctionProjectValidator:s9,packageComponentValidator:n9,deployComponentValidator:i9,setComponentFileValidator:Z6,getComponentFileValidator:t9,dropComponentFileValidator:e9};function Zd(e,t,r){try{let s=cP.get(uP.CONFIG_PARAMS.COMPONENTSROOT),n=aP.join(s,t);return oP.existsSync(n)?e?t:r.message(Jt.PROJECT_EXISTS):e?r.message(Jt.NO_PROJECT):t}catch(s){return lP.error(s),r.message(Jt.VALIDATION_ERR)}}a(Zd,"checkProjectExists");function xu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(xu,"checkFilePath");function J6(e,t,r,s){try{let n=cP.get(uP.CONFIG_PARAMS.COMPONENTSROOT),i=aP.join(n,e,t,r+".js");return oP.existsSync(i)?r:s.message(Jt.NO_FILE)}catch(n){return lP.error(n),s.message(Jt.VALIDATION_ERR)}}a(J6,"checkFileExists");function j6(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(In).custom(J6.bind(null,e.project,e.type)).custom(xu).required().messages({"string.pattern.base":Jt.BAD_FILE_NAME})});return Cn.validateBySchema(e,t)}a(j6,"getDropCustomFunctionValidator");function X6(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(xu).required(),function_content:Ie.string().required()});return Cn.validateBySchema(e,t)}a(X6,"setCustomFunctionValidator");function Z6(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),file:Ie.string().custom(xu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(Z6,"setComponentFileValidator");function e9(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),file:Ie.string().custom(xu).optional()});return Cn.validateBySchema(e,t)}a(e9,"dropComponentFileValidator");function t9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(xu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(t9,"getComponentFileValidator");function r9(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!1)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(r9,"addComponentValidator");function s9(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(s9,"dropCustomFunctionProjectValidator");function n9(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Cn.validateBySchema(e,t)}a(n9,"packageComponentValidator");function i9(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":Jt.BAD_PACKAGE}),package:Ie.string().optional()});return Cn.validateBySchema(e,t)}a(i9,"deployComponentValidator")});var sf=T((mhe,TP)=>{"use strict";var ef=require("joi"),tf=require("path"),fP=require("fs-extra"),{exec:o9}=require("child_process"),a9=require("util"),EP=a9.promisify(o9),qu=L(),{handleHDBError:Ra,hdb_errors:c9}=re(),{HTTP_STATUS_CODES:Aa}=c9,Fu=Z(),u9=je(),Oa=V();Fu.initSync();var KT=Fu.get(qu.CONFIG_PARAMS.COMPONENTSROOT),hP="npm install --omit=dev --json",l9=`${hP} --dry-run`;TP.exports={installModules:E9,auditModules:h9,installAllRootModules:_9,uninstallRootModule:d9,linkHarperdb:f9};async function _9(e=!1){await rf(),await Gu(e?"npm install --ignore-scripts":"npm install",Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(_9,"installAllRootModules");async function d9(e){await Gu(`npm uninstall ${e}`,Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(d9,"uninstallRootModule");async function f9(){await rf(),await Gu(`npm link ${qu.PACKAGE_ROOT}`,Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(f9,"linkHarperdb");async function Gu(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await EP(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
|
|
12
|
-
`,""))}return
|
|
13
|
-
`,"")}a(
|
|
10
|
+
`,"")}a(ID,"runCommand");async function I3(){try{await o3.access(_S)}catch{return!1}let e=await ID(`${_S} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return a3.eq(t,y3)}a(I3,"checkNATSServerInstalled");async function hS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await bD.getClusterUser();if(oo(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}xr.trace("create nats connection called");let i=await S3({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),xr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&xr.error("Error with Nats client connection, connection closed",o),CD()}),i}a(hS,"createConnection");function CD(){nn=void 0,no=void 0,so=void 0,io=void 0}a(CD,"clearClientCache");async function C3(){nn&&(await nn.drain(),nn=void 0,no=void 0,so=void 0,io=void 0)}a(C3,"closeConnection");var nn,io;async function ud(){return io||(io=hS(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),nn=await io),nn||io}a(ud,"getConnection");async function _u(){if(no)return no;oo(nn)&&await ud();let{domain:e}=du(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(oo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return no=await nn.jetstreamManager({domain:e,timeout:6e4}),no}a(_u,"getJetStreamManager");async function DD(){if(so)return so;oo(nn)&&await ud();let{domain:e}=du(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(oo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return so=nn.jetstream({domain:e,timeout:6e4}),so}a(DD,"getJetStream");async function ur(){let e=nn||await ud(),t=no||await _u(),r=so||await DD();return{connection:e,jsm:t,js:r}}a(ur,"getNATSReferences");async function D3(e){let t=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await bD.getClusterUser(),s=await hS(t,r,n),i=ES(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=wD.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await dS.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(D3,"getServerList");async function mS(e,t){let{jsm:r}=await ur(),n=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:ND.File,retention:yD.Limits,subjects:t,discard:T3.Old,max_msgs:s,max_bytes:i,max_age:n})}a(mS,"createLocalStream");async function UD(){let{jsm:e}=await ur(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(UD,"listStreams");async function U3(e){let{jsm:t}=await ur();await t.streams.delete(e)}a(U3,"deleteLocalStream");async function L3(e){let{connection:t}=await ur(),r=[],n=ES(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(wD.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(L3,"listRemoteStreams");async function M3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ur(),i=RD(),o={durable_name:i,ack_policy:ad.Explicit};t&&(o.deliver_policy=cd.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=fS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(ye.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(M3,"viewStream");async function*P3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ur(),i=RD(),o={durable_name:i,ack_policy:ad.Explicit};t&&(o.deliver_policy=cd.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=fS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(ye.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(P3,"viewStreamIterator");async function v3(e,t,r,n){xr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=LD(n,r);let{js:s}=await ur(),i=await fu(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:OD.encode(n);try{xr.trace(`publishToStream publishing to subject: ${o}`),b3(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return BD(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){xr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await mS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(v3,"publishToStream");function LD(e,t){t===void 0&&(t=R3());let r=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(ye.MSG_HEADERS.ORIGIN)&&r&&t.append(ye.MSG_HEADERS.ORIGIN,r),t}a(LD,"addNatsMsgHeader");function du(e){e=e.toLowerCase();let t=lu.join(Ft.get(Pe.CONFIG_PARAMS.ROOTPATH),N3);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return oo(lS)&&(lS={port:cu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:cu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.HUB,config_file:ye.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:lu.join(t,ye.PID_FILES.HUB),hdb_nats_path:t}),lS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return oo(uS)&&(uS={port:cu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:cu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,config_file:ye.NATS_CONFIG_FILES.LEAF_SERVER,domain:cu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,pid_file_path:lu.join(t,ye.PID_FILES.LEAF),hdb_nats_path:t}),uS;xr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(du,"getServerConfig");async function B3(e){let{jsm:t}=await ur(),r=await fu();try{await t.streams.add({name:e.stream_name,storage:ND.File,retention:yD.Limits,max_age:m3,max_bytes:p3,subjects:[`${ye.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(n){if(n.code!=="400")throw n}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(n){if(n.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:ad.Explicit,durable_name:e.durable_name,deliver_policy:cd.All,max_ack_pending:1e4});else throw n}}a(B3,"createWorkQueueStream");async function H3(){let{jsm:e}=await ur();(await e.consumers.info(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(xr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name),xr.info("Adding pull consumer to ingest stream"),await e.consumers.add(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:ad.Explicit,durable_name:ye.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:cd.All,max_ack_pending:1e4}))}a(H3,"updateIngestStreamConsumer");async function MD(e,t,r){let{jsm:n}=await ur(),s=await n.streams.info(t),i=PD(n.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=od.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(s.config.sources)||s.config.sources.length===0)s.config.sources=[];else for(let p=0,S=s.config.sources.length;p<S;p++)if(d=s.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await n.streams.purge(t,{filter:p}),s.config.sources.splice(f,1),await n.streams.update(t,s.config)}let h={name:_,opt_start_time:o,filter_subject:`${ye.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),s.config.sources.push(h),await n.streams.update(t,s.config)}a(MD,"addSourceToWorkStream");function PD(e){return e.split(".")[1]}a(PD,"extractServerName");async function vD(e,t,r){let{jsm:n}=await ur(),{schema:s,table:i}=r,o=`txn.${s}.${i}.${e}`;await n.streams.purge(t,{filter:o});let c=od.createNatsTableStreamName(s,i),u=await n.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await n.streams.update(t,u.config)}a(vD,"removeSourceFromWorkStream");async function x3(e,t,r=6e4,n=ES()){if(!dS.isObject(t))throw new Error("data param must be an object");let s=OD.encode(t),{connection:i}=await ur(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return fS(c.data)}a(x3,"request");function pS(e){return new Promise(async(t,r)=>{let n=_3(_S,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(pS,"reloadNATS");async function q3(){let{pid_file_path:e}=du(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await pS(e)}a(q3,"reloadNATSHub");async function F3(){let{pid_file_path:e}=du(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await pS(e)}a(F3,"reloadNATSLeaf");function G3(e,t,r){let n;switch(e.code){case gD.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case gD.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(G3,"requestErrorHandler");async function k3(e,t){let r=t+ye.SERVER_SUFFIX.LEAF;await BD(async()=>{e.subscribe===!0?await MD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await vD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(k3,"updateWorkStream");function BD(e){return d3.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(BD,"exclusiveLock");async function HD(e,t){let r=od.createNatsTableStreamName(e,t),n=await fu(),s=K3(e,t,n);await mS(r,[s])}a(HD,"createLocalTableStream");async function V3(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await HD(n,s)}}a(V3,"createTableStreams");async function xD(e,t,r=!1){if(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=od.createNatsTableStreamName(e,t),{jsm:s}=await ur();r?await s.streams.purge(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name):await s.streams.purge(n)}catch(n){if(n.message==="stream not found")xr.warn(n);else throw n}}a(xD,"purgeTableStream");async function $3(e,t){if(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await xD(e,t[r])}a($3,"purgeSchemaTableStreams");async function Y3(e){return(await _u()).streams.info(e)}a(Y3,"getStreamInfo");function K3(e,t,r){return`${ye.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(K3,"createSubjectName");async function fu(){if(uu)return uu;if(uu=(await _u())?.nc?.info?.server_name,uu===void 0)throw new Error("Unable to get jetstream manager server name");return uu}a(fu,"getJsmServerName");async function W3(){let e=await _u(),t=await fu(),r=await UD();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=Q3(n),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(s.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else if(s.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");xr.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l}await e.streams.update(s.name,s)}}}a(W3,"updateLocalStreams");function Q3(e){let{config:t}=e,r=!1;if(t.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let n=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(Q3,"updateStreamLimits")});var Eu=T((ife,VD)=>{"use strict";var aa=f_(),ca=tD(),z3=$(),J3=require("uuid").v4,sfe=require("clone"),_d=Rs(),ua=U(),j3=require("util"),ci=Nn(),{handleHDBError:lr,hdb_errors:X3}=re(),{HDB_ERROR_MSGS:ld,HTTP_STATUS_CODES:_r}=X3,{SchemaEventMsg:dd}=In(),FD=st(),{getDatabases:Z3}=(Re(),ne(Fe)),{transformReq:la}=J();VD.exports={createSchema:ej,createSchemaStructure:GD,createTable:tj,createTableStructure:kD,createAttribute:oj,dropSchema:rj,dropTable:nj,dropAttribute:sj,getBackup:aj};async function ej(e){let t=await GD(e);return _d.signalSchemaChange(new dd(process.pid,e.operation,e.schema)),t}a(ej,"createSchema");async function GD(e){let t=aa.schema_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(la(e),!await ca.checkSchemaExists(e.schema))throw lr(new Error,ld.SCHEMA_EXISTS_ERR(e.schema),_r.BAD_REQUEST,ua.LOG_LEVELS.ERROR,ld.SCHEMA_EXISTS_ERR(e.schema),!0);return await ci.createSchema(e),`database '${e.schema}' successfully created`}a(GD,"createSchemaStructure");async function tj(e){return la(e),e.hash_attribute=e.primary_key??e.hash_attribute,await kD(e)}a(tj,"createTable");async function kD(e){let t=aa.create_table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(aa.validateTableResidence(e.residence),!await ca.checkSchemaTableExists(e.schema,e.table))throw lr(new Error,ld.TABLE_EXISTS_ERR(e.schema,e.table),_r.BAD_REQUEST,ua.LOG_LEVELS.ERROR,ld.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:J3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ci.createTable(n,e);else throw lr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",_r.BAD_REQUEST);else await ci.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(kD,"createTableStructure");async function rj(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=aa.schema_object(e),n=t??r;if(n)throw lr(n,n.message,_r.BAD_REQUEST,void 0,void 0,!0);la(e);let s=await ca.checkSchemaExists(e.schema);if(s)throw lr(new Error,s,_r.NOT_FOUND,ua.LOG_LEVELS.ERROR,s,!0);let i=await ca.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ci.dropSchema(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema)),await FD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(rj,"dropSchema");async function nj(e){let t=aa.table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);la(e);let r=await ca.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,ua.LOG_LEVELS.ERROR,r,!0);return await ci.dropTable(e),await FD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(nj,"dropTable");async function sj(e){let t=aa.attribute_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);la(e);let r=await ca.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,ua.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw lr(new Error,"You cannot drop a hash attribute",_r.BAD_REQUEST,void 0,void 0,!0);if(ua.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw lr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,_r.BAD_REQUEST,void 0,void 0,!0);try{return await ci.dropAttribute(e),ij(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw z3.error(`Got an error deleting attribute ${j3.inspect(e)}.`),n}}a(sj,"dropAttribute");function ij(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(ij,"dropAttributeFromGlobal");async function oj(e){la(e);let t=Z3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw lr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,_r.BAD_REQUEST,void 0,void 0,!0);return await ci.createAttribute(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(oj,"createAttribute");function aj(e){return ci.getBackup(e)}a(aj,"getBackup")});var YD=T((afe,$D)=>{"use strict";var{OPERATIONS_ENUM:cj}=U(),SS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=cj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};$D.exports=SS});var TS=T((lfe,JD)=>{"use strict";var uj=Nn(),ufe=YD(),fd=J(),Ed=U(),lj=Z(),{handleHDBError:KD,hdb_errors:_j}=re(),{HDB_ERROR_MSGS:WD,HTTP_STATUS_CODES:QD}=_j,dj=Object.values(Ed.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),zD="To use this operation audit log must be enabled in harperdb-config.yaml";JD.exports=fj;async function fj(e){if(fd.isEmpty(e.schema))throw new Error(WD.SCHEMA_REQUIRED_ERR);if(fd.isEmpty(e.table))throw new Error(WD.TABLE_REQUIRED_ERR);if(!lj.get(Ed.CONFIG_PARAMS.LOGGING_AUDITLOG))throw KD(new Error,zD,QD.BAD_REQUEST,Ed.LOG_LEVELS.ERROR,zD,!0);let t=fd.checkSchemaTableExist(e.schema,e.table);if(t)throw KD(new Error,t,QD.NOT_FOUND,Ed.LOG_LEVELS.ERROR,t,!0);if(!fd.isEmpty(e.search_type)&&dj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await uj.readAuditLog(e)}a(fj,"readAuditLog")});var XD=T((dfe,jD)=>{"use strict";var{OPERATIONS_ENUM:Ej}=U(),gS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Ej.GET_BACKUP,this.schema=t,this.table=r}};jD.exports=gS});var tU=T((mfe,eU)=>{"use strict";var hj=Nn(),Efe=XD(),RS=J(),mj=U(),hfe=Z(),{handleHDBError:pj,hdb_errors:Sj}=re(),{HDB_ERROR_MSGS:ZD,HTTP_STATUS_CODES:Tj}=Sj;eU.exports=gj;async function gj(e){if(RS.isEmpty(e.schema))throw new Error(ZD.SCHEMA_REQUIRED_ERR);if(RS.isEmpty(e.table))throw new Error(ZD.TABLE_REQUIRED_ERR);let t=RS.checkSchemaTableExist(e.schema,e.table);if(t)throw pj(new Error,t,Tj.NOT_FOUND,mj.LOG_LEVELS.ERROR,t,!0);return await hj.getBackup(read_audit_log_object)}a(gj,"getBackup")});var aU=T((Sfe,oU)=>{var ui=require("validate.js"),nU=Xe(),_a=U(),{handleHDBError:Rj,hdb_errors:Aj}=re(),{HDB_ERROR_MSGS:_t,HTTP_STATUS_CODES:Oj}=Aj,AS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),bj={STRUCTURE_USER:"structure_user"},rU=Object.values(_a.ROLE_TYPES_ENUM),Nj="attribute_permissions",yj="attribute_name",{PERMS_CRUD_ENUM:da}=_a,wj=[Nj,...Object.values(da)],sU=[da.READ,da.INSERT,da.UPDATE],Ij=[yj,...sU];function Cj(e){let t=AS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,iU(e,t)}a(Cj,"addRoleValidation");function Dj(e){let t=AS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,iU(e,t)}a(Dj,"alterRoleValidation");function Uj(e){let t=AS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,nU.validateObject(e,t)}a(Uj,"dropRoleValidation");var Lj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function iU(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Lj.includes(n[o])||s.push(n[o]);s.length>0&&mt(_t.INVALID_ROLE_JSON_KEYS(s),r);let i=nU.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{mt(o,r)}),e.permission){let o=Mj(e);o&&mt(o,r),rU.forEach(c=>{e.permission[c]&&!ui.isBoolean(e.permission[c])&&mt(_t.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(rU.indexOf(o)<0){if(o===bj.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||mt(_t.SCHEMA_NOT_FOUND(d),r)}continue}mt(_t.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){mt(_t.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){mt(_t.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{wj.includes(l)||mt(_t.INVALID_PERM_KEY(l),r,o,u)}),Object.values(da).forEach(l=>{ui.isDefined(_[l])?ui.isBoolean(_[l])||mt(_t.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):mt(_t.TABLE_PERM_MISSING(l),r,o,u)}),ui.isDefined(_.attribute_permissions)){if(!ui.isArray(_.attribute_permissions)){mt(_t.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{mt(_t.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(p=>{!Ij.includes(p)&&p!==da.DELETE&&mt(_t.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ui.isDefined(E.attribute_name)){mt(_t.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){mt(_t.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}sU.forEach(p=>{ui.isDefined(E[p])?ui.isBoolean(E[p])||mt(_t.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):mt(_t.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;mt(_t.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return Pj(r)}a(iU,"customValidate");oU.exports={addRoleValidation:Cj,alterRoleValidation:Dj,dropRoleValidation:Uj};function Mj(e){let{operation:t,permission:r}=e;if(t===_a.OPERATIONS_ENUM.ADD_ROLE||t===_a.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 _t.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?_a.ROLE_TYPES_ENUM.SUPER_USER:_a.ROLE_TYPES_ENUM.CLUSTER_USER;return _t.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Mj,"validateNoSUPerms");function Pj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:_t.ROLE_PERMS_ERROR,...e};return Rj(new Error,n,Oj.BAD_REQUEST)}else return null}a(Pj,"generateRolePermResponse");function mt(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(mt,"addPermError")});var IS=T((gfe,_U)=>{"use strict";var cU=Cr(),uU=en(),vj=ri(),bS=aU(),NS=Rs(),Bj=require("uuid").v4,Hj=require("util"),hd=U(),xj=J(),yS=uU.searchByValue,qj=uU.searchByHash,Fj=Hj.promisify(vj.delete),Gj=jn(),kj=na(),{hdb_errors:Vj,handleHDBError:ao}=re(),{HDB_ERROR_MSGS:lU,HTTP_STATUS_CODES:hu}=Vj,{UserEventMsg:wS}=In();_U.exports={addRole:$j,alterRole:Yj,dropRole:Kj,listRoles:Wj};function OS(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(OS,"scrubRoleDetails");async function $j(e){let t=bS.addRoleValidation(e);if(t)throw t;e=OS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await yS(r)||[])}catch(i){throw ao(i)}if(n&&n.length>0)throw ao(new Error,lU.ROLE_ALREADY_EXISTS(e.role),hu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Bj());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await cU.insert(s),NS.signalUserChange(new wS(process.pid)),e=OS(e),e}a($j,"addRole");async function Yj(e){let t=bS.alterRoleValidation(e);if(t)throw t;e=OS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await cU.update(r)}catch(s){throw ao(s)}if(n&&n?.message==="updated 0 of 1 records")throw ao(new Error,"Invalid role id",hu.BAD_REQUEST,void 0,void 0,!0);return await NS.signalUserChange(new wS(process.pid)),e}a(Yj,"alterRole");async function Kj(e){let t=bS.dropRoleValidation(e);if(t)throw ao(new Error,t,hu.BAD_REQUEST,void 0,void 0,!0);let r=new kj(hd.SYSTEM_SCHEMA_NAME,hd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await qj(r));if(n.length===0)throw ao(new Error,lU.ROLE_NOT_FOUND,hu.NOT_FOUND,void 0,void 0,!0);let s=new Gj(hd.SYSTEM_SCHEMA_NAME,hd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await yS(s)),o=!1;if(xj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw ao(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,hu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Fj(c),NS.signalUserChange(new wS(process.pid)),`${n[0].role} successfully deleted`}a(Kj,"dropRole");async function Wj(){return yS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Wj,"listRoles")});var hU=T((Afe,EU)=>{"use strict";var Qj=Z(),li=require("joi"),zj=Xe(),dU=require("moment"),Jj=require("fs-extra"),CS=require("path"),jj=require("lodash"),mu=U(),{LOG_LEVELS:co}=U(),Xj="YYYY-MM-DD hh:mm:ss",Zj=CS.resolve(__dirname,"../logs");EU.exports=function(e){return zj.validateBySchema(e,eX)};var eX=li.object({from:li.custom(fU),until:li.custom(fU),level:li.valid(co.NOTIFY,co.FATAL,co.ERROR,co.WARN,co.INFO,co.DEBUG,co.TRACE),order:li.valid("asc","desc"),limit:li.number().min(1),start:li.number().min(0),log_name:li.custom(tX)});function fU(e,t){if(dU(e,dU.ISO_8601).format(Xj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(fU,"validateDatetime");function tX(e,t){if(jj.invert(mu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=Qj.get(mu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?mu.LOG_NAMES.HDB:e,i=s===mu.LOG_NAMES.INSTALL?CS.join(Zj,mu.LOG_NAMES.INSTALL):CS.join(n,s);return Jj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(tX,"validateReadLogPath")});var US=T((bfe,pU)=>{"use strict";var md=U(),rX=$(),nX=Z(),sX=hU(),DS=require("path"),mU=require("fs-extra"),{once:iX}=require("events"),{handleHDBError:oX,hdb_errors:aX}=re(),{PACKAGE_ROOT:cX}=U(),uX=DS.join(cX,"logs"),lX=1e3,_X=200;pU.exports=dX;async function dX(e){let t=sX(e);if(t)throw oX(t,t.message,aX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=nX.get(md.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?md.LOG_NAMES.HDB:e.log_name,s=n===md.LOG_NAMES.INSTALL?DS.join(uX,md.LOG_NAMES.INSTALL):DS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?lX:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(mU.statSync(s).size-(h+5)*_X,0));let S=mU.createReadStream(s,{start:p});S.on("error",P=>{rX.error(P)});let g=0,A=[],R="",v;S.on("data",P=>{let M=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=R+P;let K=0,W;for(;(W=M.exec(P))&&!S.destroyed;){v&&(v.message=P.slice(K,W.index),H(v));let[V,ce,de]=W,xe=de.split("] ["),ae=xe[0],Oe=xe[1];xe.splice(0,2),v={timestamp:ce,thread:ae,level:Oe,tags:xe,message:""},K=W.index+V.length}R=P.slice(K)}),S.on("end",P=>{S.destroyed||v&&(v.message=R.trim(),H(v))}),S.resume();function H(P){let M,K,W;switch(!0){case(i&&c&&_):M=new Date(P.timestamp),K=new Date(u),W=new Date(l),P.level===o&&M>=K&&M<=W&&g<E?g++:P.level===o&&M>=K&&M<=W&&(_i(P,f,A),g++,g===h&&S.destroy());break;case(i&&c):M=new Date(P.timestamp),K=new Date(u),P.level===o&&M>=K&&g<E?g++:P.level===o&&M>=K&&(_i(P,f,A),g++,g===h&&S.destroy());break;case(i&&_):M=new Date(P.timestamp),W=new Date(l),P.level===o&&M<=W&&g<E?g++:P.level===o&&M<=W&&(_i(P,f,A),g++,g===h&&S.destroy());break;case(c&&_):M=new Date(P.timestamp),K=new Date(u),W=new Date(l),M>=K&&M<=W&&g<E?g++:M>=K&&M<=W&&(_i(P,f,A),g++,g===h&&S.destroy());break;case i:P.level===o&&g<E?g++:P.level===o&&(_i(P,f,A),g++,g===h&&S.destroy());break;case c:M=new Date(P.timestamp),K=new Date(u),M>=K&&g<E?g++:M>=K&&g>=E&&(_i(P,f,A),g++,g===h&&S.destroy());break;case _:M=new Date(P.timestamp),W=new Date(l),M<=W&&g<E?g++:M<=W&&g>=E&&(_i(P,f,A),g++,g===h&&S.destroy());break;default:g<E?g++:(_i(P,f,A),g++,g===h&&S.destroy())}}return a(H,"onLogMessage"),await iX(S,"close"),A}a(dX,"readLog");function _i(e,t,r){t==="desc"?fX(e,r):t==="asc"?EX(e,r):r.push(e)}a(_i,"pushLineToResult");function fX(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(fX,"insertDescending");function EX(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(EX,"insertAscending")});var pd=T((Cfe,RU)=>{"use strict";var LS=require("joi"),{string:pu,boolean:SU,date:hX}=LS.types(),mX=Xe(),{validateSchemaExists:yfe,validateTableExists:wfe,validateSchemaName:Ife}=Kn(),pX=U(),SX=Ge(),TU=Z();TU.initSync();var TX=pu.invalid(TU.get(pX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(SX.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),gU={operation:pu.valid("add_node","update_node","set_node_replication"),node_name:TX,subscriptions:LS.array().items({table:pu.optional(),schema:pu.optional(),database:pu.optional(),subscribe:SU.required(),publish:SU.required().custom(RX),start_time:hX.iso()}).min(1).required()};function gX(e){return mX.validateBySchema(e,LS.object(gU))}a(gX,"addUpdateNodeValidator");function RX(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(RX,"checkForFalsy");RU.exports={addUpdateNodeValidator:gX,validation_schema:gU}});var OU=T((Ufe,AU)=>{var AX=Xe(),OX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};AU.exports=function(e){return AX.validateObject(e,OX)}});var Sd=T((Lfe,bU)=>{"use strict";var bX=U().OPERATIONS_ENUM,MS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=bX.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};bU.exports=MS});var yU=T((Pfe,NU)=>{"use strict";var NX={OPERATION:"operation",REFRESH:"refresh"},PS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},vS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};NU.exports={JWTTokens:PS,TOKEN_TYPE_ENUM:NX,JWTRSAKeys:vS}});var gu=T((Bfe,DU)=>{"use strict";var Tu=require("jsonwebtoken"),BS=require("fs-extra"),HS=J(),sn=U(),{handleHDBError:dr,hdb_errors:yX}=re(),{HTTP_STATUS_CODES:fr,AUTHENTICATION_ERROR_MSGS:Er}=yX,Su=$(),wU=y_(),FS=tn(),wX=Cr().update,IX=Sd(),CX=Rs(),{UserEventMsg:DX}=In(),di=Z();di.initSync();var xS=require("path"),{JWTTokens:UX,JWTRSAKeys:LX,TOKEN_TYPE_ENUM:Td}=yU(),MX=di.get(sn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?di.get(sn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",PX=di.get(sn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?di.get(sn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",gd="RS256",qS;DU.exports={createTokens:vX,validateOperationToken:HX,refreshOperationToken:BX,validateRefreshToken:CU};async function vX(e){if(HS.isEmpty(e)||typeof e!="object")throw dr(new Error,Er.INVALID_AUTH_OBJECT,fr.BAD_REQUEST,void 0,void 0,!0);if(HS.isEmpty(e.username))throw dr(new Error,Er.USERNAME_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);if(HS.isEmpty(e.password))throw dr(new Error,Er.PASSWORD_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await FS.findAndValidateUser(e.username,e.password),!t)throw dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Su.error(f),dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Rd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await IU(i,r.private_key,r.passphrase),c=await Tu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:PX,algorithm:gd,subject:Td.REFRESH}),u=wU.hash(c),_=new IX(sn.SYSTEM_SCHEMA_NAME,sn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await wX(_)}catch(f){Su.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw dr(new Error,Er.REFRESH_TOKEN_SAVE_FAILED,fr.INTERNAL_SERVER_ERROR);return CX.signalUserChange(new DX(process.pid)),new UX(o,c)}a(vX,"createTokens");async function IU(e,t,r){return await Tu.sign(e,{key:t,passphrase:r},{expiresIn:MX,algorithm:gd,subject:Td.OPERATION})}a(IU,"signOperationToken");async function Rd(){if(qS===void 0)try{let e=xS.join(di.getHdbBasePath(),sn.LICENSE_KEY_DIR_NAME,sn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=xS.join(di.getHdbBasePath(),sn.LICENSE_KEY_DIR_NAME,sn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=xS.join(di.getHdbBasePath(),sn.LICENSE_KEY_DIR_NAME,sn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await BS.readFile(e)).toString(),s=(await BS.readFile(t)).toString(),i=(await BS.readFile(r)).toString();qS=new LX(i,s,n)}catch(e){throw Su.error(e),dr(new Error,Er.NO_ENCRYPTION_KEYS,fr.INTERNAL_SERVER_ERROR)}return qS}a(Rd,"getJWTRSAKeys");async function BX(e){if(!e)throw dr(new Error,Er.INVALID_BODY,fr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw dr(new Error,Er.REFRESH_TOKEN_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);await CU(e.refresh_token);let t=await Rd(),r=await Tu.decode(e.refresh_token);return{operation_token:await IU({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(BX,"refreshOperationToken");async function HX(e){try{let t=await Rd(),r=await Tu.verify(e,t.public_key,{algorithms:gd,subject:Td.OPERATION});return await FS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Su.warn(t),t.name&&t.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}}a(HX,"validateOperationToken");async function CU(e){let t;try{let r=await Rd(),n=await Tu.verify(e,r.public_key,{algorithms:gd,subject:Td.REFRESH});t=await FS.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Su.warn(r),r.name&&r.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}if(!wU.validate(t.refresh_token,e))throw dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED);return t}a(CU,"validateRefreshToken")});var GS=T((qfe,MU)=>{"use strict";var xX=OU(),fa=require("passport"),qX=require("passport-local").Strategy,FX=require("passport-http").BasicStrategy,GX=require("util"),kX=tn(),LU=GX.callbackify(kX.findAndValidateUser),xfe=Nr(),VX=U(),UU=gu();fa.use(new qX(function(e,t,r){LU(e,t,r)}));fa.use(new FX(function(e,t,r){LU(e,t,r)}));fa.serializeUser(function(e,t){t(null,e)});fa.deserializeUser(function(e,t){t(null,e)});function $X(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":fa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===VX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?UU.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):UU.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:fa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a($X,"authorize");function YX(e,t){let r=xX(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(YX,"checkPermissions");MU.exports={authorize:$X,checkPermissions:YX}});var fi=T((Gfe,PU)=>{"use strict";var kS=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},VS=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};PU.exports={Node:kS,NodeSubscription:VS}});var BU=T((Vfe,vU)=>{"use strict";var KX=U().OPERATIONS_ENUM,$S=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=KX.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};vU.exports=$S});var Ru=T((Yfe,HU)=>{"use strict";var YS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},KS=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)}};HU.exports={RemotePayloadObject:YS,RemotePayloadSubscription:KS}});var qU=T((Wfe,xU)=>{"use strict";var WS=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}};xU.exports=WS});var kU=T((Xfe,GU)=>{"use strict";var WX=qU(),zfe=ft(),FU=Qe(),QX=$(),{getSchemaPath:Jfe,getTransactionAuditStorePath:jfe}=je(),{getDatabases:zX}=(Re(),ne(Fe));GU.exports=JX;async function JX(e){let t=new WX;try{let r=zX()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await FU.environmentDataSize(schema_path,e.name),o=await FU.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){QX.warn(`unable to stat table dbi due to ${r}`)}return t}a(JX,"lmdbGetTableSize")});var $U=T((eEe,VU)=>{"use strict";var QS=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};VU.exports=QS});var Ea=T((sEe,QU)=>{"use strict";var jX=require("fs-extra"),XX=require("path"),zt=require("systeminformation"),Ei=$(),ZX=st(),zS=Ge(),Od=U(),eZ=kU(),WU=Zs(),{getThreadInfo:YU}=We(),iT=Z();iT.initSync();var tZ=$U(),{openEnvironment:rEe}=Qe(),{getSchemaPath:nEe}=je(),{database:rZ}=(Re(),ne(Fe)),Ad;QU.exports={getHDBProcessInfo:ZS,getNetworkInfo:tT,getDiskInfo:eT,getMemoryInfo:XS,getCPUInfo:jS,getTimeInfo:JS,getSystemInformation:rT,systemInformation:nZ,getTableSize:nT,getMetrics:sT};function JS(){return zt.time()}a(JS,"getTimeInfo");async function jS(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await zt.cpu();l.cpu_speed=await zt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:g,...A}=await zt.currentLoad();return A.cpus=[],g.forEach(R=>{let{raw_load:v,raw_load_idle:H,raw_load_irq:P,raw_load_nice:M,raw_load_system:K,raw_load_user:W,...V}=R;A.cpus.push(V)}),l.current_load=A,l}catch(e){return Ei.error(`error in getCPUInfo: ${e}`),{}}}a(jS,"getCPUInfo");async function XS(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await zt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ei.error(`error in getMemoryInfo: ${e}`),{}}}a(XS,"getMemoryInfo");async function ZS(){let e={core:[],clustering:[]};try{let t=await zt.processes(),r;try{r=Number.parseInt(await jX.readFile(XX.join(iT.get(Od.CONFIG_PARAMS.ROOTPATH),Od.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Od.NODE_ERROR_CODES.ENOENT)Ei.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Ei.error(`error in getHDBProcessInfo: ${t}`),e}}a(ZS,"getHDBProcessInfo");async function eT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await zt.fsStats();return e.read_write=_,e.size=await zt.fsSize(),e}catch(t){return Ei.error(`error in getDiskInfo: ${t}`),e}}a(eT,"getDiskInfo");async function tT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await zt.networkInterfaceDefault(),e.latency=await zt.inetChecksite("google.com"),(await zt.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await zt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ei.error(`error in getNetworkInfo: ${t}`),e}}a(tT,"getNetworkInfo");async function rT(){if(Ad!==void 0)return Ad;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await zt.osInfo();e=c;let u=await zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Ad=e,Ad}catch(t){return Ei.error(`error in getSystemInformation: ${t}`),e}}a(rT,"getSystemInformation");async function nT(){let e=[],t=await WU.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await eZ(n));return e}a(nT,"getTableSize");async function sT(){let e=await WU.describeAll(),t={};for(let r in e){let n=t[r]={};for(let s in e[r])try{let i=rZ({database:r,table:s}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),n[s]=o}catch(i){Ei.notify(`Error getting stats for table ${s}: ${i}`)}}return t}a(sT,"getMetrics");async function KU(){if(iT.get(Od.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await ZX.getNATSReferences(),r=await t.streams.info(zS.WORK_QUEUE_CONSUMER_NAMES.stream_name),n=await e.consumers.get(zS.WORK_QUEUE_CONSUMER_NAMES.stream_name,zS.WORK_QUEUE_CONSUMER_NAMES.durable_name),s={ingest:{stream:{...r.state},consumer:{num_ack_pending:n._info.num_ack_pending,num_redelivered:n._info.num_redelivered,num_waiting:n._info.num_waiting,num_pending:n._info.num_pending}}};return r.sources&&(s.ingest.stream.sources=r.sources),s}}a(KU,"getNatsStreamInfo");async function nZ(e){let t=new tZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await rT(),t.time=JS(),t.cpu=await jS(),t.memory=await XS(),t.disk=await eT(),t.network=await tT(),t.harperdb_processes=await ZS(),t.table_size=await nT(),t.metrics=await sT(),t.threads=await YU(),t.replication=await KU(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await rT();break;case"time":t.time=JS();break;case"cpu":t.cpu=await jS();break;case"memory":t.memory=await XS();break;case"disk":t.disk=await eT();break;case"network":t.network=await tT();break;case"harperdb_processes":t.harperdb_processes=await ZS();break;case"table_size":t.table_size=await nT();break;case"database_metrics":case"metrics":t.metrics=await sT();break;case"threads":t.threads=await YU();break;case"replication":t.replication=await KU();break;default:break}return t}a(nZ,"systemInformation")});var Nd=T((oEe,zU)=>{"use strict";zU.exports={version:sZ,printVersion:iZ};var bd=ru();function sZ(){if(bd)return bd.version}a(sZ,"version");function iZ(){bd&&console.log(`HarperDB Version ${bd.version}`)}a(iZ,"printVersion")});var on=T((lEe,ZU)=>{"use strict";var oZ=Cr(),oT=J(),aZ=require("util"),uo=U(),JU=Z();JU.initSync();var cZ=GS(),jU=en(),{Node:cEe,NodeSubscription:uEe}=fi(),uZ=na(),lZ=BU(),{RemotePayloadObject:_Z,RemotePayloadSubscription:dZ}=Ru(),{handleHDBError:fZ,hdb_errors:EZ}=re(),{HTTP_STATUS_CODES:hZ,HDB_ERROR_MSGS:mZ}=EZ,pZ=jn(),SZ=Ea(),TZ=Nd(),{getDatabases:gZ}=(Re(),ne(Fe)),RZ=aZ.promisify(cZ.authorize),AZ=jU.searchByHash,OZ=jU.searchByValue;ZU.exports={authHeaderToUser:bZ,isEmpty:NZ,getNodeRecord:yZ,upsertNodeRecord:wZ,buildNodePayloads:IZ,checkClusteringEnabled:CZ,getAllNodeRecords:DZ,getSystemInfo:UZ,reverseSubscription:XU};async function bZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await RZ(t,null),e}a(bZ,"authHeaderToUser");function NZ(e){return e==null}a(NZ,"isEmpty");async function yZ(e){let t=new uZ(uo.SYSTEM_SCHEMA_NAME,uo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return AZ(t)}a(yZ,"getNodeRecord");async function wZ(e){let t=new lZ(uo.SYSTEM_SCHEMA_NAME,uo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return oZ.upsert(t)}a(wZ,"upsertNodeRecord");function XU(e){if(oT.isEmpty(e.subscribe)||oT.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(XU,"reverseSubscription");function IZ(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=oT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=XU(c),E=gZ()[u]?.[_],h=new dZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new _Z(r,t,s,n)}a(IZ,"buildNodePayloads");function CZ(){if(!JU.get(uo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw fZ(new Error,mZ.CLUSTERING_NOT_ENABLED,hZ.BAD_REQUEST,void 0,void 0,!0)}a(CZ,"checkClusteringEnabled");async function DZ(){let e=new pZ(uo.SYSTEM_SCHEMA_NAME,uo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await OZ(e))}a(DZ,"getAllNodeRecords");async function UZ(){let e=await SZ.getSystemInformation();return{hdb_version:TZ.version(),node_version:e.node_version,platform:e.platform}}a(UZ,"getSystemInfo")});var aT=T((dEe,aL)=>{"use strict";var yd=st(),eL=J(),tL=Ge(),rL=U(),wd=$(),nL=Eu(),LZ=K_(),{RemotePayloadObject:MZ}=Ru(),{handleHDBError:sL,hdb_errors:PZ}=re(),{HTTP_STATUS_CODES:iL}=PZ,{NodeSubscription:oL}=fi();aL.exports=vZ;async function vZ(e,t){let r;try{r=await yd.request(`${t}.${tL.REQUEST_SUFFIX}`,new MZ(rL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),wd.trace("Response from remote describe all request:",r)}catch(o){wd.error(`addNode received error from describe all request to remote node: ${o}`);let c=yd.requestErrorHandler(o,"add_node",t);throw sL(new Error,c,iL.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===tL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw sL(new Error,o,iL.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===rL.SYSTEM_SCHEMA_NAME){await yd.createLocalTableStream(u,c);let h=new oL(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=eL.doesSchemaExist(u),l=n[u]!==void 0,d=c?eL.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(wd.trace(`addNode creating schema: ${u}`),await nL.createSchema({operation:"create_schema",schema:u})),!d&&f){wd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new LZ(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await nL.createTable(h)}await yd.createLocalTableStream(u,c);let E=new oL(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(vZ,"reviewSubscriptions")});var Dd=T((EEe,lL)=>{"use strict";var{handleHDBError:Id,hdb_errors:BZ}=re(),{HTTP_STATUS_CODES:Cd}=BZ,{addUpdateNodeValidator:HZ}=pd(),Au=$(),uL=U(),cL=Ge(),xZ=J(),cT=st(),Ou=on(),qZ=Z(),FZ=aT(),{Node:GZ,NodeSubscription:kZ}=fi(),{broadcast:VZ}=We(),$Z="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",YZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",KZ=qZ.get(uL.CONFIG_PARAMS.CLUSTERING_NODENAME);lL.exports=WZ;async function WZ(e,t=!1){Au.trace("addNode called with:",e),Ou.checkClusteringEnabled();let r=HZ(e);if(r)throw Id(r,r.message,Cd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Ou.getNodeRecord(n);if(!xZ.isEmptyOrZeroLength(d))throw Id(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Cd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await FZ(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=$Z,o;let c=Ou.buildNodePayloads(s,KZ,uL.OPERATIONS_ENUM.ADD_NODE,await Ou.getSystemInfo());Au.trace("addNode sending remote payload:",c);let u;try{u=await cT.request(`${n}.${cL.REQUEST_SUFFIX}`,c)}catch(d){Au.error(`addNode received error from request: ${d}`);let f=cT.requestErrorHandler(d,"add_node",n);throw Id(new Error,f,Cd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===cL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${u.message}`;throw Id(new Error,d,Cd.INTERNAL_SERVER_ERROR,"error",d)}Au.trace(u);let _=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];Au.trace("Add node updating work stream for node:",n,"subscriptions:",E),await cT.updateWorkStream(E,n),s[d].start_time===void 0&&delete s[d].start_time,_.push(new kZ(E.schema,E.table,E.publish,E.subscribe))}let l=new GZ(n,_,u.system_info);return await Ou.upsertNodeRecord(l),VZ({type:"nats_update"}),i.length>0?o.message=YZ:o.message=`Successfully added '${n}' to manifest`,o}a(WZ,"addNode")});var dT=T((pEe,fL)=>{"use strict";var{handleHDBError:uT,hdb_errors:QZ}=re(),{HTTP_STATUS_CODES:lT}=QZ,{addUpdateNodeValidator:zZ}=pd(),bu=$(),dL=U(),_L=Ge(),mEe=J(),_T=st(),Nu=on(),JZ=Z(),{cloneDeep:jZ}=require("lodash"),XZ=aT(),{Node:ZZ,NodeSubscription:e5}=fi(),{broadcast:t5}=We(),r5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",n5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",s5=JZ.get(dL.CONFIG_PARAMS.CLUSTERING_NODENAME);fL.exports=i5;async function i5(e){bu.trace("updateNode called with:",e),Nu.checkClusteringEnabled();let t=zZ(e);if(t)throw uT(t,t.message,lT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Nu.getNodeRecord(r);s.length>0&&(n=jZ(s));let{added:i,skipped:o}=await XZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=r5,c;let u=Nu.buildNodePayloads(i,s5,dL.OPERATIONS_ENUM.UPDATE_NODE,await Nu.getSystemInfo());bu.trace("updateNode sending remote payload:",u);let _;try{_=await _T.request(`${r}.${_L.REQUEST_SUFFIX}`,u)}catch(l){bu.error(`updateNode received error from request: ${l}`);let d=_T.requestErrorHandler(l,"update_node",r);throw uT(new Error,d,lT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===_L.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw uT(new Error,l,lT.INTERNAL_SERVER_ERROR,"error",l)}bu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];bu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await _T.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return n||(n=[new ZZ(r,[],_.system_info)]),await o5(n[0],i,_.system_info),o.length>0?c.message=n5:c.message=`Successfully updated '${r}'`,c}a(i5,"updateNode");async function o5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new e5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Nu.upsertNodeRecord(n),t5({type:"nats_update"})}a(o5,"updateNodeTable")});var SL=T((TEe,pL)=>{"use strict";var mL=require("joi"),{string:EL}=mL.types(),a5=Xe(),hL=U(),c5=Z(),u5=Ge();pL.exports=l5;function l5(e){let t=EL.invalid(c5.get(hL.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(u5.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=mL.object({operation:EL.valid(hL.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return a5.validateBySchema(e,r)}a(l5,"removeNodeValidator")});var Ld=T((REe,bL)=>{"use strict";var{handleHDBError:TL,hdb_errors:_5}=re(),{HTTP_STATUS_CODES:gL}=_5,d5=SL(),yu=$(),RL=on(),f5=J(),Ud=U(),AL=Ge(),OL=st(),E5=Z(),{RemotePayloadObject:h5}=Ru(),{NodeSubscription:m5}=fi(),p5=sa(),S5=ri(),{broadcast:T5}=We(),g5=E5.get(Ud.CONFIG_PARAMS.CLUSTERING_NODENAME);bL.exports=R5;async function R5(e){yu.trace("removeNode called with:",e),RL.checkClusteringEnabled();let t=d5(e);if(t)throw TL(t,t.message,gL.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await RL.getNodeRecord(r);if(f5.isEmptyOrZeroLength(n))throw TL(new Error,`Node '${r}' was not found.`,gL.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new h5(Ud.OPERATIONS_ENUM.REMOVE_NODE,g5,[]),i,o=!1;try{i=await OL.request(`${r}.${AL.REQUEST_SUFFIX}`,s),yu.trace("Remove node reply from remote node:",r,i)}catch(u){yu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];yu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new m5(l.schema,l.table,!1,!1);await OL.updateWorkStream(d,r)}let c=new p5(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await S5.deleteRecord(c),T5({type:"nats_update"}),i?.status===AL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(yu.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(R5,"removeNode")});var wL=T((OEe,yL)=>{"use strict";var NL=require("joi"),{string:A5,array:O5}=NL.types(),b5=Xe(),N5=pd();yL.exports=y5;function y5(e){let t=NL.object({operation:A5.valid("configure_cluster").required(),connections:O5.items(N5.validation_schema).required()});return b5.validateBySchema(e,t)}a(y5,"configureClusterValidator")});var fT=T((NEe,LL)=>{"use strict";var w5=U(),Md=$(),I5=J(),C5=Ld(),D5=Dd(),IL=on(),U5=wL(),{handleHDBError:CL,hdb_errors:L5}=re(),{HTTP_STATUS_CODES:DL}=L5,M5="Configure cluster complete.",P5="Failed to configure the cluster. Check the logs for more details.",v5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";LL.exports=B5;async function B5(e){Md.trace("configure cluster called with:",e),IL.checkClusteringEnabled();let t=U5(e);if(t)throw CL(t,t.message,DL.BAD_REQUEST,void 0,void 0,!0);let r=await IL.getAllNodeRecords(),n=[];for(let f=0,E=r.length;f<E;f++)n.push(UL(C5,{operation:w5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let s=await Promise.allSettled(n);Md.trace("All results from configure_cluster remove node:",s);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(UL(D5,E,E.node_name))}let c=await Promise.allSettled(i);Md.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=s.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(Md.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let p=h?.value?.result;typeof p=="string"&&p.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(I5.isEmptyOrZeroLength(u))return{message:M5,connections:_};if(l)return{message:v5,failed_nodes:u,connections:_};throw CL(new Error,P5,DL.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(B5,"configureCluster");async function UL(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){throw{node_name:r,error:n}}}a(UL,"functionWrapper")});var PL=T((wEe,ML)=>{"use strict";var Pd=require("joi"),H5=Xe(),{validateSchemaExists:x5,validateTableExists:q5,validateSchemaName:F5}=Kn(),G5=Pd.object({operation:Pd.string().valid("purge_stream"),schema:Pd.string().custom(x5).custom(F5).required(),table:Pd.string().custom(q5).required()});function k5(e){return H5.validateBySchema(e,G5)}a(k5,"purgeStreamValidator");ML.exports=k5});var ET=T((CEe,vL)=>{"use strict";var{handleHDBError:V5,hdb_errors:$5}=re(),{HTTP_STATUS_CODES:Y5}=$5,K5=PL(),W5=st(),Q5=on();vL.exports=z5;async function z5(e){if(e.purge_ingest!==!0){let s=K5(e);if(s)throw V5(s,s.message,Y5.BAD_REQUEST,void 0,void 0,!0)}Q5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:n}=e;return await W5.purgeTableStream(t,r,n),n?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(z5,"purgeStream")});var pT=T((UEe,GL)=>{"use strict";var mT=on(),J5=st(),xL=Z(),vd=U(),lo=Ge(),j5=J(),hT=$(),{RemotePayloadObject:X5}=Ru(),{ErrorCode:BL}=require("nats"),HL=xL.get(vd.CONFIG_PARAMS.CLUSTERING_ENABLED),qL=xL.get(vd.CONFIG_PARAMS.CLUSTERING_NODENAME);GL.exports={clusterStatus:Z5,buildNodeStatus:FL};async function Z5(){let e={node_name:qL,is_enabled:HL,connections:[]};if(!HL)return e;let t=await mT.getAllNodeRecords();if(j5.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(FL(t[n],e.connections));return await Promise.allSettled(r),e}a(Z5,"clusterStatus");async function FL(e,t){let r=e.name,n=new X5(vd.OPERATIONS_ENUM.CLUSTER_STATUS,qL,void 0,await mT.getSystemInfo()),s,i,o=lo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await J5.request(lo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===lo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=lo.CLUSTER_STATUS_STATUSES.CLOSED,hT.error(`Error getting node status from ${r} `,s))}catch(u){hT.warn(`Error getting node status from ${r}`,u),u.code===BL.NoResponders?o=lo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===BL.Timeout?o=lo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=lo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new e8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==vd.PRE_4_0_0_VERSION&&await mT.upsertNodeRecord(u)}catch(u){hT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(FL,"buildNodeStatus");function e8(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(e8,"NodeStatusObject")});var TT=T((MEe,kL)=>{"use strict";var{handleHDBError:t8,hdb_errors:r8}=re(),{HTTP_STATUS_CODES:n8}=r8,s8=st(),i8=on(),ST=J(),Bd=require("joi"),o8=Xe(),a8=2e3,c8=Bd.object({timeout:Bd.number().min(1),connected_nodes:Bd.boolean(),routes:Bd.boolean()});kL.exports=u8;async function u8(e){i8.checkClusteringEnabled();let t=o8.validateBySchema(e,c8);if(t)throw t8(t,t.message,n8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||ST.autoCastBoolean(n),o=s===void 0||ST.autoCastBoolean(s),c={nodes:[]},u=await s8.getServerList(r??a8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:ST.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(u8,"clusterNetwork")});var KL=T((vEe,YL)=>{"use strict";var gT=require("joi"),VL=Xe(),{route_constraints:$L}=Gm();YL.exports={setRoutesValidator:l8,deleteRoutesValidator:_8};function l8(e){let t=gT.object({server:gT.valid("hub","leaf").required(),routes:$L.required()});return VL.validateBySchema(e,t)}a(l8,"setRoutesValidator");function _8(e){let t=gT.object({routes:$L.required()});return VL.validateBySchema(e,t)}a(_8,"deleteRoutesValidator")});var AT=T((HEe,JL)=>{"use strict";var _o=Lr(),RT=J(),Hd=U(),WL=KL(),{handleHDBError:QL,hdb_errors:d8}=re(),{HTTP_STATUS_CODES:zL}=d8,f8="cluster routes successfully set",E8="cluster routes successfully deleted";JL.exports={setRoutes:h8,getRoutes:m8,deleteRoutes:p8};function h8(e){let t=WL.setRoutesValidator(e);if(t)throw QL(t,t.message,zL.BAD_REQUEST,void 0,void 0,!0);let r=_o.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=RT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?_o.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):_o.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:f8,set:o,skipped:i}}a(h8,"setRoutes");function m8(){let e=_o.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(m8,"getRoutes");function p8(e){let t=WL.deleteRoutesValidator(e);if(t)throw QL(t,t.message,zL.BAD_REQUEST,void 0,void 0,!0);let r=_o.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let p=n[E];if(d.host===p.host&&d.port===p.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=RT.isEmptyOrZeroLength(n)?null:n,_o.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=RT.isEmptyOrZeroLength(s)?null:s,_o.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:E8,deleted:i,skipped:o}}a(p8,"deleteRoutes")});var XL=T((qEe,jL)=>{"use strict";var wu=require("alasql"),fo=require("recursive-iterator"),Mn=$(),S8=J(),Iu=U(),OT=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,g8(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Iu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Iu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Iu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=T8(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!Iu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new wu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function T8(e){return e.filter(t=>t[Iu.PERMS_CRUD_ENUM.READ])}a(T8,"filterReadRestrictedAttrs");function g8(e,t,r,n,s){R8(e,t,r,n,s)}a(g8,"interpretAST");function Cu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Cu,"addSchemaTableToMap");function R8(e,t,r,n,s){if(!e){Mn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof wu.yy.Insert?N8(e,t,r):e instanceof wu.yy.Select?A8(e,t,r,n,s):e instanceof wu.yy.Update?O8(e,t,r):e instanceof wu.yy.Delete?b8(e,t,r):Mn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(R8,"getRecordAttributesAST");function A8(e,t,r,n,s){if(!e){Mn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(S8.isEmptyOrZeroLength(i)){Mn.error("No schema specified");return}e.from.forEach(c=>{Cu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Cu(c.table,t,r,n,s)});let o=new fo(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Mn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new fo(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Mn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new fo(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Mn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new fo(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Mn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(A8,"getSelectAttributes");function O8(e,t,r){if(!e){Mn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new fo(e.columns),s=e.table.databaseid;Cu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&bT(e.table.tableid,s,i.columnid,t,r)}a(O8,"getUpdateAttributes");function b8(e,t,r){if(!e){Mn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new fo(e.where),s=e.table.databaseid;Cu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&bT(e.table.tableid,s,i.columnid,t,r)}a(b8,"getDeleteAttributes");function N8(e,t,r){if(!e){Mn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new fo(e.columns),s=e.into.databaseid;Cu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&bT(e.into.tableid,s,i.columnid,t,r)}a(N8,"getInsertAttributes");function bT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(bT,"pushAttribute");jL.exports=OT});var wT=T((GEe,rM)=>{var xd=Qi(),ZL=require("chalk"),qr=$(),eM=require("prompt"),{promisify:y8}=require("util"),NT=U(),w8=require("fs-extra"),I8=require("path"),C8=J(),D8=Nd(),tM=Z();tM.initSync();var U8=require("moment"),L8=y8(eM.get),M8=I8.join(tM.getHdbBasePath(),NT.LICENSE_KEY_DIR_NAME,NT.LICENSE_FILE_NAME,NT.LICENSE_FILE_NAME);rM.exports={getFingerprint:v8,setLicense:P8,parseLicense:yT,register:B8,getRegistrationInfo:x8};async function P8(e){if(e&&e.key&&e.company){try{qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await yT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw qr.error(r),qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(P8,"setLicense");async function v8(){let e={};try{e=await xd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw qr.error(r),qr.error(t),new Error(r)}return e}a(v8,"getFingerprint");async function yT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");qr.info("Validating license input...");let r=xd.validateLicense(e,t);if(qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{qr.info("writing license to disk"),await w8.writeFile(M8,JSON.stringify({license_key:e,company:t}))}catch(n){throw qr.error("Failed to write License"),n}return"Registration successful."}a(yT,"parseLicense");async function B8(){let e=await H8();return yT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(B8,"register");async function H8(){let e=await xd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:ZL.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:ZL.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{eM.start()}catch(n){qr.error(n)}let r;try{r=await L8(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(H8,"promptForRegistration");async function x8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await xd.getLicense()}catch(r){throw qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(C8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=D8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=U8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(x8,"getRegistrationInfo")});var sM=T((VEe,nM)=>{"use strict";var q8=Ge(),IT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+q8.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};nM.exports=IT});var aM=T((YEe,oM)=>{"use strict";var iM=Ge(),CT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+iM.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+iM.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};oM.exports=CT});var uM=T((WEe,cM)=>{"use strict";var DT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};cM.exports=DT});var _M=T((zEe,lM)=>{"use strict";var F8=Ge(),UT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+F8.SERVER_SUFFIX.ADMIN,this.password=r}};lM.exports=UT});var PT=T((jEe,EM)=>{"use strict";var ha=require("path"),Gd=require("fs-extra"),G8=sM(),k8=aM(),V8=uM(),$8=_M(),LT=tn(),pa=J(),hr=Lr(),Fd=U(),Du=Ge(),{CONFIG_PARAMS:dt}=Fd,Uu=$(),Lu=Z(),dM=Ts(),MT=st(),ma="clustering",Y8=1e4,fM=5;EM.exports={generateNatsConfig:W8,removeNatsConfig:Q8,getHubConfigPath:K8};function K8(){let e=Lu.get(dt.ROOTPATH);return ha.join(e,ma,Du.NATS_CONFIG_FILES.HUB_SERVER)}a(K8,"getHubConfigPath");async function W8(e=!1,t=void 0){Lu.initSync();let r=Lu.get(dt.ROOTPATH),n=ha.join(r,ma,Du.PID_FILES.HUB),s=ha.join(r,ma,Du.PID_FILES.LEAF),i=hr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ha.join(r,ma,Du.NATS_CONFIG_FILES.HUB_SERVER),c=ha.join(r,ma,Du.NATS_CONFIG_FILES.LEAF_SERVER),u=hr.getConfigFromFile(dt.CLUSTERING_TLS_CERTIFICATE),_=hr.getConfigFromFile(dt.CLUSTERING_TLS_PRIVATEKEY),l=hr.getConfigFromFile(dt.CLUSTERING_TLS_CERT_AUTH),d=hr.getConfigFromFile(dt.CLUSTERING_TLS_INSECURE),f=hr.getConfigFromFile(dt.CLUSTERING_TLS_VERIFY),E=hr.getConfigFromFile(dt.CLUSTERING_NODENAME),h=hr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await MT.checkNATSServerInstalled()||kd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await LT.listUsers(),S=hr.getConfigFromFile(dt.CLUSTERING_USER),g=await LT.getClusterUser();(pa.isEmpty(g)||g.active!==!0)&&kd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await qd(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await qd(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await qd(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),await qd(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],R=[];for(let[V,ce]of p.entries())ce.role.role===Fd.ROLE_TYPES_ENUM.CLUSTER_USER&&ce.active&&(A.push(new $8(ce.username,dM.decrypt(ce.hash))),R.push(new V8(ce.username,dM.decrypt(ce.hash))));let v=[],{hub_routes:H}=hr.getClusteringRoutes();if(!pa.isEmptyOrZeroLength(H))for(let V of H)v.push(`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@${V.host}:${V.port}`);let P=new G8(hr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,hr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NAME),hr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),v,A,R);l==null&&(delete P.tls.ca_file,delete P.leafnodes.tls.ca_file),t=pa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Fd.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Gd.writeJson(o,P),Uu.trace(`Hub server config written to ${o}`));let M=`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,K=`tls://${g.uri_encoded_name}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,W=new k8(hr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[M],[K],A,R,u,_,l,d);l==null&&delete W.tls.ca_file,(t===void 0||t===Fd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Gd.writeJson(c,W),Uu.trace(`Leaf server config written to ${c}`))}a(W8,"generateNatsConfig");async function qd(e){let t=Lu.get(e);return pa.isEmpty(t)&&kd(`port undefined for '${e}'`),await pa.isPortTaken(t)&&kd(`'${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(qd,"isPortAvailable");function kd(e){let t=`Error generating clustering config: ${e}`;Uu.error(t),console.error(t),process.exit(1)}a(kd,"generateNatsConfigError");async function Q8(e){let{port:t,config_file:r}=MT.getServerConfig(e),{username:n,decrypt_hash:s}=await LT.getClusterUser(),i=0,o=2e3;for(;i<fM;){try{let _=await MT.createConnection(t,n,s,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){Uu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=fM)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await pa.async_set_timeout(o*(i*2))}let c="0".repeat(Y8),u=ha.join(Lu.get(dt.ROOTPATH),ma,r);await Gd.writeFile(u,c),await Gd.remove(u),Uu.notify(e,"started.")}a(Q8,"removeNatsConfig")});var gM=T((ZEe,TM)=>{"use strict";var Fr=Z(),z8=Qi(),he=U(),Mu=Ge(),ys=require("path"),{PACKAGE_ROOT:$d}=U(),hM=Z(),Vd=J(),Sa="/dev/null",J8=ys.join($d,"launchServiceScripts"),mM=ys.join($d,"utility/scripts"),j8=ys.join(mM,he.HDB_RESTART_SCRIPT),pM=ys.resolve($d,"dependencies",`${process.platform}-${process.arch}`,Mu.NATS_BINARY_NAME);function SM(){let t=z8.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Vd.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Vd.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:$d}}a(SM,"generateMainServerConfig");var X8=9930;function Z8(){Fr.initSync(!0);let e=Fr.get(he.CONFIG_PARAMS.ROOTPATH),t=ys.join(e,"clustering",Mu.NATS_CONFIG_FILES.HUB_SERVER),r=ys.join(Fr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=hM.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Mu.LOG_LEVEL_FLAGS[Fr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==X8?"-"+n:""),script:pM,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Sa,i.error_file=Sa),i}a(Z8,"generateNatsHubServerConfig");var e6=9940;function t6(){Fr.initSync(!0);let e=Fr.get(he.CONFIG_PARAMS.ROOTPATH),t=ys.join(e,"clustering",Mu.NATS_CONFIG_FILES.LEAF_SERVER),r=ys.join(Fr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=hM.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Mu.LOG_LEVEL_FLAGS[Fr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==e6?"-"+n:""),script:pM,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Sa,i.error_file=Sa),i}a(t6,"generateNatsLeafServerConfig");function r6(){Fr.initSync();let e=ys.join(Fr.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:J8,autorestart:!1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Sa,t.error_file=Sa),t}a(r6,"generateClusteringUpgradeV4ServiceConfig");function n6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return Vd.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Vd.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:mM},script:j8}}a(n6,"generateRestart");function s6(){return{apps:[SM()]}}a(s6,"generateAllServiceConfigs");TM.exports={generateAllServiceConfigs:s6,generateMainServerConfig:SM,generateRestart:n6,generateNatsHubServerConfig:Z8,generateNatsLeafServerConfig:t6,generateClusteringUpgradeV4ServiceConfig:r6}});var PM=T((rhe,MM)=>{"use strict";var ve=U(),i6=J(),ws=PT(),Pu=st(),ts=Ge(),hi=gM(),Yd=Z(),mi=$(),o6=on(),{startWorker:RM,onMessageFromWorkers:a6}=We(),c6=Ea(),the=require("util"),u6=require("child_process"),l6=require("fs"),{execFile:_6}=u6,we;MM.exports={enterPM2Mode:d6,start:pi,stop:vT,reload:OM,restart:bM,list:BT,describe:yM,connect:Is,kill:p6,startAllServices:S6,startService:HT,getUniqueServicesList:wM,restartAllServices:T6,isServiceRegistered:IM,reloadStopStart:CM,restartHdb:NM,deleteProcess:h6,startClusteringProcesses:UM,startClusteringThreads:LM,isHdbRestartRunning:m6,isClusteringRunning:R6,stopClustering:g6,reloadClustering:A6};var vu=!1;a6(e=>{e.type==="restart"&&Yd.initSync(!0)});function d6(){vu=!0}a(d6,"enterPM2Mode");function Is(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{mi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Is,"connect");var mr,f6=10,AM;function pi(e,t=!1){if(vu)return E6(e);let r=_6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=mr.indexOf(r);o>-1&&mr.splice(o,1),!AM&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<f6&&(l6.existsSync(ws.getHubConfigPath())?pi(e):(await ws.generateNatsConfig(!0),pi(e),await new Promise(c=>setTimeout(c,3e3)),await ws.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ws.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Yd.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&ts.LOG_LEVEL_HIERARCHY[o]>=ts.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===ts.LOG_LEVELS.ERR||l===ts.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=ts.LOG_LEVELS[f]}if(ts.LOG_LEVEL_HIERARCHY[o]>=ts.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===ts.LOG_LEVELS.ERR||l===ts.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),mr=[],!mr&&!t){let i=a(()=>{AM=!0,mr&&(mr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}mr.push(r)}a(pi,"start");function E6(e){return new Promise(async(t,r)=>{try{await Is()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(E6,"startWithPM2");function vT(e){if(!vu){for(let t of mr||[])t.name===e&&(mr.splice(mr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Is()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(vT,"stop");function OM(e){return new Promise(async(t,r)=>{try{await Is()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(OM,"reload");function bM(e){if(!vu)for(let t of mr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Is()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(bM,"restart");function h6(e){return new Promise(async(t,r)=>{try{await Is()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(h6,"deleteProcess");async function NM(){await pi(hi.generateRestart())}a(NM,"restartHdb");async function m6(){let e=await BT();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(m6,"isHdbRestartRunning");function BT(){return new Promise(async(e,t)=>{try{await Is()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(BT,"list");function yM(e){return new Promise(async(t,r)=>{try{await Is()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(yM,"describe");function p6(){if(!vu){for(let e of mr||[])e.kill();mr=[];return}return new Promise(async(e,t)=>{try{await Is()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(p6,"kill");async function S6(){try{await UM(),await LM(),await pi(hi.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(S6,"startAllServices");async function HT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=hi.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=hi.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=hi.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=hi.generateNatsHubServerConfig(),await pi(r,t),await ws.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=hi.generateNatsLeafServerConfig(),await pi(r,t),await ws.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=hi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await pi(r)}catch(r){throw we?.disconnect(),r}}a(HT,"startService");async function wM(){try{let e=await BT(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(wM,"getUniqueServicesList");async function T6(e=[]){try{let t=!1,r=await wM();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await bM(o))}t&&await CM(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(T6,"restartAllServices");async function IM(e){if(mr?.find(r=>r.name===e))return!0;let t=await c6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(IM,"isServiceRegistered");async function CM(e){let t=Yd.get(ve.CONFIG_PARAMS.THREADS_COUNT)??Yd.get(ve.CONFIG_PARAMS.THREADS),r=await yM(e),n=i6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await vT(e),await HT(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await NM():await OM(e)}a(CM,"reloadStopStart");var DM;async function UM(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await HT(r,e)}}a(UM,"startClusteringProcesses");async function LM(){DM=RM(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Pu.createWorkQueueStream(ts.WORK_QUEUE_CONSUMER_NAMES),await Pu.updateIngestStreamConsumer(),await Pu.updateLocalStreams();let e=await o6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){mi.info("Starting clustering upgrade 4.0.0 process"),RM(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(LM,"startClusteringThreads");async function g6(){for(let e in ve.CLUSTERING_PROCESSES)if(e!==ve.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ve.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await DM.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await vT(t)}}a(g6,"stopClustering");async function R6(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await IM(t)===!1)return!1}return!0}a(R6,"isClusteringRunning");async function A6(){await ws.generateNatsConfig(!0),await Pu.reloadNATSHub(),await Pu.reloadNATSLeaf(),await ws.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await ws.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(A6,"reloadClustering")});var zd=T((she,GM)=>{"use strict";var O6=require("minimist"),{isMainThread:FT,parentPort:HM}=require("worker_threads"),it=U(),{PROCESS_DESCRIPTORS_VALIDATE:Bu}=it,rs=$(),GT=J(),Kd=PT(),Ta=st(),xT=Ge(),xM=Lr(),ns=PM(),vM=Ea(),b6=Eh(),{restartWorkers:Wd,onMessageByType:N6}=We(),{handleHDBError:y6,hdb_errors:w6}=re(),{HTTP_STATUS_CODES:I6}=w6,Qd=Z();Qd.initSync();var Hu=`Restarting HarperDB. This may take up to ${it.RESTART_TIMEOUT_MS/1e3} seconds.`,C6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",BM="Clustering is not enabled so cannot be restarted",D6="Invalid service",ga,an;GM.exports={restart:qM,restartService:kT};FT&&N6(it.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?kT({service:e.workerType}):qM({operation:"restart"})});async function qM(e){an=Object.keys(e).length===0,ga=await ns.isServiceRegistered(it.HDB_PROC_DESCRIPTOR);let t=O6(process.argv);if(t.service){await kT(t);return}if(an&&!ga){console.error(C6);return}if(an&&console.log(Hu),ga){ns.enterPM2Mode(),rs.notify(Hu);let r=b6(Object.keys(it.CONFIG_PARAM_MAP),!0);return GT.isEmptyOrZeroLength(Object.keys(r))||xM.updateConfigValue(void 0,void 0,r,!0,!0),L6(),Hu}return FT?(rs.notify(Hu),setTimeout(()=>{Wd()},50)):HM.postMessage({type:it.ITC_EVENT_TYPES.RESTART}),Hu}a(qM,"restart");async function kT(e){let{service:t}=e;if(it.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw y6(new Error,D6,I6.BAD_REQUEST,void 0,void 0,!0);if(ga=await ns.isServiceRegistered(it.HDB_PROC_DESCRIPTOR),!FT)return HM.postMessage({type:it.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Bu.clustering:if(!Qd.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=BM;break}an&&console.log("Restarting clustering"),rs.notify("Restarting clustering"),await FM();break;case Bu.clustering_config:case Bu["clustering config"]:if(!Qd.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=BM;break}an&&console.log("Restarting clustering_config"),rs.notify("Restarting clustering_config"),await ns.reloadClustering();break;case"custom_functions":case"custom functions":case Bu.harperdb:case Bu.http_workers:if(an&&!ga){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}an&&console.log("Restarting http_workers"),rs.notify("Restarting http_workers"),an?await ns.restart(it.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Wd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(rs.error(r),an&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(kT,"restartService");async function U6(){await Ta.publishToStream(`${xT.SUBJECT_PREFIXES.TXN}.${xT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,xT.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ta.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(U6,"postDummyNatsMsg");async function L6(){await FM(),await ns.restart(it.HDB_PROC_DESCRIPTOR),await GT.async_set_timeout(2e3),Qd.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await qT(),an&&(await Ta.closeConnection(),process.exit(0))}a(L6,"restartPM2Mode");async function FM(){if(!xM.getConfigFromFile(it.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await vM.getHDBProcessInfo()).clustering.length===0)rs.trace("Clustering not running, restart will start clustering services"),await Kd.generateNatsConfig(!0),await ns.startClusteringProcesses(),await ns.startClusteringThreads(),await qT(),an&&await Ta.closeConnection();else{await U6(),await Kd.generateNatsConfig(!0),ga?(rs.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await ns.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ns.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await vM.getHDBProcessInfo()).clustering.forEach(s=>{rs.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await GT.async_set_timeout(3e3),await qT(),await Ta.updateLocalStreams(),an&&await Ta.closeConnection(),rs.trace("Restart clustering restarting ingest and reply service threads");let t=Wd(it.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Wd(it.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(FM,"restartClustering");async function qT(){await Kd.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Kd.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(qT,"removeNatsConfig")});var XM=T((ahe,jM)=>{"use strict";var ohe=require("lodash"),pr=U(),{handleHDBError:kM,hdb_errors:M6}=re(),{HDB_ERROR_MSGS:P6,HTTP_STATUS_CODES:v6}=M6,VT=$();jM.exports={getRolePermissions:H6};var Eo=Object.create(null),B6=a(e=>({key:e,perms:{}}),"perms_template_obj"),KM=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),WM=a((e=!1,t=!1,r=!1,n=!1)=>({[pr.PERMS_CRUD_ENUM.READ]:e,[pr.PERMS_CRUD_ENUM.INSERT]:t,[pr.PERMS_CRUD_ENUM.UPDATE]:r,[pr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),$T=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...WM(t,r,n,s)}),"table_perms_template"),VM=a((e,t=WM())=>({attribute_name:e,describe:JM(t),[xu]:t[xu],[YT]:t[YT],[KT]:t[KT]}),"attr_perms_template"),$M=a((e,t=!1)=>({attribute_name:e,describe:t,[xu]:t}),"timestamp_attr_perms_template"),{READ:xu,INSERT:YT,UPDATE:KT}=pr.PERMS_CRUD_ENUM,QM=Object.values(pr.PERMS_CRUD_ENUM),zM=[xu,YT,KT];function H6(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[pr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(Eo[t]&&Eo[t].key===n)return Eo[t].perms;let s=x6(e,r);return Eo[t]?Eo[t].key=n:Eo[t]=B6(n),Eo[t].perms=s,s}catch(r){if(!e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<pr.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw VT.error(n),VT.debug(r),kM(new Error,P6.OUTDATED_PERMS_TRANSLATION_ERROR,v6.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
+
${r.stack}`;throw VT.error(n),kM(new Error)}}}a(H6,"getRolePermissions");function x6(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[pr.SYSTEM_SCHEMA_NAME]=n[pr.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=q6(t[i]);return}r[i]=KM(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=F6(c,u);r[i].describe||QM.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=$T()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=$T()})}),r}a(x6,"translateRolePermissions");function q6(e){let t=KM(!0);return Object.keys(e).forEach(r=>{t.tables[r]=$T(!0,!0,!0,!0,!0)}),t}a(q6,"createStructureUserPermissions");function F6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return pr.TIME_STAMP_NAMES.includes(d)&&(f=$M(d,l[xu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=VM(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=JM(l),s.attribute_permissions.push(l),c||G6(l,u)}else if(_!==o){let l;pr.TIME_STAMP_NAMES.includes(_)?l=$M(_):l=VM(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=YM(s),s}else return e.describe=YM(e),e}a(F6,"getTableAttrPerms");function YM(e){return QM.filter(t=>e[t]).length>0}a(YM,"getSchemaTableDescribePerm");function JM(e){return zM.filter(t=>e[t]).length>0}a(JM,"getAttributeDescribePerm");function G6(e,t){zM.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(G6,"checkForHashPerms")});var ZM={};Ke(ZM,{Resources:()=>Jd,keyArrayToString:()=>Ra,resetResources:()=>k6,resources:()=>Si});function k6(){return Si=new Jd}function Ra(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Jd,Si,qu=ge(()=>{eo();Jd=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(k6,"resetResources");a(Ra,"keyArrayToString")});var eP={};Ke(eP,{Headers:()=>Ti,appendHeader:()=>WT});function WT(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var Ti,Fu=ge(()=>{Ti=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(WT,"appendHeader")});var Gu={};Ke(Gu,{authentication:()=>cP,bypassAuth:()=>z6,login:()=>j6,logout:()=>X6,start:()=>J6});function z6(){aP=!0}async function cP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?K6?Y6:[]:$6?V6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Ti([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return jd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),jd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(jd){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let p=s.indexOf(";",h),S=s.indexOf("=",h);u=s.slice(S+1,p===-1?s.length:p),_=await rP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Zd.AuthAuditLog(E,h,Gt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Gt.AUTH_AUDIT_STATUS.SUCCESS?tP.notify(S):tP.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let E=e.mtlsConfig.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=e.peerCertificate.subject.CN),e.user=await rt.getUser(E,null,null))}let d;if(!e.user)if(n){if(d=ho.get(n),!d){let[E,h]=n.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await rt.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Xd.validateOperationToken)(h)}catch(g){if(g.message==="invalid token")try{return await(0,Xd.validateRefreshToken)(h),c({status:-1})}catch{throw g}}break}}catch(g){return Q6&&(ho.get(h)||(ho.set(h,h),l(p,Gt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:gi({error:g.message},e)})}ho.set(n,d),W6&&l(d.username,Gt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await rt.getUser(_.user,null,e):(aP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,sP.getSuperUser)());jd&&(e.session.update=function(E){if(!u){u=(0,iP.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):f?.headers?.set&&f.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,rP.put(E)},e.login=async function(E,h){e.user=await rt.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Si.loginPath?(f.status=302,f.headers.set("Location",Si.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new Ti);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function J6({server:e,port:t}){e.request(cP,{port:t||"all"}),nP||(nP=!0,setInterval(()=>{ho=new Map},cn.get(Gt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),oP.user.addListener(()=>{ho=new Map}))}async function j6(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function X6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var sP,Xd,iP,cn,Gt,Zd,oP,tP,V6,$6,Y6,K6,rP,jd,aP,W6,Q6,ho,nP,ef=ge(()=>{sP=x(tn());rr();qu();Xd=x(gu());Re();iP=require("uuid"),cn=x(Z()),Gt=x(U()),Zd=x($()),oP=x(qc());Fu();Aa();tP=(0,Zd.loggerWithTag)("auth-event");cn.initSync();V6=cn.get(Gt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),$6=cn.get(Gt.CONFIG_PARAMS.HTTP_CORS),Y6=cn.get(Gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),K6=cn.get(Gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),rP=ut({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),jd=cn.get(Gt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,aP=cn.get(Gt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,W6=cn.get(Gt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,Q6=cn.get(Gt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,ho=new Map;rt.onInvalidatedUser(()=>{ho=new Map});a(z6,"bypassAuth");a(cP,"authentication");a(J6,"start");a(j6,"login");a(X6,"logout")});var hP=T((She,EP)=>{"use strict";var Ie=require("joi"),uP=require("fs-extra"),lP=require("path"),Ds=Xe(),_P=Z(),dP=U(),fP=$(),{hdb_errors:Z6}=re(),{HDB_ERROR_MSGS:Jt}=Z6,Cs=/^[a-zA-Z0-9-_]+$/;EP.exports={getDropCustomFunctionValidator:t9,setCustomFunctionValidator:r9,addComponentValidator:o9,dropCustomFunctionProjectValidator:a9,packageComponentValidator:c9,deployComponentValidator:u9,setComponentFileValidator:n9,getComponentFileValidator:i9,dropComponentFileValidator:s9};function tf(e,t,r){try{let n=_P.get(dP.CONFIG_PARAMS.COMPONENTSROOT),s=lP.join(n,t);return uP.existsSync(s)?e?t:r.message(Jt.PROJECT_EXISTS):e?r.message(Jt.NO_PROJECT):t}catch(n){return fP.error(n),r.message(Jt.VALIDATION_ERR)}}a(tf,"checkProjectExists");function ku(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(ku,"checkFilePath");function e9(e,t,r,n){try{let s=_P.get(dP.CONFIG_PARAMS.COMPONENTSROOT),i=lP.join(s,e,t,r+".js");return uP.existsSync(i)?r:n.message(Jt.NO_FILE)}catch(s){return fP.error(s),n.message(Jt.VALIDATION_ERR)}}a(e9,"checkFileExists");function t9(e){let t=Ie.object({project:Ie.string().pattern(Cs).custom(tf.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Cs).custom(e9.bind(null,e.project,e.type)).custom(ku).required().messages({"string.pattern.base":Jt.BAD_FILE_NAME})});return Ds.validateBySchema(e,t)}a(t9,"getDropCustomFunctionValidator");function r9(e){let t=Ie.object({project:Ie.string().pattern(Cs).custom(tf.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(ku).required(),function_content:Ie.string().required()});return Ds.validateBySchema(e,t)}a(r9,"setCustomFunctionValidator");function n9(e){let t=Ie.object({project:Ie.string().pattern(Cs).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),file:Ie.string().custom(ku).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ds.validateBySchema(e,t)}a(n9,"setComponentFileValidator");function s9(e){let t=Ie.object({project:Ie.string().pattern(Cs).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),file:Ie.string().custom(ku).optional()});return Ds.validateBySchema(e,t)}a(s9,"dropComponentFileValidator");function i9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(ku).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ds.validateBySchema(e,t)}a(i9,"getComponentFileValidator");function o9(e){let t=Ie.object({project:Ie.string().pattern(Cs).custom(tf.bind(null,!1)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME})});return Ds.validateBySchema(e,t)}a(o9,"addComponentValidator");function a9(e){let t=Ie.object({project:Ie.string().pattern(Cs).custom(tf.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME})});return Ds.validateBySchema(e,t)}a(a9,"dropCustomFunctionProjectValidator");function c9(e){let t=Ie.object({project:Ie.string().pattern(Cs).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Ds.validateBySchema(e,t)}a(c9,"packageComponentValidator");function u9(e){let t=Ie.object({project:Ie.string().pattern(Cs).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":Jt.BAD_PACKAGE}),package:Ie.string().optional()});return Ds.validateBySchema(e,t)}a(u9,"deployComponentValidator")});var of=T((ghe,AP)=>{"use strict";var rf=require("joi"),nf=require("path"),mP=require("fs-extra"),{exec:l9}=require("child_process"),_9=require("util"),pP=_9.promisify(l9),Vu=U(),{handleHDBError:Oa,hdb_errors:d9}=re(),{HTTP_STATUS_CODES:ba}=d9,$u=Z(),f9=Xe(),Na=$();$u.initSync();var QT=$u.get(Vu.CONFIG_PARAMS.COMPONENTSROOT),SP="npm install --omit=dev --json",E9=`${SP} --dry-run`;AP.exports={installModules:S9,auditModules:T9,installAllRootModules:h9,uninstallRootModule:m9,linkHarperdb:p9};async function h9(e=!1){await sf(),await Yu(e?"npm install --ignore-scripts":"npm install",$u.get(Vu.CONFIG_PARAMS.ROOTPATH))}a(h9,"installAllRootModules");async function m9(e){await Yu(`npm uninstall ${e}`,$u.get(Vu.CONFIG_PARAMS.ROOTPATH))}a(m9,"uninstallRootModule");async function p9(){await sf(),await Yu(`npm link ${Vu.PACKAGE_ROOT}`,$u.get(Vu.CONFIG_PARAMS.ROOTPATH))}a(p9,"linkHarperdb");async function Yu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await pP(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
12
|
+
`,""))}return n&&!n.includes("Debugger listening")&&Na.error("Error running NPM command:",e,n),Na.trace(r,n),r?.replace(`
|
|
13
|
+
`,"")}a(Yu,"runCommand");async function S9(e){Na.info(`starting installModules for request: ${e}`);let t=RP(e);if(t)throw Oa(t,t.message,ba.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?E9:SP;await sf(),await gP(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let _=nf.join(QT,u),l,d=null;try{let{stdout:f,stderr:E}=await pP(s,{cwd:_});l=f?f.replace(`
|
|
14
14
|
`,""):null,d=E?E.replace(`
|
|
15
|
-
`,""):null}catch(f){f.stderr?i[u].npm_error=
|
|
16
|
-
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(mP,"parseNPMStdErr");async function h9(e){Oa.info(`starting auditModules for request: ${e}`);let t=SP(e);if(t)throw Ra(t,t.message,Aa.BAD_REQUEST);let{projects:r}=e;await rf(),await pP(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=tf.join(KT,o);s[o]={npm_output:null,npm_error:null};try{let u=await Gu("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=mP(u.stderr)}}return Oa.info(`finished auditModules with response ${s}`),s}a(h9,"auditModules");async function rf(){try{return await Gu("npm -v"),!0}catch{throw Ra(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Aa.BAD_REQUEST,void 0,void 0,!0)}}a(rf,"checkNPMInstalled");async function pP(e){if(!Array.isArray(e)||e.length===0)throw Ra(new Error,"projects argument must be an array with at least 1 element",Aa.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=tf.join(KT,i.toString());if(!await fP.pathExists(o)){t.push(i);continue}let u=tf.join(o,"package.json");await fP.pathExists(u)||r.push(i)}if(t.length>0)throw Ra(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Aa.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ra(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Aa.BAD_REQUEST,void 0,void 0,!0)}a(pP,"checkProjectPaths");function SP(e){let t=ef.object({projects:ef.array().min(1).items(ef.string()).required(),dry_run:ef.boolean().default(!1)});return u9.validateBySchema(e,t)}a(SP,"modulesValidator")});var QT=T((She,bP)=>{"use strict";var ba=require("fs-extra"),WT=require("path"),nf=V(),gP=J(),of=L(),OP=Z(),m9=Ur();bP.exports=p9;async function p9(){let e=S9(),t=OP.get(of.CONFIG_PARAMS.ROOTPATH),r=WT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+of.PACKAGE_ROOT}},n=WT.join(t,"node_modules");await ba.ensureDir(n);let i,o=!0,c=!1;try{i=await ba.readJson(r)}catch(u){if(gP.isEmptyOrZeroLength(e))return;if(u.code!==of.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!gP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await RP(_);s.dependencies[u]=l+_}if(!o){nf.notify("Installing components"),await AP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await RP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(nf.notify("Removing component",u),c=!0);c&&(nf.notify("Updating components."),await AP(r,s,i))}a(p9,"installComponents");function S9(){let e=m9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(S9,"getComponentsConfig");async function RP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":WT.extname(e)||await ba.pathExists(e)?"file:":"github:"}a(RP,"getPkgPrefix");async function AP(e,t,r){nf.trace("npm installing components package.json",t),await ba.writeFile(e,JSON.stringify(t,null," "));try{await sf().installAllRootModules(OP.get(of.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await ba.writeFile(e,JSON.stringify(r,null," ")):await ba.unlink(e),s}}a(AP,"installPackages")});var jT=T((Rhe,IP)=>{"use strict";var ke=require("fs-extra"),zT=require("fast-glob"),Se=require("path"),yP=require("tar-fs"),ghe=require("uuid").v4,JT=require("normalize-path"),sn=dP(),Nt=V(),Qe=L(),mt=Z(),ku=Ur(),T9=J(),{PACKAGE_ROOT:g9}=L(),{handleHDBError:Mt,hdb_errors:R9}=re(),{basename:A9}=require("path"),O9=QT(),wP=Z(),b9=L(),{Readable:N9}=require("stream"),{isMainThread:y9}=require("worker_threads"),{HDB_ERROR_MSGS:ho,HTTP_STATUS_CODES:Pt}=R9,w9=Se.join(g9,"application-template"),NP=Se.join(mt.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function I9(){Nt.trace("getting custom api status");let e={};try{e={port:mt.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Mt(new Error,ho.FUNCTION_STATUS,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(I9,"customFunctionsStatus");function C9(){Nt.trace("getting custom api endpoints");let e={},t=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{zT.sync(JT(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:zT.sync(JT(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:zT.sync(JT(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Mt(new Error,ho.GET_FUNCTIONS,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(C9,"getCustomFunctions");function D9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=sn.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("getting custom api endpoint file content");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=Se.join(r,s,n,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Mt(new Error,ho.GET_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(D9,"getCustomFunction");function L9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=sn.setCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("setting custom function file content");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return ke.outputFileSync(Se.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Mt(new Error,ho.SET_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(L9,"setCustomFunction");function U9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=sn.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("dropping custom function file");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return ke.unlinkSync(Se.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Mt(new Error,ho.DROP_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(U9,"dropCustomFunction");function M9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.addComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("adding component");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=Se.join(r,s);return ke.mkdirSync(n,{recursive:!0}),ke.copySync(w9,n),`Successfully added project: ${s}`}catch(n){throw Mt(new Error,ho.ADD_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,n)}}a(M9,"addComponent");function P9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.dropCustomFunctionProjectValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("dropping custom function project");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=mt.get(Qe.CONFIG_PARAMS.APPS);if(!T9.isEmptyOrZeroLength(n)){let i=!1;for(let[o,c]of n.entries())if(c.name===s){n.splice(o,1),i=!0;break}if(i)return ku.updateConfigValue(Qe.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=Se.join(r,s);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw Mt(new Error,ho.DROP_FUNCTION_PROJECT,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(P9,"dropCustomFunctionProject");async function v9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.packageComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;Nt.trace("packaging component",s);let n;try{n=await ke.realpath(Se.join(r,s))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{n=await ke.realpath(Se.join(mt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await ke.ensureDir(NP);let i=Se.join(NP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Se.join(n,"node_modules"))}),yP.pack(n,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:s,payload:c}}a(v9,"packageComponent");async function B9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.deployComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(Nt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(n){o=Se.join(r,s),i="file:"+o,await ke.ensureDir(o);let f=N9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(yP.extract(o,{finish:h})).on("error",p)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(Se.join(o,"package"),o),await ke.remove(Se.join(o,"package")))}if(await ku.addConfig(s,{package:i}),!n){await O9();let f=wP.get(b9.CONFIG_PARAMS.ROOTPATH);o=Se.join(f,"node_modules",s)}if(y9)return;let c=new Map;c.isWorker=!0;let u=(cf(),se(af)),_;u.setErrorReporter(f=>_=f);let l=A9(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Nt.info("Installed component"),`Successfully deployed: ${s}`}a(B9,"deployComponent");async function H9(){let e=ku.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await ke.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Se.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await ke.stat(d),E={name:Se.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return Nt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),s=await r(mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Se.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(Se.join(mt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(cf(),se(af)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return s}a(H9,"getComponents");async function x9(e){let t=sn.getComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let s=ku.getConfigObj()[e.project]||e.project==="harperdb"?Se.join(wP.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Se.join(s,e.project,e.file));return{message:await ke.readFile(Se.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Se.join(e.project,e.file)}'`):i}}a(x9,"getComponentFile");async function q9(e){let t=sn.setComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=Se.join(mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(s),await ke.outputFile(s,e.payload,r)):await ke.ensureDir(s),"Successfully set component: "+e.file}a(q9,"setComponentFile");async function F9(e){let t=sn.dropComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=e.file?Se.join(e.project,e.file):e.project,s=Se.join(mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(s)&&await ke.remove(s),ku.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(F9,"dropComponent");IP.exports={customFunctionsStatus:I9,getCustomFunctions:C9,getCustomFunction:D9,setCustomFunction:L9,dropCustomFunction:U9,addComponent:M9,dropCustomFunctionProject:P9,packageComponent:v9,deployComponent:B9,getComponents:H9,getComponentFile:x9,setComponentFile:q9,dropComponent:F9}});var XT=T((Ohe,DP)=>{"use strict";var nn=require("joi"),CP=je();DP.exports={readTransactionLogValidator:G9,deleteTransactionLogsBeforeValidator:k9};function G9(e){let t=nn.object({schema:nn.string().required(),table:nn.string().required(),from:nn.date().timestamp(),to:nn.date().timestamp(),limit:nn.number().min(1)});return CP.validateBySchema(e,t)}a(G9,"readTransactionLogValidator");function k9(e){let t=nn.object({schema:nn.string().required(),table:nn.string().required(),timestamp:nn.date().timestamp().required()});return CP.validateBySchema(e,t)}a(k9,"deleteTransactionLogsBeforeValidator")});var lf=T((Nhe,vP)=>{"use strict";var ZT=L(),uf=st(),LP=J(),UP=Z(),MP=Sn(),{handleHDBError:Na,hdb_errors:V9}=re(),{HTTP_STATUS_CODES:ya}=V9,{readTransactionLogValidator:$9,deleteTransactionLogsBeforeValidator:Y9}=XT(),PP="This operation relies on clustering and cannot run with it disable.",K9="Logs successfully deleted from transaction log.",W9="All logs successfully deleted from transaction log.";vP.exports={readTransactionLog:Q9,deleteTransactionLogsBefore:z9};async function*Q9(e){let t=$9(e);if(t)throw Na(t,t.message,ya.BAD_REQUEST,void 0,void 0,!0);if(!UP.get(ZT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Na(new Error,PP,ya.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=LP.checkSchemaTableExist(r,s);if(n)throw Na(new Error,n,ya.NOT_FOUND,void 0,void 0,!0);let i=MP.createNatsTableStreamName(r,s),o=await uf.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===ZT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(Q9,"readTransactionLog");async function z9(e){let t=Y9(e);if(t)throw Na(t,t.message,ya.BAD_REQUEST,void 0,void 0,!0);if(!UP.get(ZT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Na(new Error,PP,ya.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=LP.checkSchemaTableExist(r,s);if(i)throw Na(new Error,i,ya.NOT_FOUND,void 0,void 0,!0);let o=MP.createNatsTableStreamName(r,s),{jsm:c}=await uf.getNATSReferences(),u=await uf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=K9,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=W9):d=(await uf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(z9,"deleteTransactionLogsBefore")});var HP=T((whe,BP)=>{"use strict";var eg=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};BP.exports=eg});var qP=T((Che,xP)=>{"use strict";var tg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};xP.exports=tg});var sg=T((Lhe,GP)=>{"use strict";var FP=HP(),J9=qP(),{HDB_ERROR_MSGS:j9}=Nr(),rg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=j9.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new FP(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new J9(c,n[c]);i.push(u)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new FP(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};GP.exports=rg});var Ef=T((Mhe,sv)=>{"use strict";var ng=Cr(),_f=es(),us=lu(),Yu=Xn(),ig=ti(),X9=pS(),Z9=XD(),Ku=ts(),df=yS(),yt=V(),e7=CS(),t7=Id(),r7=lT(),s7=Dd(),n7=_T(),i7=dT(),o7=hT(),a7=pT(),og=gT(),Dn=J(),c7=zU(),ag=NT(),$P=Wd(),cs=L(),YP=zM(),u7=da(),KP=mu(),WP=(Xd(),se(Hu)),QP=Ur(),Gr=jT(),l7=require("alasql"),zP=lf(),JP=sf(),jP=sg(),{handleHDBError:Sr,hdb_errors:XP}=re(),{HDB_ERROR_MSGS:kt,HTTP_STATUS_CODES:Vu}=XP,k=new Map,ZP="delete",gi="insert",Ln="read",mo="update",$u="describe",kP=Yu.describeSchema.name,VP=Yu.describeTable.name,ev={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},_7="catchup",d7="handleGetJob",f7="handleGetJobsByStartDate",ff={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},E7=[us.createTable.name,us.createAttribute.name,us.dropTable.name,us.dropAttribute.name],tv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},Q=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};k.set(ng.insert.name,new Q(!1,[gi]));k.set(ng.update.name,new Q(!1,[mo]));k.set(ng.upsert.name,new Q(!1,[gi,mo]));k.set(_f.searchByConditions.name,new Q(!1,[Ln]));k.set(_f.searchByHash.name,new Q(!1,[Ln]));k.set(_f.searchByValue.name,new Q(!1,[Ln]));k.set(_f.search.name,new Q(!1,[Ln]));k.set(us.createSchema.name,new Q(!0,[]));k.set(us.createTable.name,new Q(!0,[]));k.set(us.createAttribute.name,new Q(!1,[gi]));k.set(us.dropSchema.name,new Q(!0,[]));k.set(us.dropTable.name,new Q(!0,[]));k.set(us.dropAttribute.name,new Q(!0,[]));k.set(Yu.describeSchema.name,new Q(!1,[Ln]));k.set(Yu.describeTable.name,new Q(!1,[Ln]));k.set(ig.deleteRecord.name,new Q(!1,[ZP]));k.set(Ku.addUser.name,new Q(!0,[]));k.set(Ku.alterUser.name,new Q(!0,[]));k.set(Ku.dropUser.name,new Q(!0,[]));k.set(Ku.listUsersExternal.name,new Q(!0,[]));k.set(df.listRoles.name,new Q(!0,[]));k.set(df.addRole.name,new Q(!0,[]));k.set(df.alterRole.name,new Q(!0,[]));k.set(df.dropRole.name,new Q(!0,[]));k.set(e7.name,new Q(!0,[]));k.set(t7.name,new Q(!0,[]));k.set(r7.name,new Q(!0,[]));k.set(s7.name,new Q(!0,[]));k.set(n7.name,new Q(!0,[]));k.set(i7.name,new Q(!0,[]));k.set(og.setRoutes.name,new Q(!0,[]));k.set(og.getRoutes.name,new Q(!0,[]));k.set(og.deleteRoutes.name,new Q(!0,[]));k.set(QP.setConfiguration.name,new Q(!0,[]));k.set(o7.clusterStatus.name,new Q(!0,[]));k.set(a7.name,new Q(!0,[]));k.set(ag.getFingerprint.name,new Q(!0,[]));k.set(ag.setLicense.name,new Q(!0,[]));k.set(ig.deleteFilesBefore.name,new Q(!0,[]));k.set(ig.deleteAuditLogsBefore.name,new Q(!0,[]));k.set($P.restart.name,new Q(!0,[]));k.set($P.restartService.name,new Q(!0,[]));k.set(X9.name,new Q(!0,[]));k.set(Z9.name,new Q(!0,[Ln]));k.set(u7.systemInformation.name,new Q(!0,[]));k.set(QP.getConfiguration.name,new Q(!0,[]));k.set(zP.readTransactionLog.name,new Q(!0,[]));k.set(zP.deleteTransactionLogsBefore.name,new Q(!0,[]));k.set(JP.installModules.name,new Q(!0,[]));k.set(JP.auditModules.name,new Q(!0,[]));k.set(KP.createTokens.name,new Q(!1,[]));k.set(KP.refreshOperationToken.name,new Q(!1,[]));k.set(WP.login.name,new Q(!1,[]));k.set(WP.logout.name,new Q(!1,[]));k.set(Gr.customFunctionsStatus.name,new Q(!0,[]));k.set(Gr.getCustomFunctions.name,new Q(!0,[]));k.set(Gr.getComponents.name,new Q(!0,[]));k.set(Gr.getComponentFile.name,new Q(!0,[]));k.set(Gr.setComponentFile.name,new Q(!0,[]));k.set(Gr.dropComponent.name,new Q(!0,[]));k.set(Gr.getCustomFunction.name,new Q(!0,[]));k.set(Gr.setCustomFunction.name,new Q(!0,[]));k.set(Gr.dropCustomFunction.name,new Q(!0,[]));k.set(Gr.addComponent.name,new Q(!0,[]));k.set(Gr.dropCustomFunctionProject.name,new Q(!0,[]));k.set(Gr.packageComponent.name,new Q(!0,[]));k.set(Gr.deployComponent.name,new Q(!0,[]));k.set(ag.getRegistrationInfo.name,new Q(!1,[]));k.set(Ku.userInfo.name,new Q(!1,[]));k.set(Yu.describeAll.name,new Q(!1,[]));k.set(d7,new Q(!1,[]));k.set(f7,new Q(!0,[]));k.set(_7,new Q(!0,[]));k.set(ff.CSV_DATA_LOAD,new Q(!1,[gi,mo]));k.set(ff.CSV_URL_LOAD,new Q(!1,[gi,mo]));k.set(ff.CSV_FILE_LOAD,new Q(!1,[gi,mo]));k.set(ff.IMPORT_FROM_S3,new Q(!1,[gi,mo]));k.set(tv.EXPORT_TO_S3,new Q(!0,[]));k.set(tv.EXPORT_LOCAL,new Q(!0,[]));k.set(cs.VALID_SQL_OPS_ENUM.DELETE,new Q(!1,[ZP]));k.set(cs.VALID_SQL_OPS_ENUM.SELECT,new Q(!1,[Ln]));k.set(cs.VALID_SQL_OPS_ENUM.INSERT,new Q(!1,[gi]));k.set(cs.VALID_SQL_OPS_ENUM.UPDATE,new Q(!1,[mo]));sv.exports={verifyPerms:m7,verifyPermsAst:h7,verifyBulkLoadAttributePerms:S7};function h7(e,t,r){if(Dn.isEmptyOrZeroLength(e))throw yt.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Dn.isEmptyOrZeroLength(t))throw yt.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Dn.isEmptyOrZeroLength(r))throw yt.info("verify_perms_ast has a null operation parameter"),Sr(new Error);try{let s=new jP,n=new c7(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw yt.info("No schemas defined in verifyPermsAst(), will not continue."),Sr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&ev[r])throw Sr(new Error,kt.DROP_SYSTEM,Vu.FORBIDDEN);if(c&&!u)return null;let _=YP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof l7.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=n.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=rv(t,r,o,s);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=n.getAttributesBySchemaTableName(f,d[E]),p=ug(t.role.permission,f,d[E]);cg(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw Sr(s)}}a(h7,"verifyPermsAst");function m7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw yt.info("null required parameter in verifyPerms"),Sr(new Error,kt.DEFAULT_INVALID_REQUEST,Vu.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema??e.database,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new jP;if(Dn.isEmptyOrZeroLength(e.hdb_user.role)||Dn.isEmptyOrZeroLength(e.hdb_user.role.permission))return yt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(kt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(cs.SYSTEM_SCHEMA_NAME)||n===cs.SYSTEM_SCHEMA_NAME;if(l&&ev[r])throw Sr(new Error,kt.DROP_SYSTEM,Vu.FORBIDDEN);if(u&&!l||_===!0&&(r===us.createSchema.name||r===us.dropSchema.name))return null;if(E7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=YP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===kP||r===VP){if(n===cs.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(kt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===kP&&(!d[n]||!d[n][$u]))return c.handleInvalidItem(kt.SCHEMA_NOT_FOUND(n));if(r===VP&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][$u]))return c.handleInvalidItem(kt.TABLE_NOT_FOUND(n,i))}}let f=rv(e.hdb_user,r,o,c,s);if(f)return f;if(k.get(r)&&k.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&cs.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[cs.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[cs.PERMS_CRUD_ENUM.READ]).forEach(R=>{p.push(R.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(A=>A.attribute),e.get_attributes=p)}let E=p7(e),h=ug(e.hdb_user.role.permission,n,i);return cg(E,h,r,i,n,c,s),c.getPermsResponse()}a(m7,"verifyPerms");function rv(e,t,r,s,n){if(Dn.arrayHasEmptyValues([e,t,r]))throw yt.info("hasPermissions has an invalid parameter"),Sr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||k.get(t).requires_su))return null;if(!k.get(t))throw yt.info(`operation ${t} not found.`),Sr(new Error,kt.OP_NOT_FOUND(t),Vu.BAD_REQUEST);if(k.get(t)&&k.get(t).requires_su)return yt.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(kt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][$u]===!1){s.addInvalidItem(kt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(kt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[$u]===!1)s.addInvalidItem(kt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=k.get(t).perms;!Dn.isEmpty(n)&&E.includes(n)&&(E=[n]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(yt.info(`Required ${p} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&s.addUnauthorizedTable(u,l,f)}catch(f){let E=kt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw yt.error(E),yt.error(f),Sr(XP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(rv,"hasPermissions");function cg(e,t,r,s,n,i,o){if(!e||!t)throw yt.info("no attributes specified in checkAttributePerms."),Sr(new Error);let c=k.get(r).perms;if(!c||c==="")throw yt.info(`no permissions found for ${r} in checkAttributePerms().`),Sr(new Error);if(Dn.isEmptyOrZeroLength(t))return yt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[$u]===!1){i.addInvalidItem(kt.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(cs.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Ln)throw Sr(new Error,kt.SYSTEM_TIMESTAMP_PERMS_ERR,Vu.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(kt.ATTR_NOT_FOUND(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(cg,"checkAttributePerms");function p7(e){let t=new Set;try{if(e.action)return t;if(e.operation===cs.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){yt.info(r)}return t}a(p7,"getRecordAttributes");function ug(e,t,r){let s=new Map;if(Dn.isEmpty(e))return yt.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{yt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(ug,"getAttributePermissions");function S7(e,t,r,s,n,i,o){let c=new Set(i),u=ug(e,s,n);cg(c,u,t,n,s,o,r)}a(S7,"verifyBulkLoadAttributePerms")});var mf=T((vhe,cv)=>{"use strict";cv.exports={evaluateSQL:L7,processAST:av,convertSQLToAST:ov,checkASTPermissions:iv};var T7=Cr(),nv=require("util"),g7=nv.callbackify(T7.insert),R7=es().search,A7=$C().update,O7=nv.callbackify(A7),b7=KC().convertDelete,Ri=require("alasql"),N7=Ef(),hf=V(),y7=X_(),w7=J(),Wu=L(),{hdb_errors:I7,handleHDBError:lg}=re(),{HTTP_STATUS_CODES:_g}=I7;y7(Ri);var C7=403,D7="There was a problem performing this insert. Please check the logs and try again.",dg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function L7(e,t){let r=e.parsed_sql_object;if(!r){r=ov(e.sql);let s,n=r.ast.statements[0];if(n instanceof Ri.yy.Insert?s=n.into.databaseid:n instanceof Ri.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Ri.yy.Update||n instanceof Ri.yy.Delete?s=n.table.databaseid:hf.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Ri.yy.Select)&&w7.isEmptyOrZeroLength(s))return t("No schema specified",null)}av(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(L7,"evaluateSQL");function iv(e,t){let r;try{r=N7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(iv,"checkASTPermissions");function ov(e){let t=new dg;if(!e)throw lg(new Error,"The 'sql' parameter is missing from the request body",_g.BAD_REQUEST);try{let r=e.trim(),s=Ri.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
17
|
-
`);throw s[1]?lg(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,_g.BAD_REQUEST):lg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",_g.BAD_REQUEST)}return t}a(ov,"convertSQLToAST");function av(e,t,r){try{let s=U7;if(!e.bypass_auth&&!t.permissions_checked){let i=iv(e,t);if(i&&i.length>0)return r(C7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Wu.VALID_SQL_OPS_ENUM.SELECT:s=R7,n=t.ast.statements[0];break;case Wu.VALID_SQL_OPS_ENUM.INSERT:s=M7;break;case Wu.VALID_SQL_OPS_ENUM.UPDATE:s=O7;break;case Wu.VALID_SQL_OPS_ENUM.DELETE:s=b7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(av,"processAST");function U7(e,t){hf.info(e),t("unknown sql statement")}a(U7,"nullFunction");function M7({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=P7(i,e.values)}catch(o){return r(o)}g7(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){hf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(M7,"convertInsert");function P7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=Ri.compile(`SELECT ${n.toString()} AS [${Wu.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw hf.error(r),new Error(D7)}}a(P7,"createDataObjects")});var fg=T((Hhe,lv)=>{"use strict";var{S3:v7,GetObjectCommand:B7}=require("@aws-sdk/client-s3");lv.exports={getFileStreamFromS3:H7,getS3AuthObj:uv};async function H7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await uv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new B7(r))).Body}a(H7,"getFileStreamFromS3");function uv(e,t,r){return new v7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(uv,"getS3AuthObj")});var pf=T((qhe,Tv)=>{"use strict";var hg=es(),x7=mf(),q7=fg(),{AsyncParser:F7,Transform:G7}=require("json2csv"),zu=require("stream"),kr=J(),Eg=require("fs-extra"),k7=require("path"),ls=V(),{promisify:fv}=require("util"),Qu=J(),{handleHDBError:pt,hdb_errors:V7}=re(),{HDB_ERROR_MSGS:Tr,HTTP_STATUS_CODES:St}=V7,{streamAsJSON:$7}=(Mh(),se(ub)),{Upload:Y7}=require("@aws-sdk/lib-storage"),_v=["search_by_value","search_by_hash","sql","search_by_conditions"],dv=["json","csv"],Ev="json",hv="csv",K7="Successfully exported JSON locally.",W7="Successfully exported CSV locally.",Q7=1e3,z7=hg.searchByHash,J7=hg.searchByValue,j7=fv(x7.evaluateSQL),X7=fv(zu.finished);Tv.exports={export_to_s3:ree,export_local:Z7,toCsvStream:mv};async function Z7(e){ls.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=pv(e);if(!kr.isEmpty(t))throw ls.error(t),pt(new Error,t,St.BAD_REQUEST,void 0,void 0,!0);if(kr.isEmpty(e.path))throw ls.error(Tr.MISSING_VALUE("path")),pt(new Error,Tr.MISSING_VALUE("path"),St.BAD_REQUEST,void 0,void 0,!0);let r=(kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(k7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=kr.buildFolderPath(e.path,r);await eee(e.path);let n=await Sv(e);return await tee(s,e.format,n)}a(Z7,"export_local");async function eee(e){if(ls.trace("in confirmPath"),kr.isEmptyOrZeroLength(e))throw pt(new Error,`Invalid path: ${e}`,St.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Eg.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,ls.error(s),pt(new Error,s,St.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw ls.error(r),pt(new Error,r,St.BAD_REQUEST,void 0,void 0,!0)}return!0}a(eee,"confirmPath");async function tee(e,t,r){if(ls.trace("in saveToLocal"),Qu.isEmptyOrZeroLength(e))throw pt(new Error,Tr.INVALID_VALUE("file_path"),St.BAD_REQUEST,void 0,void 0,!0);if(Qu.isEmptyOrZeroLength(t))throw pt(new Error,Tr.INVALID_VALUE("Source format"),St.BAD_REQUEST,void 0,void 0,!0);if(Qu.isEmpty(r))throw pt(new Error,Tr.NOT_FOUND("Data"),St.BAD_REQUEST,void 0,void 0,!0);if(t===Ev){let s=Eg.createWriteStream(e);return $7(r).pipe(s),await X7(s),{message:K7,path:e}}else if(t===hv){let s=Eg.createWriteStream(e),n=zu.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new F7(i,c).fromInput(n).toOutput(s).promise(!1),{message:W7,path:e}}throw pt(new Error,Tr.INVALID_VALUE("format"),St.BAD_REQUEST)}a(tee,"saveToLocal");async function ree(e){if(!e.s3||Object.keys(e.s3).length===0)throw pt(new Error,Tr.MISSING_VALUE("S3 object"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw pt(new Error,Tr.MISSING_VALUE("aws_access_key_id"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw pt(new Error,Tr.MISSING_VALUE("aws_secret_access_key"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.bucket))throw pt(new Error,Tr.MISSING_VALUE("bucket"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.key))throw pt(new Error,Tr.MISSING_VALUE("key"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.region))throw pt(new Error,Tr.MISSING_VALUE("region"),St.BAD_REQUEST);let t=pv(e);if(!kr.isEmpty(t))throw pt(new Error,t,St.BAD_REQUEST);ls.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await Sv(e)}catch(u){throw ls.error(u),u}let s,n=await q7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new zu.PassThrough;if(e.format===hv){i=e.s3.key+".csv";let u=mv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===Ev){i=e.s3.key+".json";let u=new zu.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%Q7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw pt(new Error,Tr.INVALID_VALUE("format"),St.BAD_REQUEST);return new Y7({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(ree,"export_to_s3");function mv(e,t){let r=zu.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),s={};t&&(s.fields=t.map(o=>({label:o,value:o})));let n={objectMode:!0},i=new G7(s,n);return r.pipe(i)}a(mv,"toCsvStream");function pv(e){if(ls.trace("in exportCoreValidation"),kr.isEmpty(e.format))return"format missing";if(dv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${dv.join(", ")}`;let t=e.search_operation.operation;if(kr.isEmpty(t))return"search_operation.operation missing";if(_v.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${_v.join(", ")}`}a(pv,"exportCoreValidation");async function Sv(e){ls.trace("in getRecords");let t,r;if(Qu.isEmpty(e.search_operation)||Qu.isEmptyOrZeroLength(e.search_operation.operation))throw pt(new Error,Tr.INVALID_VALUE("Search operation"),St.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=J7;break;case"search_by_hash":t=z7;break;case"search_by_conditions":t=hg.searchByConditions;break;case"sql":t=j7;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,ls.error(r),pt(new Error,r,St.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(Sv,"getRecords")});var wv={};Ye(wv,{contentTypes:()=>gg,findBestSerializer:()=>Tf,getDeserializer:()=>So,registerContentHandlers:()=>Rg,serialize:()=>gf,serializeMessage:()=>Ti});function see(e){try{return e?.[0]===123?Tg(e):e}catch{return e}}function Rg(e){e.register(iee,{serializers:[{regex:/^application\/json$/,serializer:mc},{regex:/^application\/cbor$/,serializer:function(t){return new po.EncoderStream(ju).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Sf.Readable.from((0,on.encodeIter)(t,ju)):(0,on.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,mg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,on.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,po.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function Tf(e){let r=(e.headers.asObject||e.headers).accept,s,n=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=vt.get(_);if(E){let h=(E.q||1)*d;h>n&&(s=E,i=E.type||_,n=h,o=f)}}if(!s){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(vt.keys()).join(", "))}};s=vt.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function gf(e,t,r){let s=Rv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),n=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=Tf(t);if(i.serializer.compressible===!1&&(s=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Un.createBrotliCompress)({params:{[Un.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Un.constants.BROTLI_MODE_TEXT:Un.constants.BROTLI_MODE_GENERIC,[Un.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e,r)}return s&&n?.length>Rv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Un.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ti(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Ju(e);let r=t.serialize;if(r)return r(e);let s=Tf(t);return r=t.serialize=s.serializer.serialize,r(e)}function oee(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function So(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=vt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=vt.get(e)?.deserialize||Av(e,s);return o=>oee(o).then(i)}return e&&vt.get(e)?.deserialize||Av(e,s)}function Av(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Tg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function aee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var mg,on,po,Un,Sf,Ov,pg,Sg,bv,Nv,Ju,Tg,ju,vt,gg,gv,yv,nee,iee,Rv,ga=Re(()=>{Mh();mg=x(pf()),on=require("msgpackr"),po=require("cbor-x"),Un=require("zlib"),Sf=require("stream");rr();Ov=require("../index"),pg=x(Z()),Sg=x(L()),bv=x(require("yaml")),Nv=pg.default.get(Sg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Ju=Nv?Pi:JSON.stringify,Tg=Nv?Uh:JSON.parse,ju={useRecords:!1,useToJSON:!0},vt=new Map,gg=vt;tt.contentTypes=gg;(0,Ov._assignPackageExport)("contentTypes",gg);vt.set("application/json",{serializeStream:mc,serialize:Ju,deserialize:Tg,q:.8});gv=new po.Encoder(ju);vt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new po.EncoderStream(ju).end(e)},serialize:gv.encode,deserialize:gv.decode,q:1});vt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Sf.Readable.from((0,on.encodeIter)(e,ju)):(0,on.pack)(e)},serialize:on.pack,deserialize:on.unpack,q:.9});vt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,mg.toCsvStream)(e,e?.getColumns?.())},q:.1});vt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});vt.set("text/yaml",{serialize(e){return bv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});vt.set("text/event-stream",{serializeStream:function(e){return Sf.Readable.from(aee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
18
|
-
`),e.data){let r=e.data;typeof r=="object"&&(r=
|
|
15
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=TP(f.stderr):i[u].npm_error=f.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return Na.info(`finished installModules with response ${i}`),i}a(S9,"installModules");function TP(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
|
|
16
|
+
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(TP,"parseNPMStdErr");async function T9(e){Na.info(`starting auditModules for request: ${e}`);let t=RP(e);if(t)throw Oa(t,t.message,ba.BAD_REQUEST);let{projects:r}=e;await sf(),await gP(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=nf.join(QT,o);n[o]={npm_output:null,npm_error:null};try{let u=await Yu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=TP(u.stderr)}}return Na.info(`finished auditModules with response ${n}`),n}a(T9,"auditModules");async function sf(){try{return await Yu("npm -v"),!0}catch{throw Oa(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",ba.BAD_REQUEST,void 0,void 0,!0)}}a(sf,"checkNPMInstalled");async function gP(e){if(!Array.isArray(e)||e.length===0)throw Oa(new Error,"projects argument must be an array with at least 1 element",ba.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=nf.join(QT,i.toString());if(!await mP.pathExists(o)){t.push(i);continue}let u=nf.join(o,"package.json");await mP.pathExists(u)||r.push(i)}if(t.length>0)throw Oa(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,ba.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Oa(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,ba.BAD_REQUEST,void 0,void 0,!0)}a(gP,"checkProjectPaths");function RP(e){let t=rf.object({projects:rf.array().min(1).items(rf.string()).required(),dry_run:rf.boolean().default(!1)});return f9.validateBySchema(e,t)}a(RP,"modulesValidator")});var JT=T((Ahe,wP)=>{"use strict";var ya=require("fs-extra"),zT=require("path"),af=$(),OP=J(),cf=U(),yP=Z(),g9=Lr();wP.exports=R9;async function R9(){let e=A9(),t=yP.get(cf.CONFIG_PARAMS.ROOTPATH),r=zT.join(t,"package.json"),n={dependencies:{harperdb:"file:"+cf.PACKAGE_ROOT}},s=zT.join(t,"node_modules");await ya.ensureDir(s);let i,o=!0,c=!1;try{i=await ya.readJson(r)}catch(u){if(OP.isEmptyOrZeroLength(e))return;if(u.code!==cf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!OP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await bP(_);n.dependencies[u]=l+_}if(!o){af.notify("Installing components"),await NP(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await bP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(af.notify("Removing component",u),c=!0);c&&(af.notify("Updating components."),await NP(r,n,i))}a(R9,"installComponents");function A9(){let e=g9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(A9,"getComponentsConfig");async function bP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":zT.extname(e)||await ya.pathExists(e)?"file:":"github:"}a(bP,"getPkgPrefix");async function NP(e,t,r){af.trace("npm installing components package.json",t),await ya.writeFile(e,JSON.stringify(t,null," "));try{await of().installAllRootModules(yP.get(cf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await ya.writeFile(e,JSON.stringify(r,null," ")):await ya.unlink(e),n}}a(NP,"installPackages")});var ZT=T((Nhe,UP)=>{"use strict";var ke=require("fs-extra"),jT=require("fast-glob"),pe=require("path"),CP=require("tar-fs"),bhe=require("uuid").v4,XT=require("normalize-path"),ss=hP(),yt=$(),ze=U(),pt=Z(),Ku=Lr(),O9=J(),{PACKAGE_ROOT:b9}=U(),{handleHDBError:Mt,hdb_errors:N9}=re(),{basename:y9}=require("path"),w9=JT(),DP=Z(),I9=U(),{Readable:C9}=require("stream"),{isMainThread:D9}=require("worker_threads"),{HDB_ERROR_MSGS:mo,HTTP_STATUS_CODES:Pt}=N9,U9=pe.join(b9,"application-template"),IP=pe.join(pt.get(ze.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function L9(){yt.trace("getting custom api status");let e={};try{e={port:pt.get(ze.CONFIG_PARAMS.HTTP_PORT),directory:pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Mt(new Error,mo.FUNCTION_STATUS,Pt.INTERNAL_SERVER_ERROR,yt.ERR,t)}return e}a(L9,"customFunctionsStatus");function M9(){yt.trace("getting custom api endpoints");let e={},t=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT);try{jT.sync(XT(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:jT.sync(XT(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:jT.sync(XT(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Mt(new Error,mo.GET_FUNCTIONS,Pt.INTERNAL_SERVER_ERROR,yt.ERR,r)}return e}a(M9,"getCustomFunctions");function P9(e){e.project&&(e.project=pe.parse(e.project).name),e.file&&(e.file=pe.parse(e.file).name);let t=ss.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);yt.trace("getting custom api endpoint file content");let r=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=pe.join(r,n,s,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Mt(new Error,mo.GET_FUNCTION,Pt.INTERNAL_SERVER_ERROR,yt.ERR,c)}}a(P9,"getCustomFunction");function v9(e){e.project&&(e.project=pe.parse(e.project).name),e.file&&(e.file=pe.parse(e.file).name);let t=ss.setCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);yt.trace("setting custom function file content");let r=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return ke.outputFileSync(pe.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Mt(new Error,mo.SET_FUNCTION,Pt.INTERNAL_SERVER_ERROR,yt.ERR,c)}}a(v9,"setCustomFunction");function B9(e){e.project&&(e.project=pe.parse(e.project).name),e.file&&(e.file=pe.parse(e.file).name);let t=ss.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);yt.trace("dropping custom function file");let r=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return ke.unlinkSync(pe.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Mt(new Error,mo.DROP_FUNCTION,Pt.INTERNAL_SERVER_ERROR,yt.ERR,o)}}a(B9,"dropCustomFunction");function H9(e){e.project&&(e.project=pe.parse(e.project).name);let t=ss.addComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);yt.trace("adding component");let r=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=pe.join(r,n);return ke.mkdirSync(s,{recursive:!0}),ke.copySync(U9,s),`Successfully added project: ${n}`}catch(s){throw Mt(new Error,mo.ADD_FUNCTION,Pt.INTERNAL_SERVER_ERROR,yt.ERR,s)}}a(H9,"addComponent");function x9(e){e.project&&(e.project=pe.parse(e.project).name);let t=ss.dropCustomFunctionProjectValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);yt.trace("dropping custom function project");let r=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=pt.get(ze.CONFIG_PARAMS.APPS);if(!O9.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return Ku.updateConfigValue(ze.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=pe.join(r,n);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Mt(new Error,mo.DROP_FUNCTION_PROJECT,Pt.INTERNAL_SERVER_ERROR,yt.ERR,i)}}a(x9,"dropCustomFunctionProject");async function q9(e){e.project&&(e.project=pe.parse(e.project).name);let t=ss.packageComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;yt.trace("packaging component",n);let s;try{s=await ke.realpath(pe.join(r,n))}catch(u){if(u.code!==ze.NODE_ERROR_CODES.ENOENT)throw u;try{s=await ke.realpath(pe.join(pt.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===ze.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await ke.ensureDir(IP);let i=pe.join(IP,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(pe.join(s,"node_modules"))}),CP.pack(s,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:n,payload:c}}a(q9,"packageComponent");async function F9(e){e.project&&(e.project=pe.parse(e.project).name);let t=ss.deployComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(yt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=pe.join(r,n),i="file:"+o,await ke.ensureDir(o);let f=C9.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{f.pipe(CP.extract(o,{finish:h})).on("error",p)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(pe.join(o,"package"),o),await ke.remove(pe.join(o,"package")))}if(await Ku.addConfig(n,{package:i}),!s){await w9();let f=DP.get(I9.CONFIG_PARAMS.ROOTPATH);o=pe.join(f,"node_modules",n)}if(D9)return;let c=new Map;c.isWorker=!0;let u=(lf(),ne(uf)),_;u.setErrorReporter(f=>_=f);let l=y9(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return yt.info("Installed component"),`Successfully deployed: ${n}`}a(F9,"deployComponent");async function G9(){let e=Ku.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await ke.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=pe.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await ke.stat(d),E={name:pe.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return yt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{name:pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT).split(pe.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(pe.join(pt.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(lf(),ne(uf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(G9,"getComponents");async function k9(e){let t=ss.getComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let n=Ku.getConfigObj()[e.project]||e.project==="harperdb"?pe.join(DP.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules"):pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(pe.join(n,e.project,e.file));return{message:await ke.readFile(pe.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===ze.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${pe.join(e.project,e.file)}'`):i}}a(k9,"getComponentFile");async function V9(e){let t=ss.setComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=pe.join(pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(n),await ke.outputFile(n,e.payload,r)):await ke.ensureDir(n),"Successfully set component: "+e.file}a(V9,"setComponentFile");async function $9(e){let t=ss.dropComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=e.file?pe.join(e.project,e.file):e.project,n=pe.join(pt.get(ze.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(n)&&await ke.remove(n),Ku.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a($9,"dropComponent");UP.exports={customFunctionsStatus:L9,getCustomFunctions:M9,getCustomFunction:P9,setCustomFunction:v9,dropCustomFunction:B9,addComponent:H9,dropCustomFunctionProject:x9,packageComponent:q9,deployComponent:F9,getComponents:G9,getComponentFile:k9,setComponentFile:V9,dropComponent:$9}});var eg=T((whe,MP)=>{"use strict";var is=require("joi"),LP=Xe();MP.exports={readTransactionLogValidator:Y9,deleteTransactionLogsBeforeValidator:K9};function Y9(e){let t=is.object({schema:is.string().required(),table:is.string().required(),from:is.date().timestamp(),to:is.date().timestamp(),limit:is.number().min(1)});return LP.validateBySchema(e,t)}a(Y9,"readTransactionLogValidator");function K9(e){let t=is.object({schema:is.string().required(),table:is.string().required(),timestamp:is.date().timestamp().required()});return LP.validateBySchema(e,t)}a(K9,"deleteTransactionLogsBeforeValidator")});var df=T((Che,xP)=>{"use strict";var tg=U(),_f=st(),PP=J(),vP=Z(),BP=Ts(),{handleHDBError:wa,hdb_errors:W9}=re(),{HTTP_STATUS_CODES:Ia}=W9,{readTransactionLogValidator:Q9,deleteTransactionLogsBeforeValidator:z9}=eg(),HP="This operation relies on clustering and cannot run with it disable.",J9="Logs successfully deleted from transaction log.",j9="All logs successfully deleted from transaction log.";xP.exports={readTransactionLog:X9,deleteTransactionLogsBefore:Z9};async function*X9(e){let t=Q9(e);if(t)throw wa(t,t.message,Ia.BAD_REQUEST,void 0,void 0,!0);if(!vP.get(tg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw wa(new Error,HP,Ia.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=PP.checkSchemaTableExist(r,n);if(s)throw wa(new Error,s,Ia.NOT_FOUND,void 0,void 0,!0);let i=BP.createNatsTableStreamName(r,n),o=await _f.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===tg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(X9,"readTransactionLog");async function Z9(e){let t=z9(e);if(t)throw wa(t,t.message,Ia.BAD_REQUEST,void 0,void 0,!0);if(!vP.get(tg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw wa(new Error,HP,Ia.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=PP.checkSchemaTableExist(r,n);if(i)throw wa(new Error,i,Ia.NOT_FOUND,void 0,void 0,!0);let o=BP.createNatsTableStreamName(r,n),{jsm:c}=await _f.getNATSReferences(),u=await _f.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=J9,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=j9):d=(await _f.viewStream(o,parseInt(s),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(Z9,"deleteTransactionLogsBefore")});var FP=T((Uhe,qP)=>{"use strict";var rg=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}};qP.exports=rg});var kP=T((Mhe,GP)=>{"use strict";var ng=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};GP.exports=ng});var ig=T((vhe,$P)=>{"use strict";var VP=FP(),e7=kP(),{HDB_ERROR_MSGS:t7}=Nr(),sg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=t7.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 VP(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new e7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new VP(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}};$P.exports=sg});var mf=T((Hhe,ov)=>{"use strict";var og=Cr(),ff=en(),ln=Eu(),zu=Zs(),ag=ri(),r7=TS(),n7=tU(),Ju=tn(),Ef=IS(),wt=$(),s7=US(),i7=Dd(),o7=dT(),a7=Ld(),c7=fT(),u7=ET(),l7=pT(),_7=TT(),cg=AT(),Us=J(),d7=XL(),ug=wT(),WP=zd(),un=U(),QP=XM(),f7=Ea(),zP=gu(),JP=(ef(),ne(Gu)),jP=Lr(),Gr=ZT(),E7=require("alasql"),XP=df(),ZP=of(),ev=ig(),{handleHDBError:Sr,hdb_errors:tv}=re(),{HDB_ERROR_MSGS:kt,HTTP_STATUS_CODES:Wu}=tv,k=new Map,rv="delete",Ri="insert",Ls="read",po="update",Qu="describe",YP=zu.describeSchema.name,KP=zu.describeTable.name,nv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},h7="catchup",m7="handleGetJob",p7="handleGetJobsByStartDate",hf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},S7=[ln.createTable.name,ln.createAttribute.name,ln.dropTable.name,ln.dropAttribute.name],sv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},z=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};k.set(og.insert.name,new z(!1,[Ri]));k.set(og.update.name,new z(!1,[po]));k.set(og.upsert.name,new z(!1,[Ri,po]));k.set(ff.searchByConditions.name,new z(!1,[Ls]));k.set(ff.searchByHash.name,new z(!1,[Ls]));k.set(ff.searchByValue.name,new z(!1,[Ls]));k.set(ff.search.name,new z(!1,[Ls]));k.set(ln.createSchema.name,new z(!0,[]));k.set(ln.createTable.name,new z(!0,[]));k.set(ln.createAttribute.name,new z(!1,[Ri]));k.set(ln.dropSchema.name,new z(!0,[]));k.set(ln.dropTable.name,new z(!0,[]));k.set(ln.dropAttribute.name,new z(!0,[]));k.set(zu.describeSchema.name,new z(!1,[Ls]));k.set(zu.describeTable.name,new z(!1,[Ls]));k.set(ag.deleteRecord.name,new z(!1,[rv]));k.set(Ju.addUser.name,new z(!0,[]));k.set(Ju.alterUser.name,new z(!0,[]));k.set(Ju.dropUser.name,new z(!0,[]));k.set(Ju.listUsersExternal.name,new z(!0,[]));k.set(Ef.listRoles.name,new z(!0,[]));k.set(Ef.addRole.name,new z(!0,[]));k.set(Ef.alterRole.name,new z(!0,[]));k.set(Ef.dropRole.name,new z(!0,[]));k.set(s7.name,new z(!0,[]));k.set(i7.name,new z(!0,[]));k.set(o7.name,new z(!0,[]));k.set(a7.name,new z(!0,[]));k.set(c7.name,new z(!0,[]));k.set(u7.name,new z(!0,[]));k.set(cg.setRoutes.name,new z(!0,[]));k.set(cg.getRoutes.name,new z(!0,[]));k.set(cg.deleteRoutes.name,new z(!0,[]));k.set(jP.setConfiguration.name,new z(!0,[]));k.set(l7.clusterStatus.name,new z(!0,[]));k.set(_7.name,new z(!0,[]));k.set(ug.getFingerprint.name,new z(!0,[]));k.set(ug.setLicense.name,new z(!0,[]));k.set(ag.deleteFilesBefore.name,new z(!0,[]));k.set(ag.deleteAuditLogsBefore.name,new z(!0,[]));k.set(WP.restart.name,new z(!0,[]));k.set(WP.restartService.name,new z(!0,[]));k.set(r7.name,new z(!0,[]));k.set(n7.name,new z(!0,[Ls]));k.set(f7.systemInformation.name,new z(!0,[]));k.set(jP.getConfiguration.name,new z(!0,[]));k.set(XP.readTransactionLog.name,new z(!0,[]));k.set(XP.deleteTransactionLogsBefore.name,new z(!0,[]));k.set(ZP.installModules.name,new z(!0,[]));k.set(ZP.auditModules.name,new z(!0,[]));k.set(zP.createTokens.name,new z(!1,[]));k.set(zP.refreshOperationToken.name,new z(!1,[]));k.set(JP.login.name,new z(!1,[]));k.set(JP.logout.name,new z(!1,[]));k.set(Gr.customFunctionsStatus.name,new z(!0,[]));k.set(Gr.getCustomFunctions.name,new z(!0,[]));k.set(Gr.getComponents.name,new z(!0,[]));k.set(Gr.getComponentFile.name,new z(!0,[]));k.set(Gr.setComponentFile.name,new z(!0,[]));k.set(Gr.dropComponent.name,new z(!0,[]));k.set(Gr.getCustomFunction.name,new z(!0,[]));k.set(Gr.setCustomFunction.name,new z(!0,[]));k.set(Gr.dropCustomFunction.name,new z(!0,[]));k.set(Gr.addComponent.name,new z(!0,[]));k.set(Gr.dropCustomFunctionProject.name,new z(!0,[]));k.set(Gr.packageComponent.name,new z(!0,[]));k.set(Gr.deployComponent.name,new z(!0,[]));k.set(ug.getRegistrationInfo.name,new z(!1,[]));k.set(Ju.userInfo.name,new z(!1,[]));k.set(zu.describeAll.name,new z(!1,[]));k.set(m7,new z(!1,[]));k.set(p7,new z(!0,[]));k.set(h7,new z(!0,[]));k.set(hf.CSV_DATA_LOAD,new z(!1,[Ri,po]));k.set(hf.CSV_URL_LOAD,new z(!1,[Ri,po]));k.set(hf.CSV_FILE_LOAD,new z(!1,[Ri,po]));k.set(hf.IMPORT_FROM_S3,new z(!1,[Ri,po]));k.set(sv.EXPORT_TO_S3,new z(!0,[]));k.set(sv.EXPORT_LOCAL,new z(!0,[]));k.set(un.VALID_SQL_OPS_ENUM.DELETE,new z(!1,[rv]));k.set(un.VALID_SQL_OPS_ENUM.SELECT,new z(!1,[Ls]));k.set(un.VALID_SQL_OPS_ENUM.INSERT,new z(!1,[Ri]));k.set(un.VALID_SQL_OPS_ENUM.UPDATE,new z(!1,[po]));ov.exports={verifyPerms:g7,verifyPermsAst:T7,verifyBulkLoadAttributePerms:A7};function T7(e,t,r){if(Us.isEmptyOrZeroLength(e))throw wt.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Us.isEmptyOrZeroLength(t))throw wt.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Us.isEmptyOrZeroLength(r))throw wt.info("verify_perms_ast has a null operation parameter"),Sr(new Error);try{let n=new ev,s=new d7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw wt.info("No schemas defined in verifyPermsAst(), will not continue."),Sr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&nv[r])throw Sr(new Error,kt.DROP_SYSTEM,Wu.FORBIDDEN);if(c&&!u)return null;let _=QP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof E7.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=iv(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),p=_g(t.role.permission,f,d[E]);lg(h,p,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Sr(n)}}a(T7,"verifyPermsAst");function g7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw wt.info("null required parameter in verifyPerms"),Sr(new Error,kt.DEFAULT_INVALID_REQUEST,Wu.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new ev;if(Us.isEmptyOrZeroLength(e.hdb_user.role)||Us.isEmptyOrZeroLength(e.hdb_user.role.permission))return wt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(kt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(un.SYSTEM_SCHEMA_NAME)||s===un.SYSTEM_SCHEMA_NAME;if(l&&nv[r])throw Sr(new Error,kt.DROP_SYSTEM,Wu.FORBIDDEN);if(u&&!l||_===!0&&(r===ln.createSchema.name||r===ln.dropSchema.name))return null;if(S7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=QP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===YP||r===KP){if(s===un.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(kt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===YP&&(!d[s]||!d[s][Qu]))return c.handleInvalidItem(kt.SCHEMA_NOT_FOUND(s));if(r===KP&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][Qu]))return c.handleInvalidItem(kt.TABLE_NOT_FOUND(s,i))}}let f=iv(e.hdb_user,r,o,c,n);if(f)return f;if(k.get(r)&&k.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&un.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[un.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[un.PERMS_CRUD_ENUM.READ]).forEach(A=>{p.push(A.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(g=>g.attribute),e.get_attributes=p)}let E=R7(e),h=_g(e.hdb_user.role.permission,s,i);return lg(E,h,r,i,s,c,n),c.getPermsResponse()}a(g7,"verifyPerms");function iv(e,t,r,n,s){if(Us.arrayHasEmptyValues([e,t,r]))throw wt.info("hasPermissions has an invalid parameter"),Sr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||k.get(t).requires_su))return null;if(!k.get(t))throw wt.info(`operation ${t} not found.`),Sr(new Error,kt.OP_NOT_FOUND(t),Wu.BAD_REQUEST);if(k.get(t)&&k.get(t).requires_su)return wt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(kt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Qu]===!1){n.addInvalidItem(kt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(kt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[Qu]===!1)n.addInvalidItem(kt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=k.get(t).perms;!Us.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(wt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=kt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw wt.error(E),wt.error(f),Sr(tv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(iv,"hasPermissions");function lg(e,t,r,n,s,i,o){if(!e||!t)throw wt.info("no attributes specified in checkAttributePerms."),Sr(new Error);let c=k.get(r).perms;if(!c||c==="")throw wt.info(`no permissions found for ${r} in checkAttributePerms().`),Sr(new Error);if(Us.isEmptyOrZeroLength(t))return wt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[Qu]===!1){i.addInvalidItem(kt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(un.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Ls)throw Sr(new Error,kt.SYSTEM_TIMESTAMP_PERMS_ERR,Wu.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(kt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(lg,"checkAttributePerms");function R7(e){let t=new Set;try{if(e.action)return t;if(e.operation===un.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){wt.info(r)}return t}a(R7,"getRecordAttributes");function _g(e,t,r){let n=new Map;if(Us.isEmpty(e))return wt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{wt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(_g,"getAttributePermissions");function A7(e,t,r,n,s,i,o){let c=new Set(i),u=_g(e,n,s);lg(c,u,t,s,n,o,r)}a(A7,"verifyBulkLoadAttributePerms")});var Sf=T((qhe,_v)=>{"use strict";_v.exports={evaluateSQL:v7,processAST:lv,convertSQLToAST:uv,checkASTPermissions:cv};var O7=Cr(),av=require("util"),b7=av.callbackify(O7.insert),N7=en().search,y7=QC().update,w7=av.callbackify(y7),I7=JC().convertDelete,Ai=require("alasql"),C7=mf(),pf=$(),D7=ed(),U7=J(),ju=U(),{hdb_errors:L7,handleHDBError:dg}=re(),{HTTP_STATUS_CODES:fg}=L7;D7(Ai);var M7=403,P7="There was a problem performing this insert. Please check the logs and try again.",Eg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function v7(e,t){let r=e.parsed_sql_object;if(!r){r=uv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ai.yy.Insert?n=s.into.databaseid:s instanceof Ai.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ai.yy.Update||s instanceof Ai.yy.Delete?n=s.table.databaseid:pf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ai.yy.Select)&&U7.isEmptyOrZeroLength(n))return t("No schema specified",null)}lv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(v7,"evaluateSQL");function cv(e,t){let r;try{r=C7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(cv,"checkASTPermissions");function uv(e){let t=new Eg;if(!e)throw dg(new Error,"The 'sql' parameter is missing from the request body",fg.BAD_REQUEST);try{let r=e.trim(),n=Ai.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
17
|
+
`);throw n[1]?dg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,fg.BAD_REQUEST):dg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",fg.BAD_REQUEST)}return t}a(uv,"convertSQLToAST");function lv(e,t,r){try{let n=B7;if(!e.bypass_auth&&!t.permissions_checked){let i=cv(e,t);if(i&&i.length>0)return r(M7,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ju.VALID_SQL_OPS_ENUM.SELECT:n=N7,s=t.ast.statements[0];break;case ju.VALID_SQL_OPS_ENUM.INSERT:n=H7;break;case ju.VALID_SQL_OPS_ENUM.UPDATE:n=w7;break;case ju.VALID_SQL_OPS_ENUM.DELETE:n=I7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(lv,"processAST");function B7(e,t){pf.info(e),t("unknown sql statement")}a(B7,"nullFunction");function H7({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=x7(i,e.values)}catch(o){return r(o)}b7(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){pf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(H7,"convertInsert");function x7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ai.compile(`SELECT ${s.toString()} AS [${ju.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw pf.error(r),new Error(P7)}}a(x7,"createDataObjects")});var hg=T((Ghe,fv)=>{"use strict";var{S3:q7,GetObjectCommand:F7}=require("@aws-sdk/client-s3");fv.exports={getFileStreamFromS3:G7,getS3AuthObj:dv};async function G7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await dv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new F7(r))).Body}a(G7,"getFileStreamFromS3");function dv(e,t,r){return new q7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(dv,"getS3AuthObj")});var Tf=T((Vhe,Av)=>{"use strict";var pg=en(),k7=Sf(),V7=hg(),{AsyncParser:$7,Transform:Y7}=require("json2csv"),Zu=require("stream"),kr=J(),mg=require("fs-extra"),K7=require("path"),_n=$(),{promisify:mv}=require("util"),Xu=J(),{handleHDBError:St,hdb_errors:W7}=re(),{HDB_ERROR_MSGS:Tr,HTTP_STATUS_CODES:Tt}=W7,{streamAsJSON:Q7}=(vh(),ne(_b)),{Upload:z7}=require("@aws-sdk/lib-storage"),Ev=["search_by_value","search_by_hash","sql","search_by_conditions"],hv=["json","csv"],pv="json",Sv="csv",J7="Successfully exported JSON locally.",j7="Successfully exported CSV locally.",X7=1e3,Z7=pg.searchByHash,eee=pg.searchByValue,tee=mv(k7.evaluateSQL),ree=mv(Zu.finished);Av.exports={export_to_s3:oee,export_local:nee,toCsvStream:Tv};async function nee(e){_n.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=gv(e);if(!kr.isEmpty(t))throw _n.error(t),St(new Error,t,Tt.BAD_REQUEST,void 0,void 0,!0);if(kr.isEmpty(e.path))throw _n.error(Tr.MISSING_VALUE("path")),St(new Error,Tr.MISSING_VALUE("path"),Tt.BAD_REQUEST,void 0,void 0,!0);let r=(kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(K7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=kr.buildFolderPath(e.path,r);await see(e.path);let s=await Rv(e);return await iee(n,e.format,s)}a(nee,"export_local");async function see(e){if(_n.trace("in confirmPath"),kr.isEmptyOrZeroLength(e))throw St(new Error,`Invalid path: ${e}`,Tt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await mg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,_n.error(n),St(new Error,n,Tt.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw _n.error(r),St(new Error,r,Tt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(see,"confirmPath");async function iee(e,t,r){if(_n.trace("in saveToLocal"),Xu.isEmptyOrZeroLength(e))throw St(new Error,Tr.INVALID_VALUE("file_path"),Tt.BAD_REQUEST,void 0,void 0,!0);if(Xu.isEmptyOrZeroLength(t))throw St(new Error,Tr.INVALID_VALUE("Source format"),Tt.BAD_REQUEST,void 0,void 0,!0);if(Xu.isEmpty(r))throw St(new Error,Tr.NOT_FOUND("Data"),Tt.BAD_REQUEST,void 0,void 0,!0);if(t===pv){let n=mg.createWriteStream(e);return Q7(r).pipe(n),await ree(n),{message:J7,path:e}}else if(t===Sv){let n=mg.createWriteStream(e),s=Zu.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new $7(i,c).fromInput(s).toOutput(n).promise(!1),{message:j7,path:e}}throw St(new Error,Tr.INVALID_VALUE("format"),Tt.BAD_REQUEST)}a(iee,"saveToLocal");async function oee(e){if(!e.s3||Object.keys(e.s3).length===0)throw St(new Error,Tr.MISSING_VALUE("S3 object"),Tt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw St(new Error,Tr.MISSING_VALUE("aws_access_key_id"),Tt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw St(new Error,Tr.MISSING_VALUE("aws_secret_access_key"),Tt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.bucket))throw St(new Error,Tr.MISSING_VALUE("bucket"),Tt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.key))throw St(new Error,Tr.MISSING_VALUE("key"),Tt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.region))throw St(new Error,Tr.MISSING_VALUE("region"),Tt.BAD_REQUEST);let t=gv(e);if(!kr.isEmpty(t))throw St(new Error,t,Tt.BAD_REQUEST);_n.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await Rv(e)}catch(u){throw _n.error(u),u}let n,s=await V7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Zu.PassThrough;if(e.format===Sv){i=e.s3.key+".csv";let u=Tv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===pv){i=e.s3.key+".json";let u=new Zu.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%X7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw St(new Error,Tr.INVALID_VALUE("format"),Tt.BAD_REQUEST);return new z7({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(oee,"export_to_s3");function Tv(e,t){let r=Zu.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 Y7(n,s);return r.pipe(i)}a(Tv,"toCsvStream");function gv(e){if(_n.trace("in exportCoreValidation"),kr.isEmpty(e.format))return"format missing";if(hv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${hv.join(", ")}`;let t=e.search_operation.operation;if(kr.isEmpty(t))return"search_operation.operation missing";if(Ev.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Ev.join(", ")}`}a(gv,"exportCoreValidation");async function Rv(e){_n.trace("in getRecords");let t,r;if(Xu.isEmpty(e.search_operation)||Xu.isEmptyOrZeroLength(e.search_operation.operation))throw St(new Error,Tr.INVALID_VALUE("Search operation"),Tt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=eee;break;case"search_by_hash":t=Z7;break;case"search_by_conditions":t=pg.searchByConditions;break;case"sql":t=tee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,_n.error(r),St(new Error,r,Tt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(Rv,"getRecords")});var Dv={};Ke(Dv,{contentTypes:()=>Ag,findBestSerializer:()=>Rf,getDeserializer:()=>To,registerContentHandlers:()=>Og,serialize:()=>Af,serializeMessage:()=>gi});function aee(e){try{return e?.[0]===123?Rg(e):e}catch{return e}}function Og(e){e.register(uee,{serializers:[{regex:/^application\/json$/,serializer:Sc},{regex:/^application\/cbor$/,serializer:function(t){return new So.EncoderStream(tl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?gf.Readable.from((0,os.encodeIter)(t,tl)):(0,os.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Sg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,os.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,So.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Rf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=vt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(vt.keys()).join(", "))}};n=vt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Af(e,t,r){let n=bv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=Rf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Ms.createBrotliCompress)({params:{[Ms.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Ms.constants.BROTLI_MODE_TEXT:Ms.constants.BROTLI_MODE_GENERIC,[Ms.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>bv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Ms.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function gi(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return el(e);let r=t.serialize;if(r)return r(e);let n=Rf(t);return r=t.serialize=n.serializer.serialize,r(e)}function lee(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 To(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=vt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=vt.get(e)?.deserialize||Nv(e,n);return o=>lee(o).then(i)}return e&&vt.get(e)?.deserialize||Nv(e,n)}function Nv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Rg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function _ee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var Sg,os,So,Ms,gf,yv,Tg,gg,wv,Iv,el,Rg,tl,vt,Ag,Ov,Cv,cee,uee,bv,Aa=ge(()=>{vh();Sg=x(Tf()),os=require("msgpackr"),So=require("cbor-x"),Ms=require("zlib"),gf=require("stream");rr();yv=require("../index"),Tg=x(Z()),gg=x(U()),wv=x(require("yaml")),Iv=Tg.default.get(gg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,el=Iv?vi:JSON.stringify,Rg=Iv?Ph:JSON.parse,tl={useRecords:!1,useToJSON:!0},vt=new Map,Ag=vt;rt.contentTypes=Ag;(0,yv._assignPackageExport)("contentTypes",Ag);vt.set("application/json",{serializeStream:Sc,serialize:el,deserialize:Rg,q:.8});Ov=new So.Encoder(tl);vt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new So.EncoderStream(tl).end(e)},serialize:Ov.encode,deserialize:Ov.decode,q:1});vt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?gf.Readable.from((0,os.encodeIter)(e,tl)):(0,os.pack)(e)},serialize:os.pack,deserialize:os.unpack,q:.9});vt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Sg.toCsvStream)(e,e?.getColumns?.())},q:.1});vt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});vt.set("text/yaml",{serialize(e){return wv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});vt.set("text/event-stream",{serializeStream:function(e){return gf.Readable.from(_ee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
18
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=el(r)),t+="data: "+r+`
|
|
19
19
|
`}return e.id&&(t+="id: "+e.id+`
|
|
20
20
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
21
21
|
`),t+`
|
|
22
|
-
`}else return typeof e=="object"?`data: ${
|
|
22
|
+
`}else return typeof e=="object"?`data: ${el(e)}
|
|
23
23
|
|
|
24
24
|
`:`data: ${e}
|
|
25
25
|
|
|
26
|
-
`},compressible:!1,q:.8});vt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,s]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let n=t[r];Array.isArray(n)?n.push(s):t.key=[n,s]}else t[r]=s},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});yv={type:"application/json",serializeStream:mc,serialize:Ju,deserialize:see,q:.8};vt.set("*/*",yv);vt.set("",yv);a(see,"tryJSONParse");a(Rg,"registerContentHandlers");nee=require("fastify-plugin"),iee=nee(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Tf(s.raw);n.type(c),n.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{n.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Tf,"findBestSerializer");Rv=pg.default.get(Sg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(gf,"serialize");a(Ti,"serializeMessage");a(oee,"streamToBuffer");a(So,"getDeserializer");a(Av,"deserializerUnknownType");a(aee,"transformIterable")});function bg(e,t,r,s,n,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],p=_(h);d=d.concat(p)}let f=new Set;return d.filter(E=>{let h=E.key??E;return f.has(h)?!1:(f.add(h),!0)})}else{let d=_(u),f=l(e.slice(1),!0,u.estimated_count);return f.length>0?o(d,f):d}function _(d){return d.conditions?bg(d.conditions,d.operator,r,s,n,i,o,c):Ca(d,s,d.descending||n.reverse===!0,r,n.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",g=l(h.conditions,!R,E);return R?(P,H)=>g.some(v=>v(P,H)):(P,H)=>g.every(v=>v(P,H))}let S=(h.attribute||h[0])===r.primaryKey,A=yg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=mee(r.primaryStore,h.estimated_count,E)),A}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ca(e,t,r,s,n,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],g=Pn(s.attributes,R);if(g.relationship){if(o.length<2)throw new Vr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let P=g.definition?.tableClass||g.elements?.definition?.tableClass,H=new Map,v=Ca({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,P,n,H);if(g.relationship.to){i[o[0]]=H;let U=!!Pn(P.attributes,g.relationship.to)?.elements;v=dee(v,g,P.primaryStore,U,H)}if(g.relationship.from){let U=a(Y=>Ca({attribute:g.relationship.from,value:Y},t,r,s,n,H),"searchEntry");g.elements?(i[o[0]]=H,v=fee(v,g,P.primaryStore,H,U)):v=v.flatMap(U)}return v}else if(o.length===1)o=o[0];else throw new Vr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Ng[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=an.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"sort":case"contains":case"ends_with":_=!0,E=!0;break;default:throw new Vr.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!f,f=!d,d=R}let h=o===s.primaryKey||o==null,p=h?s.primaryStore:s.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(n===!1&&!p)throw new Vr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(n===!1&&E)throw new Vr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Vr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Vr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=yg(e),!S)throw new Vr.ClientError(`Unknown search operator ${e.comparator}`)}let A={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(A).map(S?function({key:g,value:P}){return this.isSync?P&&S(P)?g:Ai.SKIP:new Promise((H,v)=>setImmediate(()=>{try{H(P&&S(P)?g:Ai.SKIP)}catch(U){v(U)}}))}:g=>g.value==null?Ai.SKIP:g);return R.hasEntries=!0,R}else return p?p.getRange(A).map(S?function({key:R,value:g}){return this.isSync?S({[o]:R})?g:Ai.SKIP:new Promise((P,H)=>setImmediate(()=>{try{P(S({[o]:R})?g:Ai.SKIP)}catch(v){H(v)}}))}:({value:R})=>R):s.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:g}){return this.isSync?g&&S(g)?R:Ai.SKIP:new Promise((P,H)=>setImmediate(()=>{try{P(g&&S(g)?R:Ai.SKIP)}catch(v){H(v)}}))})}function Pn(e,t){if(Array.isArray(t))if(t.length>1){let r=Pn(e,t[0]),s=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return s?Pn(s,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function dee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i;n.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Ps(l),o=!0);let E=n.get(f);E?E.push(d):n.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!n.filters?.some(E=>!E(d)))if(s)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?n:n.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function fee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Ps(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;s.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Ps(d)));for(let l of e){if(s.filters){let d=r.get(l);if(s.filters.some(f=>!f(d)))continue}_.set(Ps(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=n(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function yg(e,t,r,s,n,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Pn(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=s?.[l],h=yg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let p=t.propertyResolvers?.[l],S,A=a((R,g)=>{let P,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let U of h.idFilter.idSet)e={attribute:p.from,value:U};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(R);return S.idFilter&&(A.idFilter=S.idFilter),v}H=p(R,r,g),P=H?.value}else P=R[l];return P?Array.isArray(P)?P.some(h):h(P,H):!1},"recordFilter");return A}}switch(u instanceof Date&&(u=u.getTime()),Ng[o]||o){case Ag.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,an.compareKeys)(l,u[0])>=0&&(0,an.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,an.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,an.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,an.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,an.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,an.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Vr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!n&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&Af(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let p=0,S=3;function A(R){let g=R[l],P;if(typeof g!="object"||!g||E?P=d(g):Array.isArray(g)?P=g.some(d):g instanceof Date&&(P=d(g.getTime())),f&&(S++,!P&&!A.idFilter&&++p/S*(i-S)>h)){let H=Ca(e,r.transaction.getReadTxn(),!1,t).map(Ps),v=new Set(H);A.idFilter=U=>v.has(Ps(U)),A.idFilter.idSet=v}return P}return a(A,"recordFilter"),n&&(A.idFilter=d),A}a(_,"attributeComparator")}function Af(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let n;if(r.operator==="or"){n=0;for(let i of r.conditions)t(i),n+=i.estimated_count}else{n=1/0;for(let i of r.conditions)t(i),n=isFinite(n)?n*i.estimated_count/Mn(e.primaryStore):i.estimated_count}return r.estimated_count=n,r.estimated_count}let s=r.comparator||r.search_type;if(s=Ng[s]||s,s===Ag.SEARCH_TYPES.EQUALS||!s){let n=r[0]??r.attribute;if(n==null||n===e.primaryKey)r.estimated_count=1;else if(Array.isArray(n)&&n.length>1){let i=Pn(e.attributes,n[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Af(o)({value:r.value,attribute:n.length>2?n.slice(1):n[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Mn(e.indices[i.relationship.from])/(Mn(o.primaryStore)||1):c)}else{let i=e.indices[n];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(s==="contains"||s==="ends_with"||s==="ne"){let n=r[0]??r.attribute,i=e.indices[n];r.value===null&&s==="ne"?r.estimated_count=Mn(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else s==="starts_with"||s==="prefix"?r.estimated_count=lee*Mn(e.primaryStore)+1:s==="between"?r.estimated_count=uee*Mn(e.primaryStore)+1:s==="sort"?r.estimated_count=Mn(e.primaryStore)+1:r.estimated_count=cee*Mn(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Of(e){if(e)if(Oi=e,wa.lastIndex=0,Eee.test(e))try{let t=Xu(new Ia,"");if(gr!==Oi.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${gr} in '${Oi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Xu(e,t){let r=wa,s,n,i,o,c,u=decodeURIComponent,_;for(;s=r.exec(Oi);){gr=r.lastIndex;let[,l,d]=s;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(n){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=Iv}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");n=Zu(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=_ee[d],u=Og[i]?Iv:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);n=Zu(l);break;case"|":case"&":case"":case void 0:if(n==null){if(n===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:n,value:u(l)};i==="eq"&&Cv(h,l),Rf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),n=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Zu(l)),n=void 0;break;case"(":wa.lastIndex=gr;let E=Xu(l?[]:new Ia,")");switch(l){case"":Rf(e,_),e.conditions.push(E);break;case"limit":switch(E.length){case 1:e.limit=+E[0];break;case 2:e.offset=+E[0],e.limit=E[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(E[0])&&E.length===1&&!E[0].name?(e.select=E[0],e.select.asArray=!0):E.length===1?e.select=E[0]:E.length===2&&E[1]===""?e.select=E.slice(0,1):e.select=E;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=Dv(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Oi[gr]===","?r.lastIndex=++gr:o=!0,n=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");wa.lastIndex=gr,f=Xu([],"}"),f.name=l,e.push(f),Oi[gr]===","?r.lastIndex=++gr:o=!0;break;case"[":wa.lastIndex=gr,l?(f=Xu(new Ia,"]"),f.name=l):f=Xu(e.conditions?new Ia:[],"]"),e.conditions?(Rf(e,_),e.conditions.push(f),n=null):e.push(f),Oi[gr]===","?r.lastIndex=++gr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(n){let h={comparator:i||"equals",attribute:n,value:u(l)};i==="eq"&&Cv(h,l),Rf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(Zu(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=n?hee:wa,r.lastIndex=gr),gr===Oi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Rf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function Zu(e){return e.indexOf(".")>-1?e.split(".").map(Zu):decodeURIComponent(e)}function Iv(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new Vr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function Cv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Vr.ClientError("wildcard can only be used at the end of a string")}function Dv(e){let t=Lv(e[0]);return e.length>1&&(t.next=Dv(e.slice(1))),t}function Lv(e){if(Array.isArray(e)){let t=Lv(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function Ps(e){return Array.isArray(e)?e.join("\0"):e}function Mn(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function mee(e,t,r){return t*r/Mn(e)}var Vr,Ag,an,Ai,cee,uee,lee,_ee,Og,Ng,Eee,wa,hee,gr,Oi,Ia,bf=Re(()=>{Vr=x(re()),Ag=x(dt()),an=require("ordered-binary"),Ai=require("lmdb"),cee=.3,uee=.1,lee=.05,_ee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Og={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(bg,"executeConditions");a(Ca,"searchByIndex");a(Pn,"findAttribute");a(dee,"joinTo");a(fee,"joinFrom");Ng={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(yg,"filterByType");a(Af,"estimateCondition");Eee=/[()[\]|!<>.]|(=\w*=)/,wa=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,hee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Of,"parseQuery");a(Xu,"parseBlock");a(Rf,"assignOperator");a(Zu,"decodeProperty");a(Iv,"typedDecoding");a(Cv,"wildcardDecoding");a(Dv,"toSortObject");a(Lv,"toSortEntry");Ia=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}};a(Ps,"flattenKey");a(Mn,"estimatedEntryCount");a(mee,"intersectionEstimate")});function Bv(e){let t={openapi:pee,info:{title:"HarperDB HTTP REST interface",version:(0,vv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,s]of e){if(!s.path)continue;let{path:n}=s,i=n.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=s.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:g,name:P,elements:H,relationship:v,definition:U}of o){if(v)g==="array"?_[P]={type:"array",items:{$ref:bi+H.type}}:_[P]={$ref:bi+g};else{let Y=U??H?.definition;if(Y){if(!t.components.schemas[Y.type]){let K={};Y.properties.forEach(z=>{K[z.name]=new Dg(wg[z.type],z.type)}),t.components.schemas[Y.type]=new Pv(K)}g==="array"?_[P]={type:"array",items:{$ref:bi+Y.type}}:_[P]={$ref:bi+Y.type}}else g==="array"?H.type==="Any"||H.type=="ID"?_[P]={type:"array",items:{format:H.type}}:_[P]={type:"array",items:new Dg(wg[H.type],H.type)}:g==="Any"||g=="ID"?_[P]={format:g}:_[P]=new Dg(wg[g],g)}l.push(new Lg(P,"query",_[P]))}let d=Object.keys(_),f=new Lg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Lg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new Pv(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",A=typeof u.delete=="function",R="/"+n+"/";h&&(t.paths[R]={},t.paths[R].post=new See(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new Ig(l,r,{200:new Cg({$ref:bi+i})},"search for records by the specified property name and value pairs")),A&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new Mv(l,r,"delete all the records that match the provided query",{204:new Uv})),R="/"+n+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new Ig([f],r,{200:new Cg({$ref:bi+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new Tee([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),A&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new Mv([f],r,"delete a record with the given primary key",{204:new Uv})),S&&E.schema.enum.length>0&&(R="/"+n+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new Ig([f,E],r,{200:new Cg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function See(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:bi+e}}}},this.security=t,this.responses={200:{description:Ug,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Ig(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.responses=r}function Cg(e){this.description=Ug,this.content={"application/json":{schema:e}}}function Uv(){this.description="successfully processed request, no content returned to client"}function Tee(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:bi+r}}}},this.responses={200:{description:Ug}}}function Mv(e,t,r,s){this.description=r,this.parameters=e,this.security=t,this.responses=s}function Pv(e){this.type="object",this.properties=e}function Dg(e,t){this.type=e,this.format=t}function Lg(e,t,r){this.name=e,this.in=t,this.schema=r}var vv,pee,wg,bi,Ug,Hv=Re(()=>{vv=x(Od()),pee="3.0.3",wg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},bi="#/components/schemas/",Ug="successful operation";a(Bv,"generateJsonApi");a(See,"Post");a(Ig,"Get");a(Cg,"Response200");a(Uv,"Response204");a(Tee,"Put");a(Mv,"Delete");a(Pv,"ResourceSchema");a(Dg,"Type");a(Lg,"Parameter")});var yf={};Ye(yf,{start:()=>Aee});async function Ree(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Of(e);let n=new Si;try{e.responseHeaders=n;let i=e.url.slice(1),o,c;if(i!==xv){let h=Nf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Xe(e,()=>{if(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=So(r["content-type"],!0)(e.body)}catch(h){throw new Da.ClientError(h,400)}if(e.authorize=!0,i===xv&&s==="GET"){if(e?.user?.role?.permission?.super_user)return Bv(Nf);throw new Da.ServerError("Forbidden",403)}switch(s){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":n.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new Da.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Da.ServerError(`Method ${s} is not recognized`,501)}}),l=200,d;if(_==null)l=s==="GET"||s==="HEAD"?404:204,Mg.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){gee[0]=d;let h=String.fromCharCode(34,(Vt[0]&63)+62,(Vt[0]>>6)+(Vt[1]<<2&63)+62,(Vt[1]>>4)+(Vt[2]<<4&63)+62,(Vt[2]>>2)+62,(Vt[3]&63)+62,(Vt[3]>>6)+(Vt[4]<<2&63)+62,(Vt[4]>>4)+(Vt[5]<<4&63)+62,(Vt[5]>>2)+62,(Vt[6]&63)+62,(Vt[6]>>6)+(Vt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):n.setIfNone("ETag",h),Mg.lastModified&&n.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&n.setIfNone("Location",e.newLocation);let f={status:l,headers:n,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&n.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=gf(_,e,f),s==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?To.warn(i):To.info(i):To.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),n.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:n,body:void 0};return o.body=gf(i.contentType?i:i.toString(),e,o),o}}function Aee(e){Mg=e,!qv&&(qv=!0,Nf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Ree(t,r)}),e.server.ws(async(t,r,s)=>{el++;let n=new Rs;Fv||(Fv=!0,ru(l=>{el>0&&l.push({metric:"ws-connections",connections:el,byThread:!0})}));let i;t.on("error",l=>{i=!0,To.warn(l)});let o;t.on("message",a(function(d){o||(o=So(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{el--,rs(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=Nf.getMatch(u);if(rs(!!_,"connection","ws","connect"),!_)t.send(Ti(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Hr(h=>({count:h.count,total:el}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ti(E.value,r);t.send(h),Hr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var To,Da,Vt,gee,Mg,xv,qv,Nf,Fv,el,Gv=Re(()=>{ga();bn();To=x(V()),Da=x(re());bf();Ec();Zi();Bu();Hv();Vt=new Uint8Array(8),gee=new Float64Array(Vt.buffer,0,1),Mg={},xv="openapi";a(Ree,"http");el=0;a(Aee,"start")});var Pg=T((sme,kv)=>{var{recordAction:wf,recordActionBinary:Oee}=(bn(),se(su)),bee=require("fastify-plugin"),Nee=200;kv.exports=bee(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let o=n.getResponseTime(),c=performance.now(),u=n.request.routeOptions,_,l,d;u.config?.isOperation?(_=s.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),wf(o,"duration",_,d,l),Oee(n.raw.statusCode<400,"success",_,d,l);let f=Nee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{wf(performance.now()-c,"transfer",_,d,l),wf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,wf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Fg=T((ome,Kv)=>{var Lf=require("clone"),Uf=je(),yee=J(),Cf=L(),nme=V(),vg=require("fs"),Hg=require("joi"),{string:Df}=Hg.types(),{hdb_errors:wee,handleHDBError:If}=re(),{HDB_ERROR_MSGS:ime,HTTP_STATUS_CODES:Bg}=wee,{common_validators:La}=Ys(),Vv=" is required",Iee=["insert","update","upsert"],xg={database:{presence:!1,format:La.schema_format,length:La.schema_length},schema:{presence:!1,format:La.schema_format,length:La.schema_length},table:{presence:!0,format:La.schema_format,length:La.schema_length},action:{inclusion:{within:Iee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Cee={schema:Df.required(),table:Df.required(),action:Df.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Dee,AWS_SECRET:Lee,AWS_BUCKET:Uee,AWS_FILE_KEY:Mee,REGION:Pee}=Cf.S3_BUCKET_AUTH_KEYS,vee={s3:{presence:!0},[`s3.${Dee}`]:{presence:!0,type:"String"},[`s3.${Lee}`]:{presence:!0,type:"String"},[`s3.${Uee}`]:{presence:!0,type:"String"},[`s3.${Mee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Pee}`]:{presence:!0,type:"String"}},$v=Lf(xg);$v.data.presence={message:Vv};var Yv=Lf(xg);Yv.file_path.presence={message:Vv};var Bee=Object.assign(Lf(xg),vee),qg=Lf(Cee);qg.csv_url=Df.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();qg.passthrough_headers=Hg.object();function Hee(e){let t=Uf.validateObject(e,$v);return Mf(e,t)}a(Hee,"dataObject");function xee(e){let t=Uf.validateBySchema(e,Hg.object(qg));return Mf(e,t)}a(xee,"urlObject");function qee(e){let t=Uf.validateObject(e,Yv);return Mf(e,t)}a(qee,"fileObject");function Fee(e){let t=Uf.validateObject(e,Bee);return Mf(e,t)}a(Fee,"s3FileObject");function Mf(e,t){if(!t){let r=yee.checkGlobalSchemaTable(e.schema,e.table);if(r)return If(new Error,r,Bg.BAD_REQUEST);if(e.operation===Cf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{vg.accessSync(e.file_path,vg.constants.R_OK|vg.constants.F_OK)}catch(s){return s.code===Cf.NODE_ERROR_CODES.ENOENT?If(s,`No such file or directory ${s.path}`,Bg.BAD_REQUEST):s.code===Cf.NODE_ERROR_CODES.EACCES?If(s,`Permission denied ${s.path}`,Bg.BAD_REQUEST):If(s)}}return t}a(Mf,"postValidateChecks");Kv.exports={dataObject:Hee,urlObject:xee,fileObject:qee,s3FileObject:Fee}});var Gg=T((cme,Wv)=>{"use strict";var tl=V(),Pf=L();async function Gee(e,t,r,s=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===Pf.OPERATIONS_ENUM.INSERT||t.operation===Pf.OPERATIONS_ENUM.UPDATE||t.operation===Pf.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===Pf.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(tl.info(i.message),i):i.http_resp_msg?(tl.error(`Error calling operation: ${e.name}`),tl.error(i.http_resp_msg),i):(tl.error(`Error calling operation: ${e.name}`),tl.error(i),i)}}a(Gee,"callOperationFunctionAsAwait");Wv.exports={callOperationFunctionAsAwait:Gee}});var zv=T((lme,Qv)=>{"use strict";var kg=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}},Vg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};Qv.exports={BulkLoadFileObject:kg,BulkLoadDataObject:Vg}});var jv=T((dme,Jv)=>{"use strict";var $g=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};Jv.exports=$g});var Jg=T((Sme,E0)=>{"use strict";var vf=Cr(),Hf=Fg(),kee=require("needle"),vs=L(),Eme=Ge(),Ua=J(),{handleHDBError:it,hdb_errors:o0}=re(),{HTTP_STATUS_CODES:$t,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:Ro}=o0,Ma=V(),Yg=require("papaparse");Ua.promisifyPapaParse();var Bs=require("fs-extra"),Vee=require("path"),{chain:Xv}=require("stream-chain"),Zv=require("stream-json/streamers/StreamArray"),e0=require("stream-json/utils/Batch"),t0=require("stream-chain/utils/comp"),{finished:r0}=require("stream"),$ee=Z(),a0=Gg(),Yee=fg(),{BulkLoadFileObject:Wg,BulkLoadDataObject:Kee}=zv(),Qg=sg(),{verifyBulkLoadAttributePerms:c0}=Ef(),hme=jv(),mme=st(),pme=Sn(),{databases:Wee}=(Ae(),se(Fe)),{coerceType:Qee}=(xf(),se(jg)),s0="No records parsed from csv file.",go=`${$ee.get("HDB_ROOT")}/tmp`,{schema_regex:zee}=Ys(),n0=1024*1024*2,i0=5e3,Jee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};E0.exports={csvDataLoad:jee,csvURLLoad:Xee,csvFileLoad:Zee,importFromS3:ete};async function jee(e,t){let r=Hf.dataObject(e);if(r)throw it(r,r.message,$t.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=_0(e.schema,e.table),i=Yg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Kg.bind(null,n),dynamicTyping:!1}),o=new Qg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&c0(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw it(new Error,c,$t.BAD_REQUEST,void 0,void 0,!0);let u=new Kee(e.action,e.schema,e.table,i.data);return s=await a0.callOperationFunctionAsAwait(d0,u,null),s.message===s0?s0:f0(s.records,s.number_written)}catch(n){throw Ao(n)}}a(jee,"csvDataLoad");async function Xee(e){let t=Hf.urlObject(e);if(t)throw it(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${go}/${r}`;try{await tte(e,r)}catch(n){throw Ma.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+n),it(n,Ro(wt.DOWNLOAD_FILE_ERR(r)))}try{let n=new Wg(this.job_operation_function.name,e.action,e.schema,e.table,s,vs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await zg(n);return await Bf(s),i}catch(n){throw await Bf(s),Ao(n)}}a(Xee,"csvURLLoad");async function Zee(e){let t=Hf.fileObject(e);if(t)throw it(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r=new Wg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,vs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await zg(r)}catch(s){throw Ao(s)}}a(Zee,"csvFileLoad");async function ete(e){let t=Hf.s3FileObject(e);if(t)throw it(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=Vee.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${go}/${n}`;let i=new Wg(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await rte(n,e);let o=await zg(i);return await Bf(r),o}catch(s){throw await Bf(r),Ao(s)}}a(ete,"importFromS3");async function tte(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await kee("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw it(s,n,s.statusCode,vs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}nte(r,e.csv_url),await ste(t,r.raw)}a(tte,"downloadCSVFile");async function rte(e,t){try{let r=`${go}/${e}`;await Bs.mkdirp(go),await Bs.writeFile(`${go}/${e}`,"",{flag:"a+"});let s=await Bs.createWriteStream(r),n=await Yee.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){Ma.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ma.error(wt.S3_DOWNLOAD_ERR+" - "+r),it(r,Ro(wt.S3_DOWNLOAD_ERR))}}a(rte,"downloadFileFromS3");async function ste(e,t){try{await Bs.mkdirp(go),await Bs.writeFile(`${go}/${e}`,t)}catch(r){throw Ma.error(wt.WRITE_TEMP_FILE_ERR),it(r,Ro(wt.DEFAULT_BULK_LOAD_ERR))}}a(ste,"writeFileToTempFolder");async function Bf(e){if(e)try{await Bs.access(e),await Bs.unlink(e)}catch{Ma.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Bf,"deleteTempFile");function nte(e,t){if(e.statusCode!==o0.HTTP_STATUS_CODES.OK)throw it(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,$t.BAD_REQUEST);if(!Jee[e.headers["content-type"]])throw it(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,$t.BAD_REQUEST);if(!e.raw)throw it(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,$t.BAD_REQUEST)}a(nte,"validateURLResponse");async function zg(e){try{let t;switch(e.file_type){case vs.VALID_S3_FILE_TYPES.CSV:t=await ite(e);break;case vs.VALID_S3_FILE_TYPES.JSON:t=await ote(e);break;default:throw it(new Error,wt.DEFAULT_BULK_LOAD_ERR,$t.BAD_REQUEST,vs.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return f0(t.records,t.number_written)}catch(t){throw Ao(t)}}a(zg,"fileLoad");async function u0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await vf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&c0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=it(c);r(u)}}a(u0,"validateChunk");async function l0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Ua.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!Ua.isEmpty(c)&&!Ua.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await a0.callOperationFunctionAsAwait(d0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=it(c,Ro(wt.INSERT_CSV_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(l0,"insertChunk");async function ite(e){let t={records:0,number_written:0},r=_0(e.schema,e.table);try{let s=new Qg,n=Bs.createReadStream(e.file_path,{highWaterMark:n0});n.setEncoding("utf8"),await Yg.parsePromise(n,u0.bind(null,e,s),Kg.bind(null,r));let i=s.getPermsResponse();if(i)throw it(new Error,i,$t.BAD_REQUEST);return n=Bs.createReadStream(e.file_path,{highWaterMark:n0}),n.setEncoding("utf8"),await Yg.parsePromise(n,l0.bind(null,e,t),Kg.bind(null,r)),n.destroy(),t}catch(s){throw it(s,Ro(wt.PAPA_PARSE_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+s)}}a(ite,"callPapaParse");function _0(e,t){let r=Wee[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>Qee(i,n));return s}a(_0,"createTransformMap");function Kg(e,t,r){let s=e.get(r);return s?s(t):Ua.autoCast(t)}a(Kg,"typeFunction");async function ote(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Qg,n=Xv([Bs.createReadStream(e.file_path,{encoding:"utf-8"}),Zv.withParser(),c=>c.value,new e0({batchSize:i0}),t0(async c=>{await u0(e,s,r,c)})]);await new Promise((c,u)=>{r0(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw it(new Error,i,$t.BAD_REQUEST);let o=Xv([Bs.createReadStream(e.file_path,{encoding:"utf-8"}),Zv.withParser(),c=>c.value,new e0({batchSize:i0}),t0(async c=>{await l0(e,t,r,c)})]);return await new Promise((c,u)=>{r0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw it(s,Ro(wt.INSERT_JSON_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+s)}}a(ote,"insertJson");async function d0(e){let t={};try{e.data&&e.data.length>0&&ate(e.data[0])?t=await cte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ma.info(t.message))}catch(r){throw Ao(r)}return t}a(d0,"callBulkFileLoad");function ate(e){let t=Object.keys(e);for(let r of t)if(!zee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(ate,"validateColumnNames");async function cte(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=vf.insert;break;case"update":i=vf.update;break;case"upsert":i=vf.upsert;break;default:throw it(new Error,wt.INVALID_ACTION_PARAM_ERR(s),$t.BAD_REQUEST,vs.LOG_LEVELS.ERROR,wt.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Ua.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Ao(o)}}a(cte,"bulkFileLoad");function f0(e,t){return`successfully loaded ${t} of ${e} records`}a(f0,"buildResponseMsg");function Ao(e){return it(e,Ro(wt.DEFAULT_BULK_LOAD_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Ao,"buildTopLevelErrMsg")});var m0=T((gme,h0)=>{"use strict";var Xg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};h0.exports=Xg});var T0=T((Ame,S0)=>{"use strict";var ute=L(),p0=require("moment"),lte=require("uuid").v4,Zg=class{static{a(this,"JobObject")}constructor(){this.id=lte(),this.type=void 0,this.start_datetime=p0().valueOf(),this.created_datetime=p0().valueOf(),this.end_datetime=void 0,this.status=ute.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};S0.exports=Zg});var eR=T((bme,N0)=>{"use strict";var _te=require("uuid").v4,A0=Cr(),O0=es(),dte=Js(),fte=ta(),Ete=m0(),ot=L(),hte=T0(),mte=md(),_s=V(),pte=Ic(),Pa=J(),{promisify:Ste}=require("util"),Oo=require("moment"),Tte=mf(),qf=Fg(),g0=Im(),{deleteTransactionLogsBeforeValidator:gte}=XT(),{handleHDBError:Rte,hdb_errors:Ate}=re(),{HTTP_STATUS_CODES:Ote}=Ate,R0=O0.searchByValue,bte=O0.searchByHash,Nte=A0.insert,yte=Ste(Tte.evaluateSQL),wte=A0.update;N0.exports={addJob:Dte,updateJob:Ute,handleGetJob:Ite,handleGetJobsByStartDate:Cte,getJobById:b0};async function Ite(e){try{let t=await b0(e.id);return Pa.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw _s.error("There was an error getting job",t),new Error(r)}}a(Ite,"handleGetJob");async function Cte(e){try{let t=await Lte(e);if(_s.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=Oo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Oo(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw _s.error(r),new Error(r)}}a(Cte,"handleGetJobsByStartDate");async function Dte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Pa.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return _s.info(l),t.error=l,t}if(!ot.JOB_TYPE_ENUM[e.operation])return _s.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case ot.OPERATIONS_ENUM.CSV_FILE_LOAD:s=qf.fileObject(e);break;case ot.OPERATIONS_ENUM.CSV_URL_LOAD:s=qf.urlObject(e);break;case ot.OPERATIONS_ENUM.CSV_DATA_LOAD:s=qf.dataObject(e);break;case ot.OPERATIONS_ENUM.IMPORT_FROM_S3:s=qf.s3FileObject(e);break;case ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=g0(e,"date");break;case ot.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=g0(e,"timestamp");break;case ot.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=gte(e);break;default:break}if(s)throw Rte(s,s.message,Ote.BAD_REQUEST,void 0,void 0,!0);let n=new hte;n.type=e.operation===ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new dte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await R0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return _s.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=_te();try{o=await R0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return _s.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return _s.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new pte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await Nte(u)}catch(l){return _s.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,_s.trace(l)}return t}a(Dte,"addJob");async function Lte(e){let t=Oo(e.from_date,Oo.ISO_8601),r=Oo(e.to_date,Oo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new Ete(s,e.hdb_user);try{return await yte(n)}catch(i){throw _s.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(Lte,"getJobsInDateRange");async function b0(e){if(Pa.isEmptyOrZeroLength(e))return Pa.errorizeMessage("Invalid job ID specified.");let t=new fte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await bte(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return _s.error(s),Pa.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(b0,"getJobById");async function Ute(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Pa.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ot.JOB_STATUS_ENUM.COMPLETE||e.status===ot.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Oo().valueOf());let t=new mte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await wte(t),r}a(Ute,"updateJob")});var L0=T((yme,D0)=>{"use strict";var y0=J(),Rr=L(),Mte=require("moment"),Ff=Jg(),Gf=V(),w0=eR(),I0=pf(),C0=ti(),Pte=Ke(),vte=lf(),tR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Bte(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(y0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(y0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Rr.JOB_TYPE_ENUM.csv_file_load:await vn(e,Ff.csvFileLoad);break;case Rr.JOB_TYPE_ENUM.csv_url_load:await vn(e,Ff.csvURLLoad);break;case Rr.JOB_TYPE_ENUM.csv_data_load:await vn(e,Ff.csvDataLoad);break;case Rr.JOB_TYPE_ENUM.import_from_s3:await vn(e,Ff.importFromS3);break;case Rr.JOB_TYPE_ENUM.empty_trash:break;case Rr.JOB_TYPE_ENUM.export_local:await vn(e,I0.export_local);break;case Rr.JOB_TYPE_ENUM.export_to_s3:await vn(e,I0.export_to_s3);break;case Rr.JOB_TYPE_ENUM.delete_files_before:case Rr.JOB_TYPE_ENUM.delete_records_before:await vn(e,C0.deleteFilesBefore);break;case Rr.JOB_TYPE_ENUM.delete_audit_logs_before:await vn(e,C0.deleteAuditLogsBefore);break;case Rr.JOB_TYPE_ENUM.delete_transaction_logs_before:await vn(e,vte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Bte,"parseMessage");async function vn(e,t){try{e.job.status=Rr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Mte().valueOf(),await w0.updateJob(e.job),await Hte(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):Gf.error(`There was an error running ${t.name} job with id ${e.job.id}`),Gf.error(s),e.job.message=s,e.job.status=Rr.JOB_STATUS_ENUM.ERROR;try{await w0.updateJob(e.job)}catch(n){throw Gf.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(vn,"runJob");async function Hte(e){Gf.trace("launching job thread:",e),Pte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Rr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Hte,"launchJobThread");D0.exports={parseMessage:Bte,RunnerMessage:tR}});var M0=T((Ime,U0)=>{"use strict";var rR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};U0.exports=rR});var J0=T((Dme,cR)=>{"use strict";var Yf=es(),iR=mf(),kf=Jg(),Bn=lu(),Vf=Xn(),sl=ti(),xte=pS(),rl=ts(),$f=yS(),Yt=jT(),It=V(),qte=CS(),Fte=Id(),P0=lT(),Gte=Dd(),kte=_T(),Vte=dT(),$te=hT(),Yte=pT(),sR=gT(),v0=pf(),Kte=Ef(),oR=eR(),q=L(),{hdb_errors:il,handleHDBError:nl}=re(),{HTTP_STATUS_CODES:B0}=il,nR=NT(),H0=Wd(),K0=require("util"),va=Cr(),Wte=Tn(),Qte=da(),x0=L0(),q0=mu(),F0=(Xd(),se(Hu)),G0=Ur(),k0=lf(),V0=sf(),{setServerUtilities:zte}=(xf(),se(jg)),{CONTEXT:Jte}=(As(),se(Op)),{_assignPackageExport:jte}=require("../index"),{transformReq:Xte}=J(),{server:Zte}=(rr(),se(Mi)),ere=Gg(),$0=Yf.searchByHash,tre=Yf.searchByValue,rre=K0.promisify(Yf.search),sre=K0.promisify(iR.evaluateSQL),nre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},$=M0();async function W0(e,t){try{if(e.body.operation!=="read_log"&&(It.log_level===q.LOG_LEVELS.INFO||It.log_level===q.LOG_LEVELS.DEBUG||It.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;It.info(o)}}catch(s){It.error(s)}let r=await ere.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return nre[e.body.operation]&&Wte.setSchemaDataToGlobal(s=>{s&&It.error(s)}),r}a(W0,"processLocalTransaction");var Y0=ore();cR.exports={chooseOperation:Q0,getOperationFunction:z0,operation:aR,processLocalTransaction:W0};zte(cR.exports);Zte.operation=aR;function Q0(e){let t;try{t=z0(e)}catch(n){throw It.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=iR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=iR.checkASTPermissions(e,i);if(o)throw It.error(`${B0.FORBIDDEN} from operation ${e.operation}`),It.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),nl(new Error,o,il.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Kte.verifyPerms(i,n);if(o)throw It.error(`${B0.FORBIDDEN} from operation ${e.operation}`),It.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),nl(new Error,o,il.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw nl(n,"There was an error when trying to choose an operation path")}return r}a(Q0,"chooseOperation");function z0(e){if(It.trace(`getOperationFunction with operation: ${e.operation}`),Y0.has(e.operation))return Y0.get(e.operation);throw nl(new Error,il.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),il.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(z0,"getOperationFunction");jte("operation",aR);function aR(e,t){e.hdb_user=this[Jte]?.user,e.bypass_auth=!t;let r=Q0(e);return W0({body:e},r)}a(aR,"operation");async function ire(e){It.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await va.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await va.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await va.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await sl.deleteRecord(i);break;default:It.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){It.info("Invalid operation in transaction"),It.error(o)}}a(ire,"catchup");async function cn(e){Xte(e);let t,r;try{r=await oR.addJob(e),t=r.createdJob,It.info("addJob result",r);let s=new x0.RunnerMessage(t,e);return await x0.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw It.error(n),nl(s,n)}}a(cn,"executeJob");function ore(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new $(va.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new $(va.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new $(va.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new $(Yf.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new $($0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new $($0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(tre)),e.set(q.OPERATIONS_ENUM.SEARCH,new $(rre)),e.set(q.OPERATIONS_ENUM.SQL,new $(sre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new $(cn,kf.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new $(cn,kf.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new $(cn,kf.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new $(cn,kf.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new $(Bn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new $(Bn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new $(Bn.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new $(Bn.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new $(Bn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new $(Bn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new $(Bn.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new $(Bn.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new $(Vf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new $(Vf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new $(Vf.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new $(Vf.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new $(sl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new $(rl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new $(rl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new $(rl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new $(rl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new $($f.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new $($f.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new $($f.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new $($f.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new $(rl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new $(qte)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new $(Fte)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new $(P0)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(P0)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new $(Gte)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(kte)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new $(Vte)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new $(G0.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new $($te.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new $(Yte)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(sR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(sR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(sR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new $(cn,v0.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new $(cn,sl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new $(cn,sl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new $(cn,v0.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(oR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new $(oR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new $(nR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new $(nR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new $(nR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new $(H0.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new $(H0.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new $(ire)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $(Qte.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(cn,sl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(xte)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(q0.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(q0.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new $(F0.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new $(F0.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new $(G0.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $(Yt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $(Yt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $(Yt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new $(Yt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $(Yt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new $(Yt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $(Yt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $(Yt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $(Yt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $(Yt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new $(Yt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $(Yt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $(Yt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $(Yt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $(Yt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $(Yt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(k0.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(cn,k0.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $(V0.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $(V0.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new $(Bn.getBackup)),e}a(ore,"initializeOperationFunctionMap")});var Wf=T((Ume,Z0)=>{"use strict";var uR=L(),are=J(),ol=V(),{handleHDBError:lR,hdb_errors:Kf}=re(),{isMainThread:cre}=require("worker_threads"),{Readable:ure}=require("stream"),j0=require("os"),lre=require("util"),_re=qS(),dre=lre.promisify(_re.authorize),X0=J0(),{createGzip:fre,constants:Ere}=require("zlib");function hre(e){let t=`Found an uncaught exception with message: ${e.message}. ${j0.EOL}Stack: ${e.stack} ${j0.EOL}Terminating ${cre?"HDB":"thread"}.`;console.error(t),ol.fatal(t),process.exit(1)}a(hre,"handleServerUncaughtException");function mre(e,t,r){if(ol[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Kf.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(mre,"serverErrorHandler");function pre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=lR(new Error,"Invalid JSON.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(are.isEmpty(e.body.operation)){let s=lR(new Error,"Request body must include an 'operation' property.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(pre,"reqBodyValidationHandler");function Sre(e,t,r){let s;e.body.operation!==uR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==uR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==uR.OPERATIONS_ENUM.LOGOUT?dre(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{ol.warn(n),ol.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(lR(n,i,Kf.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(Sre,"authHandler");async function Tre(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=X0.chooseOperation(e.body);let n=await X0.processLocalTransaction(e,s);if(n instanceof ure&&n.headers){for(let[i,o]of n.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(fre({level:Ere.Z_BEST_SPEED})))}return n}catch(n){throw ol.error(n),n}}a(Tre,"handlePostRequest");Z0.exports={authHandler:Sre,handlePostRequest:Tre,handleServerUncaughtException:hre,serverErrorHandler:mre,reqBodyValidationHandler:pre}});var sB=T((Pme,rB)=>{"use strict";var gre=require("fastify-plugin"),{handlePostRequest:eB,authHandler:Rre,reqBodyValidationHandler:Are}=Wf();async function Ore(e){e.decorate("hdbCore",{preValidation:[Are,Rre],request:t=>tB(eB(t,response)),requestWithoutAuthentication:(t,r)=>tB(eB(t,r,!0))})}a(Ore,"hdbCore");async function tB(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(tB,"convertAsyncIterators");rB.exports=gre(Ore)});var oB=T((Hme,iB)=>{"use strict";var Bme=require("fs"),_R=Z();_R.initSync();var{CONFIG_PARAMS:nB}=L(),bre=1024*1024*1024;function Nre(e){let t=_R.get(nB.HTTP_TIMEOUT),r=_R.get(nB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:bre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Nre,"getServerOptions");iB.exports=Nre});var uB=T((qme,cB)=>{"use strict";var dR=Z();dR.initSync();var{CONFIG_PARAMS:aB}=L();function yre(){let e=dR.get(aB.HTTP_CORSACCESSLIST),t=dR.get(aB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(yre,"getCORSOptions");cB.exports=yre});var dB=T((Gme,_B)=>{"use strict";var lB=Z();lB.initSync();var wre=L();function Ire(){return lB.get(wre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Ire,"getHeaderTimeoutConfig");_B.exports=Ire});var ER={};Ye(ER,{customFunctionsServer:()=>Lre,ready:()=>wB,start:()=>Dre});function Dre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){Hn||(Hn=yB(t),tt.http((await Hn).server));let o=await Hn,c=(0,fR.dirname)(n),u=(0,fR.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!fB.has(c)){fB.add(c);try{o.register(Mre(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}},ready:wB}}async function Lre(){try{Ve.info("In Custom Functions Fastify server"+process.cwd()),Ve.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ve.debug(`Custom Functions server process ${process.pid} starting up.`),await Ure();let e=TB.get(gB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Hn=await yB(e)}catch(r){throw Ve.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ve.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ve.error(`Custom Functions ${process.pid} Error: ${e}`),Ve.error(e),process.exit(1)}}async function Ure(){try{Ve.info("Custom Functions starting configuration."),await RB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function Mre(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,EB.existsSync)(e)&&r.register(SB.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ve.error(n.message):n&&Ve.error(n),o()})}catch(s){Ve.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function yB(e){Ve.info("Custom Functions starting buildServer.");let t=(0,AB.default)(e),r=(0,hB.default)(t);r.server.headersTimeout=(0,bB.default)(),r.setErrorHandler(NB.serverErrorHandler);let s=(0,OB.default)();return s&&r.register(mB.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(pB.default),await r.register(Cre),await r.after(),Rg(r),Ve.info("Custom Functions completed buildServer."),r}function wB(){if(Hn)return Hn.then?Hn.then(e=>e.ready()):Hn.ready()}var fR,EB,hB,mB,pB,SB,TB,gB,Ve,Cre,RB,AB,OB,bB,NB,Hn,fB,IB=Re(()=>{fR=require("path"),EB=require("fs"),hB=x(require("fastify")),mB=x(require("@fastify/cors")),pB=x(Pg()),SB=x(require("@fastify/autoload")),TB=x(Z()),gB=x(L()),Ve=x(V()),Cre=x(sB()),RB=x(ts()),AB=x(oB()),OB=x(uB()),bB=x(dB()),NB=x(Wf());ga();rr();fB=new Set;a(Dre,"start");a(Lre,"customFunctionsServer");a(Ure,"setUp");a(Mre,"buildRouteFolder");a(yB,"buildServer");a(wB,"ready")});var hR={};Ye(hR,{start:()=>Pre});function Pre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,MB.default)(r,e);return e.server.http(async(n,i)=>{if(!n.isWebSocket)return new Promise(o=>s(n._nodeRequest,n._nodeResponse,()=>{o(i(n))}))}),!0}},handleFile(t,r,s){DB||(DB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=CB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,LB.default)(n,(0,UB.realpathSync)(o))}}return i(n)},{runFirst:!0})),CB.set(r,s)}}}var LB,UB,MB,CB,DB,PB=Re(()=>{LB=x(require("send")),UB=require("fs"),MB=x(require("serve-static")),CB=new Map;a(Pre,"start")});function Hre(e,t=1,r){if(mR++,(0,bo.startWorker)("server/threads/threadServer.js",{name:Jf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===Jf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});Bre.push(n),await n,Ba.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=zf.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Ba.indexOf(s);o>-1&&Ba.splice(o,1)}if(a(i,"removeWorker"),Ha){let o=Ha;Ha=[];for(let c of o)xB[c.localPort](null,c)}}}),r){let s=setInterval(()=>{pR?pR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,bo.shutdownWorkers)(),mR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function qB(e=0,t){if(typeof e=="string")try{(0,jf.existsSync)(e)&&(0,jf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=xre:r=qre(t):r=TR;let s=(0,xa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=xB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),pR=!0,r(o,(c,u)=>{if(!c){if(vB){let l=o._socket||new xa.Socket({handle:o,writable:!0,readable:!0});vB.deliverSocket(l,e,u),l.resume()}else mR>0?(Ha.length===0&&setTimeout(()=>{Ha.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Ha.push(o)):(console.log("start up a dynamic thread to handle request"),Hre(0));Hr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new xa.Socket({handle:o,writable:!0,readable:!0});Vre(l,c,e)}Hr(!0,"socket-routed")})};let n=Zc();SR.info(`HarperDB ${n.version} Server running on port ${e}`)}return s.on("error",n=>{console.error("Error in socket server",n)}),process.env._UNREF_SERVER&&s.unref(),s}function TR(e,t){let r,s=0;for(let n of Ba){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=Qf)return Qf=i,t(r);s=i}Qf=0,t(r)}function xre(e,t){let r={};e.getpeername(r);let s=r.address,n=qa.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);TR(e,o=>{qa.set(s,{worker:o,lastUsed:i}),t(o)})}function qre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new xa.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=qa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);TR(s,d=>{qa.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function Gre(){Qf=0;for(let e of Ba)e.expectedIdle=e.recentELU.idle+Fre,e.requests=1;Ba.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Vre(e,t,r){let s=kre++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),zf.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),zf.delete(s)),n.event=="destroy"&&(e.destroy(),zf.delete(s))})}var bo,xa,Jf,SR,jf,HB,vre,Ba,Ha,xB,vB,mR,Bre,pR,Qf,BB,qa,Fre,zf,kre,FB=Re(()=>{bo=x(Ke()),xa=require("net"),Jf=x(L()),SR=x(V()),jf=require("fs");bn();HB=require("worker_threads"),vre=x(Wi()),Ba=[],Ha=[],xB=[],mR=0,Bre=[];HB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Hre,"startHTTPWorker");a(qB,"startSocketServer");Qf=0;a(TR,"findMostIdleWorker");BB=36e5,qa=new Map;a(xre,"findByRemoteAddressAffinity");a(qre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of qa)r.lastUsed+BB<e&&qa.delete(t)},BB).unref();Fre=1e3;a(Gre,"updateWorkerIdleness");(0,bo.setMonitorListener)(Gre);zf=new Map,kre=1;a(Vre,"proxySocket")});var OR={};Ye(OR,{Request:()=>gR,createReuseportFd:()=>Xf});var GB,gR,RR,AR,Xf,Zf=Re(()=>{GB=require("os"),gR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let s=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=s,this.headers=new AR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new RR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},RR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},AR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,s]of this)t(s,r,this)}};(0,GB.platform)()!="win32"&&(Xf=require("node-unix-socket").createReuseportFd)});var YB=T((rpe,$B)=>{"use strict";var $re=require("cluster"),No=Z();No.initSync();var VB=L(),jme=require("util"),xn=V(),Xme=require("fs"),Yre=require("fastify"),Zme=Zc(),Kre=require("@fastify/cors"),Wre=require("@fastify/compress"),Qre=require("@fastify/static"),zre=Pg(),Jre=require("path"),{PACKAGE_ROOT:jre}=L(),Xre=Tn(),Zre=J(),ese=ts(),tse=Wi(),{server:rse}=(rr(),se(Mi)),{node_request_key:epe}=(Zf(),se(OR)),{authHandler:sse,handlePostRequest:nse,serverErrorHandler:ise,reqBodyValidationHandler:ose}=Wf(),tpe=require("net"),{registerContentHandlers:ase}=(ga(),se(wv)),cse=6e4,use=1024*1024*1024,lse="TRUE",{CONFIG_PARAMS:al}=VB,Fa;$B.exports={hdbServer:kB,start:kB};async function kB(e){try{xn.info("In Fastify server"+process.cwd()),xn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),xn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=$re.isMaster,await _se();let t=e.securePort>0;Fa=dse(t),await Fa.ready(),e||(e={}),e.isOperationsServer=!0;try{rse.http(Fa.server,e),Fa.server.closeIdleConnections||await Fa.listen({port:0,host:"::"})}catch(r){throw Fa.close(),xn.error(r),xn.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),xn.fatal(t),process.exit(1)}}a(kB,"operationsServer");async function _se(){xn.trace("Configuring HarperDB process."),Xre.setSchemaDataToGlobal(),await ese.setUsersToGlobal(),await tse.getLicense()}a(_se,"setUp");function dse(e){xn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=fse(e),r=Yre(t);r.server.headersTimeout=hse(),r.setErrorHandler(ise);let s=Ese();s&&r.register(Kre,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(zre),r.register(Wre),r.register(Qre,{root:Jre.join(jre,"studio/build-local")}),ase(r);let n=No.get(VB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Zre.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[ose,sse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),nse(i,o)}),r.get("/health",()=>"HarperDB is running."),xn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(dse,"buildServer");function fse(e){let t=No.get(al.OPERATIONSAPI_NETWORK_TIMEOUT),r=No.get(al.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:use,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(fse,"getServerOptions");function Ese(){let e=No.get(al.OPERATIONSAPI_NETWORK_CORS),t=No.get(al.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===lse)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(Ese,"getCORSOpts");function hse(){return No.get(al.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??cse}a(hse,"getHeaderTimeoutConfig")});var tH=T((ape,eH)=>{"use strict";var{decode:mse}=require("msgpackr"),{isMainThread:npe,parentPort:pse,threadId:ipe}=require("worker_threads"),NR=st(),qn=Ge(),Sse=L(),Ni=V(),KB=Z(),QB=L();Ke();var Tse=Sn(),{recordAction:gse,recordActionBinary:Rse}=(bn(),se(su)),{publishToStream:Ase}=NR,{ConsumerEvents:Ose}=require("nats"),ope={durable:qn.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qn.WORK_QUEUE_CONSUMER_NAMES.deliver_group},bse,Nse,yse,zB,JB;eH.exports={initialize:yR,workQueueListener:ZB,setSubscription:wse,setIgnoreOrigin:Cse,getDatabaseSubscriptions:Ise};async function yR(){JB=!0,Ni.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await NR.getNATSReferences();bse=e,Nse=e.info.server_name,yse=t,zB=r}a(yR,"initialize");var tE=new Map;function wse(e,t,r){let s=tE.get(e);s||tE.set(e,s=new Map),s.set(t,r),JB||yR().then(ZB)}a(wse,"setSubscription");function Ise(){return tE}a(Ise,"getDatabaseSubscriptions");var jB;function Cse(e){jB=e}a(Cse,"setIgnoreOrigin");var XB=100,WB=new Array(XB),eE=0;async function ZB(){let e=await zB.consumers.get(qn.WORK_QUEUE_CONSUMER_NAMES.stream_name,qn.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(pse?.on("message",async s=>{let{type:n}=s;n===QB.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let s of await r.status())if(s.type===Ose.HeartbeatsMissed){let n=s.data;Ni.trace(`${n} clustering ingest consumer heartbeats missed`),n===2&&(Ni.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let s of r)await WB[eE],WB[eE]=Dse(s).catch(n=>{Ni.error(n)}),++eE>=XB&&(eE=0)}catch(s){Ni.error("Error consuming clustering ingest, restarting consumer",s)}NR.clearClientCache(),await yR()}}a(ZB,"workQueueListener");async function Dse(e){let t=mse(e.data);gse(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,s=!1,n=KB.get(Sse.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(qn.MSG_HEADERS.TRANSACTED_NODES)&&r.values(qn.MSG_HEADERS.TRANSACTED_NODES).indexOf(n)>-1&&(s=!0);let i=r.get(qn.MSG_HEADERS.ORIGIN);if(s||(s=i===n&&!jB),Rse(s,"echo",e.subject,t.operation,"ingest"),s){e.ack();return}r.append(qn.MSG_HEADERS.TRANSACTED_NODES,n);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Ni.trace("processing message:",o,c,_,(l?"records: "+l.map(g=>g?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Ni.trace(`messageProcessor nats msg id: ${e.headers.get(qn.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:A}=f||{},R=tE.get(c)?.get(_);if(!R)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,R.send(t);else if(l.length===1&&!u)R.send({type:bR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:A});else{let g=l.map((P,H)=>({type:bR(o),value:P,expiresAt:E,id:d?.[H],table:_}));for(;u;)g.push({type:bR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;R.send({type:"transaction",writes:g,table:_,timestamp:p,onCommit:h,user:S,nodeName:A})}KB.get(QB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Ase(e.subject.split(".").slice(0,-1).join("."),Tse.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ni.error(o)}e.ack()}a(Dse,"messageProcessor");function bR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(bR,"convertOperation")});var UR={};Ye(UR,{disableNATS:()=>Use,publishToStream:()=>oE,setNATSReplicator:()=>wR,setPublishToStream:()=>Mse,setSubscription:()=>LR,start:()=>Lse});function Lse(){sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&vse()}function Use(e=!0){oH=e}function Mse(e,t){oE=e,LR=t}function vse(){if(oH||process.env._DISABLE_NATS)return;let e=Ds(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];wR(n,r,i)}}MR((r,s)=>{wR(r.tableName,r.databaseName,r),s&&cH(r)}),!rH&&(rH=!0)}function wR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(n=>n?.isNATSReplicator))return;r.sourcedFrom(class extends xt{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){cH(i)}static subscribe(){let i=new Rs;return LR(t,e,i),i}static subscribeOnThisThread(i){return i<Pse}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function s(n){let i=n?.transaction?.nats;if(!i)if(n?.transaction){n.transaction.nats=i=new rE(n.transaction,n);let o=n.transaction;for(;o.next;)o=o.next;o.next=n.transaction.nats,i.user=n.user,i.context=n}else i=aH;return i}a(s,"getNATSTransaction")}function cH(e){let t=sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);oE(`${CR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,DR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var sH,CR,DR,nH,iH,sE,nE,iE,oH,oE,LR,Pse,aH,rH,rE,IR,uH=Re(()=>{Ae();As();sH=x(st()),CR=x(Ge()),DR=x(Sn());Ec();nH=x(tH()),iH=x(yr()),sE=x(Z()),nE=x(L()),iE=x(V());a(Lse,"start");a(Use,"disableNATS");oE=sH.publishToStream,LR=nH.setSubscription;a(Mse,"setPublishToStream");Pse=2;a(vse,"assignReplicationSource");a(wR,"setNATSReplicator");a(cH,"publishSchema");rE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let s=this.writes_by_db.get(t);s||this.writes_by_db.set(t,s=[]),s.push(r)}commit({timestamp:t}){let r=sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(iE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&s.push(oE(`${CR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,DR.createNatsTableStreamName)(n,u.table),void 0,u)?.catch(l=>{throw iE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(s)}},IR=class extends rE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,iH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};aH=new IR});var bH=T(yo=>{"use strict";var{isMainThread:hH,parentPort:ul,threadId:aE}=require("worker_threads"),{Socket:Bse,createServer:Hse}=require("net"),{createServer:xse,IncomingMessage:qse}=require("http"),{createServer:Fse}=require("https"),{readFileSync:Ga,unlinkSync:lH,existsSync:Gse}=require("fs"),jt=V(),De=Z(),Tt=L(),{server:_E}=(rr(),se(Mi)),{WebSocketServer:kse}=require("ws"),{createServer:Vse}=require("tls"),{getTicketKeys:$se,restartNumber:Yse,getWorkerIndex:uE}=Ke(),{Headers:mH,appendHeader:Kse}=(Bu(),se(jM)),{recordAction:cl,recordActionBinary:Wse}=(bn(),se(su)),{Request:pH,createReuseportFd:_H}=(Zf(),se(OR)),{checkMemoryLimit:Qse}=Wi(),SH=require("tls"),dH=SH.createSecureContext;SH.createSecureContext=function(e){if(!e.cert||!e.key)return dH(e);let t={...e};delete t.key,delete t.cert;let r=dH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var TH=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG);if(TH){let e;if(hH)e=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){jt.info("Could not close debugger",t)}});else{let t=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&uE()>=0&&(e=t+uE())}if(e){let t=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(s){jt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,s.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){Yse<=1&&jt.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:Epe,CONFIG_PARAMS:zse}=Tt;De.initSync();var Jse=De.get(zse.HTTP_SESSIONAFFINITY),un={};yo.registerServer=xR;yo.httpServer=qR;yo.deliverSocket=HR;yo.startServers=gH;yo.when_components_loaded=null;_E.http=qR;_E.request=ene;_E.socket=tne;_E.ws=rne;var PR={},cE={},jse,yi={},lE={},Xse=[],vR=[];function gH(){return yo.when_components_loaded=FR().loadRootComponents(!0).then(()=>{ul?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)HR(s,r,n);else if(t.requestId)Zse(t);else if(t.type===Tt.ITC_EVENT_TYPES.SHUTDOWN){jt.trace("received shutdown request",aE);for(let i in un){let o=un[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(f=>f.description.includes("connections")),l=0,d=setInterval(()=>{l++;let f=l>=100,E=o[_][f?"all":"idle"]();if(E.length===0){f&&clearInterval(d);return}l===1?jt.info(`Closing ${E.length} idle connections`):f&&jt.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,p=E.length;h<p;h++){let S=E[h].socket;S._httpMessage&&!S._httpMessage.finished&&!f||(f?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
|
|
26
|
+
`},compressible:!1,q:.8});vt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});Cv={type:"application/json",serializeStream:Sc,serialize:el,deserialize:aee,q:.8};vt.set("*/*",Cv);vt.set("",Cv);a(aee,"tryJSONParse");a(Og,"registerContentHandlers");cee=require("fastify-plugin"),uee=cee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Rf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Rf,"findBestSerializer");bv=Tg.default.get(gg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Af,"serialize");a(gi,"serializeMessage");a(lee,"streamToBuffer");a(To,"getDeserializer");a(Nv,"deserializerUnknownType");a(_ee,"transformIterable")});function yg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],p=_(h);d=d.concat(p)}let f=new Set;return d.filter(E=>{let h=E.key??E;return f.has(h)?!1:(f.add(h),!0)})}else{let d=_(u),f=l(e.slice(1),!0,u.estimated_count);return f.length>0?o(d,f):d}function _(d){return d.conditions?yg(d.conditions,d.operator,r,n,s,i,o,c):Ua(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let A=h.operator==="or",R=l(h.conditions,!A,E);return A?(v,H)=>R.some(P=>P(v,H)):(v,H)=>R.every(P=>P(v,H))}let S=(h.attribute||h[0])===r.primaryKey,g=Ig(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=gee(r.primaryStore,h.estimated_count,E)),g}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ua(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let A=o[0],R=vs(n.attributes,A);if(R.relationship){if(o.length<2)throw new Vr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let v=R.definition?.tableClass||R.elements?.definition?.tableClass,H=new Map,P=Ua({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,v,s,H);if(R.relationship.to){i[o[0]]=H;let M=!!vs(v.attributes,R.relationship.to)?.elements;P=mee(P,R,v.primaryStore,M,H)}if(R.relationship.from){let M=a(K=>Ua({attribute:R.relationship.from,value:K},t,r,n,s,H),"searchEntry");R.elements?(i[o[0]]=H,P=pee(P,R,v.primaryStore,H,M)):P=P.flatMap(M)}return P}else if(o.length===1)o=o[0];else throw new Vr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(wg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=as.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"sort":case"contains":case"ends_with":_=!0,E=!0;break;default:throw new Vr.ClientError(`Unknown query comparator "${u}"`)}if(r){let A=_;_=l,l=A,A=!f,f=!d,d=A}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Vr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&E)throw new Vr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Vr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Vr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Ig(e),!S)throw new Vr.ClientError(`Unknown search operator ${e.comparator}`)}let g={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let A=p.getRange(g).map(S?function({key:R,value:v}){return this.isSync?v&&S(v)?R:Oi.SKIP:new Promise((H,P)=>setImmediate(()=>{try{H(v&&S(v)?R:Oi.SKIP)}catch(M){P(M)}}))}:R=>R.value==null?Oi.SKIP:R);return A.hasEntries=!0,A}else return p?p.getRange(g).map(S?function({key:A,value:R}){return this.isSync?S({[o]:A})?R:Oi.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(S({[o]:A})?R:Oi.SKIP)}catch(P){H(P)}}))}:({value:A})=>A):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:A,value:R}){return this.isSync?R&&S(R)?A:Oi.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(R&&S(R)?A:Oi.SKIP)}catch(P){H(P)}}))})}function vs(e,t){if(Array.isArray(t))if(t.length>1){let r=vs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?vs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function mee(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Pn(l),o=!0);let E=s.get(f);E?E.push(d):s.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!s.filters?.some(E=>!E(d)))if(n)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function pee(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Pn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Pn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(f=>!f(d)))continue}_.set(Pn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Ig(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=vs(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Ig({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let p=t.propertyResolvers?.[l],S,g=a((A,R)=>{let v,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let M of h.idFilter.idSet)e={attribute:p.from,value:M};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let P=S(A);return S.idFilter&&(g.idFilter=S.idFilter),P}H=p(A,r,R),v=H?.value}else v=A[l];return v?Array.isArray(v)?v.some(h):h(v,H):!1},"recordFilter");return g}}switch(u instanceof Date&&(u=u.getTime()),wg[o]||o){case bg.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,as.compareKeys)(l,u[0])>=0&&(0,as.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,as.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,as.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,as.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,as.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,as.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Vr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&bf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let p=0,S=3;function g(A){let R=A[l],v;if(typeof R!="object"||!R||E?v=d(R):Array.isArray(R)?v=R.some(d):R instanceof Date&&(v=d(R.getTime())),f&&(S++,!v&&!g.idFilter&&++p/S*(i-S)>h)){let H=Ua(e,r.transaction.getReadTxn(),!1,t).map(Pn),P=new Set(H);g.idFilter=M=>P.has(Pn(M)),g.idFilter.idSet=P}return v}return a(g,"recordFilter"),s&&(g.idFilter=d),g}a(_,"attributeComparator")}function bf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Ps(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=wg[n]||n,n===bg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=vs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=bf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Ps(e.indices[i.relationship.from])/(Ps(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Ps(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Eee*Ps(e.primaryStore)+1:n==="between"?r.estimated_count=fee*Ps(e.primaryStore)+1:n==="sort"?r.estimated_count=Ps(e.primaryStore)+1:r.estimated_count=dee*Ps(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Nf(e){if(e)if(bi=e,Ca.lastIndex=0,See.test(e))try{let t=rl(new Da,"");if(gr!==bi.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${gr} in '${bi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function rl(e,t){let r=Ca,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(bi);){gr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=Uv}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=nl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=hee[d],u=Ng[i]?Uv:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=nl(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&Lv(h,l),Of(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(nl(l)),s=void 0;break;case"(":Ca.lastIndex=gr;let E=rl(l?[]:new Da,")");switch(l){case"":Of(e,_),e.conditions.push(E);break;case"limit":switch(E.length){case 1:e.limit=+E[0];break;case 2:e.offset=+E[0],e.limit=E[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(E[0])&&E.length===1&&!E[0].name?(e.select=E[0],e.select.asArray=!0):E.length===1?e.select=E[0]:E.length===2&&E[1]===""?e.select=E.slice(0,1):e.select=E;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=Mv(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}bi[gr]===","?r.lastIndex=++gr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Ca.lastIndex=gr,f=rl([],"}"),f.name=l,e.push(f),bi[gr]===","?r.lastIndex=++gr:o=!0;break;case"[":Ca.lastIndex=gr,l?(f=rl(new Da,"]"),f.name=l):f=rl(e.conditions?new Da:[],"]"),e.conditions?(Of(e,_),e.conditions.push(f),s=null):e.push(f),bi[gr]===","?r.lastIndex=++gr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&Lv(h,l),Of(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(nl(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?Tee:Ca,r.lastIndex=gr),gr===bi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Of(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function nl(e){return e.indexOf(".")>-1?e.split(".").map(nl):decodeURIComponent(e)}function Uv(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new Vr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function Lv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Vr.ClientError("wildcard can only be used at the end of a string")}function Mv(e){let t=Pv(e[0]);return e.length>1&&(t.next=Mv(e.slice(1))),t}function Pv(e){if(Array.isArray(e)){let t=Pv(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function Pn(e){return Array.isArray(e)?e.join("\0"):e}function Ps(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function gee(e,t,r){return t*r/Ps(e)}var Vr,bg,as,Oi,dee,fee,Eee,hee,Ng,wg,See,Ca,Tee,gr,bi,Da,yf=ge(()=>{Vr=x(re()),bg=x(ft()),as=require("ordered-binary"),Oi=require("lmdb"),dee=.3,fee=.1,Eee=.05,hee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Ng={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(yg,"executeConditions");a(Ua,"searchByIndex");a(vs,"findAttribute");a(mee,"joinTo");a(pee,"joinFrom");wg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Ig,"filterByType");a(bf,"estimateCondition");See=/[()[\]|!<>.]|(=\w*=)/,Ca=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Tee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Nf,"parseQuery");a(rl,"parseBlock");a(Of,"assignOperator");a(nl,"decodeProperty");a(Uv,"typedDecoding");a(Lv,"wildcardDecoding");a(Mv,"toSortObject");a(Pv,"toSortEntry");Da=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(Pn,"flattenKey");a(Ps,"estimatedEntryCount");a(gee,"intersectionEstimate")});function qv(e){let t={openapi:Ree,info:{title:"HarperDB HTTP REST interface",version:(0,xv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:v,elements:H,relationship:P,definition:M}of o){if(P)R==="array"?_[v]={type:"array",items:{$ref:Ni+H.type}}:_[v]={$ref:Ni+R};else{let K=M??H?.definition;if(K){if(!t.components.schemas[K.type]){let W={};K.properties.forEach(V=>{W[V.name]=new Lg(Cg[V.type],V.type)}),t.components.schemas[K.type]=new Hv(W)}R==="array"?_[v]={type:"array",items:{$ref:Ni+K.type}}:_[v]={$ref:Ni+K.type}}else R==="array"?H.type==="Any"||H.type=="ID"?_[v]={type:"array",items:{format:H.type}}:_[v]={type:"array",items:new Lg(Cg[H.type],H.type)}:R==="Any"||R=="ID"?_[v]={format:R}:_[v]=new Lg(Cg[R],R)}l.push(new Mg(v,"query",_[v]))}let d=Object.keys(_),f=new Mg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Mg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new Hv(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",g=typeof u.delete=="function",A="/"+s+"/";h&&(t.paths[A]={},t.paths[A].post=new Aee(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[A]||(t.paths[A]={}),t.paths[A].get=new Dg(l,r,{200:new Ug({$ref:Ni+i})},"search for records by the specified property name and value pairs")),g&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new Bv(l,r,"delete all the records that match the provided query",{204:new vv})),A="/"+s+"/{"+c+"}",S&&(t.paths[A]={},t.paths[A].get=new Dg([f],r,{200:new Ug({$ref:Ni+i})},"retrieve a record by its primary key")),p&&(t.paths[A]||(t.paths[A]={}),t.paths[A].put=new Oee([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),g&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new Bv([f],r,"delete a record with the given primary key",{204:new vv})),S&&E.schema.enum.length>0&&(A="/"+s+"/{"+c+"}.{property}",t.paths[A]={},t.paths[A].get=new Dg([f,E],r,{200:new Ug({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function Aee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ni+e}}}},this.security=t,this.responses={200:{description:Pg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Dg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Ug(e){this.description=Pg,this.content={"application/json":{schema:e}}}function vv(){this.description="successfully processed request, no content returned to client"}function Oee(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ni+r}}}},this.responses={200:{description:Pg}}}function Bv(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function Hv(e){this.type="object",this.properties=e}function Lg(e,t){this.type=e,this.format=t}function Mg(e,t,r){this.name=e,this.in=t,this.schema=r}var xv,Ree,Cg,Ni,Pg,Fv=ge(()=>{xv=x(Nd()),Ree="3.0.3",Cg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ni="#/components/schemas/",Pg="successful operation";a(qv,"generateJsonApi");a(Aee,"Post");a(Dg,"Get");a(Ug,"Response200");a(vv,"Response204");a(Oee,"Put");a(Bv,"Delete");a(Hv,"ResourceSchema");a(Lg,"Type");a(Mg,"Parameter")});var If={};Ke(If,{start:()=>yee});async function Nee(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Nf(e);let s=new Ti;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==Gv){let h=wf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Ze(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=To(r["content-type"],!0)(e.body)}catch(h){throw new La.ClientError(h,400)}if(e.authorize=!0,i===Gv&&n==="GET"){if(e?.user?.role?.permission?.super_user)return qv(wf);throw new La.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new La.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new La.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,vg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){bee[0]=d;let h=String.fromCharCode(34,(Vt[0]&63)+62,(Vt[0]>>6)+(Vt[1]<<2&63)+62,(Vt[1]>>4)+(Vt[2]<<4&63)+62,(Vt[2]>>2)+62,(Vt[3]&63)+62,(Vt[3]>>6)+(Vt[4]<<2&63)+62,(Vt[4]>>4)+(Vt[5]<<4&63)+62,(Vt[5]>>2)+62,(Vt[6]&63)+62,(Vt[6]>>6)+(Vt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),vg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Af(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?go.warn(i):go.info(i):go.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Af(i.contentType?i:i.toString(),e,o),o}}function yee(e){vg=e,!kv&&(kv=!0,wf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Nee(t,r)}),e.server.ws(async(t,r,n)=>{sl++;let s=new Rn;Vv||(Vv=!0,ou(l=>{sl>0&&l.push({metric:"ws-connections",connections:sl,byThread:!0})}));let i;t.on("error",l=>{i=!0,go.warn(l)});let o;t.on("message",a(function(d){o||(o=To(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{sl--,rn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=wf.getMatch(u);if(rn(!!_,"connection","ws","connect"),!_)t.send(gi(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Hr(h=>({count:h.count,total:sl}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=gi(E.value,r);t.send(h),Hr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var go,La,Vt,bee,vg,Gv,kv,wf,Vv,sl,$v=ge(()=>{Aa();Ns();go=x($()),La=x(re());yf();mc();eo();Fu();Fv();Vt=new Uint8Array(8),bee=new Float64Array(Vt.buffer,0,1),vg={},Gv="openapi";a(Nee,"http");sl=0;a(yee,"start")});var Bg=T((ame,Yv)=>{var{recordAction:Cf,recordActionBinary:wee}=(Ns(),ne(au)),Iee=require("fastify-plugin"),Cee=200;Yv.exports=Iee(function(e,t,r){e.addHook("onResponse",async(n,s)=>{s.getResponseTime()}),e.addHook("onSend",async(n,s,i)=>{let o=s.getResponseTime(),c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Cf(o,"duration",_,d,l),wee(s.raw.statusCode<400,"success",_,d,l);let f=Cee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Cf(performance.now()-c,"transfer",_,d,l),Cf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Cf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var kg=T((lme,zv)=>{var Mf=require("clone"),Pf=Xe(),Dee=J(),Uf=U(),cme=$(),Hg=require("fs"),qg=require("joi"),{string:Lf}=qg.types(),{hdb_errors:Uee,handleHDBError:Df}=re(),{HDB_ERROR_MSGS:ume,HTTP_STATUS_CODES:xg}=Uee,{common_validators:Ma}=Kn(),Kv=" is required",Lee=["insert","update","upsert"],Fg={database:{presence:!1,format:Ma.schema_format,length:Ma.schema_length},schema:{presence:!1,format:Ma.schema_format,length:Ma.schema_length},table:{presence:!0,format:Ma.schema_format,length:Ma.schema_length},action:{inclusion:{within:Lee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Mee={schema:Lf.required(),table:Lf.required(),action:Lf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Pee,AWS_SECRET:vee,AWS_BUCKET:Bee,AWS_FILE_KEY:Hee,REGION:xee}=Uf.S3_BUCKET_AUTH_KEYS,qee={s3:{presence:!0},[`s3.${Pee}`]:{presence:!0,type:"String"},[`s3.${vee}`]:{presence:!0,type:"String"},[`s3.${Bee}`]:{presence:!0,type:"String"},[`s3.${Hee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${xee}`]:{presence:!0,type:"String"}},Wv=Mf(Fg);Wv.data.presence={message:Kv};var Qv=Mf(Fg);Qv.file_path.presence={message:Kv};var Fee=Object.assign(Mf(Fg),qee),Gg=Mf(Mee);Gg.csv_url=Lf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Gg.passthrough_headers=qg.object();function Gee(e){let t=Pf.validateObject(e,Wv);return vf(e,t)}a(Gee,"dataObject");function kee(e){let t=Pf.validateBySchema(e,qg.object(Gg));return vf(e,t)}a(kee,"urlObject");function Vee(e){let t=Pf.validateObject(e,Qv);return vf(e,t)}a(Vee,"fileObject");function $ee(e){let t=Pf.validateObject(e,Fee);return vf(e,t)}a($ee,"s3FileObject");function vf(e,t){if(!t){let r=Dee.checkGlobalSchemaTable(e.schema,e.table);if(r)return Df(new Error,r,xg.BAD_REQUEST);if(e.operation===Uf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Hg.accessSync(e.file_path,Hg.constants.R_OK|Hg.constants.F_OK)}catch(n){return n.code===Uf.NODE_ERROR_CODES.ENOENT?Df(n,`No such file or directory ${n.path}`,xg.BAD_REQUEST):n.code===Uf.NODE_ERROR_CODES.EACCES?Df(n,`Permission denied ${n.path}`,xg.BAD_REQUEST):Df(n)}}return t}a(vf,"postValidateChecks");zv.exports={dataObject:Gee,urlObject:kee,fileObject:Vee,s3FileObject:$ee}});var Vg=T((dme,Jv)=>{"use strict";var il=$(),Bf=U();async function Yee(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===Bf.OPERATIONS_ENUM.INSERT||t.operation===Bf.OPERATIONS_ENUM.UPDATE||t.operation===Bf.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===Bf.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(il.info(i.message),i):i.http_resp_msg?(il.error(`Error calling operation: ${e.name}`),il.error(i.http_resp_msg),i):(il.error(`Error calling operation: ${e.name}`),il.error(i),i)}}a(Yee,"callOperationFunctionAsAwait");Jv.exports={callOperationFunctionAsAwait:Yee}});var Xv=T((Eme,jv)=>{"use strict";var $g=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}},Yg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};jv.exports={BulkLoadFileObject:$g,BulkLoadDataObject:Yg}});var e0=T((mme,Zv)=>{"use strict";var Kg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};Zv.exports=Kg});var Xg=T((Ame,p0)=>{"use strict";var Hf=Cr(),qf=kg(),Kee=require("needle"),vn=U(),Sme=Ge(),Pa=J(),{handleHDBError:ot,hdb_errors:u0}=re(),{HTTP_STATUS_CODES:$t,HDB_ERROR_MSGS:It,CHECK_LOGS_WRAPPER:Ao}=u0,va=$(),Wg=require("papaparse");Pa.promisifyPapaParse();var Bn=require("fs-extra"),Wee=require("path"),{chain:t0}=require("stream-chain"),r0=require("stream-json/streamers/StreamArray"),n0=require("stream-json/utils/Batch"),s0=require("stream-chain/utils/comp"),{finished:i0}=require("stream"),Qee=Z(),l0=Vg(),zee=hg(),{BulkLoadFileObject:zg,BulkLoadDataObject:Jee}=Xv(),Jg=ig(),{verifyBulkLoadAttributePerms:_0}=mf(),Tme=e0(),gme=st(),Rme=Ts(),{databases:jee}=(Re(),ne(Fe)),{coerceType:Xee}=(Ff(),ne(Zg)),o0="No records parsed from csv file.",Ro=`${Qee.get("HDB_ROOT")}/tmp`,{schema_regex:Zee}=Kn(),a0=1024*1024*2,c0=5e3,ete={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};p0.exports={csvDataLoad:tte,csvURLLoad:rte,csvFileLoad:nte,importFromS3:ste};async function tte(e,t){let r=qf.dataObject(e);if(r)throw ot(r,r.message,$t.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=E0(e.schema,e.table),i=Wg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Qg.bind(null,s),dynamicTyping:!1}),o=new Jg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&_0(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw ot(new Error,c,$t.BAD_REQUEST,void 0,void 0,!0);let u=new Jee(e.action,e.schema,e.table,i.data);return n=await l0.callOperationFunctionAsAwait(h0,u,null),n.message===o0?o0:m0(n.records,n.number_written)}catch(s){throw Oo(s)}}a(tte,"csvDataLoad");async function rte(e){let t=qf.urlObject(e);if(t)throw ot(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Ro}/${r}`;try{await ite(e,r)}catch(s){throw va.error(It.DOWNLOAD_FILE_ERR(r)+" - "+s),ot(s,Ao(It.DOWNLOAD_FILE_ERR(r)))}try{let s=new zg(this.job_operation_function.name,e.action,e.schema,e.table,n,vn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await jg(s);return await xf(n),i}catch(s){throw await xf(n),Oo(s)}}a(rte,"csvURLLoad");async function nte(e){let t=qf.fileObject(e);if(t)throw ot(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r=new zg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,vn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await jg(r)}catch(n){throw Oo(n)}}a(nte,"csvFileLoad");async function ste(e){let t=qf.s3FileObject(e);if(t)throw ot(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Wee.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Ro}/${s}`;let i=new zg(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await ote(s,e);let o=await jg(i);return await xf(r),o}catch(n){throw await xf(r),Oo(n)}}a(ste,"importFromS3");async function ite(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Kee("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw ot(n,s,n.statusCode,vn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}cte(r,e.csv_url),await ate(t,r.raw)}a(ite,"downloadCSVFile");async function ote(e,t){try{let r=`${Ro}/${e}`;await Bn.mkdirp(Ro),await Bn.writeFile(`${Ro}/${e}`,"",{flag:"a+"});let n=await Bn.createWriteStream(r),s=await zee.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){va.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw va.error(It.S3_DOWNLOAD_ERR+" - "+r),ot(r,Ao(It.S3_DOWNLOAD_ERR))}}a(ote,"downloadFileFromS3");async function ate(e,t){try{await Bn.mkdirp(Ro),await Bn.writeFile(`${Ro}/${e}`,t)}catch(r){throw va.error(It.WRITE_TEMP_FILE_ERR),ot(r,Ao(It.DEFAULT_BULK_LOAD_ERR))}}a(ate,"writeFileToTempFolder");async function xf(e){if(e)try{await Bn.access(e),await Bn.unlink(e)}catch{va.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(xf,"deleteTempFile");function cte(e,t){if(e.statusCode!==u0.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,$t.BAD_REQUEST);if(!ete[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,$t.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,$t.BAD_REQUEST)}a(cte,"validateURLResponse");async function jg(e){try{let t;switch(e.file_type){case vn.VALID_S3_FILE_TYPES.CSV:t=await ute(e);break;case vn.VALID_S3_FILE_TYPES.JSON:t=await lte(e);break;default:throw ot(new Error,It.DEFAULT_BULK_LOAD_ERR,$t.BAD_REQUEST,vn.LOG_LEVELS.ERROR,It.INVALID_FILE_EXT_ERR(e))}return m0(t.records,t.number_written)}catch(t){throw Oo(t)}}a(jg,"fileLoad");async function d0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await Hf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&_0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=ot(c);r(u)}}a(d0,"validateChunk");async function f0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Pa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Pa.isEmpty(c)&&!Pa.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await l0.callOperationFunctionAsAwait(h0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=ot(c,Ao(It.INSERT_CSV_ERR),$t.INTERNAL_SERVER_ERROR,vn.LOG_LEVELS.ERROR,It.INSERT_CSV_ERR+" - "+c);r(u)}}a(f0,"insertChunk");async function ute(e){let t={records:0,number_written:0},r=E0(e.schema,e.table);try{let n=new Jg,s=Bn.createReadStream(e.file_path,{highWaterMark:a0});s.setEncoding("utf8"),await Wg.parsePromise(s,d0.bind(null,e,n),Qg.bind(null,r));let i=n.getPermsResponse();if(i)throw ot(new Error,i,$t.BAD_REQUEST);return s=Bn.createReadStream(e.file_path,{highWaterMark:a0}),s.setEncoding("utf8"),await Wg.parsePromise(s,f0.bind(null,e,t),Qg.bind(null,r)),s.destroy(),t}catch(n){throw ot(n,Ao(It.PAPA_PARSE_ERR),$t.INTERNAL_SERVER_ERROR,vn.LOG_LEVELS.ERROR,It.PAPA_PARSE_ERR+n)}}a(ute,"callPapaParse");function E0(e,t){let r=jee[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Xee(i,s));return n}a(E0,"createTransformMap");function Qg(e,t,r){let n=e.get(r);return n?n(t):Pa.autoCast(t)}a(Qg,"typeFunction");async function lte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new Jg,s=t0([Bn.createReadStream(e.file_path,{encoding:"utf-8"}),r0.withParser(),c=>c.value,new n0({batchSize:c0}),s0(async c=>{await d0(e,n,r,c)})]);await new Promise((c,u)=>{i0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ot(new Error,i,$t.BAD_REQUEST);let o=t0([Bn.createReadStream(e.file_path,{encoding:"utf-8"}),r0.withParser(),c=>c.value,new n0({batchSize:c0}),s0(async c=>{await f0(e,t,r,c)})]);return await new Promise((c,u)=>{i0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw ot(n,Ao(It.INSERT_JSON_ERR),$t.INTERNAL_SERVER_ERROR,vn.LOG_LEVELS.ERROR,It.INSERT_JSON_ERR+n)}}a(lte,"insertJson");async function h0(e){let t={};try{e.data&&e.data.length>0&&_te(e.data[0])?t=await dte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",va.info(t.message))}catch(r){throw Oo(r)}return t}a(h0,"callBulkFileLoad");function _te(e){let t=Object.keys(e);for(let r of t)if(!Zee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(_te,"validateColumnNames");async function dte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=Hf.insert;break;case"update":i=Hf.update;break;case"upsert":i=Hf.upsert;break;default:throw ot(new Error,It.INVALID_ACTION_PARAM_ERR(n),$t.BAD_REQUEST,vn.LOG_LEVELS.ERROR,It.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Pa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Oo(o)}}a(dte,"bulkFileLoad");function m0(e,t){return`successfully loaded ${t} of ${e} records`}a(m0,"buildResponseMsg");function Oo(e){return ot(e,Ao(It.DEFAULT_BULK_LOAD_ERR),$t.INTERNAL_SERVER_ERROR,vn.LOG_LEVELS.ERROR,It.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Oo,"buildTopLevelErrMsg")});var T0=T((bme,S0)=>{"use strict";var eR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};S0.exports=eR});var A0=T((yme,R0)=>{"use strict";var fte=U(),g0=require("moment"),Ete=require("uuid").v4,tR=class{static{a(this,"JobObject")}constructor(){this.id=Ete(),this.type=void 0,this.start_datetime=g0().valueOf(),this.created_datetime=g0().valueOf(),this.end_datetime=void 0,this.status=fte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};R0.exports=tR});var rR=T((Ime,I0)=>{"use strict";var hte=require("uuid").v4,N0=Cr(),y0=en(),mte=jn(),pte=na(),Ste=T0(),at=U(),Tte=A0(),gte=Sd(),dn=$(),Rte=Dc(),Ba=J(),{promisify:Ate}=require("util"),bo=require("moment"),Ote=Sf(),Gf=kg(),O0=Dm(),{deleteTransactionLogsBeforeValidator:bte}=eg(),{handleHDBError:Nte,hdb_errors:yte}=re(),{HTTP_STATUS_CODES:wte}=yte,b0=y0.searchByValue,Ite=y0.searchByHash,Cte=N0.insert,Dte=Ate(Ote.evaluateSQL),Ute=N0.update;I0.exports={addJob:Pte,updateJob:Bte,handleGetJob:Lte,handleGetJobsByStartDate:Mte,getJobById:w0};async function Lte(e){try{let t=await w0(e.id);return Ba.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw dn.error("There was an error getting job",t),new Error(r)}}a(Lte,"handleGetJob");async function Mte(e){try{let t=await vte(e);if(dn.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=bo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=bo(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw dn.error(r),new Error(r)}}a(Mte,"handleGetJobsByStartDate");async function Pte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ba.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return dn.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return dn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case at.OPERATIONS_ENUM.CSV_FILE_LOAD:n=Gf.fileObject(e);break;case at.OPERATIONS_ENUM.CSV_URL_LOAD:n=Gf.urlObject(e);break;case at.OPERATIONS_ENUM.CSV_DATA_LOAD:n=Gf.dataObject(e);break;case at.OPERATIONS_ENUM.IMPORT_FROM_S3:n=Gf.s3FileObject(e);break;case at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=O0(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=O0(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=bte(e);break;default:break}if(n)throw Nte(n,n.message,wte.BAD_REQUEST,void 0,void 0,!0);let s=new Tte;s.type=e.operation===at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new mte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await b0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return dn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=hte();try{o=await b0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return dn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return dn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new Rte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await Cte(u)}catch(l){return dn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,dn.trace(l)}return t}a(Pte,"addJob");async function vte(e){let t=bo(e.from_date,bo.ISO_8601),r=bo(e.to_date,bo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new Ste(n,e.hdb_user);try{return await Dte(s)}catch(i){throw dn.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(vte,"getJobsInDateRange");async function w0(e){if(Ba.isEmptyOrZeroLength(e))return Ba.errorizeMessage("Invalid job ID specified.");let t=new pte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Ite(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return dn.error(n),Ba.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(w0,"getJobById");async function Bte(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ba.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===at.JOB_STATUS_ENUM.COMPLETE||e.status===at.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=bo().valueOf());let t=new gte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Ute(t),r}a(Bte,"updateJob")});var P0=T((Dme,M0)=>{"use strict";var C0=J(),Rr=U(),Hte=require("moment"),kf=Xg(),Vf=$(),D0=rR(),U0=Tf(),L0=ri(),xte=We(),qte=df(),nR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Fte(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(C0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(C0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Rr.JOB_TYPE_ENUM.csv_file_load:await Bs(e,kf.csvFileLoad);break;case Rr.JOB_TYPE_ENUM.csv_url_load:await Bs(e,kf.csvURLLoad);break;case Rr.JOB_TYPE_ENUM.csv_data_load:await Bs(e,kf.csvDataLoad);break;case Rr.JOB_TYPE_ENUM.import_from_s3:await Bs(e,kf.importFromS3);break;case Rr.JOB_TYPE_ENUM.empty_trash:break;case Rr.JOB_TYPE_ENUM.export_local:await Bs(e,U0.export_local);break;case Rr.JOB_TYPE_ENUM.export_to_s3:await Bs(e,U0.export_to_s3);break;case Rr.JOB_TYPE_ENUM.delete_files_before:case Rr.JOB_TYPE_ENUM.delete_records_before:await Bs(e,L0.deleteFilesBefore);break;case Rr.JOB_TYPE_ENUM.delete_audit_logs_before:await Bs(e,L0.deleteAuditLogsBefore);break;case Rr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Bs(e,qte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Fte,"parseMessage");async function Bs(e,t){try{e.job.status=Rr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Hte().valueOf(),await D0.updateJob(e.job),await Gte(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):Vf.error(`There was an error running ${t.name} job with id ${e.job.id}`),Vf.error(n),e.job.message=n,e.job.status=Rr.JOB_STATUS_ENUM.ERROR;try{await D0.updateJob(e.job)}catch(s){throw Vf.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Bs,"runJob");async function Gte(e){Vf.trace("launching job thread:",e),xte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Rr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Gte,"launchJobThread");M0.exports={parseMessage:Fte,RunnerMessage:nR}});var B0=T((Lme,v0)=>{"use strict";var sR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};v0.exports=sR});var Z0=T((Pme,lR)=>{"use strict";var Wf=en(),aR=Sf(),$f=Xg(),Hs=Eu(),Yf=Zs(),al=ri(),kte=TS(),ol=tn(),Kf=IS(),Yt=ZT(),Ct=$(),Vte=US(),$te=Dd(),H0=dT(),Yte=Ld(),Kte=fT(),Wte=ET(),Qte=pT(),zte=TT(),iR=AT(),x0=Tf(),Jte=mf(),cR=rR(),q=U(),{hdb_errors:ul,handleHDBError:cl}=re(),{HTTP_STATUS_CODES:q0}=ul,oR=wT(),F0=zd(),z0=require("util"),Ha=Cr(),jte=gs(),Xte=Ea(),G0=P0(),k0=gu(),V0=(ef(),ne(Gu)),$0=Lr(),Y0=df(),K0=of(),{setServerUtilities:Zte}=(Ff(),ne(Zg)),{CONTEXT:ere}=(An(),ne(Np)),{_assignPackageExport:tre}=require("../index"),{transformReq:rre}=J(),{server:nre}=(rr(),ne(Pi)),sre=Vg(),W0=Wf.searchByHash,ire=Wf.searchByValue,ore=z0.promisify(Wf.search),are=z0.promisify(aR.evaluateSQL),cre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=B0();async function J0(e,t){try{if(e.body.operation!=="read_log"&&(Ct.log_level===q.LOG_LEVELS.INFO||Ct.log_level===q.LOG_LEVELS.DEBUG||Ct.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;Ct.info(o)}}catch(n){Ct.error(n)}let r=await sre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return cre[e.body.operation]&&jte.setSchemaDataToGlobal(n=>{n&&Ct.error(n)}),r}a(J0,"processLocalTransaction");var Q0=lre();lR.exports={chooseOperation:j0,getOperationFunction:X0,operation:uR,processLocalTransaction:J0};Zte(lR.exports);nre.operation=uR;function j0(e){let t;try{t=X0(e)}catch(s){throw Ct.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=aR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=aR.checkASTPermissions(e,i);if(o)throw Ct.error(`${q0.FORBIDDEN} from operation ${e.operation}`),Ct.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),cl(new Error,o,ul.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Jte.verifyPerms(i,s);if(o)throw Ct.error(`${q0.FORBIDDEN} from operation ${e.operation}`),Ct.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),cl(new Error,o,ul.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw cl(s,"There was an error when trying to choose an operation path")}return r}a(j0,"chooseOperation");function X0(e){if(Ct.trace(`getOperationFunction with operation: ${e.operation}`),Q0.has(e.operation))return Q0.get(e.operation);throw cl(new Error,ul.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),ul.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(X0,"getOperationFunction");tre("operation",uR);function uR(e,t){e.hdb_user=this[ere]?.user,e.bypass_auth=!t;let r=j0(e);return J0({body:e},r)}a(uR,"operation");async function ure(e){Ct.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await Ha.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await Ha.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await Ha.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await al.deleteRecord(i);break;default:Ct.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Ct.info("Invalid operation in transaction"),Ct.error(o)}}a(ure,"catchup");async function cs(e){rre(e);let t,r;try{r=await cR.addJob(e),t=r.createdJob,Ct.info("addJob result",r);let n=new G0.RunnerMessage(t,e);return await G0.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw Ct.error(s),cl(n,s)}}a(cs,"executeJob");function lre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(Ha.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(Ha.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(Ha.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(Wf.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(W0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(W0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(ire)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(ore)),e.set(q.OPERATIONS_ENUM.SQL,new Y(are)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(cs,$f.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(cs,$f.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(cs,$f.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(cs,$f.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Hs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Hs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Hs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Hs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Hs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Hs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Hs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Hs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(Yf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(Yf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(Yf.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(Yf.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(al.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(ol.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(ol.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(ol.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(ol.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(Kf.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(Kf.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(Kf.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(Kf.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(ol.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(Vte)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y($te)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(H0)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(H0)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Yte)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Kte)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Wte)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y($0.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Qte.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(zte)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(iR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(iR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(iR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(cs,x0.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(cs,al.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(cs,al.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(cs,x0.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(cR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(cR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(oR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(oR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(oR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(F0.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(F0.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(ure)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Xte.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(cs,al.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(kte)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(k0.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(k0.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(V0.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(V0.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y($0.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Yt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Yt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Yt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Yt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Yt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Yt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Yt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Yt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Yt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Yt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Yt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Yt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Yt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Yt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Yt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Yt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(Y0.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(cs,Y0.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(K0.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(K0.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Hs.getBackup)),e}a(lre,"initializeOperationFunctionMap")});var zf=T((Bme,rB)=>{"use strict";var _R=U(),_re=J(),ll=$(),{handleHDBError:dR,hdb_errors:Qf}=re(),{isMainThread:dre}=require("worker_threads"),{Readable:fre}=require("stream"),eB=require("os"),Ere=require("util"),hre=GS(),mre=Ere.promisify(hre.authorize),tB=Z0(),{createGzip:pre,constants:Sre}=require("zlib");function Tre(e){let t=`Found an uncaught exception with message: ${e.message}. ${eB.EOL}Stack: ${e.stack} ${eB.EOL}Terminating ${dre?"HDB":"thread"}.`;console.error(t),ll.fatal(t),process.exit(1)}a(Tre,"handleServerUncaughtException");function gre(e,t,r){if(ll[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:Qf.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(gre,"serverErrorHandler");function Rre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=dR(new Error,"Invalid JSON.",Qf.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(_re.isEmpty(e.body.operation)){let n=dR(new Error,"Request body must include an 'operation' property.",Qf.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(Rre,"reqBodyValidationHandler");function Are(e,t,r){let n;e.body.operation!==_R.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==_R.OPERATIONS_ENUM.LOGIN&&e.body.operation!==_R.OPERATIONS_ENUM.LOGOUT?mre(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{ll.warn(s),ll.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(dR(s,i,Qf.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(Are,"authHandler");async function Ore(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=tB.chooseOperation(e.body);let s=await tB.processLocalTransaction(e,n);if(s instanceof fre&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(pre({level:Sre.Z_BEST_SPEED})))}return s}catch(s){throw ll.error(s),s}}a(Ore,"handlePostRequest");rB.exports={authHandler:Are,handlePostRequest:Ore,handleServerUncaughtException:Tre,serverErrorHandler:gre,reqBodyValidationHandler:Rre}});var oB=T((xme,iB)=>{"use strict";var bre=require("fastify-plugin"),{handlePostRequest:nB,authHandler:Nre,reqBodyValidationHandler:yre}=zf();async function wre(e){e.decorate("hdbCore",{preValidation:[yre,Nre],request:t=>sB(nB(t,response)),requestWithoutAuthentication:(t,r)=>sB(nB(t,r,!0))})}a(wre,"hdbCore");async function sB(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(sB,"convertAsyncIterators");iB.exports=bre(wre)});var uB=T((Gme,cB)=>{"use strict";var Fme=require("fs"),fR=Z();fR.initSync();var{CONFIG_PARAMS:aB}=U(),Ire=1024*1024*1024;function Cre(e){let t=fR.get(aB.HTTP_TIMEOUT),r=fR.get(aB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Ire,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Cre,"getServerOptions");cB.exports=Cre});var dB=T((Vme,_B)=>{"use strict";var ER=Z();ER.initSync();var{CONFIG_PARAMS:lB}=U();function Dre(){let e=ER.get(lB.HTTP_CORSACCESSLIST),t=ER.get(lB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(Dre,"getCORSOptions");_B.exports=Dre});var hB=T((Yme,EB)=>{"use strict";var fB=Z();fB.initSync();var Ure=U();function Lre(){return fB.get(Ure.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Lre,"getHeaderTimeoutConfig");EB.exports=Lre});var mR={};Ke(mR,{customFunctionsServer:()=>vre,ready:()=>DB,start:()=>Pre});function Pre(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){xs||(xs=CB(t),rt.http((await xs).server));let o=await xs,c=(0,hR.dirname)(s),u=(0,hR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!mB.has(c)){mB.add(c);try{o.register(Hre(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:DB}}async function vre(){try{Ve.info("In Custom Functions Fastify server"+process.cwd()),Ve.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ve.debug(`Custom Functions server process ${process.pid} starting up.`),await Bre();let e=AB.get(OB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=xs=await CB(e)}catch(r){throw Ve.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ve.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ve.error(`Custom Functions ${process.pid} Error: ${e}`),Ve.error(e),process.exit(1)}}async function Bre(){try{Ve.info("Custom Functions starting configuration."),await bB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function Hre(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,pB.existsSync)(e)&&r.register(RB.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ve.error(s.message):s&&Ve.error(s),o()})}catch(n){Ve.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function CB(e){Ve.info("Custom Functions starting buildServer.");let t=(0,NB.default)(e),r=(0,SB.default)(t);r.server.headersTimeout=(0,wB.default)(),r.setErrorHandler(IB.serverErrorHandler);let n=(0,yB.default)();return n&&r.register(TB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(gB.default),await r.register(Mre),await r.after(),Og(r),Ve.info("Custom Functions completed buildServer."),r}function DB(){if(xs)return xs.then?xs.then(e=>e.ready()):xs.ready()}var hR,pB,SB,TB,gB,RB,AB,OB,Ve,Mre,bB,NB,yB,wB,IB,xs,mB,UB=ge(()=>{hR=require("path"),pB=require("fs"),SB=x(require("fastify")),TB=x(require("@fastify/cors")),gB=x(Bg()),RB=x(require("@fastify/autoload")),AB=x(Z()),OB=x(U()),Ve=x($()),Mre=x(oB()),bB=x(tn()),NB=x(uB()),yB=x(dB()),wB=x(hB()),IB=x(zf());Aa();rr();mB=new Set;a(Pre,"start");a(vre,"customFunctionsServer");a(Bre,"setUp");a(Hre,"buildRouteFolder");a(CB,"buildServer");a(DB,"ready")});var pR={};Ke(pR,{start:()=>xre});function xre(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,BB.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){MB||(MB=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=LB.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,PB.default)(s,(0,vB.realpathSync)(o))}}return i(s)},{runFirst:!0})),LB.set(r,n)}}}var PB,vB,BB,LB,MB,HB=ge(()=>{PB=x(require("send")),vB=require("fs"),BB=x(require("serve-static")),LB=new Map;a(xre,"start")});function Gre(e,t=1,r){if(SR++,(0,No.startWorker)("server/threads/threadServer.js",{name:Xf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===Xf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Fre.push(s),await s,xa.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=jf.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=xa.indexOf(n);o>-1&&xa.splice(o,1)}if(a(i,"removeWorker"),qa){let o=qa;qa=[];for(let c of o)GB[c.localPort](null,c)}}}),r){let n=setInterval(()=>{TR?TR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,No.shutdownWorkers)(),SR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function kB(e=0,t){if(typeof e=="string")try{(0,Zf.existsSync)(e)&&(0,Zf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=kre:r=Vre(t):r=RR;let n=(0,Fa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=GB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),TR=!0,r(o,(c,u)=>{if(!c){if(xB){let l=o._socket||new Fa.Socket({handle:o,writable:!0,readable:!0});xB.deliverSocket(l,e,u),l.resume()}else SR>0?(qa.length===0&&setTimeout(()=>{qa.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,qa.push(o)):(console.log("start up a dynamic thread to handle request"),Gre(0));Hr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Fa.Socket({handle:o,writable:!0,readable:!0});Wre(l,c,e)}Hr(!0,"socket-routed")})};let s=ru();gR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function RR(e,t){let r,n=0;for(let s of xa){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=Jf)return Jf=i,t(r);n=i}Jf=0,t(r)}function kre(e,t){let r={};e.getpeername(r);let n=r.address,s=Ga.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);RR(e,o=>{Ga.set(n,{worker:o,lastUsed:i}),t(o)})}function Vre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Fa.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ga.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);RR(n,d=>{Ga.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Yre(){Jf=0;for(let e of xa)e.expectedIdle=e.recentELU.idle+$re,e.requests=1;xa.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Wre(e,t,r){let n=Kre++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),jf.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),jf.delete(n)),s.event=="destroy"&&(e.destroy(),jf.delete(n))})}var No,Fa,Xf,gR,Zf,FB,qre,xa,qa,GB,xB,SR,Fre,TR,Jf,qB,Ga,$re,jf,Kre,VB=ge(()=>{No=x(We()),Fa=require("net"),Xf=x(U()),gR=x($()),Zf=require("fs");Ns();FB=require("worker_threads"),qre=x(Qi()),xa=[],qa=[],GB=[],SR=0,Fre=[];FB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Gre,"startHTTPWorker");a(kB,"startSocketServer");Jf=0;a(RR,"findMostIdleWorker");qB=36e5,Ga=new Map;a(kre,"findByRemoteAddressAffinity");a(Vre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ga)r.lastUsed+qB<e&&Ga.delete(t)},qB).unref();$re=1e3;a(Yre,"updateWorkerIdleness");(0,No.setMonitorListener)(Yre);jf=new Map,Kre=1;a(Wre,"proxySocket")});var NR={};Ke(NR,{Request:()=>AR,createReuseportFd:()=>eE});var $B,AR,OR,bR,eE,tE=ge(()=>{$B=require("os"),AR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new bR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new OR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},OR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},bR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,$B.platform)()!="win32"&&(eE=require("node-unix-socket").createReuseportFd)});var QB=T((ope,WB)=>{"use strict";var Qre=require("cluster"),yo=Z();yo.initSync();var KB=U(),tpe=require("util"),qs=$(),rpe=require("fs"),zre=require("fastify"),npe=ru(),Jre=require("@fastify/cors"),jre=require("@fastify/compress"),Xre=require("@fastify/static"),Zre=Bg(),ene=require("path"),{PACKAGE_ROOT:tne}=U(),rne=gs(),nne=J(),sne=tn(),ine=Qi(),{server:one}=(rr(),ne(Pi)),{node_request_key:spe}=(tE(),ne(NR)),{authHandler:ane,handlePostRequest:cne,serverErrorHandler:une,reqBodyValidationHandler:lne}=zf(),ipe=require("net"),{registerContentHandlers:_ne}=(Aa(),ne(Dv)),dne=6e4,fne=1024*1024*1024,Ene="TRUE",{CONFIG_PARAMS:_l}=KB,ka;WB.exports={hdbServer:YB,start:YB};async function YB(e){try{qs.info("In Fastify server"+process.cwd()),qs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),qs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Qre.isMaster,await hne();let t=e.securePort>0;ka=mne(t),await ka.ready(),e||(e={}),e.isOperationsServer=!0;try{one.http(ka.server,e),ka.server.closeIdleConnections||await ka.listen({port:0,host:"::"})}catch(r){throw ka.close(),qs.error(r),qs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),qs.fatal(t),process.exit(1)}}a(YB,"operationsServer");async function hne(){qs.trace("Configuring HarperDB process."),rne.setSchemaDataToGlobal(),await sne.setUsersToGlobal(),await ine.getLicense()}a(hne,"setUp");function mne(e){qs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=pne(e),r=zre(t);r.server.headersTimeout=Tne(),r.setErrorHandler(une);let n=Sne();n&&r.register(Jre,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Zre),r.register(jre),r.register(Xre,{root:ene.join(tne,"studio/build-local")}),_ne(r);let s=yo.get(KB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!nne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[lne,ane],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),cne(i,o)}),r.get("/health",()=>"HarperDB is running."),qs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(mne,"buildServer");function pne(e){let t=yo.get(_l.OPERATIONSAPI_NETWORK_TIMEOUT),r=yo.get(_l.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:fne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(pne,"getServerOptions");function Sne(){let e=yo.get(_l.OPERATIONSAPI_NETWORK_CORS),t=yo.get(_l.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Ene)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(Sne,"getCORSOpts");function Tne(){return yo.get(_l.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??dne}a(Tne,"getHeaderTimeoutConfig")});var sH=T((_pe,nH)=>{"use strict";var{decode:gne}=require("msgpackr"),{isMainThread:cpe,parentPort:Rne,threadId:upe}=require("worker_threads"),wR=st(),Fs=Ge(),Ane=U(),yi=$(),zB=Z(),jB=U();We();var One=Ts(),{recordAction:bne,recordActionBinary:Nne}=(Ns(),ne(au)),{publishToStream:yne}=wR,{ConsumerEvents:wne}=require("nats"),lpe={durable:Fs.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Fs.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Ine,Cne,Dne,XB,ZB;nH.exports={initialize:IR,workQueueListener:rH,setSubscription:Une,setIgnoreOrigin:Mne,getDatabaseSubscriptions:Lne};async function IR(){ZB=!0,yi.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await wR.getNATSReferences();Ine=e,Cne=e.info.server_name,Dne=t,XB=r}a(IR,"initialize");var nE=new Map;function Une(e,t,r){let n=nE.get(e);n||nE.set(e,n=new Map),n.set(t,r),ZB||IR().then(rH)}a(Une,"setSubscription");function Lne(){return nE}a(Lne,"getDatabaseSubscriptions");var eH;function Mne(e){eH=e}a(Mne,"setIgnoreOrigin");var tH=100,JB=new Array(tH),rE=0;async function rH(){let e=await XB.consumers.get(Fs.WORK_QUEUE_CONSUMER_NAMES.stream_name,Fs.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Rne?.on("message",async n=>{let{type:s}=n;s===jB.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let n of await r.status())if(n.type===wne.HeartbeatsMissed){let s=n.data;yi.trace(`${s} clustering ingest consumer heartbeats missed`),s===2&&(yi.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let n of r)await JB[rE],JB[rE]=Pne(n).catch(s=>{yi.error(s)}),++rE>=tH&&(rE=0)}catch(n){yi.error("Error consuming clustering ingest, restarting consumer",n)}wR.clearClientCache(),await IR()}}a(rH,"workQueueListener");async function Pne(e){let t=gne(e.data);bne(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,n=!1,s=zB.get(Ane.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Fs.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Fs.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(Fs.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!eH),Nne(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(Fs.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;yi.trace("processing message:",o,c,_,(l?"records: "+l.map(R=>R?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),yi.trace(`messageProcessor nats msg id: ${e.headers.get(Fs.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:g}=f||{},A=nE.get(c)?.get(_);if(!A)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,A.send(t);else if(l.length===1&&!u)A.send({type:yR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:g});else{let R=l.map((v,H)=>({type:yR(o),value:v,expiresAt:E,id:d?.[H],table:_}));for(;u;)R.push({type:yR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;A.send({type:"transaction",writes:R,table:_,timestamp:p,onCommit:h,user:S,nodeName:g})}zB.get(jB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&yne(e.subject.split(".").slice(0,-1).join("."),One.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){yi.error(o)}e.ack()}a(Pne,"messageProcessor");function yR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(yR,"convertOperation")});var PR={};Ke(PR,{disableNATS:()=>Bne,publishToStream:()=>cE,setNATSReplicator:()=>CR,setPublishToStream:()=>Hne,setSubscription:()=>MR,start:()=>vne});function vne(){iE.default.get(oE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&qne()}function Bne(e=!0){uH=e}function Hne(e,t){cE=e,MR=t}function qne(){if(uH||process.env._DISABLE_NATS)return;let e=Dn(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];CR(s,r,i)}}vR((r,n)=>{CR(r.tableName,r.databaseName,r),n&&_H(r)}),!iH&&(iH=!0)}function CR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends xt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ue],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ue]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ue],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ue],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ue]})}static defineSchema(i){_H(i)}static subscribe(){let i=new Rn;return MR(t,e,i),i}static subscribeOnThisThread(i){return i<xne}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new sE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=lH;return i}a(n,"getNATSTransaction")}function _H(e){let t=iE.default.get(oE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);cE(`${UR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,LR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var oH,UR,LR,aH,cH,iE,oE,aE,uH,cE,MR,xne,lH,iH,sE,DR,dH=ge(()=>{Re();An();oH=x(st()),UR=x(Ge()),LR=x(Ts());mc();aH=x(sH()),cH=x(yr()),iE=x(Z()),oE=x(U()),aE=x($());a(vne,"start");a(Bne,"disableNATS");cE=oH.publishToStream,MR=aH.setSubscription;a(Hne,"setPublishToStream");xne=2;a(qne,"assignReplicationSource");a(CR,"setNATSReplicator");a(_H,"publishSchema");sE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=iE.default.get(oE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(aE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(cE(`${UR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,LR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw aE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},DR=class extends sE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,cH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};lH=new DR});var wH=T(wo=>{"use strict";var{isMainThread:SH,parentPort:fl,threadId:uE}=require("worker_threads"),{Socket:Fne,createServer:Gne}=require("net"),{createServer:kne,IncomingMessage:Vne}=require("http"),{createServer:$ne}=require("https"),{readFileSync:Va,unlinkSync:fH,existsSync:Yne}=require("fs"),jt=$(),De=Z(),gt=U(),{server:fE}=(rr(),ne(Pi)),{WebSocketServer:Kne}=require("ws"),{createServer:Wne}=require("tls"),{getTicketKeys:Qne,restartNumber:zne,getWorkerIndex:_E}=We(),{Headers:TH,appendHeader:Jne}=(Fu(),ne(eP)),{recordAction:dl,recordActionBinary:jne}=(Ns(),ne(au)),{Request:gH,createReuseportFd:EH}=(tE(),ne(NR)),{checkMemoryLimit:Xne}=Qi(),RH=require("tls"),hH=RH.createSecureContext;RH.createSecureContext=function(e){if(!e.cert||!e.key)return hH(e);let t={...e};delete t.key,delete t.cert;let r=hH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var AH=De.get(gt.CONFIG_PARAMS.THREADS_DEBUG);if(AH){let e;if(SH)e=De.get(gt.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){jt.info("Could not close debugger",t)}});else{let t=De.get(gt.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&_E()>=0&&(e=t+_E())}if(e){let t=De.get(gt.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=De.get(gt.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){jt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){zne<=1&&jt.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:Spe,CONFIG_PARAMS:Zne}=gt;De.initSync();var ese=De.get(Zne.HTTP_SESSIONAFFINITY),us={};wo.registerServer=FR;wo.httpServer=GR;wo.deliverSocket=qR;wo.startServers=OH;wo.when_components_loaded=null;fE.http=GR;fE.request=sse;fE.socket=ise;fE.ws=ose;var BR={},lE={},tse,wi={},dE={},rse=[],HR=[];function OH(){return wo.when_components_loaded=kR().loadRootComponents(!0).then(()=>{fl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)qR(n,r,s);else if(t.requestId)nse(t);else if(t.type===gt.ITC_EVENT_TYPES.SHUTDOWN){jt.trace("received shutdown request",uE);for(let i in us){let o=us[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(f=>f.description.includes("connections")),l=0,d=setInterval(()=>{l++;let f=l>=100,E=o[_][f?"all":"idle"]();if(E.length===0){f&&clearInterval(d);return}l===1?jt.info(`Closing ${E.length} idle connections`):f&&jt.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,p=E.length;h<p;h++){let S=E[h].socket;S._httpMessage&&!S._httpMessage.finished&&!f||(f?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
|
|
27
27
|
Connection: close\r
|
|
28
28
|
\r
|
|
29
|
-
`))}},25).unref()}o.close?.(()=>{if(De.get(
|
|
30
|
-
`)}a(EH,"defaultNotFound")});async function IH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await GR.get(e,{returnNonexistent:!0});n=new $R(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await GR.get(e);i&&i.delete()}n=new fE(e,t)}return s&&(s.id=e,s.user={username:t?.username},ll.put(s)),n}function kR(){return dE++,dE>65500&&(dE=1),dE}function VR(e,t,r=e){let{topic:s,retain:n}=e;e.data=t,e.async=!0,e.authorize=!0;let i=pi.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Xe(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var NH,wi,yH,wH,GR,ll,dE,fE,$R,CH=Re(()=>{Ae();vu();NH=x(yr()),wi=x(V());Zi();yH=x(Ke()),wH=x(bH());rr();GR=ct({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),ll=ct({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,yH.getWorkerIndex)()===0&&(async()=>{await wH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of ll.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await tt.getUser(r.user.username)),Xe(r,()=>{try{VR(r,t)}catch{(0,wi.warn)("Failed to publish will",t)}ll.delete(e.id,r)})}})();a(IH,"getSession");dE=1;a(kR,"getNextMessageId");fE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,rh:i,startTime:o}=t,c=n.indexOf("?"),u,_;if(c>-1?(u=n.slice(c),_=n.slice(0,c)):_=n,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(A=>A.topic===n),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,wi.trace)("Resuming subscription from",n,"from",o);let E=pi.getMatch(_);if(!E){let A=new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);throw A.statusCode=404,A}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let A=f.url.slice(1);if(A.indexOf("#")>-1&&A.indexOf("#")!==A.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,A.indexOf("+")===A.length-1)f.onlyChildren=!0,f.url="/"+A.slice(0,A.length-1);else{let R=A.split("/"),g;for(let v=0;v<R.length;v++)if(R[v].indexOf("+")>-1)if(R[v]==="+")g=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(s&&g)throw new Error("Filters can not be combined");let P=!0;R[R.length-1]==="#"&&(R.length--,P=!1),g&&(s=a(v=>{let U=v.id;if(!Array.isArray(U)||P&&U.length!==R.length)return!1;for(let Y=0;Y<R.length;Y++)if(R[Y]!=="+"&&R[Y]!==U[Y])return!1;return!0},"filter"));let H=R.indexOf("+");f.url="/"+(H>-1?R.slice(0,H):R).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Xe(f,async()=>{let A=await p.subscribe(f);if(!A)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!A[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let R of A)try{let g;if(R.type&&R.type!=="put"&&R.type!=="delete"&&R.type!=="message"&&R.type!=="patch"||s&&!s(R))continue;r?(R.topic=n,g=this.needsAcknowledge(R)):(R.acknowledge?.(),g=kR());let P=R.id;Array.isArray(P)&&(P=Ta(P)),P==null&&(P=""),this.listener(h+"/"+P,R.value,g,t)}catch(g){(0,wi.warn)(g)}})(),A});return S.topic=n,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=kR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,VR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Xe(r,async()=>{if(!t){let s=await ll.get(this.sessionId,r);s?.doesExist()&&await VR(s,s.data,r)}await ll.delete(this.sessionId,r)}).catch(s=>{(0,wi.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(VR,"publish");$R=class extends fE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=kR(),s={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(s.acknowledge=t.acknowledge),this.awaitingAcks.set(r,s),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,wi.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,NH.getNextMonotonicTime)()),(0,wi.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),GR.put(this.sessionRecord)),t.qos}}});var YR={};Ye(YR,{bypassAuth:()=>sne,start:()=>nne});function sne(){PH=!0}function nne({server:e,port:t,network:r,webSocket:s,securePort:n,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return s&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=UH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Ar.info)("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},s))),(t||n)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Ar.error)(E)}else if(u.required)return(0,Ar.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&PH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,MH.getSuperUser)());let{onMessage:d,onClose:f}=UH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Ar.info)("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function UH(e,t,r,s,n){LH||(LH=!0,ru(d=>{EE>0&&d.push({metric:"mqtt-connections",connections:EE,byThread:!0})}));let i;EE++;let o,c={protocolVersion:4},u=(0,mE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){EE--,i||(i=!0,o?.disconnect(),n.sessions.delete(o),rs(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{s?.then&&(s=await s),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{s=await tt.getUser(d.username,d.password.toString(),r),(0,hE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&DH.notify({username:s.username,status:ln.AUTH_AUDIT_STATUS.SUCCESS,type:ln.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,hE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&DH.error({username:s.username,status:ln.AUTH_AUDIT_STATUS.FAILURE,type:ln.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return rs(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let g=e.deserialize||(e.deserialize=So(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?g(d.will.payload):void 0,delete d.will.payload}o=IH({user:s,...d}),o=await o,n.sessions.add(o)}catch(g){return(0,Ar.error)(g),rs(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:g.code||5,returnCode:g.code||128})}rs(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((g,P,H,v)=>{try{let U=g.indexOf("/",1),Y=U>0?g.slice(0,U):g;f({cmd:"publish",topic:g,payload:E(P),messageId:H||Math.floor(Math.random()*1e8),qos:v.qos},Y)}catch(U){(0,Ar.error)(U),o?.disconnect(),n.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let g of d.subscriptions){let P;try{P=(await o.addSubscription(g,g.qos>=1)).qos||0}catch(H){(0,Ar.error)(H),P=c.protocolVersion<5?128:H.statusCode===403?135:H.statusCode===404?143:128}h.push(P)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let g=[];for(let P of d.unsubscriptions)g.push(o.removeSubscription(P)?0:17);f({cmd:"unsuback",granted:g,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=So(r?.headers.get?.("content-type"))),A=d.payload?.length>0?S(d.payload):void 0,R;try{R=await o.publish(d,A)}catch(g){(0,Ar.warn)(g),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:R===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),n.sessions.delete(o),rs(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Ar.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,mE.generate)(h,c);t(S),Hr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ti(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var mE,MH,hE,ln,Ar,DH,PH,LH,EE,vH=Re(()=>{mE=require("mqtt-packet");CH();MH=x(ts());ga();bn();rr();hE=x(Z()),ln=x(L()),Ar=x(V()),DH=(0,Ar.loggerWithTag)("auth-event"),PH=(0,hE.get)(ln.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(sne,"bypassAuth");a(nne,"start");EE=0;a(UH,"onSocket")});var af={};Ye(af,{component_errors:()=>Va,loadComponent:()=>pE,loadComponentDirectories:()=>$H,setErrorReporter:()=>cne});function $H(e,t){t&&(WR=t),e&&(QR=e);let r=[];if((0,Hs.existsSync)(KR)){let n=(0,Hs.readdirSync)(KR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,gt.join)(KR,o);r.push(pE(c,WR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(pE(s,WR,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{VH=!0})}function cne(e){dl=e}async function pE(e,t,r,s,n,i){if(!HH.has(e)){HH.set(e,!0),n&&(QR=n);try{let o;s&&(Va=new Map);let c=(0,gt.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Hs.existsSync)(c)?o=s?(0,kH.getConfigObj)():(0,xH.parseDocument)((0,Hs.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=zR;let u=[],_=s;for(let l in o){let d=o[l];if(Va.set(s?l:(0,gt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let R=e,g;for(;!(0,Hs.existsSync)(g=(0,gt.join)(R,"node_modules",l));)if(R=(0,gt.dirname)(R),R.length<(0,GH.getHdbBasePath)().length){g=null;break}if(g)f=await pE(g,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=ane[l];if(!f)continue;u.push(f);let h=a(R=>(R.origin=r,ct(R)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,A=!p?.https&&p?.port;if(ka.isMainThread&&(f=await f.startOnMainThread?.({server:tt,ensureTable:h,port:A,securePort:S,resources:t,...d})||f,s&&p))for(let R of[A,S])try{if(+R&&!BH.includes(R)){let g=JR.get(jR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&_l.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!Xf)&&(BH.push(R),qB(R,g))}}catch(g){console.error("Error listening on socket",R,g,l)}if(t.isWorker&&(f=await f.start?.({server:tt,ensureTable:h,port:A,securePort:S,resources:t,...d})||f),QR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,FH.handleHDBError)("Can not reference parent directories");let R=(0,gt.join)(e,d.files).replace(/\\/g,"/"),g=R.indexOf("/*");if(g>-1&&d.files!==zR[l]?.files&&!(0,Hs.existsSync)(R.slice(0,g)))throw new Error(`The path '${R.slice(0,g)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let P=(0,gt.basename)(e),H=d.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+P+H.slice(2):H==="."?"/"+P:"/"+P+"/"+H;let v,U,Y;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",U=(0,gt.join)(e,z)}else(Y=R.indexOf("/*"))>-1&&(U=R.slice(0,Y+1),v=(0,gt.relative)(e,U));let K=!1;if(ka.isMainThread&&f.setupDirectory&&(K=await f.setupDirectory?.(H,U,t)),t.isWorker&&f.handleDirectory&&(K=await f.handleDirectory?.(H,U,t)),K)continue;for(let z of await(0,qH.default)(R,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:me}=z;_=!0;let ce=(0,gt.relative)(e,ne).replace(/\\/g,"/");if(v)if(ce.startsWith(v))ce=ce.slice(v.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${ce}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let xe=H+(H.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let le=await one(ne);ka.isMainThread&&await f.setupFile?.(le,xe,ne,t),t.isWorker&&await f.handleFile?.(le,xe,ne,t)}else ka.isMainThread&&await f.setupDirectory?.(xe,ne,t),t.isWorker&&await f.handleDirectory?.(xe,ne,t)}catch(le){le.message=`Could not load ${me.isFile()?"file":"directory"} '${ne}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${le.message}`,dl?.(le),((0,$a.getWorkerIndex)()===0?console:_l.default).error(le),t.set(d.path||"/",new fl(le)),Va.set(s?l:(0,gt.basename)(e),le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,gt.basename)(e)}' due to: ${h.message}`,dl?.(h),((0,$a.getWorkerIndex)()===0?console:_l.default).error(h),t.set(d.path||"/",new fl(h),null,!0),Va.set(s?l:(0,gt.basename)(e),h.message)}}if(ka.isMainThread&&!VH&&i&&(0,$a.watchDir)(e,async()=>$H()),o.extensionModule)return await Ql((0,gt.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;dl?.(new Error(l)),((0,$a.getWorkerIndex)()===0?console:_l.default).error(l),Va.set((0,gt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,dl?.(o),t.set("",new fl(o))}}}var Hs,gt,ka,xH,JR,jR,qH,$a,_l,FH,GH,ine,kH,one,KR,QR,VH,WR,Va,ane,zR,BH,HH,dl,fl,cf=Re(()=>{Hs=require("fs"),gt=require("path"),ka=require("worker_threads"),xH=require("yaml"),JR=x(Z()),jR=x(L());jO();tb();rb();Gv();IB();PB();qH=x(require("fast-glob")),$a=x(Ke()),_l=x(V());yh();rr();FH=x(re());As();Ae();FB();GH=x(Z()),ine=x(YB());Xd();uH();vH();kH=x(Ur());Zf();({readFile:one}=Hs.promises),KR=JR.get(jR.CONFIG_PARAMS.COMPONENTSROOT),QR=new Map,Va=new Map;a($H,"loadComponentDirectories");ane={REST:yf,rest:yf,graphqlSchema:Nh,jsResource:Ih,fastifyRoutes:ER,login:Dh,static:hR,operationsApi:ine,customFunctions:{},http:{},clustering:UR,authentication:Hu,mqtt:YR},zR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(zR,"static",{value:{files:"web/**"}});BH=[],HH=new Map;a(cne,"setErrorReporter");a(pE,"loadComponent");fl=class extends xt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var FR=T((Fpe,KH)=>{var{isMainThread:YH}=require("worker_threads"),{getTables:une}=(Ae(),se(Fe)),{loadComponentDirectories:lne,loadComponent:_ne}=(cf(),se(af)),{resetResources:dne}=(vu(),se(JM)),fne=QT(),Ene=Ur(),{dirname:hne}=require("path"),{getConnection:mne}=st(),pne=Z(),Sne=L(),XR=new Map;async function Tne(e=!1){!YH&&pne.get(Sne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&mne();try{YH&&await fne()}catch(s){console.error(s)}let t=dne();une(),t.isWorker=e,await _ne(hne(Ene.getConfigFilePath()),t,"hdb",!0,XR),await lne(XR,t);let r=[];for(let[s]of XR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Tne,"loadRootComponents");KH.exports.loadRootComponents=Tne});var Ke=T((kpe,Ci)=>{"use strict";var{Worker:gne,MessageChannel:Rne,parentPort:_n,isMainThread:sA,threadId:Ane,workerData:Fn}=require("worker_threads"),{PACKAGE_ROOT:One}=L(),{join:JH,isAbsolute:bne,extname:Nne}=require("path"),{server:jH}=(rr(),se(Mi)),{watch:yne,readdir:wne}=require("fs/promises"),{totalmem:WH}=require("os"),El=L(),XH=Z(),Gn=V(),{randomBytes:Ine}=require("crypto"),{_assignPackageExport:Cne}=require("../index"),Dne=L(),QH=1024*1024,Ii=[],ds=[],Lne=50,nA=1e4,Une="restart",ZH="request_thread_info",ex="resource_report",tx="thread_info",rx="added-port",Mne="ack",ZR;Cne("threads",ds);Ci.exports={startWorker:eA,restartWorkers:oA,shutdownWorkers:xne,workers:Ii,setMonitorListener:Kne,onMessageFromWorkers:qne,onMessageByType:ux,broadcast:Gne,broadcastWithAcknowledgement:Vne,setChildListenerByType:Hne,getWorkerIndex:sx,getWorkerCount:nx,getTicketKeys:ox,setMainIsWorker:vne,setTerminateTimeout:Pne,restartNumber:Fn?.restartNumber||1};ds.onMessageByType=ux;ds.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ds.find(s=>s.threadId===e);if(r)return r.postMessage(t),!0};var iA;function Pne(e){nA=e}a(Pne,"setTerminateTimeout");function sx(){return Fn?Fn.workerIndex:iA?0:void 0}a(sx,"getWorkerIndex");function nx(){return Fn?Fn.workerCount:iA?1:void 0}a(nx,"getWorkerCount");function vne(e){iA=e}a(vne,"setMainIsWorker");var ix=1,SE;function ox(){return SE||(SE=sA?Ine(48):Fn.ticketKeys,SE)}a(ox,"getTicketKeys");Object.defineProperty(jH,"workerIndex",{get(){return sx()}});Object.defineProperty(jH,"workerCount",{get(){return nx()}});var ax={[ZH](e,t){$ne(t)},[ex](e,t){Yne(t,e)}};function eA(e,t={}){let r=process.constrainedMemory?.()||WH();r=Math.min(r,WH(),2e4*QH);let s=XH.get(El.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/QH/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of ds){let _=new Rne;_.existingPort=u,i.push(_),o.push(_.port2)}Nne(e)||(e+=".js");let c=new gne(bne(e)?e:JH(One,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:ix=t.threadCount,name:t.name,restartNumber:Ci.exports.restartNumber,ticketKeys:ox()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:rx,port:u,threadId:c.threadId},[u]);return gE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>eA(e,t),c.on("error",u=>{console.error("Worker error:",u),Gn.error("Worker error:",u)}),c.on("exit",u=>{Ii.splice(Ii.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Lne?(t.unexpectedRestarts=c.unexpectedRestarts+1,eA(e,t)):Gn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{ax[u.type]?.(u,c)}),Ii.push(c),Qne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(eA,"startWorker");var Bne=[El.THREAD_TYPES.HTTP];async function oA(e=null,t=Math.max(ix>3,1),r=!0){if(sA){if(r){let{loadRootComponents:o}=FR();await o()}Ci.exports.restartNumber++,t<1&&(t=t*Ii.length);let s=[],n=[];for(let o of Ii.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Gn.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ci.exports.restartNumber,type:El.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Bne.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),nA*2).unref();o.on("exit",()=>{clearTimeout(l),s.splice(s.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(s.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===Dne.ITC_EVENT_TYPES.CHILD_STARTED&&(Gn.trace("Worker has started",_.threadId),d(),n.splice(n.indexOf(l)),_.off("message",f))},"startListener");Gn.trace("Waiting for worker to start",_.threadId),_.on("message",f)});n.push(l),s.length>=t&&await Promise.race(s),n.length>=t&&await Promise.race(n)}}await Promise.all(s),await Promise.all(n);let{restartService:i}=Wd();r&&(e==="http"||!e)&&XH.get(El.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else _n.postMessage({type:Une,workerType:e})}a(oA,"restartWorkers");function Hne(e,t){ax[e]=t}a(Hne,"setChildListenerByType");function xne(e){return oA(e,1/0,!1)}a(xne,"shutdownWorkers");var cx=[];function qne(e){cx.push(e)}a(qne,"onMessageFromWorkers");var tA=new Map;function ux(e,t){let r=tA.get(e);r||tA.set(e,r=[]),r.push(t)}a(ux,"onMessageByType");var Fne=10;async function Gne(e){let t=0;for(let r of ds)try{r.postMessage(e),t++>Fne&&(t=0,await new Promise(setImmediate))}catch(s){Gn.error("Unable to send message to worker",s)}}a(Gne,"broadcast");var TE=new Map,kne=1;function Vne(e){return new Promise(t=>{let r=0;for(let s of ds)try{let n=kne++,i=a(()=>{TE.delete(n),--r===0&&t(),s!==_n&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,TE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of TE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){Gn.error("Unable to send message to worker",n)}r===0&&t()})}a(Vne,"broadcastWithAcknowledgement");function $ne(e){e.postMessage({type:tx,workers:lx()})}a($ne,"sendThreadInfo");function lx(){let e=Date.now();return Ii.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(lx,"getChildWorkerInfo");function Yne(e,t){e.resources=t,e.resources.updated=Date.now()}a(Yne,"recordResourceReport");var rA;function Kne(e){rA=e}a(Kne,"setMonitorListener");var Wne=1e3,zH=!1;function Qne(){zH||(zH=!0,setInterval(()=>{for(let e of Ii){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}rA&&rA()},Wne).unref())}a(Qne,"startMonitoring");var zne=1e3;if(_n){gE(_n);for(let e=0,t=Fn.addPorts.length;e<t;e++){let r=Fn.addPorts[e];r.threadId=Fn.addThreadIds[e],gE(r)}setInterval(()=>{let e=process.memoryUsage();_n.postMessage({type:ex,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},zne).unref(),ZR=a(()=>new Promise((e,t)=>{_n.on("message",r),_n.postMessage({type:ZH});function r(s){s.type===tx&&(_n.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else ZR=lx;Ci.exports.getThreadInfo=ZR;function gE(e,t){ds.push(e),e.on("message",r=>{if(r.type===rx)r.port.threadId=r.threadId,gE(r.port);else if(r.type===Mne){let s=TE.get(r.id);s&&s()}else{for(let n of cx)n(r,e);let s=tA.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){Gn.error(i)}}}).on("close",()=>{ds.splice(ds.indexOf(e),1)}).on("exit",()=>{ds.splice(ds.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(gE,"addPort");if(sA){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await wne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(JH(s,i.name));try{for await(let{filename:i}of yne(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await oA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");Ci.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else _n.on("message",async e=>{let{type:t}=e;t===El.ITC_EVENT_TYPES.SHUTDOWN&&(Ci.exports.restartNumber=e.restartNumber,_n.unref(),setTimeout(()=>{Gn.warn("Thread did not voluntarily terminate",Ane),process.exit(0)},nA).unref())})});var aC={};Ye(aC,{AUDIT_STORE_OPTIONS:()=>gx,createAuditEntry:()=>Zl,openAuditStore:()=>bE,readAuditEntry:()=>Lt,setAuditRetention:()=>jne,transactionKeyEncoder:()=>Tx});function bE(e){let t=e.auditStore=e.openDB(mx.AUDIT_STORE_NAME,gx);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=RE){clearTimeout(s),s=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-aA})){if((_[0]&15)===lA){let l=Lt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Jne){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,aA/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,OE.getWorkerIndex)()===(0,OE.getWorkerCount)()-1&&n(RE),t}function jne(e,t=RE){aA=e,RE=t}function Zl(e,t,r,s,n,i,o){let c=Rx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?Ya.setFloat64(0,s):Es.set(Wh),u=9),f(0),f(t),d(r),Ya.setFloat64(u,e),u+=8,n?d(n):Es[u++]=0,Es[s?8:0]=c;let l=Es.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Ka.writeKey)(E,Es,u);let p=u-h-1;p>127?p>16383?(dA.error("Key or username was too large for audit entry",E),u=h+1,Es[h]=0):(Es.copyWithin(h+2,h+1,u),Ya.setUint16(h,p|32768),u++):Es[h]=p}function f(E){E<128?Es[u++]=E:E<16384?(Ya.setUint16(u,E|32768),u+=2):E<1056964608?(Ya.setUint32(u,E|3221225472),u+=4):(Es[u]=255,Ya.setUint32(u+1,E),u+=5)}}function Lt(e){try{let t=e.dataView||(e.dataView=new _A(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let s=t.readInt(),n=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:Rx[s&7],tableId:i,get recordId(){return hx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?hx(e,l,d):void 0},getValue(f,E,h){if(s&cA||s&uA&&!E)return f.decoder.decode(e.subarray(t.position));if(s&uA&&h)return fA(f.getEntry(this.recordId),h,f)}}}catch{return dA.error("Reading audit entry error",e),{}}}function hx(e,t,r){let s=e.subarray(t,r);return(0,Ka.readKey)(s,0,r-t)}var Ka,AE,mx,px,OE,Sx,dA,Es,Ya,Tx,gx,aA,Jne,RE,cA,uA,_x,lA,dx,fx,Ex,Rx,_A,Bi=Re(()=>{Ka=require("ordered-binary"),AE=x(Z()),mx=x(dt()),px=x(L()),OE=x(Ke()),Sx=x(J());qo();dA=x(V());NE();(0,AE.initSync)();Es=Buffer.alloc(1024),Ya=new DataView(Es.buffer,Es.byteOffset,1024),Tx={writeKey(e,t,r){return e===gc?(t.set(gc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Ka.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Ka.readKey)(e,t,r)}},gx={encoding:"binary",keyEncoder:Tx},aA=(0,Sx.convertToMS)((0,AE.get)(px.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Jne=1e3,RE=1e4;a(bE,"openAuditStore");a(jne,"setAuditRetention");cA=16,uA=32,_x=1,lA=2,dx=3,fx=4,Ex=5,Rx={put:_x|cA,[_x]:"put",delete:lA,[lA]:"delete",message:dx|cA,[dx]:"message",invalidate:fx,[fx]:"invalidate",patch:Ex|uA,[Ex]:"patch"};a(Zl,"createAuditEntry");a(Lt,"readAuditEntry");_A=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(hx,"readKeySafely")});var EA={};Ye(EA,{add:()=>yE,applyReverse:()=>Ax,getRecordAtTime:()=>fA,rebuildUpdateBefore:()=>wE});function yE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function wE(e,t){let r=null;for(let s in e)if(s in t){let n=t[s];if(n?.__op__){let i=e[s];if(i?.__op__)if(i.__op__===n.__op__)r||(r={}),r[s]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[s]=i,yE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function Ax(e,t){for(let r in t){let s=t[r];if(s?.__op__){let n=Xne[s.__op__]?.reverse;if(n)n(e,r,{value:s.value});else throw new Error(`Unsupported operation ${s.__op__}`)}else e[r]=Ox}}function fA(e,t,r){let s=r.rootStore.auditStore,n=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=s.get(i),_=Lt(u);switch(_.type){case"put":n=_.getValue(r);break;case"patch":Ax(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===Ox&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=s.get(i),_=Lt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(n[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)n[u]=null;return n}var Xne,Ox,NE=Re(()=>{Bi();a(yE,"add");yE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Xne={add:yE};a(wE,"rebuildUpdateBefore");a(Ax,"applyReverse");Ox={};a(fA,"getRecordAtTime")});function $r(e){return e[Ct]||(e[Ct]=Object.create(null))}function UE(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Oe])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a string, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a string, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a number, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new hs.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new hs.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new hs.ClientError(`${c} must be a number, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a boolean, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new hs.ClientError(`${c} must be a Date, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){$r(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be an object, attempt to assign ${l}`);$r(this)[c]=l},"set")}_={get(){let l=this[Ct];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[de]?.[c];return f.update(E)}return f}let d=this[de]?.[c];if(d&&typeof d=="object"){let f=Nx(d,o);if(f)return l||(l=this[Ct]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,s[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Ct];return u?.[o]!==void 0?u[o]:this[de]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new hs.ClientError("Can not add a property to a sealed table schema");$r(this)[o]=c}),i("deleteProperty",function(o){$r(this)[o]=void 0}),i("toJSON",function(){let o=this[Ct],c;for(let _ in o){c||(c=Object.assign({},this[de]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[de])),Object.assign(c,this)),c||this[de]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function Nx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){if(n?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=n}},UE(r,t)),new r(e)):new IE(e);case Array:let s=new DE(e.length);s[de]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=Nx(o,t?.elements)),s[n]=o}return s;default:return e}}function z_(e){let t=e[Ct],r;for(let n in t){r||(r=Object.assign({},e[de]));let i=t[n];if(i&&typeof i=="object")if(i.__op__){let o=r[n];i=i.update(o)}else i=z_(i);r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[de])),Object.assign(r,e)),r||e[de]}function Io(e,t=e[Ct]){let r;if(bx.call(e,de)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=Io(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[s]=i}return Object.freeze(r)}for(let s in t){r||(r=Object.assign({},e[de]));let n=t[s];if(n&&typeof n=="object")if(n.__op__){let i=EA[n?.__op__];if(i)i(r,s,n);else throw new Error("Invalid CRDT operation "+n.__op__);continue}else n=Io(n);r[s]=n}return r?Object.freeze(r):bx.call(e,de)?e[de]:e}function CE(e){let t=e[de];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[wo]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[de]===n){if(CE(i))return!0}else return!0}}else{let r=e[Ct];if(r&&!t)return!0;for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[de]===i){if(CE(n))return!0}else return!0}else return!0}}return!1}var hs,Ct,IE,bx,wo,DE,LE,J_=Re(()=>{As();hs=x(re());NE();Ct=Symbol("own-data");a($r,"getChanges");a(UE,"assignTrackedAccessors");a(Nx,"trackObject");IE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=t}};UE(IE,{});a(z_,"collapseData");bx=Object.prototype.hasOwnProperty;a(Io,"deepFreeze");a(CE,"hasChanges");wo=Symbol.for("has-array-changes"),DE=class extends Array{static{a(this,"TrackedArray")}[wo];constructor(t){super(t)}splice(...t){return this[wo]=!0,super.splice(...t)}push(...t){return this[wo]=!0,super.push(...t)}pop(){return this[wo]=!0,super.pop()}unshift(...t){return this[wo]=!0,super.unshift(...t)}shift(){return this[wo]=!0,super.shift()}};DE.prototype.constructor=Array;LE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Op={};Ye(Op,{CONTEXT:()=>Oe,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>ms,RECORD_PROPERTY:()=>de,Resource:()=>xt,snake_case:()=>eie,transformForSelect:()=>PE});function eie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function yx(e,t){if(hl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(hl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),s=new mA;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){hl=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function Yr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Oe]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Oe]||i):l=i:(l=n,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Oe]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[],_=!0;for(let E of n){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=n.id??null,c==null&&(_=!0))}else c=n??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return Xe(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new ME(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new ME(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Kr(e,t){let r=new Cx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function hA(e,t,r){let s=e[de];if(s){let n=e[Ct];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:n&&i in n?n[i]:(c=t?.[i])?c(e,r):s[i]}}else return t?n=>{let i=t[n];return i?i(e,r):e[n]}:n=>e[n]}function PE(e,t){let r=t?.propertyResolvers,s=t[Oe],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):hA(c,r,s)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(hA(u,r,s));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(hA(u,r,s)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){n||(n={});let u=n[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=n[c.name]=PE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var wx,Ix,Cx,Oe,Le,ms,de,Zne,xt,ME,hl,mA,As=Re(()=>{wx=require("crypto");Ec();Ix=require("../index"),Cx=x(re());J_();Zi();bf();Oe=Symbol.for("context"),Le=Symbol.for("primary-key"),ms=Symbol("is-collection"),de=Symbol("stored-record"),Zne={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},xt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let s=r?.[Oe];this[Oe]=s!==void 0?s:r||null}static get=Yr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=PE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Yr(function(t,r,s,n){if(Array.isArray(n)&&t[ms]){let i=[],o=s.authorize;for(let c of n){let u=t.constructor,_=u.getResource(c[u.primaryKey],s,{async:!0});_.then?i.push(_.then(l=>l.put(c,s))):i.push(_.put(c,s))}return Promise.all(i)}return t.put?t.put(n,r):Kr(t,"put")},{hasContent:!0,type:"update"});static patch=Yr(function(t,r,s,n){return t.patch?t.patch(n,r):Kr(t,"patch")},{hasContent:!0,type:"update"});static delete=Yr(function(t,r,s,n){return t.delete?t.delete(r):Kr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,wx.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),Xe(s,()=>{let i=new this(n,s),o=i.update?i.update(r):Kr(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=Yr(function(t,r,s,n){return t.invalidate?t.invalidate(r):Kr(t,"delete")},{hasContent:!1,type:"update"});static post=Yr(function(t,r,s,n){return t[Le]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Yr(function(t,r,s,n){return t.connect?t.connect(n,r):Kr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Yr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Kr(t,"subscribe")},{type:"read"});static publish=Yr(function(t,r,s,n){return t[Le]!=null&&t.update?.(),t.publish?t.publish(n,r):Kr(t,"publish")},{hasContent:!0,type:"create"});static search=Yr(function(t,r,s,n){let i=t.search?t.search(r):Kr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=PE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Yr(function(t,r,s,n){return t.search?t.search(n,r):Kr(t,"search")},{hasContent:!0,type:"read"});static copy=Yr(function(t,r,s,n){return t.copy?t.copy(n,r):Kr(t,"copy")},{type:"create"});static move=Yr(function(t,r,s,n){return t.move?t.move(n,r):Kr(t,"move")},{type:"delete"});post(t){if(this[ms])return this.constructor.create(this[Le],t,this[Oe]);Kr(this,"post")}static isCollection(t){return t?.[ms]}static coerceId(t){return t}static parseQuery(t){return Of(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let o=t.slice(n+1);t=t.slice(0,n);let c=r?.headers&&Zne[o];if(c)r.headers.set("accept",c);else if(s)s.property=o;else return{query:{property:o},id:yx(t,this),isCollection:hl}}let i=yx(t,this);return hl?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[Oe],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[Le]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[ms]=!0),n}subscribe(t){return new Rs}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Rs}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Le]}getContext(){return this[Oe]}};xt.prototype[Oe]=null;(0,Ix._assignPackageExport)("Resource",xt);a(eie,"snake_case");ME=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(yx,"pathToId");mA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Yr,"transactional");a(Kr,"missingMethod");a(hA,"selectFromObject");a(PE,"transformForSelect")});function Lx(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;Wa||((0,vE.onMessageByType)(Dx,l=>{Ux(l.path)}),Wa=Object.create(null));let o=Wa[n]||(Wa[n]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Ta(t);let u=new SA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function Ux(e,t){if(!Wa)return;let r=Wa[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(n){throw n.message+=" in "+e,n}let s;for(let{key:n,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=n;let o=Lt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Ta(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=n){(0,pA.info)("omitting",u,h.startTime,n);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(s?s.push(h):s=[h]),h.txnInProgress=o.version),h.listener(u,o,n,p)}catch(p){console.error(p),(0,pA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(s)for(let n of s)n.txnInProgress=null,n.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Mx(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",()=>{(0,vE.broadcast)({type:Dx,path:n}),Ux(n,!0)})}}var pA,vE,Dx,Wa,lSe,SA,Px=Re(()=>{pA=x(V()),vE=x(Ke());Ec();vu();Bi();Dx="transaction",lSe=Buffer.alloc(4096);a(Lx,"addSubscription");SA=class extends Rs{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(Ux,"notifyFromTransactionData");a(Mx,"listenToCommits")});var jg={};Ye(jg,{coerceType:()=>BE,makeTable:()=>qE,setServerUtilities:()=>uie,updateResource:()=>HE});function qE(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:p}=e;p||(p=[]),Mx(i,u);let S=Jh(i,s,u),A=0,R,g,P={},H=Promise.resolve(),v,U,Y;for(let W of p)(W.assignCreatedTime||W.name==="__createdtime__")&&(v=W),(W.assignUpdatedTime||W.name==="__updatedtime__")&&(U=W),W.expiresAt&&(Y=W),W.isPrimaryKey&&(P=W);let K,z=[],ne=[],me=1,ce=2,xe={},le={},Dt=864e5,Ul,Ml,$n,qA=!1,rh,xq=i.getRange({start:!1,end:!1}).constructor,qq=10,Fq=6;E&&kA();class ze extends xt{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=v;static updatedTimeProperty=U;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),g=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(D=>{let y=this.sources.slice(0,-1);if(y=y.filter(M=>M[D]&&(!M[D].reliesOnPrototype||M.prototype[D])),y.length>0)if(y.length===1){let M=y[0];return(G,C,B)=>{if(G?.source!==M)return M[D](C,B,G)}}else return(M,G,C)=>{let B=[];for(let F of y){if(M?.source===F)break;B.push(F[D](G,C,M))}return Promise.all(B)}},"getApplyToIntermediateSource"),N=this.sources[this.sources.length-1],b=a(D=>{if(N[D]&&(!N[D].reliesOnPrototype||N.prototype[D]))return(y,M,G)=>{if(!y?.source)return N[D](M,G,y)}},"getApplyToCanonicalSource");return xe={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},le={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let D=!1,y=a(async(M,G)=>{let C=M.value,B=M.table?rt[c][M.table]:ze;if(c===qs.SYSTEM_SCHEMA_NAME&&(M.table===qs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||M.table===qs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),M.id===void 0&&(M.id=C[B.primaryKey],M.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(M));M.source=m;let F=await B.getResource(M.id,G,Qa);switch(M.type){case"put":return F._writeUpdate(C,!0,Qa);case"patch":return F._writeUpdate(C,!1,Qa);case"delete":return F._writeDelete(Qa);case"publish":return F._writePublish(C,Qa);case"invalidate":return F.invalidate(Qa);default:Ze.error("Unknown operation",M.type,M.id)}},"writeUpdate");try{let M=m.subscribe;M&&h==null&&(h=!0);let G=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Do.getWorkerIndex)()):(0,Do.getWorkerIndex)()===0,C=M&&G&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let B;for await(let F of C)try{if(!(F.type==="transaction"?F.writes[0]:F)){Ze.error("Bad subscription event",F);continue}if(F.source=m,B)if(F.beginTxn)B.resolve();else{y(F,B);continue}if(F.type==="end_txn")continue;let be=Xe(F,()=>{if(F.type==="transaction"){let ee=[];for(let Me of F.writes)try{ee.push(y(Me,F))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Me)+" of event "+JSON.stringify(F),ae}return Promise.all(ee)}else if(F.type==="define_schema"){let ee=this.attributes.slice(0),Me;for(let ae of F.attributes)ee.find(qe=>qe.name===ae.name)||(ee.push(ae),Me=!0);Me&&(ct({table:n,database:c,attributes:ee,origin:"cluster"}),Al.signalSchemaChange(new Ol.SchemaEventMsg(process.pid,qs.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return F.beginTxn?(B=F,y(F,F),new Promise(ee=>{B.resolve=ee})):y(F,F)});D&&(await be,Al.signalUserChange(new Ol.UserEventMsg(process.pid))),F.onCommit&&(be?.then?be.then(F.onCommit):F.onCommit())}catch(oe){Ze.error("error in subscription handler",oe)}}}catch(M){Ze.error(M)}})(),this}static getResource(m,O,w){let N=super.getResource(m,O,w);if(m!=null){Za(m);try{if(N.hasOwnProperty(de))return N;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!w?.async||i.cache?.get(m),D=Ts(O),y=D.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return sh(m,O,{transaction:y},b,M=>{if(M?HE(N,M):N[de]=null,O.onlyIfCached&&O.noCacheStore){if(!N.doesExist())throw new ps.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let G=nh(m,M,O,N);if(G)return D?.disregardReadTxn(),N[TA]=!0,RA(G,C=>(HE(N,C),N))}return N})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return N}ensureLoaded(){let m=nh(this[Le],this[Wr],this[Oe]);if(m)return this[TA]=!0,RA(m,O=>{this[Wr]=O,this[de]=O.value,this[gl]=O.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,Dt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");Dt=Dt||(d+f)/4,oh()}static enableAuditing(m=!0){E=m,m&&kA(),ze.audit=m}static coerceId(m){return m===""?null:BE(m,P)}static async dropTable(){if(delete rt[c][n],c===o){for(let m of p)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Al.signalSchemaChange(new Ol.SchemaEventMsg(process.pid,qs.OPERATIONS_ENUM.DROP_TABLE,c,n))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[ms])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let O=ze.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:n,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Oe]?.returnNonexistent)return this}allowRead(m,O){let w=vl(m);if(w?.read){if(w.isSuperUser)return!0;let N=w.attribute_permissions,b=O?.select;if(N?.length>0||qA&&b){if(O||(O={}),b){let D=N?.length>0&&gA(N,"read");O.select=b.map(y=>{let M=y.name||y;if(!D||D[M]){let G=$n[M]?.definition?.tableClass;if(G){if(y.name||(y={name:y}),!G.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else O.select=N.filter(D=>D.read&&!$n[D.attribute_name]).map(D=>D.attribute_name);return O}else return!0}}allowUpdate(m,O){let w=vl(m);if(w?.update){let N=w.attribute_permissions;if(N?.length>0){let b=gA(N,"update");for(let D in O)if(!b[D])return!1;for(let D of N){let y=D.attribute_name;!D.update&&!(y in O)&&(O[y]=this.getProperty(y))}}return!0}}allowCreate(m,O){if(this[ms]){let w=vl(m);if(w?.insert){let N=w.attribute_permissions;if(N?.length>0){let b=gA(N,"insert");for(let D in O)if(!b[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return vl(m)?.delete}update(m,O){if(!Ts(this[Oe]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let N;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[de]={},this[Ct]=m):(N=this[Ct],N&&(m=Object.assign(N,m)),this[Ct]=N=m)),this._writeUpdate(this[Ct],O),this}addTo(m,O){if(typeof O=="number")this[ml]===Bx?this.set(m,(+this.getProperty(m)||0)+O):(this[ml]||this.update(),this.set(m,new LE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let O=this[Oe],w=this[Le];Za(w),Ts(this[Oe]).addWrite({key:w,store:i,invalidated:!0,entry:this[Wr],nodeName:this[Oe]?.nodeName,before:xe.invalidate?.bind(this,O,w),beforeIntermediate:le.invalidate?.bind(this,O,w),commit:(b,D)=>{if(D?.version>b)return;let y=null;for(let M in r)y||(y={}),y[M]=this.getProperty(M);S(w,y,this[Wr],b,pl,E,this[Oe],0,"invalidate")}})}static evict(m,O,w){let N=this.Source,b;if(!((g||E)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==w))){if(g){if(i.hasLock(m,b.version))return;let D;for(let y in r)D||(D={}),D[y]=O[y];if(D)return S(m,D,b,w,Sl,null,null,0,null,!0)}return i.ifVersion(w,()=>{Pl(m,O,null)}),E?S(m,null,b,w,Sl,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=n,m.schema||=c,kx.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,w){let N=this[Oe],b=Ts(N),D=this[Le];Za(D);let y=this[Wr];this[ml]=O?Bx:oie;let M={key:D,store:i,entry:y,nodeName:N?.nodeName,validate:G=>{m||(m=this[Ct]),O||m&&CE(m)?(this.validate(m,!O),N?.source||(U&&(m[U.name]=U.type==="Date"?new Date(G):U.type==="String"?new Date(G).toISOString():G),O&&(t&&m[t]!==D&&(m[t]=D),v&&(y?.value?m[v.name]=y?.value[v.name]:m[v.name]=v.type==="Date"?new Date(G):v.type==="String"?new Date(G).toISOString():G),m=Io(m)))):b.removeWrite(M)},before:O?xe.put?()=>xe.put(N,D,m):null:xe.patch?()=>xe.patch(N,D,m):xe.put?()=>xe.put(N,D,Io(this)):null,beforeIntermediate:O?le.put?()=>le.put(N,D,m):null:le.patch?()=>le.patch(N,D,m):le.put?()=>le.put(N,D,Io(this)):null,commit:(G,C,B)=>{if(B){if(N&&C?.version>(N.lastModified||0)&&(N.lastModified=C.version),this[Wr]=C,C?.value?.[de])throw new Error("Can not assign a record to a record, check for circular references");O||(this[de]=C?.value??null)}this[Ct]=m,this[gl]=G;let F=C?.value,oe=m;if(this[ml]=0,C?.version>=G)if(E){let ae=C.localTime,qe=C.version;for(;oe&&(ae>G||qe>=G&&ae>0);){let te=u.get(ae),j=Lt(te);if(qe=j.version,qe>G){if(j.type==="patch"){let ge=j.getValue(i);oe=wE(oe,ge)}else if(j.type==="put"||j.type==="delete")return}else if(qe===G)return;ae=j.previousLocalTime}}else{if(O)return;oe=wE(oe,F)}let be;if(O?be=oe:(this[de]=F,be=O?oe:Io(this,oe)),this[de]=be,be?.[de])throw new Error("Can not assign a record to a record, check for circular references");let ee;O||(ee=m),Pl(D,F,be);let Me=O?"put":"patch";S(D,be,C,G,0,E,N,N.expiresAt||(d?d+Date.now():0),Me,!1,ee)}};b.addWrite(M)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[ms]){for await(let O of this.search(m))(await ze.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[de]?this._writeDelete(m):!1}_writeDelete(m){let O=Ts(this[Oe]),w=this[Le];Za(w);let N=this[Oe];return O.addWrite({key:w,store:i,resource:this,nodeName:N?.nodeName,before:xe.delete?.bind(this,N,w),beforeIntermediate:le.delete?.bind(this,N,w),commit:(b,D,y)=>{let M=D?.value;y&&(N&&D?.version>(N.lastModified||0)&&(N.lastModified=D.version),HE(this,D)),!(D?.version>b)&&(Pl(this[Le],M),Ze.trace("Write delete entry",w,b),E||h?(S(w,null,this[Wr],b,0,E,this[Oe],0,"delete"),E||oh()):i.remove(this[Le]))}}),!0}search(m){let O=this[Oe],w=Ts(O);if(!m)throw new Error("No query provided");let N=m.conditions;N?N.length===void 0&&(N=N[Symbol.iterator]?Array.from(N):[N]):N=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(N=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(N));let b,D={};function y(j,ge){let Be;switch(ge){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+ge)}let Fs=Be&&{},Yn;for(let $e of j){if($e.conditions){$e.conditions=y($e.conditions,$e.operator);continue}let Bt=$e[0]??$e.attribute,jr=Bt==null?P:Pn(p,Bt);if(jr){if(Be){let Gs=Ps(Bt),Ht=Fs[Gs];Ht?(Ht.push($e),Yn=!0):Fs[Gs]=[$e]}(jr.type||Og[$e.comparator])&&($e[1]===void 0?$e.value=G($e.value,jr):$e[1]=G($e[1],jr))}else if(Bt!=null)throw(0,ps.handleHDBError)(new Error,`${Bt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(Yn)for(let $e in Fs){let Bt=Fs[$e],jr=Bt.length;if(jr>1)for(let Gs=0;Gs<jr;Gs++){let Ht=Bt[Gs];if(Ht.comparator==="ge"||Ht.comparator==="greater_than_equal")for(let Kn=0;Kn<jr;Kn++){let Po=Bt[Kn];(Po.comparator==="le"||Po.comparator==="less_than_equal")&&(Ht.comparator="between",Ht.value=[Ht.value,Po.value],j.splice(j.indexOf(Po),1))}if(Ht.comparator==="equals"||!Ht.comparator){for(let Kn=0;Kn<jr;Kn++)if(Kn!==Gs){let Po=Bt[Kn];j.splice(j.indexOf(Po),1)}break}}}return j}a(y,"prepareConditions");function M(j,ge){if(m.enforceExecutionOrder)return j;for(let Be of j)Be.conditions&&(Be.conditions=M(Be.conditions,Be.operator));return j.length>1&&ge!=="or"?(0,Gx.sortBy)(j,Af(ze)):j}a(M,"orderConditions");function G(j,ge){return Array.isArray(j)?j.map(Be=>BE(Be,ge)):BE(j,ge)}a(G,"coerceTypedValues");let C=m.operator;(N.length>0||C)&&(N=y(N,C));let B=typeof m.sort=="object"&&m.sort,F;if(B&&C!=="or"){let j=B.attribute;if(b=N.find(ge=>Ps(ge.attribute)===Ps(j)),!b){if(!Pn(p,j))throw(0,ps.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);b={attribute:j,comparator:"sort"},N.push(b)}b.descending=!!B.descending}N=M(N,C),B&&(N[0]===b?B.next&&(F={dbOrderedAttribute:B.attribute,attribute:B.next.attribute,descending:B.next.descending,next:B.next.next}):(b&&N.splice(N.indexOf(b),1),F=B));let oe=m.select;if(N.length===0&&(N=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:N,operator:C,postOrdering:F,selectApplied:!!oe};let be=w.useReadTxn(),ee=bg(N,C,ze,be,m,O,(j,ge)=>FA(j,oe,O,be,ge),D),Me=m.ensureLoaded!==!1;F||(ee=te(ee));let ae=ze.transformEntryForSelect(oe,O,be,D,Me,!0),qe=ze.transformToOrderedSelect(ee,oe,F,be,O,ae);function te(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(te,"applyOffset"),F&&(qe=te(qe)),qe.onDone=()=>{qe.onDone=null,w.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(oe){let j=[];for(let ge of oe)ge==="*"?j.push(...p.map(Be=>Be.name)):j.push(ge.name||ge);return j}return p.map(j=>j.name)},qe}static transformToOrderedSelect(m,O,w,N,b,D){let y=new xq;if(w){m=FA(m,O,N,b,null);let M;y.iterate=function(){let C,B=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),F,oe=w.dbOrderedAttribute,be,ee,Me=!0;function ae(te){let j=te.next&&ae(te.next),ge=te.descending;return(Be,Fs)=>{let Yn=ih(Be,te.attribute,N),$e=ih(Fs,te.attribute,N),Bt=ge?(0,Lo.compareKeys)($e,Yn):(0,Lo.compareKeys)(Yn,$e);return Bt===0?j?.(Be,Fs)||0:Bt}}a(ae,"createComparator");let qe=ae(w);return{async next(){let te;if(C)if(te=C.next(),te.done){if(F)return y.onDone&&y.onDone(),te}else return{value:await D.call(this,te.value)};M=[],be&&M.push(be);do if(te=await B.next(),te.done){if(F=!0,M.length)break;return y.onDone&&y.onDone(),te}else{let j=te.value;if(j?.then&&(j=await j),oe){let ge=ih(j,oe,N);if(Me)Me=!1,ee=ge;else if(ge!==ee){ee=ge,be=j;break}}M.push(j)}while(!0);return w.isGrouped,M.sort(qe),C=M[Symbol.iterator](),te=C.next(),te.done?(y.onDone&&y.onDone(),te):{value:await D.call(this,te.value)}},return(){y.onDone&&y.onDone(),B.return()},throw(){y.onDone&&y.onDone(),B.throw()}}};let G=a(C=>{if(typeof O=="object"&&Array.isArray(C.attribute))for(let B=0;B<O.length;B++){let F=O[B],oe;if(F.name===C.attribute[0]){for(oe=F.sort||(F.sort={});oe.next;)oe=oe.next;oe.attribute=C.attribute.slice(1),oe.descending=C.descending}else F===C.attribute[0]&&(O[B]=oe={name:F,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&G(C.next)},"applySortingOnSelect");G(w)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(D);return y}static transformEntryForSelect(m,O,w,N,b,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(B=>B?.key??B,"transform");return m===t?C:m.asArray?B=>[C(B)]:B=>({[t]:C(B)})}let y;b&&g&&!m?.every(C=>{let B;return typeof C=="object"?B=C.name:B=C,r[B]||B===t})&&(y=!0);let M,G=a(function(C){let B;if(C!=null){if(rh=C,B=C.value||C.deref?.(),!B&&(C.key===void 0||C.deref)){if(C=sh(C.key??C,O,{transaction:w,lazy:m?.length<4},this.isSync,F=>F),C?.then)return C.then(G.bind(this));B=C?.value}if(y&&(C.metadataFlags&(pl|Sl)||C.expiresAt&&C.expiresAt<Date.now())){let F=nh(C.key??C,C,O);if(F?.then)return F.then(G)}}if(B==null)return D?Co.SKIP:B;if(m&&!(m[0]==="*"&&m.length===1)){let F,oe=a((ee,Me)=>{let ae;typeof ee=="object"?ae=ee.name:ae=ee;let qe=$n?.[ae],te;if(qe){let j=N?.[ae];if(j)if(j.hasMappings){let Be=qe.from?B[qe.from]:Ps(C.key);te=j.get(Be),te||(te=[])}else te=j.fromRecord?.(B);else te=qe(B,O,C);let ge=a(Be=>{if(Be&&typeof Be=="object"){let Fs=qe.definition?.tableClass||ze;M||(M={});let Yn=M[ae]||(M[ae]=Fs.transformEntryForSelect(ae===ee?null:ee.select||(Array.isArray(ee)?ee:null),O,w,j,b));if(Array.isArray(Be)){let $e=[],Bt=Fs.transformToOrderedSelect(Be,ee.select,typeof ee.sort=="object"&&ee.sort,O,w,Yn)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),jr=a(Ht=>{for(;!Ht.done;){if(Ht?.then)return Ht.then(jr);$e.push(Ht.value),Ht=Bt.next()}Me($e,ae)},"nextValue"),Gs=jr(Bt.next());Gs&&(F||(F=[]),F.push(Gs));return}else if(Be=Yn.call(this,Be),Be?.then){F||(F=[]),F.push(Be.then($e=>Me($e,ae)));return}}Me(Be,ae)},"handleResolvedValue");te?.then?(F||(F=[]),F.push(te.then(ge))):ge(te);return}else te=B[ae],te&&typeof te=="object"&&ae!==ee&&(te=ze.transformEntryForSelect(ee.select||ee,O,w,null)({value:te}));Me(te,ae)},"selectAttribute"),be;if(typeof m=="string")oe(m,ee=>{be=ee});else if(Array.isArray(m))if(m.asArray)be=[],m.forEach((ee,Me)=>{ee==="*"?m[Me]=B:oe(ee,ae=>be[Me]=ae)});else{be={};let ee=m.forceNulls;for(let Me of m)if(Me==="*")for(let ae in B)be[ae]=B[ae];else oe(Me,(ae,qe)=>{ae===void 0&&ee&&(ae=null),be[qe]=ae})}else throw new ps.ClientError("Invalid select"+m);return F?Promise.all(F).then(()=>be):be}return B},"transform");return G}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||ct({table:n,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let O=!m.rawEvents,w=Lx(ze,this[Le]??null,function(y,M,G,C){try{let B=M.getValue?.(i,O);if(!B&&M.type==="patch"&&O){let F=i.getEntry(y);F?.version===M.version?B=F.value:B=M.getValue?.(i,!0,G),M.type="put"}this.send({id:y,timestamp:G,value:B,version:M.version,type:M.type,beginTxn:C})}catch(B){Ze.error(B)}},m.startTime||0,this[ms]);this[ms]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.crossThreads===!1&&(w.crossThreads=!1),m.supportsTransactions&&(w.supportsTransactions=!0);let N=this[Le],b=m.previousCount;b>1e3&&(b=1e3);let D=m.startTime;if(this[ms]){if(D){if(b)throw new ps.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:M}of u.getRange({start:D,exclusiveStart:!0})){let G=Lt(M);if(G.tableId!==s)continue;let C=G.recordId;if(N==null||qx(N,C)){let B=G.getValue(i,O,y);w.send({id:C,timestamp:y,value:B,version:G.version,type:G.type})}w.startTime=y}}else if(b){let y=[];for(let{key:M,value:G}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Lt(G);if(C.tableId!==s)continue;let B=C.recordId;if(N==null||qx(N,B)){let F=C.getValue(i,O,M);if(y.push({id:B,timestamp:M,value:F,version:C.version,type:C.type}),--b<=0)break}}catch(C){Ze.error("Error getting history entry",M,C)}for(let M=y.length;M>0;)w.send(y[--M]);y[0]&&(w.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:M,version:G,localTime:C}of i.getRange({start:N??!1,end:N==null?void 0:[N,Lo.MAXIMUM_KEY],versions:!0}))M&&w.send({id:y,timestamp:C,value:M,version:G,type:"put"})}else{b&&!D&&(D=0);let y=this[Wr]?.localTime;if(y===zh&&(i.cache?.delete(N),this[Wr]=i.getEntry(N),Ze.trace("re-retrieved record",y,this[Wr]?.localTime),y=this[Wr]?.localTime),Ze.trace("Subscription from",D,"from",N,y),D<y){let M=[],G=y;do{let C=u.get(G);if(C){m.omitCurrent=!0;let B=Lt(C),F=B.getValue(i,O,G);O&&(B.type="put"),M.push({id:N,value:F,timestamp:G,...B}),G=B.previousLocalTime}else break;b&&b--}while(G>D&&b!==0);for(let C=M.length;C>0;)w.send(M[--C]);w.startTime=y}!m.omitCurrent&&this.doesExist()&&w.send({id:N,timestamp:y,value:this,version:this[gl],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[de]||this[ml])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let w=Ts(this[Oe]),N=this[Le]||null;Za(N);let b=this[Oe];w.addWrite({key:N,store:i,entry:this[Wr],nodeName:b?.nodeName,validate:()=>{this.validate(m)},before:xe.publish?.bind(this,b,N,m),beforeIntermediate:le.publish?.bind(this,b,N,m),commit:(D,y,M)=>{y===void 0&&h&&!E&&oh(),S(N,y?.value??null,y,y?.version||D,0,!0,b,y?.expiresAt,"message",!1,m)}})}validate(m,O){let w,N=a((b,D,y)=>{if(D.type&&b!=null)if(O&&b.__op__&&(b=b.value),D.properties){typeof b!="object"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be an object${D.type?" ("+D.type+")":""}`);let M=D.properties;for(let G=0,C=M.length;G<C;G++){let B=M[G],F=N(b[B.name],B,y+"."+B.name);F&&(b[B.name]=F)}}else switch(D.type){case"Int":(typeof b!="number"||b>>0!==b)&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(M=>typeof M=="string")||(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a string`);break;case"Boolean":typeof b!="boolean"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(b)){if(D.elements)for(let M=0,G=b.length;M<G;M++){let C=b[M],B=N(C,D.elements,y+"[*]");B&&(b[M]=B)}}else(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a Buffer or Uint8Array`);break}D.nullable===!1&&b==null&&(w||(w=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let b=0,D=p.length;b<D;b++){let y=p[b];if(!y.relationship&&(!O||y.name in m)){let M=N(m[y.name],y,y.name);M&&(m[y.name]=M)}}if(w)throw new ps.ClientError(w.join(". "))}getUpdatedTime(){return this[gl]}wasLoadedFromSource(){return g?!!this[TA]:void 0}static async addAttributes(m){let O=p.slice(0);for(let w of m){if(!w.name)throw new ps.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new ps.ClientError("Attribute names cannot include backticks or forward slashes");O.push(w)}return ct({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static async removeAttributes(m){let O=p.filter(w=>!m.includes(w.name));return ct({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,w=5e3,N=1e3,b;O>w&&!m?.exactCount&&(b=N);let D=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:b}))y!=null&&D++;if(b){let y=D;D=0;for(let{value:Me}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Me!=null&&D++;let M=b*2,G=(D+y)/M,C=Math.pow((D-y+1)/b/2,2)+G*(1-G)/M,B=Math.max(Math.sqrt(C)*O,1),F=Math.round(G*O),oe=Math.max(F-1.96*B,0),be=Math.min(F+1.96*B,O),ee=Math.pow(10,Math.round(Math.log10(B)));return ee>F&&(ee=ee/10),D=Math.round(F/ee)*ee,{recordCount:D,estimatedRange:[Math.round(oe),Math.round(be)]}}return{recordCount:D}}static updatedAttributes(){$n=this.propertyResolvers={$id:(m,O,w)=>({value:w.key}),$updatedtime:(m,O,w)=>w.version,$record:(m,O,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),qA=!0,O.to)m.elements?.definition?($n[m.name]=m.resolve=(w,N,b)=>{let D=w[O.from?O.from:t],y=m.elements.definition.tableClass;return b?Ca({attribute:O.to,value:D},Ts(N).getReadTxn(),!1,y,!1).asArray:y.search([{attribute:O.to,value:D}],N).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${n}" must have an array type referencing a table as the elements`);else if(O.from){let w=m.definition||m.elements?.definition;w?($n[m.name]=m.resolve=(N,b,D)=>{let y=N[O.from];if(y!==void 0){if(m.elements){let M,G=y.map(C=>{let B=D?w.tableClass.primaryStore.getEntry(C,{transaction:Ts(b).getReadTxn()}):w.tableClass.get(C,b);return B?.then&&(M=!0),B});return O.filterMissing?M?Promise.all(G).then(C=>C.filter(Fx)):G.filter(Fx):M?Promise.all(G):G}return D?w.tableClass.primaryStore.getEntry(y,{transaction:Ts(b).getReadTxn()}):w.tableClass.get(y,b)}},m.set=(N,b)=>{if(Array.isArray(b)){let D=b.map(y=>y[Le]||y[w.tableClass.primaryKey]);N[O.from]=D}else{let D=b[Le]||b[w.tableClass.primaryKey];N[O.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.from):console.error(`The relationship property "${m.name}" in table "${n}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${n}" must use either "from" or "to" arguments`)}UE(this,this)}static async deleteHistory(m=0){let O;for(let{key:w,value:N}of u.getRange({start:0,end:m}))await Tl(),Lt(N).tableId===s&&(O=u.remove(w));await O}static async*getHistory(m=0,O=1/0){for(let{key:w,value:N}of u.getRange({start:m,end:O})){await Tl();let b=Lt(N);b.tableId===s&&(yield{id:b.recordId,localTime:w,version:b.version,type:b.type,value:b.getValue(i,!0,w),user:b.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return O;let N=w.localTime;if(!N)throw new Error("The entry does not have a local audit time");let b=0;do{await Tl();let D=u.get(N);if(D){let y=Lt(D);O.push({id:y.recordId,localTime:N,version:y.version,type:y.type,value:y.getValue(i,!0,N),user:y.user}),N=y.previousLocalTime}else break}while(b<1e3&&N);return O.reverse()}static cleanup(){K?.remove()}}ze.updatedAttributes();let Gq=ze.prototype;return Gq[iie]=!0,d&&ze.setTTLExpiration(d/1e3),Y&&kq(),ze;function Pl(W,m,O){let w;for(let N in r){let b=r[N],D=b.isIndexing,y=O?.[N],M=m?.[N];if(y===M&&!D)continue;w=!0;let G=b.indexNulls,C=(0,Rl.getIndexedValues)(M,G);if(C){vx&&b.prefetch(C.map(B=>({key:B,value:W})),xx);for(let B=0,F=C.length;B<F;B++)b.remove(C[B],W)}if(C=(0,Rl.getIndexedValues)(y,G),C){vx&&b.prefetch(C.map(B=>({key:B,value:W})),xx);for(let B=0,F=C.length;B<F;B++)b.put(C[B],W)}}return w}a(Pl,"updateIndices");function Za(W){switch(typeof W){case"number":return!0;case"string":if(W.length<659)return!0;if(W.length>Hx)throw new Error("Primary key size is too large: "+W.length);break;case"object":if(W===null)return!0;break;case"bigint":if(W<2n**64n&&W>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof W)}if((0,Lo.writeKey)(W,aie,0)>Hx)throw new Error("Primary key size is too large: "+W.length);return!0}a(Za,"checkValidId");function sh(W,m,O,w,N){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return N(null,W);let D=i.getEntry(W,O);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),N(D,W)},"whenPrefetched");return w?b():me>0?(me--,b()):new Promise((D,y)=>{me===0?(me--,i.prefetch([W],()=>{M(),G()})):(z.push(W),ne.push(G),z.length>Fq&&(me--,M()));function M(){if(z.length>0){let C=ne;i.prefetch(z,()=>{me===-1?M():me++;for(let B of C)B()}),z=[],ne=[],ce>2&&ce--}else me=ce,ce<qq&&ce++}a(M,"prefetch");function G(){try{D(b())}catch(C){y(C)}}a(G,"load")})}a(sh,"loadLocalRecord");function vl(W){if(!W?.role)return;let m=W.role.permission;if(m.super_user)return cie;let O=m[c],w,N=O?.tables;if(N)return N[n];if(c==="data"&&(w=m[n])&&!w.tables)return w}a(vl,"getTablePermissions");function nh(W,m,O,w){if(g){let N;if(O.noCache?N=!0:(m?(!m.value||m.metadataFlags&(pl|Sl)||m.expiresAt&&m.expiresAt<Date.now())&&(N=!0):N=!0,rs(!N,"cache-hit",n)),N){let b=GA(W,m,O).then(D=>(D?.value?.[de]&&Ze.error("Can not assign a record with a record property"),O&&(D?.version>(O.lastModified||0)&&(O.lastModified=D.version),O.lastRefreshed=Date.now()),D));if(O?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,W)){if(b.catch(D=>Ze.warn(D)),O?.onlyIfCached&&!w.doesExist())throw new ps.ServerError("Entry is not cached",504);return}else return b}}}a(nh,"ensureLoadedFromSource");function Ts(W){let m=W?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new Xi,m.lmdbDb=i,m;m=O}while(!0)}else return new W_}a(Ts,"txnForContext");function ih(W,m,O){if(!W)return;rh=W;let w=W.value||W.deref?.()||(rh=i.getEntry(W.key))?.value;if(typeof m=="object"){let b=$n,D=w;for(let y=0,M=m.length;y<M;y++){let G=m[y],C=b?.[G];D=C&&D?C(D,O,!0)?.value:D?.[G],b=C?.definition?.tableClass?.propertyResolvers}return D}let N=$n[m];return N?N(w,O):w[m]}a(ih,"getAttributeValue");function FA(W,m,O,w,N){let b=N?.length,D={transaction:w,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function M(G,C){let B=G?.value;if(!B)return Co.SKIP;for(let F=0;F<b;F++)if(!y?.includes(F)&&!N[F](B,G))return Co.SKIP;return C!==void 0&&(G.key=C),G}if(a(M,"processEntry"),b>0||!W.hasEntries){let G=W.map(C=>{if(y=null,typeof C=="object"&&C.key!==void 0)return b>0?M(C):C;if(C==null)return Co.SKIP;for(let B=0;B<b;B++){let oe=N[B].idFilter;if(oe){if(!oe(C))return Co.SKIP;y||(y=[]),y.push(B)}}return sh(C,O,D,!1,M)});return Array.isArray(W)&&(G=G.filter(C=>C!==Co.SKIP)),G.hasEntries=!0,G}return W}a(FA,"transformToEntries");async function GA(W,m,O){let w=m?.metadataFlags,N=m?.version,b,D;if(!i.attemptLock(W,N,()=>{clearTimeout(D);let C=i.getEntry(W);!C||!C.value||C.metadataFlags&(pl|Sl)?b(GA(W,i.getEntry(W),O)):b(C)}))return new Promise(C=>{b=C,D=setTimeout(()=>{i.unlock(W,N)},nie)});let y=m?.value,M={requestContext:O,replacingRecord:y,replacingVersion:N,source:null,resourceCache:O?.resourceCache},G=O?.responseHeaders;return new Promise((C,B)=>{let F;RA(Xe(M,async oe=>{let be=performance.now(),ee,Me,ae;try{for(let ge of ze.sources)if(ge.get&&(!ge.get.reliesOnPrototype||ge.prototype.get)&&(M.source=ge,ee=await ge.get(W,M),ee))break;ae=w&pl;let te=M.lastModified||ae&&N;Me=ae||te>N||!y,te||(te=(0,Rl.getNextMonotonicTime)());let j=performance.now()-be;if(Hr(j,"cache-resolution",n),G&&YT(G,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),oe.timestamp=te,d&&!M.expiresAt&&(M.expiresAt=Date.now()+d),ee){if(typeof ee!="object")throw new Error("Only objects can be cached and stored in tables");typeof ee.toJSON=="function"&&(ee=ee.toJSON()),t&&ee[t]!==W&&(ee[t]=W)}F=!0,C({version:te,value:ee})}catch(te){te.message+=` while resolving record ${W} for ${n}`,y&&((te.code==="ECONNRESET"||te.code==="ECONNREFUSED"||te.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(te.statusCode===500||te.statusCode===502||te.statusCode===503||te.statusCode===504))?(C({version:N,value:y}),Ze.trace(te.message,"(returned stale record)")):B(te),M.transaction.abort();return}if(O?.noCacheStore){M.transaction.abort();return}Ts(M).addWrite({key:W,store:i,entry:m,nodeName:"source",commit:(te,j)=>{if(j?.version!==N)return;let ge=Pl(W,y,ee);ee?(le.put?.(M,W,ee),S(W,ee,j,te,0,E&&Me||null,M,M.expiresAt,"put",!!ae)):(le.delete?.(M,W),E||h?S(W,null,j,te,0,E&&Me||null,M,0,"delete",!!ae):i.remove(W,N))}})}),()=>{i.unlock(W,N)},oe=>{i.unlock(W,N),F&&Ze.error("Error committing cache update",oe)})})}a(GA,"getFromSource");function oh(){if(Dt!==Ul&&(Ul=Dt,(0,Do.getWorkerIndex)()===(0,Do.getWorkerCount)()-1)){if(Ml&&clearTimeout(Ml),!Dt)return;let W=new Date;W.setMonth(0),W.setDate(1),W.setHours(0),W.setMinutes(0),W.setSeconds(0);let m=Math.ceil((Date.now()-W.getTime())/Dt)*Dt+W.getTime(),O=a(w=>{Ze.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),Ml=setTimeout(()=>H=H.then(async()=>{if(O(Math.max(w+Dt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ml);return}let N=50,b=new Array(N),D=0;Ze.trace(`Starting cleanup scan for ${n}`);try{let y=0;for(let{key:M,value:G,version:C,expiresAt:B}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let F;G===null&&!E&&C+sie<Date.now()?F=i.remove(M,C):B&&B+f<Date.now()&&(F=ze.evict(M,G,C),y++),F&&(await b[D],b[D]=F.catch(oe=>{Ze.error("Cleanup error",oe)}),++D>=N&&(D=0)),await Tl()}Ze.trace(`Finished cleanup scan for ${n}, evicted ${y} entries`)}catch(y){Ze.trace(`Error in cleanup scan for ${n}:`,y)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(oh,"scheduleCleanup");function kA(){K=u?.addDeleteRemovalCallback(s,W=>{let m=i.getEntry(W);m?.value===null&&i.remove(W,m.version)})}a(kA,"addDeleteRemoval");function kq(){(0,Do.getWorkerIndex)()===0&&setInterval(async()=>{try{let W=Y.name,m=r[W];if(!m)throw new Error(`expiresAt attribute ${Y} must be indexed`);for(let{value:O}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let w=i.getEntry(O);w?.value?.[W]<Date.now()&&ze.evict(O,w.value,w.version),await Tl()}}catch(W){Ze.error("Error in evicting old records",W)}},rie).unref()}a(kq,"runRecordExpirationEviction")}function gA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function xx(){}function uie(e){kx=e}function BE(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?(typeof e!="number"&&!lie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,xE.autoCast)(e):e}function qx(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}function RA(e,t,r){return e?.then?e.then(t,r):t(e)}function HE(e,t){e[Wr]=t,e[de]=t?.value??null,e[gl]=t?.version}function Fx(e){return e!=null}function xs(e){try{return JSON.stringify(e)}catch{return e}}var qs,Co,Rl,Gx,bl,ps,Al,Ol,Ze,Lo,Do,xE,tie,kx,rie,sie,vx,nie,gl,iie,Wr,ml,Bx,oie,TA,Qa,pl,Sl,aie,Hx,cie,ISe,lie,Tl,xf=Re(()=>{qs=x(L()),Co=require("lmdb"),Rl=x(yr()),Gx=require("lodash");As();$p();bl=x(Z());Px();ps=x(re()),Al=x(gn()),Ol=x(Is());Ae();bf();Ze=x(V());J_();Zi();Lo=require("ordered-binary"),Do=x(Ke());Bi();xE=x(J());qo();bn();NE();Bu();tie=new Uint8Array(9);tie[8]=192;rie=6e4,sie=864e5;bl.initSync();vx=bl.get(qs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),nie=1e4,gl=Symbol.for("version"),iie=Symbol.for("incremental-update"),Wr=Symbol("entry"),ml=Symbol("is-saving"),Bx=1,oie=2,TA=Symbol("loaded-from-source"),Qa={isNotification:!0,ensureLoaded:!1},pl=1,Sl=8,aie=Buffer.allocUnsafeSlow(8192),Hx=1978,cie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},ISe=(0,xE.convertToMS)(bl.get(qs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(qE,"makeTable");a(gA,"attributesAsObject");a(xx,"noop");a(uie,"setServerUtilities");lie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(BE,"coerceType");a(qx,"isDescendantId");Tl=a(()=>new Promise(setImmediate),"rest");a(RA,"when");a(HE,"updateResource");a(Fx,"exists");a(xs,"stringify")});var Fe={};Ye(Fe,{database:()=>zc,databases:()=>rt,dropDatabase:()=>zp,dropTableMeta:()=>mie,getDatabases:()=>Ds,getTables:()=>_ie,onUpdatedTable:()=>MR,readMetaDb:()=>Nl,resetDatabases:()=>die,table:()=>ct,tables:()=>wr});function _ie(){return $E||Ds(),wr||{}}function Ds(){if($E)return rt;$E=!0,ja=new Map;let e=(0,Xt.getHdbBasePath)()&&(0,et.join)((0,Xt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),t=(0,Xt.get)(zr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Xt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Qr.existsSync)(e)?e:(0,et.join)((0,Xt.getHdbBasePath)(),zr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Qr.existsSync)(e))for(let r of(0,Qr.readdirSync)(e,{withFileTypes:!0})){let s=(0,et.basename)(r.name,".mdb");r.isFile()&&(0,et.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Nl((0,et.join)(e,r.name),null,s)}if((0,Qr.existsSync)((0,Ja.getBaseSchemaPath)())){for(let r of(0,Qr.readdirSync)((0,Ja.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,et.join)((0,Ja.getBaseSchemaPath)(),r.name),n=(0,et.join)((0,Ja.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Qr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,et.extname)(i.name).toLowerCase()===".mdb"){let o=(0,et.join)(n,i.name);Nl((0,et.join)(s,i.name),(0,et.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,Qr.existsSync)(n))for(let o of(0,Qr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,et.extname)(o.name).toLowerCase()===".mdb"&&Nl((0,et.join)(n,o.name),(0,et.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,et.join)(c.path,(0,et.basename)(o+".mdb"));(0,Qr.existsSync)(u)&&Nl(u,o,r,null,!0)}}for(let r in rt){let s=ja.get(r);if(s){let n=rt[r];r.includes("delete")&&Ss.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Ss.trace(`delete table class ${i}`),delete n[i])}else if(delete rt[r],r==="data"){for(let n in wr)delete wr[n];delete wr[YE]}}return ja=null,rt}}function die(){$E=!1;for(let[,e]of Di)e.needsDeletion=!0;Ds();for(let[e,t]of Di)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Di.delete(e));return rt}function Nl(e,t,r=bA,s,n){let i=new AA.default(e,!1);try{let o=Di.get(e);o?o.needsDeletion=!1:(o=(0,GE.open)(i),Di.set(e,o));let c=new Uo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(FE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,Qr.existsSync)(s)&&(i.path=s,_=(0,GE.open)(i),_.isLegacy=!0):_=bE(o));let l=Kx(r),d=l[YE],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[p,S]=E.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let A=f.get(p);A||f.set(p,A={attributes:[]}),(S==null||h.is_hash_attribute)&&(A.primary=h),S!=null&&A.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let z of p)if(z.is_hash_attribute||z.isPrimaryKey){S=z;break}if(!S){Ss.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let A=l[E],R={},g=[],P,H,v=typeof S.audit=="boolean"?S.audit:(0,Xt.get)(zr.CONFIG_PARAMS.LOGGING_AUDITLOG),U=S.trackDeletes,Y=S.expiration,K=S.eviction;if(A)R=A.indices,g=A.attributes,A.schemaVersion++;else{P=S.tableId,P?P>=(u.get(za)||0)&&u.putSync(za,P+1):(S.tableId=P=u.get(za),P||(P=1),u.putSync(za,P+1),u.putSync(S.key,S));let z=new Uo.default(!S.is_hash_attribute,S.is_hash_attribute);H=t_(o.openDB(S.key,z)),H.rootStore=o,H.tableId=P}for(let z of p){z.attribute=z.name;try{if(!z.is_hash_attribute&&(z.indexed||z.attribute&&!z.name)){if(!R[z.name]){let me=new Uo.default(!z.is_hash_attribute,z.is_hash_attribute);R[z.name]=o.openDB(z.key,me),R[z.name].indexNulls=z.indexNulls}let ne=g.find(me=>me.name===z.name);ne?g.splice(g.indexOf(ne),1,z):g.push(z)}}catch(ne){Ss.error("Error trying to update attribute",z,g,R,ne)}}if(!A){A=Wx(l,E,qE({primaryStore:H,auditStore:_,audit:v,expirationMS:Y&&Y*1e3,evictionMS:K&&K*1e3,trackDeletes:U,tableName:E,tableId:P,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),A.schemaVersion=1;for(let z of NA)z(A)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Kx(e){let t=rt[e];if(t||(e==="data"?t=rt[e]=wr:e==="system"?Object.defineProperty(rt,"system",{value:t=Object.create(null),configurable:!0}):t=rt[e]=Object.create(null)),ja&&!ja.has(e)){let r=new Set;t[YE]=r,ja.set(e,r)}return t}function Wx(e,t,r){return e[t]=r,r}function zc({database:e,table:t}){e||(e=bA),Ds();let r=Kx(e),s=(0,et.join)((0,Xt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),n=(0,Xt.get)(zr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(n.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&n[e]?.tables?.[t]?.path;s=i||n[e]?.path||process.env.STORAGE_PATH||(0,Xt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||((0,Qr.existsSync)(s)?s:(0,et.join)((0,Xt.getHdbBasePath)(),zr.LEGACY_DATABASES_DIR_NAME));let o=(0,et.join)(s,(i?t:e)+".mdb"),c=Di.get(o);if(!c){let u=new AA.default(o,!1);c=(0,GE.open)(u),Di.set(o,c)}return c}async function zp(e){if(!rt[e])throw new Error("Schema does not exist");let t=rt[e];for(let r in t){let n=t[r].primaryStore.rootStore;Di.delete(n.path),n.status==="open"&&(await n.close(),await Vx.remove(n.path))}if(e==="data"){for(let r in wr)delete wr[r];delete wr[YE]}delete rt[e]}function ct({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=bA);let l=zc({database:t,table:e}),d=rt[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,p,S;u==null&&(u=!0);let A=new Uo.default(!1);for(let U of i)U.attribute?(U.name=U.attribute,U.indexed=!0):U.attribute=U.name,U.expiresAt&&(U.indexed=!0);let R,g;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let U=l.auditStore;U||(U=bE(l)),h=i.find(ne=>ne.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Xt.get)(zr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),s&&(h.eviction=s),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),Ss.trace(`${e} table loading, opening primary store`);let Y=new Uo.default(!1,!0),K=e+"/",z=t_(l.openDB(K,Y));z.rootStore=l,S=l.dbisDb=l.openDB(FE.INTERNAL_DBIS_NAME,A),z.tableId=S.get(za),z.tableId||(z.tableId=1),S.putSync(za,z.tableId+1),h.tableId=z.tableId,f=Wx(d,e,qE({primaryStore:z,auditStore:U,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:s&&s*1e3,primaryKey:E,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,R=!0,v(),S.put(K,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(FE.INTERNAL_DBIS_NAME,A)),f.dbisDB=S;let P=[];for(let{key:U,value:Y}of S.getRange({start:!0})){let[K,z]=U.toString().split("/");if(z===""&&(z=Y.name),z){if(K!==e)continue}else z=K;if(!i.find(me=>me.name===z)?.indexed&&Y.indexed&&!Y.isPrimaryKey){v(),R=!0,S.remove(U);let me=f.indices[K];me&&P.push(me)}}let H=[];try{for(let U of i||[]){if(U.relationship)continue;let Y=e+"/"+(U.name||"");Object.defineProperty(U,"key",{value:Y,configurable:!0});let K=S.get(Y);if(U.isPrimaryKey){if(K=K||S.get(Y=e+"/")||{},o!==f.audit||(+r||void 0)!==(+K.expiration||void 0)||(+s||void 0)!==(+K.eviction||void 0)){let ne=Object.assign({},K);typeof o=="boolean"&&(o&&f.enableAuditing(o),ne.audit=o),r&&(ne.expiration=+r),s&&(ne.eviction=+s),R=!0,v(),S.put(Y,ne)}continue}K?.attribute&&!K.name&&(K.indexed=!0);let z=!K||K.type!==U.type||K.indexed!==U.indexed||K.nullable!==U.nullable||JSON.stringify(K.attributes)!==JSON.stringify(U.attributes)||JSON.stringify(K.elements)!==JSON.stringify(U.elements);if(U.indexed){let ne=new Uo.default(!0,!1),me=l.openDB(Y,ne);(z||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<yl.workerData?.restartNumber)&&(R=!0,v(),K=S.get(Y),(z||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<yl.workerData?.restartNumber)&&(R=!0,U.lastIndexedKey=K?.lastIndexedKey||!1,U.indexingPID=process.pid,me.isIndexing=!0,Object.defineProperty(U,"dbi",{value:me}),U.indexNulls===void 0&&(U.indexNulls=!0),H.push(U)),S.put(Y,U)),K?.indexNulls&&U.indexNulls===void 0&&(U.indexNulls=!0),me.indexNulls=U.indexNulls,p[U.name]=me}else z&&(R=!0,v(),S.put(Y,U))}}finally{g&&g()}if(R&&(f.schemaVersion++,f.updatedAttributes()),Ss.trace(`${e} table loading, running index`),H.length>0||P.length>0?f.indexingOperation=hie(f,H,P):R&&kE.signalSchemaChange(new VE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,R)for(let U of NA)U(f,_!=="cluster");return(r||s||n)&&f.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),Ss.trace(`${e} table loaded`),f;function v(){g||l.transactionSync(()=>({then(U){g=U}}))}a(v,"startTxn")}async function hie(e,t,r){try{let s=e.schemaVersion;await kE.signalSchemaChange(new VE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,n=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,$x.getIndexedValues)(l[h]);if(p)for(let S=0,A=p.length;S<A;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,Ss.error(f)}),yl.workerData&&yl.workerData.restartNumber!==Yx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>fie?await n:u>Eie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,n=e.dbisDB.put(_.key,_)}await n,await kE.signalSchemaChange(new VE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Ss.error("Error in indexing",s)}}function mie({table:e,database:t}){let r=zc({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function MR(e){NA.push(e)}var Xt,FE,GE,et,Qr,Ja,Uo,AA,zr,Vx,OA,$x,kE,VE,yl,Ss,Yx,bA,YE,wr,rt,za,NA,$E,Di,ja,fie,Eie,Ae=Re(()=>{Xt=x(Z()),FE=x(dt()),GE=require("lmdb"),et=require("path"),Qr=require("fs"),Ja=x(Je());xf();Uo=x(r_()),AA=x(n_()),zr=x(L()),Vx=x(require("fs-extra")),OA=require("../index"),$x=x(yr()),kE=x(gn()),VE=x(Is()),yl=require("worker_threads"),Ss=x(V()),Yx=x(Ke());Bi();qo();bA="data",YE=Symbol("defined-tables");(0,Xt.initSync)();wr=Object.create(null),rt=Object.create(null);(0,OA._assignPackageExport)("databases",rt);(0,OA._assignPackageExport)("tables",wr);za=Symbol.for("next-table-id"),NA=[],Di=new Map;a(_ie,"getTables");a(Ds,"getDatabases");a(die,"resetDatabases");a(Nl,"readMetaDb");a(Kx,"ensureDB");a(Wx,"setTable");a(zc,"database");a(zp,"dropDatabase");a(ct,"table");fie=1e3,Eie=10;a(hie,"runIndexing");a(mie,"dropTableMeta");a(MR,"onUpdatedTable")});var J=T((HSe,aq)=>{"use strict";var Li=require("path"),Xx=require("fs-extra"),Or=V(),Qx=require("fs-extra"),KE=require("os"),pie=require("net"),Sie=require("recursive-iterator"),at=L(),Tie=RO(),zx=require("papaparse"),WE=require("moment"),{inspect:gie}=require("util"),Jx=require("is-number"),BSe=require("lodash"),Rie=require("minimist"),Aie=require("https"),Oie=require("http"),{hdb_errors:QE}=re(),bie=/^((\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)))$/,Zx=require("util").promisify(setTimeout),Nie=100,yie=5,wie="",Iie=4,jx={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};aq.exports={isEmpty:Jr,isEmptyOrZeroLength:dn,arrayHasEmptyValues:Lie,arrayHasEmptyOrZeroLengthValues:Uie,buildFolderPath:Mie,isBoolean:eq,errorizeMessage:Cie,stripFileExtension:vie,autoCast:Bie,autoCastJSON:tq,autoCastJSONDeep:wA,removeDir:Hie,compareVersions:xie,isCompatibleDataVersion:qie,escapeRawValue:Fie,unescapeValue:Gie,stringifyProps:kie,timeoutPromise:$ie,isClusterOperation:Kie,getClusterUser:Qie,checkGlobalSchemaTable:Wie,getHomeDir:sq,getPropsFilePath:Vie,promisifyPapaParse:zie,removeBOM:nq,createEventPromise:Jie,checkProcessRunning:jie,checkSchemaTableExist:Xie,checkSchemaExists:iq,checkTableExists:oq,getStartOfTomorrowInSeconds:Zie,getLimitKey:eoe,isObject:Pie,isNotEmptyAndHasValue:Die,autoCasterIsNumberCheck:rq,backtickASTSchemaItems:toe,isPortTaken:Yie,createForkArgs:roe,autoCastBoolean:soe,async_set_timeout:Zx,getTableHashAttribute:noe,doesSchemaExist:ioe,doesTableExist:ooe,stringifyObj:aoe,ms_to_time:coe,changeExtension:uoe,getEnvCliRootPath:IA,noBootFile:loe,httpRequest:_oe,transformReq:doe,convertToMS:foe,PACKAGE_ROOT:at.PACKAGE_ROOT};function Cie(e){return e instanceof Error?e:new Error(e)}a(Cie,"errorizeMessage");function Jr(e){return e==null}a(Jr,"isEmpty");function Die(e){return!Jr(e)&&(e||e===0||e===""||eq(e))}a(Die,"isNotEmptyAndHasValue");function dn(e){return Jr(e)||e.length===0||e.size===0}a(dn,"isEmptyOrZeroLength");function Lie(e){if(Jr(e))return!0;for(let t=0;t<e.length;t++)if(Jr(e[t]))return!0;return!1}a(Lie,"arrayHasEmptyValues");function Uie(e){if(dn(e))return!0;for(let t=0;t<e.length;t++)if(dn(e[t]))return!0;return!1}a(Uie,"arrayHasEmptyOrZeroLengthValues");function Mie(...e){try{return e.join(Li.sep)}catch{console.error(e)}}a(Mie,"buildFolderPath");function eq(e){return Jr(e)?!1:e===!0||e===!1}a(eq,"isBoolean");function Pie(e){return Jr(e)?!1:typeof e=="object"}a(Pie,"isObject");function vie(e){return dn(e)?wie:e.slice(0,-Iie)}a(vie,"stripFileExtension");function Bie(e){return Jr(e)||e===""||typeof e!="string"?e:jx[e]!==void 0?jx[e]:rq(e)===!0?Number(e):bie.test(e)?new Date(e):e}a(Bie,"autoCast");function tq(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(tq,"autoCastJSON");function wA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=wA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=wA(r);s!==r&&(e[t]=s)}return e}else return tq(e)}a(wA,"autoCastJSONDeep");function rq(e){if(e.startsWith("0.")&&Jx(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Jx(e))}a(rq,"autoCasterIsNumberCheck");async function Hie(e){if(dn(e))throw new Error(`Directory path: ${e} does not exist`);try{await Qx.emptyDir(e),await Qx.remove(e)}catch(t){throw Or.error(`Error removing files in ${e} -- ${t}`),t}}a(Hie,"removeDir");function xie(e,t){if(dn(e)){Or.info("Invalid current version sent as parameter.");return}if(dn(t)){Or.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(xie,"compareVersions");function qie(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(qie,"isCompatibleDataVersion");function Fie(e){if(Jr(e))return e;let t=String(e);return t==="."?at.UNICODE_PERIOD:t===".."?at.UNICODE_PERIOD+at.UNICODE_PERIOD:t.replace(at.FORWARD_SLASH_REGEX,at.UNICODE_FORWARD_SLASH)}a(Fie,"escapeRawValue");function Gie(e){if(Jr(e))return e;let t=String(e);return t===at.UNICODE_PERIOD?".":t===at.UNICODE_PERIOD+at.UNICODE_PERIOD?"..":String(e).replace(at.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Gie,"unescapeValue");function kie(e,t){if(Jr(e))return Or.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+KE.EOL}!dn(s)&&s[0]===";"?r+=" "+s+n+KE.EOL:dn(s)||(r+=s+"="+n+KE.EOL)}catch{Or.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(kie,"stringifyProps");function sq(){let e;try{e=KE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(sq,"getHomeDir");function Vie(){let e=Li.join(sq(),at.HDB_HOME_DIR_NAME,at.BOOT_PROPS_FILE_NAME);return Xx.existsSync(e)||(e=Li.join(__dirname,"../","hdb_boot_properties.file")),e}a(Vie,"getPropsFilePath");function $ie(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a($ie,"timeoutPromise");async function Yie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=pie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(Yie,"isPortTaken");function Kie(e){try{return at.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Or.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Kie,"isClusterOperation");function Wie(e,t){let r=(Ae(),se(Fe)).getDatabases();if(!r[e])return QE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return QE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Wie,"checkGlobalSchemaTable");function Qie(e,t){if(Jr(t)){Or.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Jr(e)||dn(e)){Or.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){Or.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Or.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Qie,"getClusterUser");function zie(){zx.parsePromise=function(e,t,r){return new Promise(function(s,n){zx.parse(e,{header:!0,transformHeader:nq,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(zie,"promisifyPapaParse");function nq(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(nq,"removeBOM");function Jie(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Or.info(`Got cluster status event response: ${gie(n)}`);try{i.cancel()}catch{Or.error("Error trying to cancel timeout.")}s(n)})})}a(Jie,"createEventPromise");async function jie(e){let t=!0,r=0;do await Zx(Nie*r++),(await Tie.findPs(e)).length>0&&(t=!1);while(t&&r<yie);if(t)throw new Error(`process ${e} was not started`)}a(jie,"checkProcessRunning");function Xie(e,t){let r=iq(e);if(r)return r;let s=oq(e,t);if(s)return s}a(Xie,"checkSchemaTableExist");function iq(e){let{getDatabases:t}=(Ae(),se(Fe));if(!t()[e])return QE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(iq,"checkSchemaExists");function oq(e,t){let{getDatabases:r}=(Ae(),se(Fe));if(!r()[e][t])return QE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(oq,"checkTableExists");function Zie(){let e=WE().utc().add(1,at.MOMENT_DAYS_TAG).startOf(at.MOMENT_DAYS_TAG).unix(),t=WE().utc().unix();return e-t}a(Zie,"getStartOfTomorrowInSeconds");function eoe(){return WE().utc().format("DD-MM-YYYY")}a(eoe,"getLimitKey");function toe(e){try{let t=new Sie(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){Or.error("Got an error back ticking items."),Or.error(t)}}a(toe,"backtickASTSchemaItems");function roe(e){return[e]}a(roe,"createForkArgs");function soe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(soe,"autoCastBoolean");function noe(e,t){let{getDatabases:r}=(Ae(),se(Fe)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(noe,"getTableHashAttribute");function ioe(e){let{getDatabases:t}=(Ae(),se(Fe));return t()[e]!==void 0}a(ioe,"doesSchemaExist");function ooe(e,t){let{getDatabases:r}=(Ae(),se(Fe));return r()[e]?.[t]!==void 0}a(ooe,"doesTableExist");function aoe(e){try{return JSON.stringify(e)}catch{return e}}a(aoe,"stringifyObj");function coe(e){let t=WE.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(coe,"ms_to_time");function uoe(e,t){let r=Li.basename(e,Li.extname(e));return Li.join(Li.dirname(e),r+t)}a(uoe,"changeExtension");function IA(){if(process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Rie(process.argv);if(e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(IA,"getEnvCliRootPath");var yA;function loe(){if(yA)return yA;let e=IA();IA()&&Xx.pathExistsSync(Li.join(e,at.HDB_CONFIG_FILE))&&(yA=!0)}a(loe,"noBootFile");function _oe(e,t){let r;return e.protocol==="http:"?r=Oie:r=Aie,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(_oe,"httpRequest");function doe(e){if(!e.schema&&!e.database){e.schema=at.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(doe,"transformReq");function foe(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(foe,"convertToMS")});var Z=T((qSe,_q)=>{"use strict";var CA=require("fs-extra"),Mo=require("path"),cq=require("os"),Eoe=require("properties-reader"),Il=V(),wl=J(),ue=L(),zE=Ur(),hoe="Error initializing environment manager",JE="BOOT_PROPS_FILE_PATH",uq=!1,moe={[ue.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},kn={};_q.exports={BOOT_PROPS_FILE_PATH:JE,getHdbBasePath:poe,setHdbBasePath:Soe,get:lq,initSync:goe,setProperty:Ue,initTestEnvironment:Roe};function poe(){return kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(poe,"getHdbBasePath");function Soe(e){kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Soe,"setHdbBasePath");function lq(e){let t=zE.getConfigValue(e);return t===void 0?kn[e]:t}a(lq,"get");function Ue(e,t){moe[e]&&(kn[e]=t),zE.updateConfigObject(e,t)}a(Ue,"setProperty");function Toe(){let e;try{e=wl.getPropsFilePath(),CA.accessSync(e,CA.constants.F_OK|CA.constants.R_OK),uq=!0;let t=Eoe(e);return kn[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),kn[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),kn[JE]=e,!0}catch{return Il.trace(`Environment manager found no properties file at ${e}`),!1}}a(Toe,"doesPropFileExist");function goe(e=!1){try{(uq||Toe()||wl.noBootFile())&&(zE.initConfig(e),kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=zE.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Il.error(hoe),Il.error(t),console.error(t),process.exit(1)}}a(goe,"initSync");function Roe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Mo.join(__dirname,"../../","unitTests");kn[JE]=Mo.join(u,"hdb_boot_properties.file"),Ue(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Mo.join(u,"settings.test")),Ue(ue.HDB_SETTINGS_NAMES.INSTALL_USER,cq.userInfo()?cq.userInfo().username:void 0),Ue(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ue(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Mo.join(u,"envDir","log")),Ue(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Mo.join(u,"envDir")),Ue(ue.CONFIG_PARAMS.STORAGE_PATH,Mo.join(u,"envDir")),n&&(Ue(ue.CONFIG_PARAMS.HTTP_SECUREPORT,lq(ue.CONFIG_PARAMS.HTTP_PORT)),Ue(ue.CONFIG_PARAMS.HTTP_PORT,null)),Ue(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Ue(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ue(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,wl.isEmpty(i)?!1:i),Ue(ue.CONFIG_PARAMS.HTTP_CORS,wl.isEmpty(i)?!1:i),Ue(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ue(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Mo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ue(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,wl.isEmpty(c)?!1:c),o&&(Ue("CORS_ACCESSLIST",o),Ue(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ue(ue.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ue(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ue(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${JE}. Please check your boot props and settings files`;Il.fatal(r),Il.error(t)}}a(Roe,"initTestEnvironment")});var mq=T((GSe,hq)=>{"use strict";var Eq=require("joi"),{string:Cl,boolean:dq,array:Aoe}=Eq.types(),fq=L(),Ooe=je();hq.exports=boe;function boe(e){let t=Eq.object({operation:Cl.valid(fq.OPERATIONS_ENUM.ADD_NODE,fq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Cl.required(),subscriptions:Aoe.items({schema:Cl.required(),table:Cl.optional(),hash_attribute:Cl.optional(),subscribe:dq.required(),publish:dq.required()}).min(1).required()});return Ooe.validateBySchema(e,t)}a(boe,"updateRemoteSourceValidator")});var Dl=T((VSe,pq)=>{"use strict";var DA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};pq.exports=DA});var Aq=T((YSe,Rq)=>{"use strict";var Noe=mq(),Vn=V(),LA=Ge(),Sq=L(),UA=is(),MA=st(),Tq=lu(),yoe=$_(),{Node:woe,NodeSubscription:gq}=di(),PA=Dl(),vA=J(),Ioe=Z(),{cloneDeep:Coe}=require("lodash"),{broadcast:Doe}=Ke();Rq.exports=Loe;async function Loe(e){try{let t=Noe(e);if(t)return Vn.error(`Validation error in updateRemoteSource: ${t.message}`),new PA(LA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=Coe(await UA.getNodeRecord(s)),c=!vA.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Vn.trace(`Existing record found for ${s}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!vA.doesSchemaExist(f)){Vn.trace(`updateRemoteSource creating schema: ${f}`);try{await Tq.createSchema({operation:"create_schema",schema:f})}catch(h){Vn.error(h)}}if(E&&!vA.doesTableExist(f,E)){let h=new yoe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Vn.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await Tq.createTable(h)}catch(p){Vn.error(p)}Vn.trace(`Creating local stream for ${f}.${E}`),await MA.createLocalTableStream(f,E)}if(f===Sq.SYSTEM_SCHEMA_NAME&&await MA.createLocalTableStream(f,E),await MA.updateWorkStream(d,s),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let A=o.subscriptions[p];if(A.schema===f&&A.table===E){A.publish=d.publish,A.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new gq(f,E,d.publish,d.subscribe))}else i.push(new gq(f,E,d.publish,d.subscribe))}c||(o=new woe(s,i,void 0),Vn.trace(`No record found for ${s}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=n,await UA.upsertNodeRecord(u),Doe({type:"nats_update"}),new PA(LA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Ioe.get(Sq.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await UA.getSystemInfo())}catch(t){Vn.error(t);let r=t.message?t.message:t;return new PA(LA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Loe,"updateRemoteSource")});var yq=T((WSe,Nq)=>{"use strict";var bq=require("joi"),{string:Oq}=bq.types(),Uoe=L(),Moe=je();Nq.exports=Poe;function Poe(e){let t=bq.object({operation:Oq.valid(Uoe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:Oq.required()});return Moe.validateBySchema(e,t)}a(Poe,"removeRemoteSourceValidator")});var Iq=T((zSe,wq)=>{"use strict";var voe=yq(),jE=V(),XE=Ge(),BA=L(),Boe=is(),Hoe=J(),xoe=st(),qoe=Z(),ZE=Dl(),{NodeSubscription:Foe}=di(),Goe=ra(),koe=ti(),{broadcast:Voe}=Ke(),$oe=qoe.get(BA.CONFIG_PARAMS.CLUSTERING_NODENAME);wq.exports=Yoe;async function Yoe(e){try{let t=voe(e);if(t)return jE.error(`Validation error in removeRemoteSource: ${t.message}`),new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,s=await Boe.getNodeRecord(r);if(Hoe.isEmptyOrZeroLength(s)){let i=`No record found for node '${r}'`;return jE.error(i),new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}s=s[0];for(let i=0,o=s.subscriptions.length;i<o;i++){let c=s.subscriptions[i];jE.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Foe(c.schema,c.table,!1,!1);await xoe.updateWorkStream(u,r)}let n=new Goe(BA.SYSTEM_SCHEMA_NAME,BA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await koe.deleteRecord(n),Voe({type:"nats_update"}),new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${$oe} successfully removed node '${r}'.`)}catch(t){jE.error(t);let r=t.message?t.message:t;return new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Yoe,"removeRemoteSource")});var Mq=T((jSe,Uq)=>{"use strict";var eh=V(),th=L(),Cq=Ge(),Dq=Z(),Koe=J(),Lq=Dl(),Woe=is(),Qoe=md(),zoe=Cr();Uq.exports=Joe;async function Joe(e){try{eh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Koe.ms_to_time(t),s=new joe(Dq.get(th.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),Dq.get(th.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT),r,await Woe.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new Qoe(th.SYSTEM_SCHEMA_NAME,th.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await zoe.update(i)}catch(n){eh.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return eh.trace("getRemoteSourceConfig response:",s),new Lq(Cq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){eh.error(t);let r=t.message?t.message:t;return new Lq(Cq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Joe,"getRemoteSourceConfig");function joe(e,t,r,s){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=s}a(joe,"ConfigResponseObject")});var Hq=T((ZSe,Bq)=>{"use strict";var Pq=Z();Pq.initSync();var vq=st(),Ll=V(),Xa=L(),HA=Ge(),Xoe=Aq(),Zoe=Iq(),eae=Mq(),tae=Dl(),{encode:rae,decode:sae}=require("msgpackr"),nae=Tn(),iae=Xn(),oae=require("util"),aae=L(),{isMainThread:cae,parentPort:uae}=require("worker_threads");Ke();var lae=oae.promisify(nae.setSchemaDataToGlobal),xA=Pq.get(Xa.CONFIG_PARAMS.CLUSTERING_NODENAME);Bq.exports=_ae;async function _ae(){try{Ll.notify("Starting reply service."),await lae();let e=await vq.getConnection(),t=`${xA}.__request__`,r=e.subscribe(t,{queue:xA});await dae(r)}catch(e){Ll.error(e)}}a(_ae,"initialize");async function dae(e){for await(let t of e){let r=sae(t.data),s;switch(r.operation){case Xa.OPERATIONS_ENUM.ADD_NODE:case Xa.OPERATIONS_ENUM.UPDATE_NODE:s=await Xoe(r);break;case Xa.OPERATIONS_ENUM.REMOVE_NODE:s=await Zoe(r);break;case Xa.OPERATIONS_ENUM.CLUSTER_STATUS:s=await eae(r);break;case Xa.OPERATIONS_ENUM.DESCRIBE_ALL:s=await fae();break;default:let n=`node '${xA}' reply service received unrecognized request operation`;Ll.error(n),s=new tae(HA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}Ll.trace(s),t.respond(rae(s))}}a(dae,"handleRequest");async function fae(){try{return{status:HA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await iae.describeAll()}}catch(e){return Ll.error(e),{status:HA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(fae,"getRemoteDescribeAll");cae||uae.on("message",async e=>{let{type:t}=e;t===aae.ITC_EVENT_TYPES.SHUTDOWN&&vq.closeConnection()})});var Eae=Hq();(async()=>{try{await Eae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
29
|
+
`))}},25).unref()}o.close?.(()=>{if(De.get(gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&_E()==0)try{fH(De.get(gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,uE),o.cantCleanupProperly||jt.warn("Had to forcefully exit the thread",uE),process.exit(0)},5e3).unref()})}if(AH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){jt.info("Could not close debugger",i)}}}).ref();let e=[];if(EH&&!ese)for(let t in us){let r=us[t];if(isNaN(t)&&_E()==0){Yne(t)&&fH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),jt.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=EH(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),jt.trace("Listening on port "+t,uE)}).on("error",i)}))}Promise.all(e).then(()=>{fl?.postMessage({type:gt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(OH,"startServers");SH||OH();function qR(e,t,r){let n=e?.read?e:new Fne({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=us[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=us[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(jt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(qR,"deliverSocket");var mH=new Map;function nse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=mH.get(s),r){case"connection":i=qR(void 0,t),mH.set(s,i),i.write=(c,u,_)=>(fl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(fl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),fl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(nse,"proxyRequest");function FR(e,t,r=!0){!+t&&t!==De.get(gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(De.get(gt.CONFIG_PARAMS.HTTP_PORT),10));let n=us[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",pH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else us[t]=e;e.on("unhandled",pH)}a(FR,"registerServer");function bH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],De.get(gt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:De.get(gt.CONFIG_PARAMS.HTTP_PORT),secure:De.get(gt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),De.get(gt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:De.get(gt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&De.get(gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:De.get(gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(bH,"getPorts");function GR(e,t){for(let{port:r,secure:n}of bH(t))NH(r,n,t?.isOperationsServer),typeof e=="function"?HR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,FR(e,r,!1)),dE[r]=xR(HR,r),tse=xR(rse,r)}a(GR,"httpServer");function NH(e,t,r){if(!wi[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:De.get(n+"_keepAliveTimeout"),headersTimeout:De.get(n+"_headersTimeout"),requestTimeout:De.get(n+"_timeout")},i=De.get(n+"_mtls"),o=De.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=De.get(n+"tls_privateKey"),_=De.get(n+"tls_certificate"),l=De.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:Va(u),ciphers:De.get("tls_ciphers"),cert:Va(_),ca:l&&Va(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:Qne()})}let c=Xne();wi[e]=(t?$ne:kne)(s,async(u,_)=>{try{let d=performance.now(),f=new gH(u,_);r&&(f.isOperationsServer=!0);let E=await dE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=yH(f)}if(c?E.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):E.headers?.set?.("Server","HarperDB"),E.status===-1){for(let H of E.headers||[])_.setHeader(H[0],H[1]);return u.baseRequest=f,_.baseResponse=E,wi[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,g=E.body,A;if(!E.handlesHeaders){let H=E.headers||new TH;g?g.length>=0&&(typeof g=="string"?H.set("Content-Length",Buffer.byteLength(g)):H.set("Content-Length",g.length),A=!0):(H.set("Content-Length","0"),A=!0);let P=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(P+=", miss"),Jne(H,"Server-Timing",P,!0),_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),A&&_.end(g)}let R=f.handlerPath,v=f.method;if(dl(S,"duration",R,v,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),jne(h<400,"success",R,v),!A)if(g?.pipe){g.pipe(_),g.destroy&&_.on("close",()=>{g.destroy()});let H=0;g.on("data",P=>{H+=P.length}),g.on("end",()=>{dl(performance.now()-p,"transfer",R,v),dl(H,"bytes-sent",R,v)})}else g?.then?g.then(H=>{_.end(H)},l):_.end(g)}catch(d){l(d)}function l(d){let f=d.headers;_.writeHead(d.statusCode||500,f&&(f[Symbol.iterator]?Array.from(f):f)),_.end(d.toString()),d.statusCode?d.statusCode===500?jt.warn(d):jt.info(d):jt.error(d)}a(l,"onError")}),i&&(wi[e].mtlsConfig=i),t&&(wi[e].on("secureConnection",u=>{u._parent.startTime&&dl(performance.now()-u._parent.startTime,"tls-handshake",e),dl(u.isSessionReused(),"tls-reused",e)}),wi[e].isSecure=!0),FR(wi[e],e)}return wi[e]}a(NH,"getHTTPServer");function xR(e,t){let r=yH;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(xR,"makeCallbackChain");function yH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new TH}}a(yH,"unhandled");function sse(e,t){GR(e,{requestOnly:!0,...t})}a(sse,"onRequest");function ise(e,t){let r;if(t.securePort){let n=De.get("tls_privateKey"),s=De.get("tls_certificate"),i=t.mtls?.certificateAuthority||De.get("tls_certificateAuthority");r=Wne({ciphers:De.get("tls_ciphers"),key:Va(n),cert:Va(s),ca:i&&Va(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),us[t.securePort]=r}return t.port&&(r=Gne(e),us[t.port]=r),r}a(ise,"onSocket");Object.defineProperty(Vne.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function ose(e,t){let r;for(let{port:n,secure:s}of bH(t)){lE[n]||(lE[n]=new Kne({server:r=NH(n,s)}),lE[n].on("connection",async(c,u)=>{try{let _=new gH(u);_.isWebSocket=!0;let l=dE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=BR[n];if(d){let E;for(let h=0;h<f.length;h++){let p=f[h];p.protocol===d&&(E=!0,p.listener(c,_,l))}if(E)return}for(let E=0;E<f.length;E++){let h=f[E];h.protocol||h.listener(c,_,l)}}catch(_){jt.warn("Error handling WebSocket connection",_)}}),lE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=BR[n];o||(o=BR[n]=[]),o.push({listener:e,protocol:i}),dE[n]=xR(HR,n)}return r}a(ose,"onWebSocket");function pH(e,t){t.writeHead(404),t.end(`Not found
|
|
30
|
+
`)}a(pH,"defaultNotFound")});async function UH({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await VR.get(e,{returnNonexistent:!0});s=new KR(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await VR.get(e);i&&i.delete()}s=new hE(e,t)}return n&&(n.id=e,n.user={username:t?.username},El.put(n)),s}function $R(){return EE++,EE>65500&&(EE=1),EE}function YR(e,t,r=e){let{topic:n,retain:s}=e;e.data=t,e.async=!0,e.authorize=!0;let i=Si.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var IH,Ii,CH,DH,VR,El,EE,hE,KR,LH=ge(()=>{Re();qu();IH=x(yr()),Ii=x($());eo();CH=x(We()),DH=x(wH());rr();VR=ut({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),El=ut({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,CH.getWorkerIndex)()===0&&(async()=>{await DH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of El.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await rt.getUser(r.user.username)),Ze(r,()=>{try{YR(r,t)}catch{(0,Ii.warn)("Failed to publish will",t)}El.delete(e.id,r)})}})();a(UH,"getSession");EE=1;a($R,"getNextMessageId");hE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(g=>g.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Ii.trace)("Resuming subscription from",s,"from",o);let E=Si.getMatch(_);if(!E){let g=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw g.statusCode=404,g}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let g=f.url.slice(1);if(g.indexOf("#")>-1&&g.indexOf("#")!==g.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,g.indexOf("+")===g.length-1)f.onlyChildren=!0,f.url="/"+g.slice(0,g.length-1);else{let A=g.split("/"),R;for(let P=0;P<A.length;P++)if(A[P].indexOf("+")>-1)if(A[P]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&R)throw new Error("Filters can not be combined");let v=!0;A[A.length-1]==="#"&&(A.length--,v=!1),R&&(n=a(P=>{let M=P.id;if(!Array.isArray(M)||v&&M.length!==A.length)return!1;for(let K=0;K<A.length;K++)if(A[K]!=="+"&&A[K]!==M[K])return!1;return!0},"filter"));let H=A.indexOf("+");f.url="/"+(H>-1?A.slice(0,H):A).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Ze(f,async()=>{let g=await p.subscribe(f);if(!g)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!g[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let A of g)try{let R;if(A.type&&A.type!=="put"&&A.type!=="delete"&&A.type!=="message"&&A.type!=="patch"||n&&!n(A))continue;r?(A.topic=s,R=this.needsAcknowledge(A)):(A.acknowledge?.(),R=$R());let v=A.id;Array.isArray(v)&&(v=Ra(v)),v==null&&(v=""),this.listener(h+"/"+v,A.value,R,t)}catch(R){(0,Ii.warn)(R)}})(),g});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=$R();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,YR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Ze(r,async()=>{if(!t){let n=await El.get(this.sessionId,r);n?.doesExist()&&await YR(n,n.data,r)}await El.delete(this.sessionId,r)}).catch(n=>{(0,Ii.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(YR,"publish");KR=class extends hE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=$R(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Ii.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,IH.getNextMonotonicTime)()),(0,Ii.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),VR.put(this.sessionRecord)),t.qos}}});var WR={};Ke(WR,{bypassAuth:()=>ase,start:()=>cse});function ase(){HH=!0}function cse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=vH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Ar.info)("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Ar.error)(E)}else if(u.required)return(0,Ar.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&HH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,BH.getSuperUser)());let{onMessage:d,onClose:f}=vH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Ar.info)("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function vH(e,t,r,n,s){PH||(PH=!0,ou(d=>{mE>0&&d.push({metric:"mqtt-connections",connections:mE,byThread:!0})}));let i;mE++;let o,c={protocolVersion:4},u=(0,SE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){mE--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),rn(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await rt.getUser(d.username,d.password.toString(),r),(0,pE.get)(ls.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&MH.notify({username:n.username,status:ls.AUTH_AUDIT_STATUS.SUCCESS,type:ls.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,pE.get)(ls.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&MH.error({username:n.username,status:ls.AUTH_AUDIT_STATUS.FAILURE,type:ls.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return rn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let R=e.deserialize||(e.deserialize=To(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=UH({user:n,...d}),o=await o,s.sessions.add(o)}catch(R){return(0,Ar.error)(R),rn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}rn(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,v,H,P)=>{try{let M=R.indexOf("/",1),K=M>0?R.slice(0,M):R;f({cmd:"publish",topic:R,payload:E(v),messageId:H||Math.floor(Math.random()*1e8),qos:P.qos},K)}catch(M){(0,Ar.error)(M),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let v;try{v=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(H){(0,Ar.error)(H),v=c.protocolVersion<5?128:H.statusCode===403?135:H.statusCode===404?143:128}h.push(v)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let v of d.unsubscriptions)R.push(o.removeSubscription(v)?0:17);f({cmd:"unsuback",granted:R,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=To(r?.headers.get?.("content-type"))),g=d.payload?.length>0?S(d.payload):void 0,A;try{A=await o.publish(d,g)}catch(R){(0,Ar.warn)(R),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:A===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),rn(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Ar.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,SE.generate)(h,c);t(S),Hr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return gi(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var SE,BH,pE,ls,Ar,MH,HH,PH,mE,xH=ge(()=>{SE=require("mqtt-packet");LH();BH=x(tn());Aa();Ns();rr();pE=x(Z()),ls=x(U()),Ar=x($()),MH=(0,Ar.loggerWithTag)("auth-event"),HH=(0,pE.get)(ls.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(ase,"bypassAuth");a(cse,"start");mE=0;a(vH,"onSocket")});var uf={};Ke(uf,{component_errors:()=>Ya,loadComponent:()=>TE,loadComponentDirectories:()=>WH,setErrorReporter:()=>dse});function WH(e,t){t&&(zR=t),e&&(JR=e);let r=[];if((0,Hn.existsSync)(QR)){let s=(0,Hn.readdirSync)(QR,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Rt.join)(QR,o);r.push(TE(c,zR,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(TE(n,zR,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{KH=!0})}function dse(e){ml=e}async function TE(e,t,r,n,s,i){if(!FH.has(e)){FH.set(e,!0),s&&(JR=s);try{let o;n&&(Ya=new Map);let c=(0,Rt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Hn.existsSync)(c)?o=n?(0,YH.getConfigObj)():(0,GH.parseDocument)((0,Hn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=jR;let u=[],_=n;for(let l in o){let d=o[l];if(Ya.set(n?l:(0,Rt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,R;for(;!(0,Hn.existsSync)(R=(0,Rt.join)(A,"node_modules",l));)if(A=(0,Rt.dirname)(A),A.length<(0,$H.getHdbBasePath)().length){R=null;break}if(R)f=await TE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=_se[l];if(!f)continue;u.push(f);let h=a(A=>(A.origin=r,ut(A)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,g=!p?.https&&p?.port;if($a.isMainThread&&(f=await f.startOnMainThread?.({server:rt,ensureTable:h,port:g,securePort:S,resources:t,...d})||f,n&&p))for(let A of[g,S])try{if(+A&&!qH.includes(A)){let R=XR.get(ZR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&hl.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!eE)&&(qH.push(A),kB(A,R))}}catch(R){console.error("Error listening on socket",A,R,l)}if(t.isWorker&&(f=await f.start?.({server:rt,ensureTable:h,port:g,securePort:S,resources:t,...d})||f),JR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,VH.handleHDBError)("Can not reference parent directories");let A=(0,Rt.join)(e,d.files).replace(/\\/g,"/"),R=A.indexOf("/*");if(R>-1&&d.files!==jR[l]?.files&&!(0,Hn.existsSync)(A.slice(0,R)))throw new Error(`The path '${A.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let v=(0,Rt.basename)(e),H=d.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+v+H.slice(2):H==="."?"/"+v:"/"+v+"/"+H;let P,M,K;if(d.root){let V=d.root;V.startsWith("/")&&(V=V.slice(1)),V.endsWith("/")&&(V=V.slice(0,-1)),V+="/",M=(0,Rt.join)(e,V)}else(K=A.indexOf("/*"))>-1&&(M=A.slice(0,K+1),P=(0,Rt.relative)(e,M));let W=!1;if($a.isMainThread&&f.setupDirectory&&(W=await f.setupDirectory?.(H,M,t)),t.isWorker&&f.handleDirectory&&(W=await f.handleDirectory?.(H,M,t)),W)continue;for(let V of await(0,kH.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:ce,dirent:de}=V;_=!0;let xe=(0,Rt.relative)(e,ce).replace(/\\/g,"/");if(P)if(xe.startsWith(P))xe=xe.slice(P.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${xe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let ae=H+(H.endsWith("/")?"":"/")+xe;try{if(de.isFile()){let Oe=await lse(ce);$a.isMainThread&&await f.setupFile?.(Oe,ae,ce,t),t.isWorker&&await f.handleFile?.(Oe,ae,ce,t)}else $a.isMainThread&&await f.setupDirectory?.(ae,ce,t),t.isWorker&&await f.handleDirectory?.(ae,ce,t)}catch(Oe){Oe.message=`Could not load ${de.isFile()?"file":"directory"} '${ce}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Oe.message}`,ml?.(Oe),((0,Ka.getWorkerIndex)()===0?console:hl.default).error(Oe),t.set(d.path||"/",new pl(Oe)),Ya.set(n?l:(0,Rt.basename)(e),Oe.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Rt.basename)(e)}' due to: ${h.message}`,ml?.(h),((0,Ka.getWorkerIndex)()===0?console:hl.default).error(h),t.set(d.path||"/",new pl(h),null,!0),Ya.set(n?l:(0,Rt.basename)(e),h.message)}}if($a.isMainThread&&!KH&&i&&(0,Ka.watchDir)(e,async()=>WH()),o.extensionModule)return await Jl((0,Rt.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;ml?.(new Error(l)),((0,Ka.getWorkerIndex)()===0?console:hl.default).error(l),Ya.set((0,Rt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,ml?.(o),t.set("",new pl(o))}}}var Hn,Rt,$a,GH,XR,ZR,kH,Ka,hl,VH,$H,use,YH,lse,QR,JR,KH,zR,Ya,_se,jR,qH,FH,ml,pl,lf=ge(()=>{Hn=require("fs"),Rt=require("path"),$a=require("worker_threads"),GH=require("yaml"),XR=x(Z()),ZR=x(U());ZO();nb();sb();$v();UB();HB();kH=x(require("fast-glob")),Ka=x(We()),hl=x($());Ih();rr();VH=x(re());An();Re();VB();$H=x(Z()),use=x(QB());ef();dH();xH();YH=x(Lr());tE();({readFile:lse}=Hn.promises),QR=XR.get(ZR.CONFIG_PARAMS.COMPONENTSROOT),JR=new Map,Ya=new Map;a(WH,"loadComponentDirectories");_se={REST:If,rest:If,graphqlSchema:wh,jsResource:Dh,fastifyRoutes:mR,login:Lh,static:pR,operationsApi:use,customFunctions:{},http:{},clustering:PR,authentication:Gu,mqtt:WR},jR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(jR,"static",{value:{files:"web/**"}});qH=[],FH=new Map;a(dse,"setErrorReporter");a(TE,"loadComponent");pl=class extends xt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var kR=T(($pe,zH)=>{var{isMainThread:QH}=require("worker_threads"),{getTables:fse}=(Re(),ne(Fe)),{loadComponentDirectories:Ese,loadComponent:hse}=(lf(),ne(uf)),{resetResources:mse}=(qu(),ne(ZM)),pse=JT(),Sse=Lr(),{dirname:Tse}=require("path"),{getConnection:gse}=st(),Rse=Z(),Ase=U(),eA=new Map;async function Ose(e=!1){!QH&&Rse.get(Ase.CONFIG_PARAMS.CLUSTERING_ENABLED)&&gse();try{QH&&await pse()}catch(n){console.error(n)}let t=mse();fse(),t.isWorker=e,await hse(Tse(Sse.getConfigFilePath()),t,"hdb",!0,eA),await Ese(eA,t);let r=[];for(let[n]of eA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Ose,"loadRootComponents");zH.exports.loadRootComponents=Ose});var We=T((Kpe,Di)=>{"use strict";var{Worker:bse,MessageChannel:Nse,parentPort:_s,isMainThread:iA,threadId:yse,workerData:Gs}=require("worker_threads"),{PACKAGE_ROOT:wse}=U(),{join:ZH,isAbsolute:Ise,extname:Cse}=require("path"),{server:ex}=(rr(),ne(Pi)),{watch:Dse,readdir:Use}=require("fs/promises"),{totalmem:JH}=require("os"),Sl=U(),tx=Z(),ks=$(),{randomBytes:Lse}=require("crypto"),{_assignPackageExport:Mse}=require("../index"),Pse=U(),jH=1024*1024,Ci=[],fn=[],vse=50,oA=1e4,Bse="restart",rx="request_thread_info",nx="resource_report",sx="thread_info",ix="added-port",Hse="ack",tA;Mse("threads",fn);Di.exports={startWorker:rA,restartWorkers:cA,shutdownWorkers:kse,workers:Ci,setMonitorListener:Jse,onMessageFromWorkers:Vse,onMessageByType:dx,broadcast:Yse,broadcastWithAcknowledgement:Wse,setChildListenerByType:Gse,getWorkerIndex:ox,getWorkerCount:ax,getTicketKeys:ux,setMainIsWorker:qse,setTerminateTimeout:xse,restartNumber:Gs?.restartNumber||1};fn.onMessageByType=dx;fn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=fn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var aA;function xse(e){oA=e}a(xse,"setTerminateTimeout");function ox(){return Gs?Gs.workerIndex:aA?0:void 0}a(ox,"getWorkerIndex");function ax(){return Gs?Gs.workerCount:aA?1:void 0}a(ax,"getWorkerCount");function qse(e){aA=e}a(qse,"setMainIsWorker");var cx=1,gE;function ux(){return gE||(gE=iA?Lse(48):Gs.ticketKeys,gE)}a(ux,"getTicketKeys");Object.defineProperty(ex,"workerIndex",{get(){return ox()}});Object.defineProperty(ex,"workerCount",{get(){return ax()}});var lx={[rx](e,t){Qse(t)},[nx](e,t){zse(t,e)}};function rA(e,t={}){let r=process.constrainedMemory?.()||JH();r=Math.min(r,JH(),2e4*jH);let n=tx.get(Sl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/jH/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of fn){let _=new Nse;_.existingPort=u,i.push(_),o.push(_.port2)}Cse(e)||(e+=".js");let c=new bse(Ise(e)?e:ZH(wse,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:cx=t.threadCount,name:t.name,restartNumber:Di.exports.restartNumber,ticketKeys:ux()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:ix,port:u,threadId:c.threadId},[u]);return AE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>rA(e,t),c.on("error",u=>{console.error("Worker error:",u),ks.error("Worker error:",u)}),c.on("exit",u=>{Ci.splice(Ci.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<vse?(t.unexpectedRestarts=c.unexpectedRestarts+1,rA(e,t)):ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{lx[u.type]?.(u,c)}),Ci.push(c),Xse(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(rA,"startWorker");var Fse=[Sl.THREAD_TYPES.HTTP];async function cA(e=null,t=Math.max(cx>3,1),r=!0){if(iA){if(r){let{loadRootComponents:o}=kR();await o()}Di.exports.restartNumber++,t<1&&(t=t*Ci.length);let n=[],s=[];for(let o of Ci.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Di.exports.restartNumber,type:Sl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Fse.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),oA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===Pse.ITC_EVENT_TYPES.CHILD_STARTED&&(ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");ks.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=zd();r&&(e==="http"||!e)&&tx.get(Sl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else _s.postMessage({type:Bse,workerType:e})}a(cA,"restartWorkers");function Gse(e,t){lx[e]=t}a(Gse,"setChildListenerByType");function kse(e){return cA(e,1/0,!1)}a(kse,"shutdownWorkers");var _x=[];function Vse(e){_x.push(e)}a(Vse,"onMessageFromWorkers");var nA=new Map;function dx(e,t){let r=nA.get(e);r||nA.set(e,r=[]),r.push(t)}a(dx,"onMessageByType");var $se=10;async function Yse(e){let t=0;for(let r of fn)try{r.postMessage(e),t++>$se&&(t=0,await new Promise(setImmediate))}catch(n){ks.error("Unable to send message to worker",n)}}a(Yse,"broadcast");var RE=new Map,Kse=1;function Wse(e){return new Promise(t=>{let r=0;for(let n of fn)try{let s=Kse++,i=a(()=>{RE.delete(s),--r===0&&t(),n!==_s&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,RE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of RE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Wse,"broadcastWithAcknowledgement");function Qse(e){e.postMessage({type:sx,workers:fx()})}a(Qse,"sendThreadInfo");function fx(){let e=Date.now();return Ci.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(fx,"getChildWorkerInfo");function zse(e,t){e.resources=t,e.resources.updated=Date.now()}a(zse,"recordResourceReport");var sA;function Jse(e){sA=e}a(Jse,"setMonitorListener");var jse=1e3,XH=!1;function Xse(){XH||(XH=!0,setInterval(()=>{for(let e of Ci){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}sA&&sA()},jse).unref())}a(Xse,"startMonitoring");var Zse=1e3;if(_s){AE(_s);for(let e=0,t=Gs.addPorts.length;e<t;e++){let r=Gs.addPorts[e];r.threadId=Gs.addThreadIds[e],AE(r)}setInterval(()=>{let e=process.memoryUsage();_s.postMessage({type:nx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Zse).unref(),tA=a(()=>new Promise((e,t)=>{_s.on("message",r),_s.postMessage({type:rx});function r(n){n.type===sx&&(_s.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else tA=fx;Di.exports.getThreadInfo=tA;function AE(e,t){fn.push(e),e.on("message",r=>{if(r.type===ix)r.port.threadId=r.threadId,AE(r.port);else if(r.type===Hse){let n=RE.get(r.id);n&&n()}else{for(let s of _x)s(r,e);let n=nA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){ks.error(i)}}}).on("close",()=>{fn.splice(fn.indexOf(e),1)}).on("exit",()=>{fn.splice(fn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(AE,"addPort");if(iA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await Use(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(ZH(n,i.name));try{for await(let{filename:i}of Dse(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await cA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");Di.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else _s.on("message",async e=>{let{type:t}=e;t===Sl.ITC_EVENT_TYPES.SHUTDOWN&&(Di.exports.restartNumber=e.restartNumber,_s.unref(),setTimeout(()=>{ks.warn("Thread did not voluntarily terminate",yse),process.exit(0)},oA).unref())})});var uC={};Ke(uC,{AUDIT_STORE_OPTIONS:()=>Ox,createAuditEntry:()=>t_,openAuditStore:()=>yE,readAuditEntry:()=>Ut,setAuditRetention:()=>tie,transactionKeyEncoder:()=>Ax});function yE(e){let t=e.auditStore=e.openDB(Tx.AUDIT_STORE_NAME,Ox);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=OE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-uA})){if((_[0]&15)===dA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=eie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,uA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,NE.getWorkerIndex)()===(0,NE.getWorkerCount)()-1&&s(OE),t}function tie(e,t=OE){uA=e,OE=t}function t_(e,t,r,n,s,i,o){let c=bx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Wa.setFloat64(0,n):En.set(zh),u=9),f(0),f(t),d(r),Wa.setFloat64(u,e),u+=8,s?d(s):En[u++]=0,En[n?8:0]=c;let l=En.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Qa.writeKey)(E,En,u);let p=u-h-1;p>127?p>16383?(EA.error("Key or username was too large for audit entry",E),u=h+1,En[h]=0):(En.copyWithin(h+2,h+1,u),Wa.setUint16(h,p|32768),u++):En[h]=p}function f(E){E<128?En[u++]=E:E<16384?(Wa.setUint16(u,E|32768),u+=2):E<1056964608?(Wa.setUint32(u,E|3221225472),u+=4):(En[u]=255,Wa.setUint32(u+1,E),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new fA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:bx[n&7],tableId:i,get recordId(){return Sx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Sx(e,l,d):void 0},getValue(f,E,h){if(n&lA||n&_A&&!E)return f.decoder.decode(e.subarray(t.position));if(n&_A&&h)return hA(f.getEntry(this.recordId),h,f)}}}catch{return EA.error("Reading audit entry error",e),{}}}function Sx(e,t,r){let n=e.subarray(t,r);return(0,Qa.readKey)(n,0,r-t)}var Qa,bE,Tx,gx,NE,Rx,EA,En,Wa,Ax,Ox,uA,eie,OE,lA,_A,Ex,dA,hx,mx,px,bx,fA,Hi=ge(()=>{Qa=require("ordered-binary"),bE=x(Z()),Tx=x(ft()),gx=x(U()),NE=x(We()),Rx=x(J());Go();EA=x($());wE();(0,bE.initSync)();En=Buffer.alloc(1024),Wa=new DataView(En.buffer,En.byteOffset,1024),Ax={writeKey(e,t,r){return e===Ac?(t.set(Ac,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Qa.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Qa.readKey)(e,t,r)}},Ox={encoding:"binary",keyEncoder:Ax},uA=(0,Rx.convertToMS)((0,bE.get)(gx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,eie=1e3,OE=1e4;a(yE,"openAuditStore");a(tie,"setAuditRetention");lA=16,_A=32,Ex=1,dA=2,hx=3,mx=4,px=5,bx={put:Ex|lA,[Ex]:"put",delete:dA,[dA]:"delete",message:hx|lA,[hx]:"message",invalidate:mx,[mx]:"invalidate",patch:px|_A,[px]:"patch"};a(t_,"createAuditEntry");a(Ut,"readAuditEntry");fA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(Sx,"readKeySafely")});var mA={};Ke(mA,{add:()=>IE,applyReverse:()=>Nx,getRecordAtTime:()=>hA,rebuildUpdateBefore:()=>CE});function IE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function CE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,IE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function Nx(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=rie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=yx}}function hA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ut(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":Nx(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===yx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ut(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var rie,yx,wE=ge(()=>{Hi();a(IE,"add");IE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};rie={add:IE};a(CE,"rebuildUpdateBefore");a(Nx,"applyReverse");yx={};a(hA,"getRecordAtTime")});function $r(e){return e[Dt]||(e[Dt]=Object.create(null))}function PE(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Ae])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new hn.ClientError(`${c} must be a string, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new hn.ClientError(`${c} must be a string, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new hn.ClientError(`${c} must be a number, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new hn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new hn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new hn.ClientError(`${c} must be a number, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new hn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new hn.ClientError(`${c} must be a Date, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new hn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){$r(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new hn.ClientError(`${c} must be an object, attempt to assign ${l}`);$r(this)[c]=l},"set")}_={get(){let l=this[Dt];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[_e]?.[c];return f.update(E)}return f}let d=this[_e]?.[c];if(d&&typeof d=="object"){let f=Ix(d,o);if(f)return l||(l=this[Dt]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Dt];return u?.[o]!==void 0?u[o]:this[_e]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new hn.ClientError("Can not add a property to a sealed table schema");$r(this)[o]=c}),i("deleteProperty",function(o){$r(this)[o]=void 0}),i("toJSON",function(){let o=this[Dt],c;for(let _ in o){c||(c=Object.assign({},this[_e]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[_e])),Object.assign(c,this)),c||this[_e]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function Ix(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=s}},PE(r,t)),new r(e)):new DE(e);case Array:let n=new LE(e.length);n[_e]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=Ix(o,t?.elements)),n[s]=o}return n;default:return e}}function j_(e){let t=e[Dt],r;for(let s in t){r||(r=Object.assign({},e[_e]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=j_(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[_e])),Object.assign(r,e)),r||e[_e]}function Co(e,t=e[Dt]){let r;if(wx.call(e,_e)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Co(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[_e]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=mA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Co(s);r[n]=s}return r?Object.freeze(r):wx.call(e,_e)?e[_e]:e}function UE(e){let t=e[_e];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Io]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[_e]===s){if(UE(i))return!0}else return!0}}else{let r=e[Dt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[_e]===i){if(UE(s))return!0}else return!0}else return!0}}return!1}var hn,Dt,DE,wx,Io,LE,ME,X_=ge(()=>{An();hn=x(re());wE();Dt=Symbol("own-data");a($r,"getChanges");a(PE,"assignTrackedAccessors");a(Ix,"trackObject");DE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=t}};PE(DE,{});a(j_,"collapseData");wx=Object.prototype.hasOwnProperty;a(Co,"deepFreeze");a(UE,"hasChanges");Io=Symbol.for("has-array-changes"),LE=class extends Array{static{a(this,"TrackedArray")}[Io];constructor(t){super(t)}splice(...t){return this[Io]=!0,super.splice(...t)}push(...t){return this[Io]=!0,super.push(...t)}pop(){return this[Io]=!0,super.pop()}unshift(...t){return this[Io]=!0,super.unshift(...t)}shift(){return this[Io]=!0,super.shift()}};LE.prototype.constructor=Array;ME=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Np={};Ke(Np,{CONTEXT:()=>Ae,ID_PROPERTY:()=>Ue,IS_COLLECTION:()=>mn,RECORD_PROPERTY:()=>_e,Resource:()=>xt,snake_case:()=>sie,transformForSelect:()=>BE});function sie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Cx(e,t){if(Tl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Tl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new SA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Tl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Yr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Ae]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[Ae]||i):l=i:(l=s,c=l[Ue]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ae]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return Ze(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new vE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new vE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Kr(e,t){let r=new Lx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function pA(e,t,r){let n=e[_e];if(n){let s=e[Dt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function BE(e,t){let r=t?.propertyResolvers,n=t[Ae],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):pA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(pA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(pA(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=BE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var Dx,Ux,Lx,Ae,Ue,mn,_e,nie,xt,vE,Tl,SA,An=ge(()=>{Dx=require("crypto");mc();Ux=require("../index"),Lx=x(re());X_();eo();yf();Ae=Symbol.for("context"),Ue=Symbol.for("primary-key"),mn=Symbol("is-collection"),_e=Symbol("stored-record"),nie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},xt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ue]=t;let n=r?.[Ae];this[Ae]=n!==void 0?n:r||null}static get=Yr(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=BE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Yr(function(t,r,n,s){if(Array.isArray(s)&&t[mn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Kr(t,"put")},{hasContent:!0,type:"update"});static patch=Yr(function(t,r,n,s){return t.patch?t.patch(s,r):Kr(t,"patch")},{hasContent:!0,type:"update"});static delete=Yr(function(t,r,n,s){return t.delete?t.delete(r):Kr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,Dx.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),Ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r):Kr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=Yr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Kr(t,"delete")},{hasContent:!1,type:"update"});static post=Yr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Yr(function(t,r,n,s){return t.connect?t.connect(s,r):Kr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Yr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Kr(t,"subscribe")},{type:"read"});static publish=Yr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.publish?t.publish(s,r):Kr(t,"publish")},{hasContent:!0,type:"create"});static search=Yr(function(t,r,n,s){let i=t.search?t.search(r):Kr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=BE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Yr(function(t,r,n,s){return t.search?t.search(s,r):Kr(t,"search")},{hasContent:!0,type:"read"});static copy=Yr(function(t,r,n,s){return t.copy?t.copy(s,r):Kr(t,"copy")},{type:"create"});static move=Yr(function(t,r,n,s){return t.move?t.move(s,r):Kr(t,"move")},{type:"delete"});post(t){if(this[mn])return this.constructor.create(this[Ue],t,this[Ae]);Kr(this,"post")}static isCollection(t){return t?.[mn]}static coerceId(t){return t}static parseQuery(t){return Nf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&nie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:Cx(t,this),isCollection:Tl}}let i=Cx(t,this);return Tl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ae],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Ue]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Ue],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[mn]=!0),s}subscribe(t){return new Rn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Rn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Ue]}getContext(){return this[Ae]}};xt.prototype[Ae]=null;(0,Ux._assignPackageExport)("Resource",xt);a(sie,"snake_case");vE=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(Cx,"pathToId");SA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Yr,"transactional");a(Kr,"missingMethod");a(pA,"selectFromObject");a(BE,"transformForSelect")});function Px(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;za||((0,HE.onMessageByType)(Mx,l=>{vx(l.path)}),za=Object.create(null));let o=za[s]||(za[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Ra(t);let u=new gA(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function vx(e,t){if(!za)return;let r=za[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Ut(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Ra(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,TA.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,p)}catch(p){console.error(p),(0,TA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Bx(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,HE.broadcast)({type:Mx,path:s}),vx(s,!0)})}}var TA,HE,Mx,za,ESe,gA,Hx=ge(()=>{TA=x($()),HE=x(We());mc();qu();Hi();Mx="transaction",ESe=Buffer.alloc(4096);a(Px,"addSubscription");gA=class extends Rn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(vx,"notifyFromTransactionData");a(Bx,"listenToCommits")});var Zg={};Ke(Zg,{coerceType:()=>xE,makeTable:()=>GE,setServerUtilities:()=>fie,updateResource:()=>qE});function GE(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:p}=e;p||(p=[]),Bx(i,u);let S=Xh(i,n,u),g=0,A,R,v={},H=Promise.resolve(),P,M,K;for(let Q of p)(Q.assignCreatedTime||Q.name==="__createdtime__")&&(P=Q),(Q.assignUpdatedTime||Q.name==="__updatedtime__")&&(M=Q),Q.expiresAt&&(K=Q),Q.isPrimaryKey&&(v=Q);let W,V=[],ce=[],de=1,xe=2,ae={},Oe={},$e=864e5,Fn,vo,Ys,GA=!1,sh,Gq=i.getRange({start:!1,end:!1}).constructor,kq=10,Vq=6;E&&$A();class Je extends xt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=P;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),R=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(D=>{let y=this.sources.slice(0,-1);if(y=y.filter(L=>L[D]&&(!L[D].reliesOnPrototype||L.prototype[D])),y.length>0)if(y.length===1){let L=y[0];return(G,C,B)=>{if(G?.source!==L)return L[D](C,B,G)}}else return(L,G,C)=>{let B=[];for(let F of y){if(L?.source===F)break;B.push(F[D](G,C,L))}return Promise.all(B)}},"getApplyToIntermediateSource"),N=this.sources[this.sources.length-1],b=a(D=>{if(N[D]&&(!N[D].reliesOnPrototype||N.prototype[D]))return(y,L,G)=>{if(!y?.source)return N[D](L,G,y)}},"getApplyToCanonicalSource");return ae={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},Oe={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let D=!1,y=a(async(L,G)=>{let C=L.value,B=L.table?nt[c][L.table]:Je;if(c===qn.SYSTEM_SCHEMA_NAME&&(L.table===qn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||L.table===qn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),L.id===void 0&&(L.id=C[B.primaryKey],L.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(L));L.source=m;let F=await B.getResource(L.id,G,Ja);switch(L.type){case"put":return F._writeUpdate(C,!0,Ja);case"patch":return F._writeUpdate(C,!1,Ja);case"delete":return F._writeDelete(Ja);case"publish":return F._writePublish(C,Ja);case"invalidate":return F.invalidate(Ja);default:et.error("Unknown operation",L.type,L.id)}},"writeUpdate");try{let L=m.subscribe;L&&h==null&&(h=!0);let G=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Uo.getWorkerIndex)()):(0,Uo.getWorkerIndex)()===0,C=L&&G&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let B;for await(let F of C)try{if(!(F.type==="transaction"?F.writes[0]:F)){et.error("Bad subscription event",F);continue}if(F.source=m,B)if(F.beginTxn)B.resolve();else{y(F,B);continue}if(F.type==="end_txn")continue;let be=Ze(F,()=>{if(F.type==="transaction"){let ee=[];for(let Me of F.writes)try{ee.push(y(Me,F))}catch(oe){throw oe.message+=" writing "+JSON.stringify(Me)+" of event "+JSON.stringify(F),oe}return Promise.all(ee)}else if(F.type==="define_schema"){let ee=this.attributes.slice(0),Me;for(let oe of F.attributes)ee.find(qe=>qe.name===oe.name)||(ee.push(oe),Me=!0);Me&&(ut({table:s,database:c,attributes:ee,origin:"cluster"}),yl.signalSchemaChange(new wl.SchemaEventMsg(process.pid,qn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return F.beginTxn?(B=F,y(F,F),new Promise(ee=>{B.resolve=ee})):y(F,F)});D&&(await be,yl.signalUserChange(new wl.UserEventMsg(process.pid))),F.onCommit&&(be?.then?be.then(F.onCommit):F.onCommit())}catch(ie){et.error("error in subscription handler",ie)}}}catch(L){et.error(L)}})(),this}static getResource(m,O,w){let N=super.getResource(m,O,w);if(m!=null){tc(m);try{if(N.hasOwnProperty(_e))return N;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!w?.async||i.cache?.get(m),D=Tn(O),y=D.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return ih(m,O,{transaction:y},b,L=>{if(L?qE(N,L):N[_e]=null,O.onlyIfCached&&O.noCacheStore){if(!N.doesExist())throw new pn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let G=oh(m,L,O,N);if(G)return D?.disregardReadTxn(),N[RA]=!0,OA(G,C=>(qE(N,C),N))}return N})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return N}ensureLoaded(){let m=oh(this[Ue],this[Wr],this[Ae]);if(m)return this[RA]=!0,OA(m,O=>{this[Wr]=O,this[_e]=O.value,this[bl]=O.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,$e=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");$e=$e||(d+f)/4,ch()}static enableAuditing(m=!0){E=m,m&&$A(),Je.audit=m}static coerceId(m){return m===""?null:xE(m,v)}static async dropTable(){if(delete nt[c][s],c===o){for(let m of p)l.remove(Je.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Je.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));yl.signalSchemaChange(new wl.SchemaEventMsg(process.pid,qn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[mn])return this.search(m);if(this[Ue]===null){if(m?.conditions)return this.search(m);let O=Je.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:s,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ae]?.returnNonexistent)return this}allowRead(m,O){let w=Hl(m);if(w?.read){if(w.isSuperUser)return!0;let N=w.attribute_permissions,b=O?.select;if(N?.length>0||GA&&b){if(O||(O={}),b){let D=N?.length>0&&AA(N,"read");O.select=b.map(y=>{let L=y.name||y;if(!D||D[L]){let G=Ys[L]?.definition?.tableClass;if(G){if(y.name||(y={name:y}),!G.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else O.select=N.filter(D=>D.read&&!Ys[D.attribute_name]).map(D=>D.attribute_name);return O}else return!0}}allowUpdate(m,O){let w=Hl(m);if(w?.update){let N=w.attribute_permissions;if(N?.length>0){let b=AA(N,"update");for(let D in O)if(!b[D])return!1;for(let D of N){let y=D.attribute_name;!D.update&&!(y in O)&&(O[y]=this.getProperty(y))}}return!0}}allowCreate(m,O){if(this[mn]){let w=Hl(m);if(w?.insert){let N=w.attribute_permissions;if(N?.length>0){let b=AA(N,"insert");for(let D in O)if(!b[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Hl(m)?.delete}update(m,O){if(!Tn(this[Ae]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let N;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[Dt]=m):(N=this[Dt],N&&(m=Object.assign(N,m)),this[Dt]=N=m)),this._writeUpdate(this[Dt],O),this}addTo(m,O){if(typeof O=="number")this[gl]===qx?this.set(m,(+this.getProperty(m)||0)+O):(this[gl]||this.update(),this.set(m,new ME(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let O=this[Ae],w=this[Ue];tc(w),Tn(this[Ae]).addWrite({key:w,store:i,invalidated:!0,entry:this[Wr],nodeName:this[Ae]?.nodeName,before:ae.invalidate?.bind(this,O,w),beforeIntermediate:Oe.invalidate?.bind(this,O,w),commit:(b,D)=>{if(D?.version>b)return;let y=null;for(let L in r)y||(y={}),y[L]=this.getProperty(L);S(w,y,this[Wr],b,Rl,E,this[Ae],0,"invalidate")}})}static evict(m,O,w){let N=this.Source,b;if(!((R||E)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==w))){if(R){if(i.hasLock(m,b.version))return;let D;for(let y in r)D||(D={}),D[y]=O[y];if(D)return S(m,D,b,w,Al,null,null,0,null,!0)}return i.ifVersion(w,()=>{Bl(m,O,null)}),E?S(m,null,b,w,Al,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=s,m.schema||=c,Yx.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,w){let N=this[Ae],b=Tn(N),D=this[Ue];tc(D);let y=this[Wr];this[gl]=O?qx:lie;let L={key:D,store:i,entry:y,nodeName:N?.nodeName,validate:G=>{m||(m=this[Dt]),O||m&&UE(m)?(this.validate(m,!O),N?.source||(M&&(m[M.name]=M.type==="Date"?new Date(G):M.type==="String"?new Date(G).toISOString():G),O&&(t&&m[t]!==D&&(m[t]=D),P&&(y?.value?m[P.name]=y?.value[P.name]:m[P.name]=P.type==="Date"?new Date(G):P.type==="String"?new Date(G).toISOString():G),m=Co(m)))):b.removeWrite(L)},before:O?ae.put?()=>ae.put(N,D,m):null:ae.patch?()=>ae.patch(N,D,m):ae.put?()=>ae.put(N,D,Co(this)):null,beforeIntermediate:O?Oe.put?()=>Oe.put(N,D,m):null:Oe.patch?()=>Oe.patch(N,D,m):Oe.put?()=>Oe.put(N,D,Co(this)):null,commit:(G,C,B)=>{if(B){if(N&&C?.version>(N.lastModified||0)&&(N.lastModified=C.version),this[Wr]=C,C?.value?.[_e])throw new Error("Can not assign a record to a record, check for circular references");O||(this[_e]=C?.value??null)}this[Dt]=m,this[bl]=G;let F=C?.value,ie=m;if(this[gl]=0,C?.version>=G)if(E){let oe=C.localTime,qe=C.version;for(;ie&&(oe>G||qe>=G&&oe>0);){let te=u.get(oe),j=Ut(te);if(qe=j.version,qe>G){if(j.type==="patch"){let Te=j.getValue(i);ie=CE(ie,Te)}else if(j.type==="put"||j.type==="delete")return}else if(qe===G)return;oe=j.previousLocalTime}}else{if(O)return;ie=CE(ie,F)}let be;if(O?be=ie:(this[_e]=F,be=O?ie:Co(this,ie)),this[_e]=be,be?.[_e])throw new Error("Can not assign a record to a record, check for circular references");let ee;O||(ee=m),Bl(D,F,be);let Me=O?"put":"patch";S(D,be,C,G,0,E,N,N.expiresAt||(d?d+Date.now():0),Me,!1,ee)}};b.addWrite(L)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[mn]){for await(let O of this.search(m))(await Je.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let O=Tn(this[Ae]),w=this[Ue];tc(w);let N=this[Ae];return O.addWrite({key:w,store:i,resource:this,nodeName:N?.nodeName,before:ae.delete?.bind(this,N,w),beforeIntermediate:Oe.delete?.bind(this,N,w),commit:(b,D,y)=>{let L=D?.value;y&&(N&&D?.version>(N.lastModified||0)&&(N.lastModified=D.version),qE(this,D)),!(D?.version>b)&&(Bl(this[Ue],L),et.trace("Write delete entry",w,b),E||h?(S(w,null,this[Wr],b,0,E,this[Ae],0,"delete"),E||ch()):i.remove(this[Ue]))}}),!0}search(m){let O=this[Ae],w=Tn(O);if(!m)throw new Error("No query provided");let N=m.conditions;N?N.length===void 0&&(N=N[Symbol.iterator]?Array.from(N):[N]):N=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ue]&&(N=[{attribute:null,comparator:"prefix",value:this[Ue]}].concat(N));let b,D={};function y(j,Te){let Be;switch(Te){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Te)}let Gn=Be&&{},Ks;for(let Ye of j){if(Ye.conditions){Ye.conditions=y(Ye.conditions,Ye.operator);continue}let Bt=Ye[0]??Ye.attribute,jr=Bt==null?v:vs(p,Bt);if(jr){if(Be){let kn=Pn(Bt),Ht=Gn[kn];Ht?(Ht.push(Ye),Ks=!0):Gn[kn]=[Ye]}(jr.type||Ng[Ye.comparator])&&(Ye[1]===void 0?Ye.value=G(Ye.value,jr):Ye[1]=G(Ye[1],jr))}else if(Bt!=null)throw(0,pn.handleHDBError)(new Error,`${Bt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(Ks)for(let Ye in Gn){let Bt=Gn[Ye],jr=Bt.length;if(jr>1)for(let kn=0;kn<jr;kn++){let Ht=Bt[kn];if(Ht.comparator==="ge"||Ht.comparator==="greater_than_equal")for(let Ws=0;Ws<jr;Ws++){let Bo=Bt[Ws];(Bo.comparator==="le"||Bo.comparator==="less_than_equal")&&(Ht.comparator="between",Ht.value=[Ht.value,Bo.value],j.splice(j.indexOf(Bo),1))}if(Ht.comparator==="equals"||!Ht.comparator){for(let Ws=0;Ws<jr;Ws++)if(Ws!==kn){let Bo=Bt[Ws];j.splice(j.indexOf(Bo),1)}break}}}return j}a(y,"prepareConditions");function L(j,Te){if(m.enforceExecutionOrder)return j;for(let Be of j)Be.conditions&&(Be.conditions=L(Be.conditions,Be.operator));return j.length>1&&Te!=="or"?(0,$x.sortBy)(j,bf(Je)):j}a(L,"orderConditions");function G(j,Te){return Array.isArray(j)?j.map(Be=>xE(Be,Te)):xE(j,Te)}a(G,"coerceTypedValues");let C=m.operator;(N.length>0||C)&&(N=y(N,C));let B=typeof m.sort=="object"&&m.sort,F;if(B&&C!=="or"){let j=B.attribute;if(b=N.find(Te=>Pn(Te.attribute)===Pn(j)),!b){if(!vs(p,j))throw(0,pn.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);b={attribute:j,comparator:"sort"},N.push(b)}b.descending=!!B.descending}N=L(N,C),B&&(N[0]===b?B.next&&(F={dbOrderedAttribute:B.attribute,attribute:B.next.attribute,descending:B.next.descending,next:B.next.next}):(b&&N.splice(N.indexOf(b),1),F=B));let ie=m.select;if(N.length===0&&(N=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:N,operator:C,postOrdering:F,selectApplied:!!ie};let be=w.useReadTxn(),ee=yg(N,C,Je,be,m,O,(j,Te)=>kA(j,ie,O,be,Te),D),Me=m.ensureLoaded!==!1;F||(ee=te(ee));let oe=Je.transformEntryForSelect(ie,O,be,D,Me,!0),qe=Je.transformToOrderedSelect(ee,ie,F,be,O,oe);function te(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(te,"applyOffset"),F&&(qe=te(qe)),qe.onDone=()=>{qe.onDone=null,w.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(ie){let j=[];for(let Te of ie)Te==="*"?j.push(...p.map(Be=>Be.name)):j.push(Te.name||Te);return j}return p.map(j=>j.name)},qe}static transformToOrderedSelect(m,O,w,N,b,D){let y=new Gq;if(w){m=kA(m,O,N,b,null);let L;y.iterate=function(){let C,B=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),F,ie=w.dbOrderedAttribute,be,ee,Me=!0;function oe(te){let j=te.next&&oe(te.next),Te=te.descending;return(Be,Gn)=>{let Ks=ah(Be,te.attribute,N),Ye=ah(Gn,te.attribute,N),Bt=Te?(0,Lo.compareKeys)(Ye,Ks):(0,Lo.compareKeys)(Ks,Ye);return Bt===0?j?.(Be,Gn)||0:Bt}}a(oe,"createComparator");let qe=oe(w);return{async next(){let te;if(C)if(te=C.next(),te.done){if(F)return y.onDone&&y.onDone(),te}else return{value:await D.call(this,te.value)};L=[],be&&L.push(be);do if(te=await B.next(),te.done){if(F=!0,L.length)break;return y.onDone&&y.onDone(),te}else{let j=te.value;if(j?.then&&(j=await j),ie){let Te=ah(j,ie,N);if(Me)Me=!1,ee=Te;else if(Te!==ee){ee=Te,be=j;break}}L.push(j)}while(!0);return w.isGrouped,L.sort(qe),C=L[Symbol.iterator](),te=C.next(),te.done?(y.onDone&&y.onDone(),te):{value:await D.call(this,te.value)}},return(){y.onDone&&y.onDone(),B.return()},throw(){y.onDone&&y.onDone(),B.throw()}}};let G=a(C=>{if(typeof O=="object"&&Array.isArray(C.attribute))for(let B=0;B<O.length;B++){let F=O[B],ie;if(F.name===C.attribute[0]){for(ie=F.sort||(F.sort={});ie.next;)ie=ie.next;ie.attribute=C.attribute.slice(1),ie.descending=C.descending}else F===C.attribute[0]&&(O[B]=ie={name:F,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&G(C.next)},"applySortingOnSelect");G(w)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(D);return y}static transformEntryForSelect(m,O,w,N,b,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(B=>B?.key??B,"transform");return m===t?C:m.asArray?B=>[C(B)]:B=>({[t]:C(B)})}let y;b&&R&&!m?.every(C=>{let B;return typeof C=="object"?B=C.name:B=C,r[B]||B===t})&&(y=!0);let L,G=a(function(C){let B;if(C!=null){if(sh=C,B=C.value||C.deref?.(),!B&&(C.key===void 0||C.deref)){if(C=ih(C.key??C,O,{transaction:w,lazy:m?.length<4},this.isSync,F=>F),C?.then)return C.then(G.bind(this));B=C?.value}if(y&&(C.metadataFlags&(Rl|Al)||C.expiresAt&&C.expiresAt<Date.now())){let F=oh(C.key??C,C,O);if(F?.then)return F.then(G)}}if(B==null)return D?Do.SKIP:B;if(m&&!(m[0]==="*"&&m.length===1)){let F,ie=a((ee,Me)=>{let oe;typeof ee=="object"?oe=ee.name:oe=ee;let qe=Ys?.[oe],te;if(qe){let j=N?.[oe];if(j)if(j.hasMappings){let Be=qe.from?B[qe.from]:Pn(C.key);te=j.get(Be),te||(te=[])}else te=j.fromRecord?.(B);else te=qe(B,O,C);let Te=a(Be=>{if(Be&&typeof Be=="object"){let Gn=qe.definition?.tableClass||Je;L||(L={});let Ks=L[oe]||(L[oe]=Gn.transformEntryForSelect(oe===ee?null:ee.select||(Array.isArray(ee)?ee:null),O,w,j,b));if(Array.isArray(Be)){let Ye=[],Bt=Gn.transformToOrderedSelect(Be,ee.select,typeof ee.sort=="object"&&ee.sort,O,w,Ks)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),jr=a(Ht=>{for(;!Ht.done;){if(Ht?.then)return Ht.then(jr);Ye.push(Ht.value),Ht=Bt.next()}Me(Ye,oe)},"nextValue"),kn=jr(Bt.next());kn&&(F||(F=[]),F.push(kn));return}else if(Be=Ks.call(this,Be),Be?.then){F||(F=[]),F.push(Be.then(Ye=>Me(Ye,oe)));return}}Me(Be,oe)},"handleResolvedValue");te?.then?(F||(F=[]),F.push(te.then(Te))):Te(te);return}else te=B[oe],te&&typeof te=="object"&&oe!==ee&&(te=Je.transformEntryForSelect(ee.select||ee,O,w,null)({value:te}));Me(te,oe)},"selectAttribute"),be;if(typeof m=="string")ie(m,ee=>{be=ee});else if(Array.isArray(m))if(m.asArray)be=[],m.forEach((ee,Me)=>{ee==="*"?m[Me]=B:ie(ee,oe=>be[Me]=oe)});else{be={};let ee=m.forceNulls;for(let Me of m)if(Me==="*")for(let oe in B)be[oe]=B[oe];else ie(Me,(oe,qe)=>{oe===void 0&&ee&&(oe=null),be[qe]=oe})}else throw new pn.ClientError("Invalid select"+m);return F?Promise.all(F).then(()=>be):be}return B},"transform");return G}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||ut({table:s,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let O=!m.rawEvents,w=Px(Je,this[Ue]??null,function(y,L,G,C){try{let B=L.getValue?.(i,O);if(!B&&L.type==="patch"&&O){let F=i.getEntry(y);F?.version===L.version?B=F.value:B=L.getValue?.(i,!0,G),L.type="put"}this.send({id:y,timestamp:G,value:B,version:L.version,type:L.type,beginTxn:C})}catch(B){et.error(B)}},m.startTime||0,this[mn]);this[mn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.crossThreads===!1&&(w.crossThreads=!1),m.supportsTransactions&&(w.supportsTransactions=!0);let N=this[Ue],b=m.previousCount;b>1e3&&(b=1e3);let D=m.startTime;if(this[mn]){if(D){if(b)throw new pn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:L}of u.getRange({start:D,exclusiveStart:!0})){let G=Ut(L);if(G.tableId!==n)continue;let C=G.recordId;if(N==null||kx(N,C)){let B=G.getValue(i,O,y);w.send({id:C,timestamp:y,value:B,version:G.version,type:G.type})}w.startTime=y}}else if(b){let y=[];for(let{key:L,value:G}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Ut(G);if(C.tableId!==n)continue;let B=C.recordId;if(N==null||kx(N,B)){let F=C.getValue(i,O,L);if(y.push({id:B,timestamp:L,value:F,version:C.version,type:C.type}),--b<=0)break}}catch(C){et.error("Error getting history entry",L,C)}for(let L=y.length;L>0;)w.send(y[--L]);y[0]&&(w.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:L,version:G,localTime:C}of i.getRange({start:N??!1,end:N==null?void 0:[N,Lo.MAXIMUM_KEY],versions:!0}))L&&w.send({id:y,timestamp:C,value:L,version:G,type:"put"})}else{b&&!D&&(D=0);let y=this[Wr]?.localTime;if(y===jh&&(i.cache?.delete(N),this[Wr]=i.getEntry(N),et.trace("re-retrieved record",y,this[Wr]?.localTime),y=this[Wr]?.localTime),et.trace("Subscription from",D,"from",N,y),D<y){let L=[],G=y;do{let C=u.get(G);if(C){m.omitCurrent=!0;let B=Ut(C),F=B.getValue(i,O,G);O&&(B.type="put"),L.push({id:N,value:F,timestamp:G,...B}),G=B.previousLocalTime}else break;b&&b--}while(G>D&&b!==0);for(let C=L.length;C>0;)w.send(L[--C]);w.startTime=y}!m.omitCurrent&&this.doesExist()&&w.send({id:N,timestamp:y,value:this,version:this[bl],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[_e]||this[gl])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let w=Tn(this[Ae]),N=this[Ue]||null;tc(N);let b=this[Ae];w.addWrite({key:N,store:i,entry:this[Wr],nodeName:b?.nodeName,validate:()=>{this.validate(m)},before:ae.publish?.bind(this,b,N,m),beforeIntermediate:Oe.publish?.bind(this,b,N,m),commit:(D,y,L)=>{y===void 0&&h&&!E&&ch(),S(N,y?.value??null,y,y?.version||D,0,!0,b,y?.expiresAt,"message",!1,m)}})}validate(m,O){let w,N=a((b,D,y)=>{if(D.type&&b!=null)if(O&&b.__op__&&(b=b.value),D.properties){typeof b!="object"&&(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be an object${D.type?" ("+D.type+")":""}`);let L=D.properties;for(let G=0,C=L.length;G<C;G++){let B=L[G],F=N(b[B.name],B,y+"."+B.name);F&&(b[B.name]=F)}}else switch(D.type){case"Int":(typeof b!="number"||b>>0!==b)&&(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a string`);break;case"Boolean":typeof b!="boolean"&&(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(b)){if(D.elements)for(let L=0,G=b.length;L<G;L++){let C=b[L],B=N(C,D.elements,y+"[*]");B&&(b[L]=B)}}else(w||(w=[])).push(`Value ${xn(b)} in property ${y} must be a Buffer or Uint8Array`);break}D.nullable===!1&&b==null&&(w||(w=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let b=0,D=p.length;b<D;b++){let y=p[b];if(!y.relationship&&(!O||y.name in m)){let L=N(m[y.name],y,y.name);L&&(m[y.name]=L)}}if(w)throw new pn.ClientError(w.join(". "))}getUpdatedTime(){return this[bl]}wasLoadedFromSource(){return R?!!this[RA]:void 0}static async addAttributes(m){let O=p.slice(0);for(let w of m){if(!w.name)throw new pn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new pn.ClientError("Attribute names cannot include backticks or forward slashes");O.push(w)}return ut({table:s,database:c,schemaDefined:_,attributes:O}),Je.indexingOperation}static async removeAttributes(m){let O=p.filter(w=>!m.includes(w.name));return ut({table:s,database:c,schemaDefined:_,attributes:O}),Je.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,w=5e3,N=1e3,b;O>w&&!m?.exactCount&&(b=N);let D=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:b}))y!=null&&D++;if(b){let y=D;D=0;for(let{value:Me}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Me!=null&&D++;let L=b*2,G=(D+y)/L,C=Math.pow((D-y+1)/b/2,2)+G*(1-G)/L,B=Math.max(Math.sqrt(C)*O,1),F=Math.round(G*O),ie=Math.max(F-1.96*B,0),be=Math.min(F+1.96*B,O),ee=Math.pow(10,Math.round(Math.log10(B)));return ee>F&&(ee=ee/10),D=Math.round(F/ee)*ee,{recordCount:D,estimatedRange:[Math.round(ie),Math.round(be)]}}return{recordCount:D}}static updatedAttributes(){Ys=this.propertyResolvers={$id:(m,O,w)=>({value:w.key}),$updatedtime:(m,O,w)=>w.version,$record:(m,O,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),GA=!0,O.to)m.elements?.definition?(Ys[m.name]=m.resolve=(w,N,b)=>{let D=w[O.from?O.from:t],y=m.elements.definition.tableClass;return b?Ua({attribute:O.to,value:D},Tn(N).getReadTxn(),!1,y,!1).asArray:y.search([{attribute:O.to,value:D}],N).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let w=m.definition||m.elements?.definition;w?(Ys[m.name]=m.resolve=(N,b,D)=>{let y=N[O.from];if(y!==void 0){if(m.elements){let L,G=y.map(C=>{let B=D?w.tableClass.primaryStore.getEntry(C,{transaction:Tn(b).getReadTxn()}):w.tableClass.get(C,b);return B?.then&&(L=!0),B});return O.filterMissing?L?Promise.all(G).then(C=>C.filter(Vx)):G.filter(Vx):L?Promise.all(G):G}return D?w.tableClass.primaryStore.getEntry(y,{transaction:Tn(b).getReadTxn()}):w.tableClass.get(y,b)}},m.set=(N,b)=>{if(Array.isArray(b)){let D=b.map(y=>y[Ue]||y[w.tableClass.primaryKey]);N[O.from]=D}else{let D=b[Ue]||b[w.tableClass.primaryKey];N[O.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}PE(this,this)}static async deleteHistory(m=0){let O;for(let{key:w,value:N}of u.getRange({start:0,end:m}))await Ol(),Ut(N).tableId===n&&(O=u.remove(w));await O}static async*getHistory(m=0,O=1/0){for(let{key:w,value:N}of u.getRange({start:m,end:O})){await Ol();let b=Ut(N);b.tableId===n&&(yield{id:b.recordId,localTime:w,version:b.version,type:b.type,value:b.getValue(i,!0,w),user:b.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return O;let N=w.localTime;if(!N)throw new Error("The entry does not have a local audit time");let b=0;do{await Ol();let D=u.get(N);if(D){let y=Ut(D);O.push({id:y.recordId,localTime:N,version:y.version,type:y.type,value:y.getValue(i,!0,N),user:y.user}),N=y.previousLocalTime}else break}while(b<1e3&&N);return O.reverse()}static cleanup(){W?.remove()}}Je.updatedAttributes();let $q=Je.prototype;return $q[uie]=!0,d&&Je.setTTLExpiration(d/1e3),K&&Yq(),Je;function Bl(Q,m,O){let w;for(let N in r){let b=r[N],D=b.isIndexing,y=O?.[N],L=m?.[N];if(y===L&&!D)continue;w=!0;let G=b.indexNulls,C=(0,Nl.getIndexedValues)(L,G);if(C){xx&&b.prefetch(C.map(B=>({key:B,value:Q})),Gx);for(let B=0,F=C.length;B<F;B++)b.remove(C[B],Q)}if(C=(0,Nl.getIndexedValues)(y,G),C){xx&&b.prefetch(C.map(B=>({key:B,value:Q})),Gx);for(let B=0,F=C.length;B<F;B++)b.put(C[B],Q)}}return w}a(Bl,"updateIndices");function tc(Q){switch(typeof Q){case"number":return!0;case"string":if(Q.length<659)return!0;if(Q.length>Fx)throw new Error("Primary key size is too large: "+Q.length);break;case"object":if(Q===null)return!0;break;case"bigint":if(Q<2n**64n&&Q>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof Q)}if((0,Lo.writeKey)(Q,_ie,0)>Fx)throw new Error("Primary key size is too large: "+Q.length);return!0}a(tc,"checkValidId");function ih(Q,m,O,w,N){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return N(null,Q);let D=i.getEntry(Q,O);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),N(D,Q)},"whenPrefetched");return w?b():de>0?(de--,b()):new Promise((D,y)=>{de===0?(de--,i.prefetch([Q],()=>{L(),G()})):(V.push(Q),ce.push(G),V.length>Vq&&(de--,L()));function L(){if(V.length>0){let C=ce;i.prefetch(V,()=>{de===-1?L():de++;for(let B of C)B()}),V=[],ce=[],xe>2&&xe--}else de=xe,xe<kq&&xe++}a(L,"prefetch");function G(){try{D(b())}catch(C){y(C)}}a(G,"load")})}a(ih,"loadLocalRecord");function Hl(Q){if(!Q?.role)return;let m=Q.role.permission;if(m.super_user)return die;let O=m[c],w,N=O?.tables;if(N)return N[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(Hl,"getTablePermissions");function oh(Q,m,O,w){if(R){let N;if(O.noCache?N=!0:(m?(!m.value||m.metadataFlags&(Rl|Al)||m.expiresAt&&m.expiresAt<Date.now())&&(N=!0):N=!0,rn(!N,"cache-hit",s)),N){let b=VA(Q,m,O).then(D=>(D?.value?.[_e]&&et.error("Can not assign a record with a record property"),O&&(D?.version>(O.lastModified||0)&&(O.lastModified=D.version),O.lastRefreshed=Date.now()),D));if(O?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,Q)){if(b.catch(D=>et.warn(D)),O?.onlyIfCached&&!w.doesExist())throw new pn.ServerError("Entry is not cached",504);return}else return b}}}a(oh,"ensureLoadedFromSource");function Tn(Q){let m=Q?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new Zi,m.lmdbDb=i,m;m=O}while(!0)}else return new z_}a(Tn,"txnForContext");function ah(Q,m,O){if(!Q)return;sh=Q;let w=Q.value||Q.deref?.()||(sh=i.getEntry(Q.key))?.value;if(typeof m=="object"){let b=Ys,D=w;for(let y=0,L=m.length;y<L;y++){let G=m[y],C=b?.[G];D=C&&D?C(D,O,!0)?.value:D?.[G],b=C?.definition?.tableClass?.propertyResolvers}return D}let N=Ys[m];return N?N(w,O):w[m]}a(ah,"getAttributeValue");function kA(Q,m,O,w,N){let b=N?.length,D={transaction:w,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function L(G,C){let B=G?.value;if(!B)return Do.SKIP;for(let F=0;F<b;F++)if(!y?.includes(F)&&!N[F](B,G))return Do.SKIP;return C!==void 0&&(G.key=C),G}if(a(L,"processEntry"),b>0||!Q.hasEntries){let G=Q.map(C=>{if(y=null,typeof C=="object"&&C.key!==void 0)return b>0?L(C):C;if(C==null)return Do.SKIP;for(let B=0;B<b;B++){let ie=N[B].idFilter;if(ie){if(!ie(C))return Do.SKIP;y||(y=[]),y.push(B)}}return ih(C,O,D,!1,L)});return Array.isArray(Q)&&(G=G.filter(C=>C!==Do.SKIP)),G.hasEntries=!0,G}return Q}a(kA,"transformToEntries");async function VA(Q,m,O){let w=m?.metadataFlags,N=m?.version,b,D;if(!i.attemptLock(Q,N,()=>{clearTimeout(D);let C=i.getEntry(Q);!C||!C.value||C.metadataFlags&(Rl|Al)?b(VA(Q,i.getEntry(Q),O)):b(C)}))return new Promise(C=>{b=C,D=setTimeout(()=>{i.unlock(Q,N)},cie)});let y=m?.value,L={requestContext:O,replacingRecord:y,replacingVersion:N,source:null,resourceCache:O?.resourceCache},G=O?.responseHeaders;return new Promise((C,B)=>{let F;OA(Ze(L,async ie=>{let be=performance.now(),ee,Me,oe;try{for(let Te of Je.sources)if(Te.get&&(!Te.get.reliesOnPrototype||Te.prototype.get)&&(L.source=Te,ee=await Te.get(Q,L),ee))break;oe=w&Rl;let te=L.lastModified||oe&&N;Me=oe||te>N||!y,te||(te=(0,Nl.getNextMonotonicTime)());let j=performance.now()-be;if(Hr(j,"cache-resolution",s),G&&WT(G,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),ie.timestamp=te,d&&!L.expiresAt&&(L.expiresAt=Date.now()+d),ee){if(typeof ee!="object")throw new Error("Only objects can be cached and stored in tables");typeof ee.toJSON=="function"&&(ee=ee.toJSON()),t&&ee[t]!==Q&&(ee[t]=Q)}F=!0,C({version:te,value:ee})}catch(te){te.message+=` while resolving record ${Q} for ${s}`,y&&((te.code==="ECONNRESET"||te.code==="ECONNREFUSED"||te.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(te.statusCode===500||te.statusCode===502||te.statusCode===503||te.statusCode===504))?(C({version:N,value:y}),et.trace(te.message,"(returned stale record)")):B(te),L.transaction.abort();return}if(O?.noCacheStore){L.transaction.abort();return}Tn(L).addWrite({key:Q,store:i,entry:m,nodeName:"source",commit:(te,j)=>{if(j?.version!==N)return;let Te=Bl(Q,y,ee);ee?(Oe.put?.(L,Q,ee),S(Q,ee,j,te,0,E&&Me||null,L,L.expiresAt,"put",!!oe)):(Oe.delete?.(L,Q),E||h?S(Q,null,j,te,0,E&&Me||null,L,0,"delete",!!oe):i.remove(Q,N))}})}),()=>{i.unlock(Q,N)},ie=>{i.unlock(Q,N),F&&et.error("Error committing cache update",ie)})})}a(VA,"getFromSource");function ch(){if($e!==Fn&&(Fn=$e,(0,Uo.getWorkerIndex)()===(0,Uo.getWorkerCount)()-1)){if(vo&&clearTimeout(vo),!$e)return;let Q=new Date;Q.setMonth(0),Q.setDate(1),Q.setHours(0),Q.setMinutes(0),Q.setSeconds(0);let m=Math.ceil((Date.now()-Q.getTime())/$e)*$e+Q.getTime(),O=a(w=>{et.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),vo=setTimeout(()=>H=H.then(async()=>{if(O(Math.max(w+$e,Date.now())),i.rootStore.status!=="open"){clearTimeout(vo);return}let N=50,b=new Array(N),D=0;et.trace(`Starting cleanup scan for ${s}`);try{let y=0;for(let{key:L,value:G,version:C,expiresAt:B}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let F;G===null&&!E&&C+aie<Date.now()?F=i.remove(L,C):B&&B+f<Date.now()&&(F=Je.evict(L,G,C),y++),F&&(await b[D],b[D]=F.catch(ie=>{et.error("Cleanup error",ie)}),++D>=N&&(D=0)),await Ol()}et.trace(`Finished cleanup scan for ${s}, evicted ${y} entries`)}catch(y){et.trace(`Error in cleanup scan for ${s}:`,y)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(ch,"scheduleCleanup");function $A(){W=u?.addDeleteRemovalCallback(n,Q=>{let m=i.getEntry(Q);m?.value===null&&i.remove(Q,m.version)})}a($A,"addDeleteRemoval");function Yq(){(0,Uo.getWorkerIndex)()===0&&setInterval(async()=>{try{let Q=K.name,m=r[Q];if(!m)throw new Error(`expiresAt attribute ${K} must be indexed`);for(let{value:O}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let w=i.getEntry(O);w?.value?.[Q]<Date.now()&&Je.evict(O,w.value,w.version),await Ol()}}catch(Q){et.error("Error in evicting old records",Q)}},oie).unref()}a(Yq,"runRecordExpirationEviction")}function AA(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 Gx(){}function fie(e){Yx=e}function xE(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?(typeof e!="number"&&!Eie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,FE.autoCast)(e):e}function kx(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function OA(e,t,r){return e?.then?e.then(t,r):t(e)}function qE(e,t){e[Wr]=t,e[_e]=t?.value??null,e[bl]=t?.version}function Vx(e){return e!=null}function xn(e){try{return JSON.stringify(e)}catch{return e}}var qn,Do,Nl,$x,Il,pn,yl,wl,et,Lo,Uo,FE,iie,Yx,oie,aie,xx,cie,bl,uie,Wr,gl,qx,lie,RA,Ja,Rl,Al,_ie,Fx,die,LSe,Eie,Ol,Ff=ge(()=>{qn=x(U()),Do=require("lmdb"),Nl=x(yr()),$x=require("lodash");An();Kp();Il=x(Z());Hx();pn=x(re()),yl=x(Rs()),wl=x(In());Re();yf();et=x($());X_();eo();Lo=require("ordered-binary"),Uo=x(We());Hi();FE=x(J());Go();Ns();wE();Fu();iie=new Uint8Array(9);iie[8]=192;oie=6e4,aie=864e5;Il.initSync();xx=Il.get(qn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),cie=1e4,bl=Symbol.for("version"),uie=Symbol.for("incremental-update"),Wr=Symbol("entry"),gl=Symbol("is-saving"),qx=1,lie=2,RA=Symbol("loaded-from-source"),Ja={isNotification:!0,ensureLoaded:!1},Rl=1,Al=8,_ie=Buffer.allocUnsafeSlow(8192),Fx=1978,die={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},LSe=(0,FE.convertToMS)(Il.get(qn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(GE,"makeTable");a(AA,"attributesAsObject");a(Gx,"noop");a(fie,"setServerUtilities");Eie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(xE,"coerceType");a(kx,"isDescendantId");Ol=a(()=>new Promise(setImmediate),"rest");a(OA,"when");a(qE,"updateResource");a(Vx,"exists");a(xn,"stringify")});var Fe={};Ke(Fe,{database:()=>Xc,databases:()=>nt,dropDatabase:()=>jp,dropTableMeta:()=>gie,getDatabases:()=>Dn,getTables:()=>hie,onUpdatedTable:()=>vR,readMetaDb:()=>Cl,resetDatabases:()=>mie,table:()=>ut,tables:()=>wr});function hie(){return KE||Dn(),wr||{}}function Dn(){if(KE)return nt;KE=!0,Za=new Map;let e=(0,Xt.getHdbBasePath)()&&(0,tt.join)((0,Xt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),t=(0,Xt.get)(zr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Xt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Qr.existsSync)(e)?e:(0,tt.join)((0,Xt.getHdbBasePath)(),zr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Qr.existsSync)(e))for(let r of(0,Qr.readdirSync)(e,{withFileTypes:!0})){let n=(0,tt.basename)(r.name,".mdb");r.isFile()&&(0,tt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Cl((0,tt.join)(e,r.name),null,n)}if((0,Qr.existsSync)((0,Xa.getBaseSchemaPath)())){for(let r of(0,Qr.readdirSync)((0,Xa.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,tt.join)((0,Xa.getBaseSchemaPath)(),r.name),s=(0,tt.join)((0,Xa.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Qr.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,tt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,tt.join)(s,i.name);Cl((0,tt.join)(n,i.name),(0,tt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,Qr.existsSync)(s))for(let o of(0,Qr.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,tt.extname)(o.name).toLowerCase()===".mdb"&&Cl((0,tt.join)(s,o.name),(0,tt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,tt.join)(c.path,(0,tt.basename)(o+".mdb"));(0,Qr.existsSync)(u)&&Cl(u,o,r,null,!0)}}for(let r in nt){let n=Za.get(r);if(n){let s=nt[r];r.includes("delete")&&Sn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Sn.trace(`delete table class ${i}`),delete s[i])}else if(delete nt[r],r==="data"){for(let s in wr)delete wr[s];delete wr[WE]}}return Za=null,nt}}function mie(){KE=!1;for(let[,e]of Ui)e.needsDeletion=!0;Dn();for(let[e,t]of Ui)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ui.delete(e));return nt}function Cl(e,t,r=yA,n,s){let i=new bA.default(e,!1);try{let o=Ui.get(e);o?o.needsDeletion=!1:(o=(0,VE.open)(i),Ui.set(e,o));let c=new Mo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(kE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,Qr.existsSync)(n)&&(i.path=n,_=(0,VE.open)(i),_.isLegacy=!0):_=yE(o));let l=zx(r),d=l[WE],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[p,S]=E.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let g=f.get(p);g||f.set(p,g={attributes:[]}),(S==null||h.is_hash_attribute)&&(g.primary=h),S!=null&&g.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let V of p)if(V.is_hash_attribute||V.isPrimaryKey){S=V;break}if(!S){Sn.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let g=l[E],A={},R=[],v,H,P=typeof S.audit=="boolean"?S.audit:(0,Xt.get)(zr.CONFIG_PARAMS.LOGGING_AUDITLOG),M=S.trackDeletes,K=S.expiration,W=S.eviction;if(g)A=g.indices,R=g.attributes,g.schemaVersion++;else{v=S.tableId,v?v>=(u.get(ja)||0)&&u.putSync(ja,v+1):(S.tableId=v=u.get(ja),v||(v=1),u.putSync(ja,v+1),u.putSync(S.key,S));let V=new Mo.default(!S.is_hash_attribute,S.is_hash_attribute);H=n_(o.openDB(S.key,V)),H.rootStore=o,H.tableId=v}for(let V of p){V.attribute=V.name;try{if(!V.is_hash_attribute&&(V.indexed||V.attribute&&!V.name)){if(!A[V.name]){let de=new Mo.default(!V.is_hash_attribute,V.is_hash_attribute);A[V.name]=o.openDB(V.key,de),A[V.name].indexNulls=V.indexNulls}let ce=R.find(de=>de.name===V.name);ce?R.splice(R.indexOf(ce),1,V):R.push(V)}}catch(ce){Sn.error("Error trying to update attribute",V,R,A,ce)}}if(!g){g=Jx(l,E,GE({primaryStore:H,auditStore:_,audit:P,expirationMS:K&&K*1e3,evictionMS:W&&W*1e3,trackDeletes:M,tableName:E,tableId:v,primaryKey:S.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),g.schemaVersion=1;for(let V of wA)V(g)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function zx(e){let t=nt[e];if(t||(e==="data"?t=nt[e]=wr:e==="system"?Object.defineProperty(nt,"system",{value:t=Object.create(null),configurable:!0}):t=nt[e]=Object.create(null)),Za&&!Za.has(e)){let r=new Set;t[WE]=r,Za.set(e,r)}return t}function Jx(e,t,r){return e[t]=r,r}function Xc({database:e,table:t}){e||(e=yA),Dn();let r=zx(e),n=(0,tt.join)((0,Xt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),s=(0,Xt.get)(zr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Xt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||((0,Qr.existsSync)(n)?n:(0,tt.join)((0,Xt.getHdbBasePath)(),zr.LEGACY_DATABASES_DIR_NAME));let o=(0,tt.join)(n,(i?t:e)+".mdb"),c=Ui.get(o);if(!c){let u=new bA.default(o,!1);c=(0,VE.open)(u),Ui.set(o,c)}return c}async function jp(e){if(!nt[e])throw new Error("Schema does not exist");let t=nt[e];for(let r in t){let s=t[r].primaryStore.rootStore;Ui.delete(s.path),s.status==="open"&&(await s.close(),await Kx.remove(s.path))}if(e==="data"){for(let r in wr)delete wr[r];delete wr[WE]}delete nt[e]}function ut({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=yA);let l=Xc({database:t,table:e}),d=nt[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,p,S;u==null&&(u=!0);let g=new Mo.default(!1);for(let M of i)M.attribute?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let A,R;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=l.auditStore;M||(M=yE(l)),h=i.find(ce=>ce.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Xt.get)(zr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),n&&(h.eviction=n),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),Sn.trace(`${e} table loading, opening primary store`);let K=new Mo.default(!1,!0),W=e+"/",V=n_(l.openDB(W,K));V.rootStore=l,S=l.dbisDb=l.openDB(kE.INTERNAL_DBIS_NAME,g),V.tableId=S.get(ja),V.tableId||(V.tableId=1),S.putSync(ja,V.tableId+1),h.tableId=V.tableId,f=Jx(d,e,GE({primaryStore:V,auditStore:M,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:E,tableName:e,tableId:V.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,A=!0,P(),S.put(W,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(kE.INTERNAL_DBIS_NAME,g)),f.dbisDB=S;let v=[];for(let{key:M,value:K}of S.getRange({start:!0})){let[W,V]=M.toString().split("/");if(V===""&&(V=K.name),V){if(W!==e)continue}else V=W;if(!i.find(de=>de.name===V)?.indexed&&K.indexed&&!K.isPrimaryKey){P(),A=!0,S.remove(M);let de=f.indices[W];de&&v.push(de)}}let H=[];try{for(let M of i||[]){if(M.relationship)continue;let K=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:K,configurable:!0});let W=S.get(K);if(M.isPrimaryKey){if(W=W||S.get(K=e+"/")||{},o!==f.audit||(+r||void 0)!==(+W.expiration||void 0)||(+n||void 0)!==(+W.eviction||void 0)){let ce=Object.assign({},W);typeof o=="boolean"&&(o&&f.enableAuditing(o),ce.audit=o),r&&(ce.expiration=+r),n&&(ce.eviction=+n),A=!0,P(),S.put(K,ce)}continue}W?.attribute&&!W.name&&(W.indexed=!0);let V=!W||W.type!==M.type||W.indexed!==M.indexed||W.nullable!==M.nullable||JSON.stringify(W.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(W.elements)!==JSON.stringify(M.elements);if(M.indexed){let ce=new Mo.default(!0,!1),de=l.openDB(K,ce);(V||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<Dl.workerData?.restartNumber)&&(A=!0,P(),W=S.get(K),(V||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<Dl.workerData?.restartNumber)&&(A=!0,M.lastIndexedKey=W?.lastIndexedKey||!1,M.indexingPID=process.pid,de.isIndexing=!0,Object.defineProperty(M,"dbi",{value:de}),M.indexNulls===void 0&&(M.indexNulls=!0),H.push(M)),S.put(K,M)),W?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),de.indexNulls=M.indexNulls,p[M.name]=de}else V&&(A=!0,P(),S.put(K,M))}}finally{R&&R()}if(A&&(f.schemaVersion++,f.updatedAttributes()),Sn.trace(`${e} table loading, running index`),H.length>0||v.length>0?f.indexingOperation=Tie(f,H,v):A&&$E.signalSchemaChange(new YE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,A)for(let M of wA)M(f,_!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),Sn.trace(`${e} table loaded`),f;function P(){R||l.transactionSync(()=>({then(M){R=M}}))}a(P,"startTxn")}async function Tie(e,t,r){try{let n=e.schemaVersion;await $E.signalSchemaChange(new YE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,Wx.getIndexedValues)(l[h]);if(p)for(let S=0,g=p.length;S<g;S++)E.dbi.put(p[S],_)}}),s.then(()=>u--,f=>{u--,Sn.error(f)}),Dl.workerData&&Dl.workerData.restartNumber!==Qx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>pie?await s:u>Sie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await $E.signalSchemaChange(new YE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){Sn.error("Error in indexing",n)}}function gie({table:e,database:t}){let r=Xc({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 vR(e){wA.push(e)}var Xt,kE,VE,tt,Qr,Xa,Mo,bA,zr,Kx,NA,Wx,$E,YE,Dl,Sn,Qx,yA,WE,wr,nt,ja,wA,KE,Ui,Za,pie,Sie,Re=ge(()=>{Xt=x(Z()),kE=x(ft()),VE=require("lmdb"),tt=require("path"),Qr=require("fs"),Xa=x(je());Ff();Mo=x(s_()),bA=x(o_()),zr=x(U()),Kx=x(require("fs-extra")),NA=require("../index"),Wx=x(yr()),$E=x(Rs()),YE=x(In()),Dl=require("worker_threads"),Sn=x($()),Qx=x(We());Hi();Go();yA="data",WE=Symbol("defined-tables");(0,Xt.initSync)();wr=Object.create(null),nt=Object.create(null);(0,NA._assignPackageExport)("databases",nt);(0,NA._assignPackageExport)("tables",wr);ja=Symbol.for("next-table-id"),wA=[],Ui=new Map;a(hie,"getTables");a(Dn,"getDatabases");a(mie,"resetDatabases");a(Cl,"readMetaDb");a(zx,"ensureDB");a(Jx,"setTable");a(Xc,"database");a(jp,"dropDatabase");a(ut,"table");pie=1e3,Sie=10;a(Tie,"runIndexing");a(gie,"dropTableMeta");a(vR,"onUpdatedTable")});var J=T((GSe,lq)=>{"use strict";var Li=require("path"),tq=require("fs-extra"),Or=$(),jx=require("fs-extra"),QE=require("os"),Rie=require("net"),Aie=require("recursive-iterator"),ct=U(),Oie=OO(),Xx=require("papaparse"),zE=require("moment"),{inspect:bie}=require("util"),Zx=require("is-number"),FSe=require("lodash"),Nie=require("minimist"),yie=require("https"),wie=require("http"),{hdb_errors:JE}=re(),Iie=/^((\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)))$/,rq=require("util").promisify(setTimeout),Cie=100,Die=5,Uie="",Lie=4,eq={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};lq.exports={isEmpty:Jr,isEmptyOrZeroLength:ds,arrayHasEmptyValues:vie,arrayHasEmptyOrZeroLengthValues:Bie,buildFolderPath:Hie,isBoolean:nq,errorizeMessage:Mie,stripFileExtension:qie,autoCast:Fie,autoCastJSON:sq,autoCastJSONDeep:CA,removeDir:Gie,compareVersions:kie,isCompatibleDataVersion:Vie,escapeRawValue:$ie,unescapeValue:Yie,stringifyProps:Kie,timeoutPromise:Qie,isClusterOperation:Jie,getClusterUser:Xie,checkGlobalSchemaTable:jie,getHomeDir:oq,getPropsFilePath:Wie,promisifyPapaParse:Zie,removeBOM:aq,createEventPromise:eoe,checkProcessRunning:toe,checkSchemaTableExist:roe,checkSchemaExists:cq,checkTableExists:uq,getStartOfTomorrowInSeconds:noe,getLimitKey:soe,isObject:xie,isNotEmptyAndHasValue:Pie,autoCasterIsNumberCheck:iq,backtickASTSchemaItems:ioe,isPortTaken:zie,createForkArgs:ooe,autoCastBoolean:aoe,async_set_timeout:rq,getTableHashAttribute:coe,doesSchemaExist:uoe,doesTableExist:loe,stringifyObj:_oe,ms_to_time:doe,changeExtension:foe,getEnvCliRootPath:DA,noBootFile:Eoe,httpRequest:hoe,transformReq:moe,convertToMS:poe,PACKAGE_ROOT:ct.PACKAGE_ROOT};function Mie(e){return e instanceof Error?e:new Error(e)}a(Mie,"errorizeMessage");function Jr(e){return e==null}a(Jr,"isEmpty");function Pie(e){return!Jr(e)&&(e||e===0||e===""||nq(e))}a(Pie,"isNotEmptyAndHasValue");function ds(e){return Jr(e)||e.length===0||e.size===0}a(ds,"isEmptyOrZeroLength");function vie(e){if(Jr(e))return!0;for(let t=0;t<e.length;t++)if(Jr(e[t]))return!0;return!1}a(vie,"arrayHasEmptyValues");function Bie(e){if(ds(e))return!0;for(let t=0;t<e.length;t++)if(ds(e[t]))return!0;return!1}a(Bie,"arrayHasEmptyOrZeroLengthValues");function Hie(...e){try{return e.join(Li.sep)}catch{console.error(e)}}a(Hie,"buildFolderPath");function nq(e){return Jr(e)?!1:e===!0||e===!1}a(nq,"isBoolean");function xie(e){return Jr(e)?!1:typeof e=="object"}a(xie,"isObject");function qie(e){return ds(e)?Uie:e.slice(0,-Lie)}a(qie,"stripFileExtension");function Fie(e){return Jr(e)||e===""||typeof e!="string"?e:eq[e]!==void 0?eq[e]:iq(e)===!0?Number(e):Iie.test(e)?new Date(e):e}a(Fie,"autoCast");function sq(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(sq,"autoCastJSON");function CA(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=CA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=CA(r);n!==r&&(e[t]=n)}return e}else return sq(e)}a(CA,"autoCastJSONDeep");function iq(e){if(e.startsWith("0.")&&Zx(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Zx(e))}a(iq,"autoCasterIsNumberCheck");async function Gie(e){if(ds(e))throw new Error(`Directory path: ${e} does not exist`);try{await jx.emptyDir(e),await jx.remove(e)}catch(t){throw Or.error(`Error removing files in ${e} -- ${t}`),t}}a(Gie,"removeDir");function kie(e,t){if(ds(e)){Or.info("Invalid current version sent as parameter.");return}if(ds(t)){Or.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(kie,"compareVersions");function Vie(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Vie,"isCompatibleDataVersion");function $ie(e){if(Jr(e))return e;let t=String(e);return t==="."?ct.UNICODE_PERIOD:t===".."?ct.UNICODE_PERIOD+ct.UNICODE_PERIOD:t.replace(ct.FORWARD_SLASH_REGEX,ct.UNICODE_FORWARD_SLASH)}a($ie,"escapeRawValue");function Yie(e){if(Jr(e))return e;let t=String(e);return t===ct.UNICODE_PERIOD?".":t===ct.UNICODE_PERIOD+ct.UNICODE_PERIOD?"..":String(e).replace(ct.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Yie,"unescapeValue");function Kie(e,t){if(Jr(e))return Or.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+QE.EOL}!ds(n)&&n[0]===";"?r+=" "+n+s+QE.EOL:ds(n)||(r+=n+"="+s+QE.EOL)}catch{Or.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Kie,"stringifyProps");function oq(){let e;try{e=QE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(oq,"getHomeDir");function Wie(){let e=Li.join(oq(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return tq.existsSync(e)||(e=Li.join(__dirname,"../","hdb_boot_properties.file")),e}a(Wie,"getPropsFilePath");function Qie(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Qie,"timeoutPromise");async function zie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Rie.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(zie,"isPortTaken");function Jie(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Or.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Jie,"isClusterOperation");function jie(e,t){let r=(Re(),ne(Fe)).getDatabases();if(!r[e])return JE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return JE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(jie,"checkGlobalSchemaTable");function Xie(e,t){if(Jr(t)){Or.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Jr(e)||ds(e)){Or.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){Or.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Or.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Xie,"getClusterUser");function Zie(){Xx.parsePromise=function(e,t,r){return new Promise(function(n,s){Xx.parse(e,{header:!0,transformHeader:aq,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Zie,"promisifyPapaParse");function aq(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(aq,"removeBOM");function eoe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Or.info(`Got cluster status event response: ${bie(s)}`);try{i.cancel()}catch{Or.error("Error trying to cancel timeout.")}n(s)})})}a(eoe,"createEventPromise");async function toe(e){let t=!0,r=0;do await rq(Cie*r++),(await Oie.findPs(e)).length>0&&(t=!1);while(t&&r<Die);if(t)throw new Error(`process ${e} was not started`)}a(toe,"checkProcessRunning");function roe(e,t){let r=cq(e);if(r)return r;let n=uq(e,t);if(n)return n}a(roe,"checkSchemaTableExist");function cq(e){let{getDatabases:t}=(Re(),ne(Fe));if(!t()[e])return JE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(cq,"checkSchemaExists");function uq(e,t){let{getDatabases:r}=(Re(),ne(Fe));if(!r()[e][t])return JE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(uq,"checkTableExists");function noe(){let e=zE().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=zE().utc().unix();return e-t}a(noe,"getStartOfTomorrowInSeconds");function soe(){return zE().utc().format("DD-MM-YYYY")}a(soe,"getLimitKey");function ioe(e){try{let t=new Aie(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){Or.error("Got an error back ticking items."),Or.error(t)}}a(ioe,"backtickASTSchemaItems");function ooe(e){return[e]}a(ooe,"createForkArgs");function aoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(aoe,"autoCastBoolean");function coe(e,t){let{getDatabases:r}=(Re(),ne(Fe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(coe,"getTableHashAttribute");function uoe(e){let{getDatabases:t}=(Re(),ne(Fe));return t()[e]!==void 0}a(uoe,"doesSchemaExist");function loe(e,t){let{getDatabases:r}=(Re(),ne(Fe));return r()[e]?.[t]!==void 0}a(loe,"doesTableExist");function _oe(e){try{return JSON.stringify(e)}catch{return e}}a(_oe,"stringifyObj");function doe(e){let t=zE.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(doe,"ms_to_time");function foe(e,t){let r=Li.basename(e,Li.extname(e));return Li.join(Li.dirname(e),r+t)}a(foe,"changeExtension");function DA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Nie(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(DA,"getEnvCliRootPath");var IA;function Eoe(){if(IA)return IA;let e=DA();DA()&&tq.pathExistsSync(Li.join(e,ct.HDB_CONFIG_FILE))&&(IA=!0)}a(Eoe,"noBootFile");function hoe(e,t){let r;return e.protocol==="http:"?r=wie:r=yie,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(hoe,"httpRequest");function moe(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(moe,"transformReq");function poe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(poe,"convertToMS")});var Z=T((VSe,Eq)=>{"use strict";var UA=require("fs-extra"),Po=require("path"),_q=require("os"),Soe=require("properties-reader"),Ll=$(),Ul=J(),ue=U(),jE=Lr(),Toe="Error initializing environment manager",XE="BOOT_PROPS_FILE_PATH",dq=!1,goe={[ue.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Vs={};Eq.exports={BOOT_PROPS_FILE_PATH:XE,getHdbBasePath:Roe,setHdbBasePath:Aoe,get:fq,initSync:boe,setProperty:Le,initTestEnvironment:Noe};function Roe(){return Vs[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Roe,"getHdbBasePath");function Aoe(e){Vs[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Aoe,"setHdbBasePath");function fq(e){let t=jE.getConfigValue(e);return t===void 0?Vs[e]:t}a(fq,"get");function Le(e,t){goe[e]&&(Vs[e]=t),jE.updateConfigObject(e,t)}a(Le,"setProperty");function Ooe(){let e;try{e=Ul.getPropsFilePath(),UA.accessSync(e,UA.constants.F_OK|UA.constants.R_OK),dq=!0;let t=Soe(e);return Vs[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Vs[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Vs[XE]=e,!0}catch{return Ll.trace(`Environment manager found no properties file at ${e}`),!1}}a(Ooe,"doesPropFileExist");function boe(e=!1){try{(dq||Ooe()||Ul.noBootFile())&&(jE.initConfig(e),Vs[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=jE.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Ll.error(Toe),Ll.error(t),console.error(t),process.exit(1)}}a(boe,"initSync");function Noe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Po.join(__dirname,"../../","unitTests");Vs[XE]=Po.join(u,"hdb_boot_properties.file"),Le(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Po.join(u,"settings.test")),Le(ue.HDB_SETTINGS_NAMES.INSTALL_USER,_q.userInfo()?_q.userInfo().username:void 0),Le(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Le(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Po.join(u,"envDir","log")),Le(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Le(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Le(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Le(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Po.join(u,"envDir")),Le(ue.CONFIG_PARAMS.STORAGE_PATH,Po.join(u,"envDir")),s&&(Le(ue.CONFIG_PARAMS.HTTP_SECUREPORT,fq(ue.CONFIG_PARAMS.HTTP_PORT)),Le(ue.CONFIG_PARAMS.HTTP_PORT,null)),Le(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Le(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Le(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ul.isEmpty(i)?!1:i),Le(ue.CONFIG_PARAMS.HTTP_CORS,Ul.isEmpty(i)?!1:i),Le(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Le(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Le(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Le(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Le(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Po.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Le(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ul.isEmpty(c)?!1:c),o&&(Le("CORS_ACCESSLIST",o),Le(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Le(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Le(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Le(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Le(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Le(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Le(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${XE}. Please check your boot props and settings files`;Ll.fatal(r),Ll.error(t)}}a(Noe,"initTestEnvironment")});var Tq=T((YSe,Sq)=>{"use strict";var pq=require("joi"),{string:Ml,boolean:hq,array:yoe}=pq.types(),mq=U(),woe=Xe();Sq.exports=Ioe;function Ioe(e){let t=pq.object({operation:Ml.valid(mq.OPERATIONS_ENUM.ADD_NODE,mq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Ml.required(),subscriptions:yoe.items({schema:Ml.required(),table:Ml.optional(),hash_attribute:Ml.optional(),subscribe:hq.required(),publish:hq.required()}).min(1).required()});return woe.validateBySchema(e,t)}a(Ioe,"updateRemoteSourceValidator")});var Pl=T((WSe,gq)=>{"use strict";var LA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};gq.exports=LA});var Nq=T((zSe,bq)=>{"use strict";var Coe=Tq(),$s=$(),MA=Ge(),Rq=U(),PA=on(),vA=st(),Aq=Eu(),Doe=K_(),{Node:Uoe,NodeSubscription:Oq}=fi(),BA=Pl(),HA=J(),Loe=Z(),{cloneDeep:Moe}=require("lodash"),{broadcast:Poe}=We();bq.exports=voe;async function voe(e){try{let t=Coe(e);if(t)return $s.error(`Validation error in updateRemoteSource: ${t.message}`),new BA(MA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=Moe(await PA.getNodeRecord(n)),c=!HA.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&$s.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!HA.doesSchemaExist(f)){$s.trace(`updateRemoteSource creating schema: ${f}`);try{await Aq.createSchema({operation:"create_schema",schema:f})}catch(h){$s.error(h)}}if(E&&!HA.doesTableExist(f,E)){let h=new Doe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),$s.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await Aq.createTable(h)}catch(p){$s.error(p)}$s.trace(`Creating local stream for ${f}.${E}`),await vA.createLocalTableStream(f,E)}if(f===Rq.SYSTEM_SCHEMA_NAME&&await vA.createLocalTableStream(f,E),await vA.updateWorkStream(d,n),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let g=o.subscriptions[p];if(g.schema===f&&g.table===E){g.publish=d.publish,g.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new Oq(f,E,d.publish,d.subscribe))}else i.push(new Oq(f,E,d.publish,d.subscribe))}c||(o=new Uoe(n,i,void 0),$s.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await PA.upsertNodeRecord(u),Poe({type:"nats_update"}),new BA(MA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Loe.get(Rq.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await PA.getSystemInfo())}catch(t){$s.error(t);let r=t.message?t.message:t;return new BA(MA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(voe,"updateRemoteSource")});var Cq=T((jSe,Iq)=>{"use strict";var wq=require("joi"),{string:yq}=wq.types(),Boe=U(),Hoe=Xe();Iq.exports=xoe;function xoe(e){let t=wq.object({operation:yq.valid(Boe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:yq.required()});return Hoe.validateBySchema(e,t)}a(xoe,"removeRemoteSourceValidator")});var Uq=T((ZSe,Dq)=>{"use strict";var qoe=Cq(),ZE=$(),eh=Ge(),xA=U(),Foe=on(),Goe=J(),koe=st(),Voe=Z(),th=Pl(),{NodeSubscription:$oe}=fi(),Yoe=sa(),Koe=ri(),{broadcast:Woe}=We(),Qoe=Voe.get(xA.CONFIG_PARAMS.CLUSTERING_NODENAME);Dq.exports=zoe;async function zoe(e){try{let t=qoe(e);if(t)return ZE.error(`Validation error in removeRemoteSource: ${t.message}`),new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await Foe.getNodeRecord(r);if(Goe.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return ZE.error(i),new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];ZE.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new $oe(c.schema,c.table,!1,!1);await koe.updateWorkStream(u,r)}let s=new Yoe(xA.SYSTEM_SCHEMA_NAME,xA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Koe.deleteRecord(s),Woe({type:"nats_update"}),new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Qoe} successfully removed node '${r}'.`)}catch(t){ZE.error(t);let r=t.message?t.message:t;return new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(zoe,"removeRemoteSource")});var Bq=T((tTe,vq)=>{"use strict";var rh=$(),nh=U(),Lq=Ge(),Mq=Z(),Joe=J(),Pq=Pl(),joe=on(),Xoe=Sd(),Zoe=Cr();vq.exports=eae;async function eae(e){try{rh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Joe.ms_to_time(t),n=new tae(Mq.get(nh.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),Mq.get(nh.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT),r,await joe.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new Xoe(nh.SYSTEM_SCHEMA_NAME,nh.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Zoe.update(i)}catch(s){rh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return rh.trace("getRemoteSourceConfig response:",n),new Pq(Lq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){rh.error(t);let r=t.message?t.message:t;return new Pq(Lq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(eae,"getRemoteSourceConfig");function tae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(tae,"ConfigResponseObject")});var Fq=T((nTe,qq)=>{"use strict";var Hq=Z();Hq.initSync();var xq=st(),vl=$(),ec=U(),qA=Ge(),rae=Nq(),nae=Uq(),sae=Bq(),iae=Pl(),{encode:oae,decode:aae}=require("msgpackr"),cae=gs(),uae=Zs(),lae=require("util"),_ae=U(),{isMainThread:dae,parentPort:fae}=require("worker_threads");We();var Eae=lae.promisify(cae.setSchemaDataToGlobal),FA=Hq.get(ec.CONFIG_PARAMS.CLUSTERING_NODENAME);qq.exports=hae;async function hae(){try{vl.notify("Starting reply service."),await Eae();let e=await xq.getConnection(),t=`${FA}.__request__`,r=e.subscribe(t,{queue:FA});await mae(r)}catch(e){vl.error(e)}}a(hae,"initialize");async function mae(e){for await(let t of e){let r=aae(t.data),n;switch(r.operation){case ec.OPERATIONS_ENUM.ADD_NODE:case ec.OPERATIONS_ENUM.UPDATE_NODE:n=await rae(r);break;case ec.OPERATIONS_ENUM.REMOVE_NODE:n=await nae(r);break;case ec.OPERATIONS_ENUM.CLUSTER_STATUS:n=await sae(r);break;case ec.OPERATIONS_ENUM.DESCRIBE_ALL:n=await pae();break;default:let s=`node '${FA}' reply service received unrecognized request operation`;vl.error(s),n=new iae(qA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}vl.trace(n),t.respond(oae(n))}}a(mae,"handleRequest");async function pae(){try{return{status:qA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await uae.describeAll()}}catch(e){return vl.error(e),{status:qA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(pae,"getRemoteDescribeAll");dae||fae.on("message",async e=>{let{type:t}=e;t===_ae.ITC_EVENT_TYPES.SHUTDOWN&&xq.closeConnection()})});var Sae=Fq();(async()=>{try{await Sae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|