harperdb 4.3.0-beta.5 → 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 +3 -3
- package/launchServiceScripts/launchNatsIngestService.js +19 -19
- package/launchServiceScripts/launchNatsReplyService.js +19 -19
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +19 -19
- package/npm-shrinkwrap.json +95 -70
- package/package.json +2 -2
- package/resources/DatabaseTransaction.d.ts +4 -4
- 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.1b4b013e.js → main.e02ed83a.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -19
- /package/studio/build-local/static/js/{main.1b4b013e.js.LICENSE.txt → main.e02ed83a.js.LICENSE.txt} +0 -0
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
"use strict";var kq=Object.create;var ec=Object.defineProperty;var Vq=Object.getOwnPropertyDescriptor;var $q=Object.getOwnPropertyNames;var Yq=Object.getPrototypeOf,Kq=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})},$A=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $q(t))!Kq.call(e,n)&&n!==r&&ec(e,n,{get:()=>t[n],enumerable:!(s=Vq(t,n))||s.enumerable});return e};var x=(e,t,r)=>(r=e!=null?kq(Yq(e)):{},$A(t||!e||!e.__esModule?ec(r,"default",{value:e,enumerable:!0}):r,e)),se=e=>$A(ec({},"__esModule",{value:!0}),e);var WA=T((pae,KA)=>{var Wq=require("fast-glob"),{statSync:oh,existsSync:ah,readFileSync:Qq,writeFileSync:zq}=require("fs"),{spawnSync:Jq,spawn:jq,execFileSync:mae}=require("child_process"),{isMainThread:Xq}=require("worker_threads"),{join:Wn,relative:YA}=require("path"),{PACKAGE_ROOT:gs}=L(),{tmpdir:Zq,platform:eF}=require("os");require("source-map-support").install();var tF=["resources","server","dataLayer","components"],tc="ts-build",ch,rF=__filename.endsWith("tsBuild.js");if(rF){if(Xq){let r;try{oh(Wn(gs,tc)),r=!0}catch{}if(r)for(let s of Wq.sync(tF.map(n=>n+"/**/*.ts"),{cwd:gs})){let n=0,i=0;try{n=oh(Wn(gs,s)).mtimeMs-5e3,i=oh(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."),ch=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),ch=!0;if(ch){let s=Wn(gs,"node_modules/.bin/tsc");eF()==="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(Zq(),"harperdb-tsc.pid"),o;if(ah(i))try{process.kill(+Qq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=jq(s,["--watch"],{cwd:gs,detached:!0,stdio:"ignore"});zq(i,c.pid.toString()),c.unref()}}}}let e=KA.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=YA(gs,s[0]),o;i.startsWith(tc)?o=Wn(gs,YA(tc,i)):o=Wn(gs,tc,i);let c=Wn(o,r),u=c+".js";if(ah(u))return u;if(c.includes(".")&&ah(c))return c}return t(r,s,n)}}});var L=T((gae,aO)=>{"use strict";var Xr=require("path"),sF=require("fs"),{relative:Sae,join:Tae}=Xr,{existsSync:nF}=sF;function iF(){let e=__dirname;for(;!nF(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(iF,"getHDBPackageRoot");var Qn=iF(),QA="js",Hl=QA,oF="harperdb-config.yaml",aF="defaultConfig.yaml",cF="hdb",zA=`harperdb.${Hl}`,JA=`customFunctionsServer.${Hl}`,uF=`restartHdb.${Hl}`,lh="HarperDB",Bl="Custom Functions",xl="Clustering Hub",ql="Clustering Leaf",lF="Clustering Ingest Service",_F="Clustering Reply Service",dF="foreground.pid",fF="hdb.pid",EF="data",hF={HDB:lh,CLUSTERING_HUB:xl,CLUSTERING_LEAF:ql,CLUSTERING_INGEST_SERVICE:lF,CLUSTERING_REPLY_SERVICE:_F,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"},mF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},pF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},SF={harperdb:lh,"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"},TF={CLUSTERING_HUB_PROC_DESCRIPTOR:xl,CLUSTERING_LEAF_PROC_DESCRIPTOR:ql},uh={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")},gF={HDB:Xr.join(uh.HDB,zA),CUSTOM_FUNCTIONS:Xr.join(uh.CUSTOM_FUNCTIONS,JA)},RF={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")},AF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},jA="support@harperdb.io",OF="customer-success@harperdb.io",XA=1,bF=4141,ZA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",NF="https://www.harperdb.io/product",yF=`For support, please submit a request at ${ZA} or contact ${jA}`,eO=`For license support, please contact ${OF}`,wF="None of the specified records were found.",IF="hash attribute not found",CF=`Your current license only supports ${XA} role. ${eO}`,DF="Your current license only supports 3 connections to a node.",LF="127.0.0.1",UF=1,MF=/^\.$/,PF=/^\.\.$/,vF="U+002E",BF=/\//g,HF="U+002F",xF=/U\+002F/g,qF=/^U\+002E$/,FF=/^U\+002EU\+002E$/,GF="d",kF=999999,VF="*",$F="--max-old-space-size=",YF="system",KF="__hdb_hash",WF=".harperdb",QF=".hdb",zF="keys",JF="hdb_boot_properties.file",jF=".updateConfig.json",XF="SIGTSTP",ZF=24,eG=6e4,tG=448,rG="blob",sG="trash",nG="database",iG="schema",oG="transactions",aG=".count",cG="id",uG="PROCESS_NAME",tO={SETTINGS_PATH_KEY:"settings_path"},rO=require("lodash"),lG={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"},_G={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},dG={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},fG={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"},EG={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},Ar="hdb_internal:",hG={CREATE_SCHEMA:Ar+"create_schema",CREATE_TABLE:Ar+"create_table",CREATE_ATTRIBUTE:Ar+"create_attribute",ADD_USER:Ar+"add_user",ALTER_USER:Ar+"alter_user",DROP_USER:Ar+"drop_user",HDB_NODES:Ar+"hdb_nodes",HDB_USERS:Ar+"hdb_users",HDB_WORKERS:Ar+"hdb_workers",CATCHUP:Ar+"catchup",SCHEMA_CATCHUP:Ar+"schema_catchup",WORKER_ROOM:Ar+"cluster_workers"},mG={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"},pG="060493.ks",SG=".license",TG={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"},gG={CSV:".csv",JSON:".json"},RG={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},AG={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 Be=Object.create(null);Be[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;Be[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;Be[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;Be[X.READ_LOG]=X.READ_LOG;Be[X.ADD_NODE]=X.ADD_NODE;Be[X.LIST_USERS]=X.LIST_USERS;Be[X.LIST_ROLES]=X.LIST_ROLES;Be[X.USER_INFO]=X.USER_INFO;Be[X.SQL]=X.SQL;Be[X.GET_JOB]=X.GET_JOB;Be[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;Be[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;Be[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;Be[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;Be[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;Be[X.REMOVE_NODE]=X.REMOVE_NODE;Be[X.RESTART]=X.RESTART;Be[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;Be[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;Be[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;Be[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;Be[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;Be[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;Be[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;Be[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;Be[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var OG={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"},bG={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"},NG=rO.invert(sO),yG={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_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"},nO={settings_path:tO.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_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];nO[t.toLowerCase()]=t}var wG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},IG={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"},CG={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"},DG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},LG={VERSION_DEFAULT:"2.2.0"},UG={DEVELOPMENT:8192,DEFAULT:512},MG={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"},PG={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"},vG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},iO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},BG=Symbol("metadata"),HG="__clustering__",xG=Object.values(iO),qG=15984864e5,oO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},FG=rO.invert(oO),GG={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,VG=`\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:Ak.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(yk,"findPs")});var dt=T((Iae,bO)=>{"use strict";var wk="__dbis__",Ik="__txns__",Ck="__environment_name__",Dk="__dbi_defintion__",Lk={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"},Uk=["__createdtime__","__updatedtime__"],Mk="\uFFFF",OO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},Pk=Object.values(OO);bO.exports={AUDIT_STORE_NAME:Ik,INTERNAL_DBIS_NAME:wk,DBI_DEFINITION_NAME:Dk,SEARCH_TYPES:Lk,TIMESTAMP_NAMES:Uk,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Ck,TRANSACTIONS_DBI_NAMES_ENUM:OO,TRANSACTIONS_DBIS:Pk,OVERFLOW_MARKER:Mk}});var Or=T((Cae,MO)=>{"use strict";var NO=L(),yO=dt(),wO={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},IO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),CO={500:IO("There was an error processing your request."),400:"Invalid request"},vk=CO[wO.INTERNAL_SERVER_ERROR],Bk={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.`},Hk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},xk={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"},qk={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 ${yO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${yO.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"},Fk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${NO.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 ${NO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},DO={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},Gk={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`},Vk={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"},$k={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Yk={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.`},UO={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}`},Kk={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."},Wk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Qk={...DO,...xk,...Bk,...Gk,...kk,...Vk,...$k,...Yk,...Fk,...LO,...UO,...Kk,...Wk,...Hk};MO.exports={CHECK_LOGS_WRAPPER:IO,HDB_ERROR_MSGS:Qk,DEFAULT_ERROR_MSGS:CO,DEFAULT_ERROR_RESP:vk,HTTP_STATUS_CODES:wO,LMDB_ERRORS_ENUM:qk,AUTHENTICATION_ERROR_MSGS:DO,VALIDATION_ERROR_MSGS:LO,ITC_ERRORS:UO}});var re=T((Lae,BO)=>{"use strict";var Ho=Or(),zk=V(),Jk=L(),$l=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,PO),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&&zk[n](i)}},Th=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}},gh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function PO(e,t,r,s=Jk.LOG_LEVELS.ERROR,n=null,i=!1){if(vO(e))return e;let o=new $l(e,t,r,s,n);return i&&delete o.stack,o}a(PO,"handleHDBError");function vO(e){return e.__proto__.constructor.name===$l.name}a(vO,"isHDBError");BO.exports={isHDBError:vO,handleHDBError:PO,ClientError:Th,ServerError:gh,hdb_errors:Ho}});var Je=T((Mae,VO)=>{"use strict";var dc=L(),jk=J(),er=Z(),fc=require("path"),Xk=require("minimist"),HO=require("fs-extra"),xO=require("lodash");er.initSync();var{CONFIG_PARAMS:zn,DATABASES_PARAM_CONFIG:cc,SYSTEM_SCHEMA_NAME:Yl}=dc,uc,lc,_c;function qO(){if(uc!==void 0)return uc;if(er.getHdbBasePath()!==void 0)return uc=er.get(zn.STORAGE_PATH)||fc.join(er.getHdbBasePath(),dc.DATABASES_DIR_NAME),uc}a(qO,"getBaseSchemaPath");function FO(){if(lc!==void 0)return lc;if(er.getHdbBasePath()!==void 0)return lc=kO(Yl),lc}a(FO,"getSystemSchemaPath");function GO(){if(_c!==void 0)return _c;if(er.getHdbBasePath()!==void 0)return _c=er.get(dc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||fc.join(er.getHdbBasePath(),dc.TRANSACTIONS_DIR_NAME),_c}a(GO,"getTransactionAuditStoreBasePath");function Zk(e,t){let r=er.get(zn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||fc.join(GO(),e.toString())}a(Zk,"getTransactionAuditStorePath");function kO(e,t){e=e.toString(),t=t&&t.toString();let r=er.get(dc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||fc.join(qO(),e)}a(kO,"getSchemaPath");function eV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,Xk(process.argv));let s=r[zn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!jk.isObject(s))throw o;i=s}for(let o of i){let c=o[Yl];if(!c)continue;let u=er.get(zn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[cc.PATH];if(_)return xO.set(u,[Yl,cc.TABLES,t,cc.PATH],_),er.setProperty(zn.DATABASES,u),_;let l=c?.[cc.PATH];if(l)return xO.set(u,[Yl,cc.PATH],l),er.setProperty(zn.DATABASES,u),l}}let n=r[zn.STORAGE_PATH.toUpperCase()];if(n){if(!HO.pathExistsSync(n))throw new Error(n+" does not exist");let i=fc.join(n,e);return HO.mkdirsSync(i),er.setProperty(zn.STORAGE_PATH,n),i}return FO()}a(eV,"initSystemSchemaPaths");function tV(){uc=void 0,lc=void 0,_c=void 0}a(tV,"resetPaths");VO.exports={getBaseSchemaPath:qO,getSystemSchemaPath:FO,getTransactionAuditStorePath:Zk,getTransactionAuditStoreBasePath:GO,getSchemaPath:kO,initSystemSchemaPaths:eV,resetPaths:tV}});var br=T((Hae,QO)=>{"use strict";var rV=Or().LMDB_ERRORS_ENUM,vae=require("lmdb"),sV=dt(),Bae=require("buffer").Buffer,{OVERFLOW_MARKER:$O,MAX_SEARCH_KEY_LENGTH:Kl}=sV,YO=["number","string","symbol","boolean","bigint"];function nV(e){if(e=e?.primaryStore||e,!e)throw new Error(rV.ENV_REQUIRED)}a(nV,"validateEnv");function iV(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(iV,"stringifyData");function oV(e){return e instanceof Date?e.valueOf():e}a(oV,"convertKeyValueToWrite");function aV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(YO.includes(typeof e))return e.length>Kl?[e.slice(0,Kl)+$O]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if(YO.includes(typeof i))i.length>Kl?r.push(i.slice(0,Kl)+$O):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(aV,"getIndexedValues");var Wl=0,KO=0;function WO(){KO=Date.now()-performance.now()}a(WO,"adjustStartTime");WO();var cV=6e4;setInterval(WO,cV).unref();function uV(){let e=performance.now()+KO;return e>Wl?(Wl=e,e):(Wl+=488e-6,Wl)}a(uV,"getNextMonotonicTime");QO.exports={validateEnv:nV,stringifyData:iV,convertKeyValueToWrite:oV,getNextMonotonicTime:uV,getIndexedValues:aV}});var zO,Rs,Rh,Ec=Re(()=>{zO=require("events"),Rs=class extends zO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Rh;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)}},Rh=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 JO,tt,tr=Re(()=>{JO=require("../index"),tt={};(0,JO._assignPackageExport)("server",tt)});var bh={};Ye(bh,{loadGQLSchema:()=>dV,start:()=>Oh,startOnMainThread:()=>_V});function Oh({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):lV.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,Ah.dirname)(s),S.tableClass):i.set((0,Ah.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass))}}var Ah,jO,lV,_V,dV,XO=Re(()=>{Ah=require("path");Ae();jO=x(Ke()),lV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Oh,"start");_V=Oh,dV=Oh({ensureTable:ct}).handleFile});async function Ql(e){return fV?(hc||(hc=EV(mV)),(await(await hc).import(e)).namespace):import(e)}async function EV(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:hV,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,eb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:Ht,tables:Nr,databases:rt})}};let s=await(0,ZO.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),hc}function hV(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 mV(){return{Resource:Ht,tables:Nr}}var ZO,eb,fV,hc,Nh=Re(()=>{As();Ae();ZO=require("fs/promises"),eb=require("path"),fV=!1;a(Ql,"secureImport");a(EV,"getCompartment");a(hV,"secureOnlyFetch");a(mV,"getGlobalVars")});var wh={};Ye(wh,{handleFile:()=>pV});async function pV(e,t,r,s){let n=new Map,i=(0,tb.pathToFileURL)(r).toString(),o=await Ql(i);u(o.default)&&s.set((0,yh.dirname)(t),o.default),c(o,(0,yh.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 tb,yh,rb=Re(()=>{tb=require("url");Nh();yh=require("path");a(pV,"handleFile")});var Ch={};Ye(Ch,{start:()=>SV});function SV({resources:e}){e.set("login",Ih),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Ih,sb=Re(()=>{As();a(SV,"start");Ih=class extends Ht{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 lb={};Ye(lb,{parse:()=>Lh,streamAsJSON:()=>mc,stringify:()=>Pi});function mc(e){return new Dh({value:e})}function nb(e){return console.error(e),JSON.stringify(e.toString())}function ib(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Pi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===cb)return ub(e);if(t.resolution)return t.resolution.then(()=>Pi(e));throw t}}function ub(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let s=0;s<e.length;s++)s>0&&(r+=","),r+=ub(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 Lh(e){return RV.test(e)?TV.parse(e):JSON.parse(e)}var ob,ab,TV,gV,cb,Dh,RV,Uh=Re(()=>{ob=require("stream"),ab=x(require("json-bigint-fixes")),TV=(0,ab.default)({useNativeBigInt:!0}),gV=1e4,cb={};BigInt.prototype.toJSON=function(){throw cb};a(mc,"streamAsJSON");Dh=class extends ob.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],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),nb)}catch(n){yield nb(n)}else yield Pi(t)}else yield Pi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);ib(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>gV?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return ib(this.readIterator(t.childIterator),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(nb,"handleError");a(ib,"when");a(Pi,"stringify");a(ub,"jsStringify");RV=/-?\d{16,}/;a(Lh,"parse")});var Ob=T((Zae,Ab)=>{"use strict";var Mh=require("recursive-iterator"),AV=require("alasql"),Ph=require("clone"),_b=J(),{handleHDBError:db,hdb_errors:OV}=re(),{HDB_ERROR_MSGS:fb,HTTP_STATUS_CODES:Eb}=OV,{getDatabases:bV}=(Ae(),se(Fe)),NV=["DISTINCT_ARRAY"],hb=Symbol("validateTables"),vh=Symbol("validateTable"),Xae=Symbol("getAllColumns"),mb=Symbol("validateAllColumns"),zl=Symbol("findColumn"),pb=Symbol("validateOrderBy"),pc=Symbol("validateSegment"),Bh=Symbol("validateColumn"),Sb=Symbol("setColumnsForTable"),Tb=Symbol("checkColumnsForAsterisk"),gb=Symbol("validateGroupBy"),Rb=Symbol("hasColumns"),Hh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[hb](),this[Tb](),this[mb]()}[hb](){if(this[Rb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[vh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[vh](t.table)})}}[Rb](){let t=!1,r=new Mh(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[vh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=bV();if(!r[t.databaseid])throw db(new Error,fb.SCHEMA_NOT_FOUND(t.databaseid),Eb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw db(new Error,fb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Eb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=Ph(n);i.table=Ph(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)}[Tb](){let t=new Mh(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Sb](r.tableid)}[Sb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new AV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[mb](){this[pc](this.statement.columns,!1),this[pc](this.statement.joins,!1),this[pc](this.statement.where,!1),this[gb](this.statement.group,!1),this[pc](this.statement.order,!0)}[pc](t,r){if(!t)return;let s=new Mh(t),n=[];for(let{node:i,path:o}of s)!_b.isEmpty(i)&&!_b.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[pb](i):n.push(this[Bh](i)));return n}[gb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&NV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Ph(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`}[pb](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[Bh](t)}[Bh](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]}};Ab.exports=Hh});var Nb=T((tce,bb)=>{"use strict";var xh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};bb.exports=xh});var wb=T((sce,yb)=>{"use strict";var qh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};yb.exports=qh});var Lb={};Ye(Lb,{HAS_EXPIRATION:()=>Wh,LAST_TIMESTAMP_PLACEHOLDER:()=>gc,LOCAL_TIMESTAMP:()=>yV,METADATA:()=>Sc,NO_TIMESTAMP:()=>Gh,PENDING_LOCAL_TIME:()=>Qh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Kh,RecordEncoder:()=>$h,TIMESTAMP_ASSIGN_LAST:()=>IV,TIMESTAMP_ASSIGN_NEW:()=>Cb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Db,TIMESTAMP_PLACEHOLDER:()=>Jl,TIMESTAMP_RECORD_PREVIOUS:()=>kh,fromResource:()=>e_,getUpdateRecord:()=>zh,handleLocalTimeForGets:()=>t_});function DV(){return Tc[0]=Tc[0]^64,wV.getFloat64(0)}function e_(e){Yh=!0;try{return e()}finally{Yh=!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))),!Yh)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 zh(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?xo=i?.localTime?kh|Db:Gh:xo=u?i?.localTime?kh|16384:Cb|16384:Gh,l>0&&(c|=Wh),Xl=c,Vh=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=Ct(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 Ib,Fh,Jl,gc,Kh,yV,Sc,Tc,wV,Gh,Cb,IV,Db,kh,Wh,Qh,CV,jl,xo,Xl,Vh,$h,oce,Yh,vi,qo=Re(()=>{Ib=require("msgpackr");Bi();Fh=x(V()),Jl=new Uint8Array([1,1,1,1,4,64,0,0]),gc=new Uint8Array([1,1,1,1,1,0,0,0]),Kh=new Uint8Array([1,1,1,1,3,64,0,0]),yV=Symbol("local-timestamp"),Sc=Symbol("metadata"),Tc=new Uint8Array(8),wV=new DataView(Tc.buffer,0,8),Gh=0,Cb=0,IV=1,Db=3,kh=4,Wh=16,Qh=1,xo=0,Xl=-1,Vh=0,$h=class extends Ib.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=Vh;c>=0&&(i+=2,Xl=-1,u&&(i+=8,Vh=0));let _=CV=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=DV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Wh&&(_=(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(DV,"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?(Fh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Fh.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(zh,"getUpdateRecord")});var r_=T((cce,Ub)=>{"use strict";var jh=Z(),Xh=L(),{RecordEncoder:LV}=(qo(),se(Lb));jh.initSync();var UV=jh.get(Xh.CONFIG_PARAMS.STORAGE_COMPRESSION),MV=jh.get(Xh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,PV=Xh.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=UV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=MV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:LV},this.alwaysLazyProperty=s=>s===PV)}};Ub.exports=Jh});var n_=T((lce,Pb)=>{"use strict";var Fo=Z(),Rc=L();Fo.initSync();var vV=Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Mb=Fo.get(Rc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),BV=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=vV,this.noFSAccess=!0,Mb!==void 0&&(this.overlappingSync=Mb),this.noReadAhead=BV}};Pb.exports=s_;s_.MAX_DBS=1e4});var We=T((dce,$b)=>{"use strict";var em=require("lmdb"),Os=require("fs-extra"),yr=require("path"),i_=br(),Hb=V(),rr=Or().LMDB_ERRORS_ENUM,o_=wb(),tm=r_(),xb=n_(),Jn=dt(),vb=L(),{table:HV,resetDatabases:xV}=(Ae(),se(Fe)),Bb=Z(),bs=Jn.INTERNAL_DBIS_NAME,qb=Jn.DBI_DEFINITION_NAME,qV="data.mdb",FV="lock.mdb",Ac=".mdb",GV="-lock",Zh=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 em.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(rr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(rr.ENV_NAME_REQUIRED)}a(a_,"pathEnvNameValidation");async function rm(e,t,r=!0){try{await Os.access(e)}catch(s){throw s.code==="ENOENT"?new Error(rr.INVALID_BASE_PATH):s}try{let s=yr.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(yr.join(e,t,qV),Os.constants.R_OK|Os.constants.F_OK),yr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(rr.INVALID_ENVIRONMENT)}else throw new Error(rr.INVALID_ENVIRONMENT);throw s}}a(rm,"validateEnvironmentPath");function c_(e,t){if(i_.validateEnv(e),t===void 0)throw new Error(rr.DBI_NAME_REQUIRED)}a(c_,"validateEnvDBIName");async function kV(e,t,r=!1,s=!1){a_(e,t);let n=yr.basename(e);t=t.toString();let i=Bb.get(vb.CONFIG_PARAMS.DATABASES);i||Bb.setProperty(vb.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await rm(e,t,s),Fb(e,t,r)}catch(o){if(o.message===rr.INVALID_ENVIRONMENT){let c=yr.join(e,t);await Os.mkdirp(s?c:e);let u=new xb(s?c:c+Ac,!1),_=em.open(u);_.dbis=Object.create(null);let l=new tm(!1);_.openDB(bs,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=sm(e,t,r);return _[Jn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(kV,"createEnvironment");async function VV(e,t,r,s=!0){a_(e,t),t=t.toString();let n=yr.join(e,t);return HV({table:t,database:yr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(VV,"copyEnvironment");async function Fb(e,t,r=!1){a_(e,t),t=t.toString();let s=sm(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 rm(e,t),i=yr.join(e,t+Ac),o=n!=i,c=new xb(n,o),u=em.open(c);u.dbis=Object.create(null);let _=kb(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(Fb,"openEnvironment");async function $V(e,t,r=!1){a_(e,t),t=t.toString();let s=yr.join(e,t+Ac),n=await rm(e,t);if(global.lmdb_map!==void 0){let i=sm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Gb(o),delete global.lmdb_map[i]}}await Os.remove(n),await Os.remove(n===s?n+GV:yr.join(yr.dirname(n),FV))}a($V,"deleteEnvironment");async function Gb(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(Gb,"closeEnvironment");function sm(e,t,r=!1){let n=`${yr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(sm,"getCachedEnvironmentName");function YV(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{Hb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(YV,"listDBIDefinitions");function kb(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(kb,"listDBIs");function KV(e,t){let s=Zr(e,bs).getEntry(t),n=new o_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Hb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(KV,"getDBIDefinition");function Vb(e,t,r,s=!r){if(c_(e,t),t=t.toString(),t===bs)throw new Error(rr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Zr(e,t)}catch(n){if(n.message===rr.DBI_DOES_NOT_EXIST){let i=new tm(r,s===!0),o=e.openDB(t,i),c=new o_(r===!0,s);return o[qb]=c,Zr(e,bs).putSync(t,c),e.dbis[t]=o,o}throw n}}a(Vb,"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=KV(e,t):r=new o_,r===void 0)throw new Error(rr.DBI_DOES_NOT_EXIST);let s;try{let n=new tm(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(rr.DBI_DOES_NOT_EXIST):n}return s[qb]=r,e.dbis[t]=s,s}a(Zr,"openDBI");function WV(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(WV,"statDBI");async function QV(e,t){try{let r=yr.join(e,t+Ac);return(await Os.stat(r)).size}catch{throw new Error(rr.INVALID_ENVIRONMENT)}}a(QV,"environmentDataSize");function zV(e,t){if(c_(e,t),t=t.toString(),t===bs)throw new Error(rr.CANNOT_DROP_INTERNAL_DBIS_NAME);Zr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Zr(e,bs).removeSync(t)}a(zV,"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===rr.DBI_DOES_NOT_EXIST)Vb(e,i,i!==t,i===t),s=!0;else throw o}}s&&xV()}a(JV,"initializeDBIs");$b.exports={openDBI:Zr,openEnvironment:Fb,createEnvironment:kV,listDBIs:kb,listDBIDefinitions:YV,createDBI:Vb,dropDBI:zV,statDBI:WV,deleteEnvironment:$V,initializeDBIs:JV,TransactionCursor:Zh,environmentDataSize:QV,copyEnvironment:VV,closeEnvironment:Gb}});var Kb=T((Ece,Yb)=>{"use strict";var nm=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};Yb.exports=nm});var Qb=T((mce,Wb)=>{"use strict";var im=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}};Wb.exports=im});var Jb=T((Sce,zb)=>{"use strict";var om=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};zb.exports=om});var Go=T((Oce,Zb)=>{"use strict";var jV=We(),XV=Kb(),ZV=Qb(),e$=Jb(),Vs=br(),Oc=Or().LMDB_ERRORS_ENUM,t$=dt(),mn=L(),r$=J(),s$=require("uuid"),gce=require("lmdb"),{handleHDBError:n$,hdb_errors:i$}=re(),{OVERFLOW_MARKER:Rce,MAX_SEARCH_KEY_LENGTH:Ace}=t$,jb=Z();jb.initSync();var u_=jb.get(mn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),am=mn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Hi=mn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function o$(e,t,r,s,n=Vs.getNextMonotonicTime()){_m(e,t,r,s),cm(e,t,r);let i=new XV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];Xb(_,!0,n);let l=a$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return um(o,c,s,i,n)}a(o$,"insertRecords");function a$(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(a$,"insertRecord");function c$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(c$,"removeSkippedRecords");function Xb(e,t,r){let s=r>0;(s||!Number.isInteger(e[Hi]))&&(e[Hi]=r||(r=Vs.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[am]))&&(e[am]=r||Vs.getNextMonotonicTime()):delete e[am]}a(Xb,"setTimestamps");function cm(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),jV.initializeDBIs(e,t,r)}a(cm,"initializeTransaction");async function u$(e,t,r,s,n=Vs.getNextMonotonicTime()){_m(e,t,r,s),cm(e,t,r);let i=new ZV,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=lm(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return um(c,u,s,i,n,o)}a(u$,"updateRecords");async function l$(e,t,r,s,n=Vs.getNextMonotonicTime()){try{_m(e,t,r,s)}catch(u){throw n$(u,u.message,i$.HTTP_STATUS_CODES.BAD_REQUEST)}cm(e,t,r);let i=new e$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;r$.isEmpty(_[t])?(l=s$.v4(),_[t]=l):l=_[t];let d=lm(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return um(o,c,s,i,n)}a(l$,"upsertRecords");async function um(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(),c$(r,i),s}a(um,"finalizeWrite");function lm(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(Xb(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:lm(e,t,r,s,n,i,o))}a(lm,"updateUpsertRecord");function _$(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(_$,"validateBasic");function _m(e,t,r,s){if(_$(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Oc.RECORDS_REQUIRED):new Error(Oc.RECORDS_MUST_BE_ARRAY)}a(_m,"validateWrite");function l_(){}a(l_,"noop");Zb.exports={insertRecords:o$,updateRecords:u$,upsertRecords:l$}});var xi=T((Nce,d$)=>{d$.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,rN)=>{"use strict";var tN=J(),eN=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"}},f$=$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(),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()),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()).required();function m$(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(m$,"checkValidTable");function p$(e,t){return tN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(p$,"validateSchemaExists");function S$(e,t){let r=t.state.ancestors[0].schema;return tN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(S$,"validateTableExists");function T$(e,t){return e.toLowerCase()===eN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${eN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(T$,"validateSchemaName");rN.exports={common_validators:jn,schema_regex:ko,hdb_schema_table:f$,validateSchemaExists:p$,validateTableExists:S$,validateSchemaName:T$,checkValidTable:m$,hdb_database:E$,hdb_table:h$}});var je=T((Ice,sN)=>{"use strict";var sr=require("validate.js");sr.validators.type=function(e,t,r,s){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:g$,validateObjectAsync:R$,validateBySchema:A$};function g$(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(g$,"validateObject");async function R$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await sr.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(R$,"validateObjectAsync");function A$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(A$,"validateBySchema")});var __=T((Dce,nN)=>{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 O$(e){return e=yc(e),ft.table.presence=!1,ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(O$,"schema_object");function b$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(b$,"table_object");function N$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,Nc.validateObject(e,ft)}a(N$,"create_table_object");function y$(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(y$,"attribute_object");function w$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(w$,"describe_table");function I$(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(I$,"validateTableResidence");nN.exports={schema_object:O$,create_table_object:N$,table_object:b$,attribute_object:y$,describe_table:w$,validateTableResidence:I$}});var oN=T((Uce,iN)=>{"use strict";var C$=require("uuid"),dm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||C$.v4(),this.schema_table=`${this.schema}.${this.table}`}};iN.exports=dm});var d_=T((Pce,aN)=>{"use strict";var D$=oN(),fm=class extends D${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}};aN.exports=fm});var uN=T((Bce,cN)=>{"use strict";cN.exports=U$;var L$="inserted";function U$(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===L$?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(U$,"returnObject")});var f_=T((xce,EN)=>{"use strict";var M$=L(),Em=We(),P$=Go(),{getSystemSchemaPath:v$,getSchemaPath:B$}=Je(),H$=xi(),x$=__(),q$=d_(),F$=uN(),{handleHDBError:lN,hdb_errors:dN}=re(),_N=J(),{HTTP_STATUS_CODES:G$}=dN,hm=H$.hdb_attribute,fN=[];for(let e=0;e<hm.attributes.length;e++)fN.push(hm.attributes[e].attribute);var k$="inserted";EN.exports=V$;async function V$(e){let t=x$.attribute_object(e);if(t)throw lN(new Error,t.message,dN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&_N.checkGlobalSchemaTable(e.schema,e.table);if(r)throw lN(new Error,r,G$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=_N.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 q$(e.schema,e.table,e.attribute,e.id);try{let i=await Em.openEnvironment(B$(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}`);Em.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Em.openEnvironment(v$(),M$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await P$.insertRecords(o,hm.hash_attribute,fN,[n]);return F$(k$,c,{records:[n]},u)}catch(i){throw i}}a(V$,"lmdbCreateAttribute")});var pm=T((Fce,mN)=>{var{hdb_table:$$,hdb_database:hN}=Ys(),Y$=je(),mm=require("joi"),K$={undefined:"undefined",null:"null"},W$=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||K$[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"),Q$=mm.object({database:hN,schema:hN,table:$$,records:mm.array().items(mm.object().custom(W$)).required()});mN.exports=function(e){return Y$.validateBySchema(e,Q$)}});var wc=T((Vce,SN)=>{"use strict";var pn=J(),pN=V(),kce=pm(),{getDatabases:z$}=(Ae(),se(Fe)),{ClientError:qi}=re();SN.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=z$()[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 pN.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 pN.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,TN)=>{"use strict";var j$=L().OPERATIONS_ENUM,Sm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=j$.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};TN.exports=Sm});var Uc=T((Qce,gN)=>{"use strict";var Wce=Ic(),E_=L(),gm=J(),Tm=V(),X$=require("uuid"),{handleHDBError:Cc,hdb_errors:Z$}=re(),{HDB_ERROR_MSGS:Dc,HTTP_STATUS_CODES:Lc}=Z$;gN.exports=e1;function e1(e,t,r){for(let n=0;n<t.length;n++)t1(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];r1(i,r,e.operation)}}a(e1,"processRows");function t1(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(gm.isEmptyOrZeroLength(e)||gm.isEmpty(e.trim()))throw Cc(new Error,Dc.ATTR_NAME_NULLISH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(t1,"validateAttribute");function r1(e,t,r){if(!e.hasOwnProperty(t)||gm.isEmptyOrZeroLength(e[t])){if(r===E_.OPERATIONS_ENUM.INSERT||r===E_.OPERATIONS_ENUM.UPSERT){e[t]=X$.v4();return}throw Tm.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 Tm.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 Tm.error(e),Cc(new Error,Dc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(r1,"validateHash")});var AN=T((Jce,RN)=>{"use strict";var Rm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};RN.exports=Rm});var NN=T((Xce,bN)=>{"use strict";var Am=We(),s1=V(),ON=Or().LMDB_ERRORS_ENUM;bN.exports=n1;async function n1(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 Am.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==ON.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Am.closeEnvironment(global.lmdb_map[s]),await Am.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==ON.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){s1.error(t)}}a(n1,"cleanLMDBMap")});var Sn=T((eue,CN)=>{"use strict";var Mc=require("crypto"),i1=Z(),{CONFIG_PARAMS:o1}=L(),wN="aes-256-cbc",a1=32,c1=16,Om=64,IN=32,u1=Om+IN,yN=new Map;CN.exports={encrypt:l1,decrypt:_1,createNatsTableStreamName:d1};function l1(e){let t=Mc.randomBytes(a1),r=Mc.randomBytes(c1),s=Mc.createCipheriv(wN,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(l1,"encrypt");function _1(e){let t=e.substr(0,Om),r=e.substr(Om,IN),s=e.substr(u1,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Mc.createDecipheriv(wN,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(_1,"decrypt");function d1(e,t){let r=i1.get(o1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=yN.get(r);return s||(s=Mc.createHash("md5").update(r).digest("hex"),yN.set(r,s)),s}a(d1,"createNatsTableStreamName")});var Xn=T((sue,LN)=>{"use strict";var rue=es(),h_=V(),DN=__(),f1=Sn(),m_=J(),{handleHDBError:p_,hdb_errors:E1}=re(),{HDB_ERROR_MSGS:S_,HTTP_STATUS_CODES:bm}=E1,h1=Z();h1.initSync();var{getDatabases:Nm}=(Ae(),se(Fe));LN.exports={describeAll:m1,describeTable:T_,describeSchema:p1};async function m1(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=Nm(),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(m1,"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=DN.describe_table(e);if(i)throw i;let c=Nm()[r];if(!c)throw p_(new Error,S_.SCHEMA_NOT_FOUND(e.schema),bm.NOT_FOUND);let u=c[s];if(!u)throw p_(new Error,S_.TABLE_NOT_FOUND(e.schema,e.table),bm.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=f1.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 p1(e){m_.transformReq(e);let t=DN.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=Nm()[s];if(!i)throw p_(new Error,S_.SCHEMA_NOT_FOUND(e.schema),bm.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(p1,"describeSchema")});var Tn=T((aue,BN)=>{var S1=xi(),{callbackify:MN,promisify:T1}=require("util"),{getDatabases:PN}=(Ae(),se(Fe));BN.exports={setSchemaDataToGlobal:UN,getTableSchema:g1,getSystemSchema:R1,setSchemaDataToGlobalAsync:T1(UN)};var vN=Xn(),iue=MN(vN.describeAll),oue=MN(vN.describeTable);function UN(e){global.hdb_schema=PN(),e&&e()}a(UN,"setSchemaDataToGlobal");function g1(e,t,r){let s=PN()[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(g1,"getTableSchema");function R1(){return S1}a(R1,"getSystemSchema")});var wr=T((uue,FN)=>{"use strict";var R_=pm(),xt=J(),A1=require("util"),A_=Ns(),O1=Tn(),HN=V(),{handleHDBError:Fi,hdb_errors:b1}=re(),{HTTP_STATUS_CODES:Gi}=b1,N1=A1.promisify(O1.getTableSchema),y1="updated",xN="inserted",qN="upserted";FN.exports={insert:I1,update:C1,upsert:D1,validation:w1,flush:L1};async function w1(e){if(xt.isEmpty(e))throw new Error("invalid update parameters defined.");if(xt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(xt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await N1(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&&xt.isEmptyOrZeroLength(c[s]))throw HN.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(!xt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw HN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!xt.isEmpty(c[s])&&c[s]!==""&&n.has(xt.autoCast(c[s]))&&(c.skip=!0),n.add(xt.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(w1,"validation");async function I1(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);xt.transformReq(e);let r=xt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.createRecords(e);return g_(xN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(I1,"insertData");async function C1(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);xt.transformReq(e);let r=xt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.updateRecords(e);return xt.isEmpty(s.existing_rows)?g_(y1,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(C1,"updateData");async function D1(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);xt.transformReq(e);let r=xt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.upsertRecords(e);return g_(qN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(D1,"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===xN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===qN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(g_,"returnObject");function L1(e){return xt.transformReq(e),A_.flush(e.schema,e.table)}a(L1,"flush")});var wm=T((_ue,VN)=>{var U1=je(),ym=require("joi"),{hdb_table:M1,hdb_database:GN}=Ys(),kN={schema:GN,database:GN,table:M1},P1={date:ym.date().iso().required()},v1={timestamp:ym.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};VN.exports=function(e,t){let r=t==="timestamp"?{...kN,...v1}:{...kN,...P1},s=ym.object(r);return U1.validateBySchema(e,s)}});var KN=T((due,YN)=>{var B1=je(),Im=require("joi"),{hdb_table:H1,hdb_database:$N}=Ys(),x1=Im.object({schema:$N,database:$N,table:H1,hash_values:Im.array().required(),ids:Im.array()});YN.exports=function(e){return B1.validateBySchema(e,x1)}});var QN=T((fue,WN)=>{"use strict";var Cm=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}},Dm=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}},Lm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};WN.exports={InsertObject:Cm,NoSQLSeachObject:Dm,DeleteResponseObject:Lm}});var ti=T((hue,ZN)=>{"use strict";var JN=wm(),q1=KN(),ki=J(),zN=require("moment"),jN=V(),{promisify:F1,callbackify:G1}=require("util"),Vi=L(),k1=Tn(),Um=F1(k1.getTableSchema),Mm=Ns(),{DeleteResponseObject:V1}=QN(),{handleHDBError:Zn,hdb_errors:$1}=re(),{HDB_ERROR_MSGS:O_,HTTP_STATUS_CODES:ei}=$1,Y1="records successfully deleted",K1=G1(XN);ZN.exports={delete:K1,deleteRecord:XN,deleteFilesBefore:W1,deleteAuditLogsBefore:Q1};async function W1(e){let t=JN(e,"date");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(ki.transformReq(e),!zN(e.date,zN.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 Mm.deleteRecordsBefore(e);if(await Um(e.schema,e.table),jN.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(W1,"deleteFilesBefore");async function Q1(e){let t=JN(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 Mm.deleteAuditLogsBefore(e);return await Um(e.schema,e.table),jN.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(Q1,"deleteAuditLogsBefore");async function XN(e){e.ids&&(e.hash_values=e.ids);let t=q1(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 Um(e.schema,e.table);let s=await Mm.deleteRecords(e);return ki.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${Y1}`),s}catch(s){if(s.message===Vi.SEARCH_NOT_FOUND_MESSAGE){let n=new V1;return n.message=Vi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(XN,"deleteRecord")});var b_=T((pue,ry)=>{var z1=require("crypto"),ey=9;function J1(e){let t=X1(ey),r=ty(e+t);return t+r}a(J1,"createHash");function j1(e,t){let r=e?.substr(0,ey),s=r+ty(t+r);return e===s}a(j1,"validateHash");function X1(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(X1,"generateSalt");function ty(e){return z1.createHash("md5").update(e).digest("hex")}a(ty,"md5");ry.exports={hash:J1,validate:j1}});var ny=T((Tue,sy)=>{var Pm=je(),Yt={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 Z1(e){return Yt.password.presence=!0,Yt.username.presence=!0,Yt.role.presence=!0,Yt.active.presence=!0,Pm.validateObject(e,Yt)}a(Z1,"addUserValidation");function eY(e){return Yt.password.presence=!1,Yt.username.presence=!0,Yt.role.presence=!1,Yt.active.presence=!1,Pm.validateObject(e,Yt)}a(eY,"alterUserValidation");function tY(e){return Yt.password.presence=!1,Yt.username.presence=!0,Yt.role.presence=!1,Yt.active.presence=!1,Pm.validateObject(e,Yt)}a(tY,"dropUserValidation");sy.exports={addUserValidation:Z1,alterUserValidation:eY,dropUserValidation:tY}});var Ge=T((Aue,oy)=>{"use strict";var{platform:Rue}=require("os"),rY="nats-server.zip",vm="nats-server",sY=process.platform==="win32"?`${vm}.exe`:vm,Bm="HDB",nY=/^[^\s.,*>]+$/,iy="__request__",iY=a(e=>`${e}.${iy}`,"REQUEST_SUBJECT"),oY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},aY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},cY={HUB:"hub.pid",LEAF:"leaf.pid"},uY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},lY={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Bm,deliver_subject:"__HDB__.WORKQUEUE"},_Y={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Bm,deliver_subject:"HDB.SCHEMAQUEUE"},dY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Bm,deliver_subject:"HDB.USERQUEUE"},fY={SUCCESS:"success",ERROR:"error"},EY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},hY={TXN:"txn",MSGID:"msgid"},Vo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},mY={[Vo.ERR]:1,[Vo.WRN]:2,[Vo.INF]:3,[Vo.DBG]:4,[Vo.TRC]:5},pY={debug:"-D",trace:"-DVV"};oy.exports={NATS_SERVER_ZIP:rY,NATS_SERVER_NAME:vm,NATS_BINARY_NAME:sY,PID_FILES:cY,NATS_CONFIG_FILES:aY,SERVER_SUFFIX:uY,WORK_QUEUE_CONSUMER_NAMES:lY,SCHEMA_QUEUE_CONSUMER_NAMES:_Y,USER_QUEUE_CONSUMER_NAMES:dY,NATS_TERM_CONSTRAINTS_RX:nY,REQUEST_SUFFIX:iy,UPDATE_REMOTE_RESPONSE_STATUSES:fY,CLUSTER_STATUS_STATUSES:EY,REQUEST_SUBJECT:iY,SUBJECT_PREFIXES:hY,MSG_HEADERS:oY,LOG_LEVELS:Vo,LOG_LEVEL_FLAGS:pY,LOG_LEVEL_HIERARCHY:mY}});var cy=T((bue,ay)=>{"use strict";var SY={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
|
-
`)},TY="certificate.pem",gY="privateKey.pem",RY="ca.pem";ay.exports={CERTIFICATE_VALUES:SY,CERTIFICATE_PEM_NAME:TY,PRIVATEKEY_PEM_NAME:gY,CA_PEM_NAME:RY}});var xm=T((yue,fy)=>{"use strict";var dy=require("fs-extra"),ae=require("joi"),AY=require("os"),{boolean:Ie,string:Ir,number:Dt,array:Hm}=ae.types(),{totalmem:uy}=require("os"),$i=require("path"),OY=V(),N_=J(),Nue=cy(),ly=L(),bY=je(),_y="log",NY="components",yY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",wY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",IY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",CY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",DY="rootPath config parameter is undefined",LY="clustering.enabled config parameter is undefined",Yi=Dt.min(0).required(),y_=Hm.items({host:Ir.required(),port:Yi}).empty(null),Ws;fy.exports={configValidator:UY,routesValidator:xY,route_constraints:y_};function UY(e){if(Ws=e.rootPath,N_.isEmpty(Ws))throw DY;let t=Ie.required(),r=Dt.min(0).max(1e3).empty(null).default(HY),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=ae.string().empty(null).default(Pc),c=ae.custom(PY).empty(null).default(Pc),u=e.clustering?.enabled;if(N_.isEmpty(u))throw LY;let _;return u===!0?_=ae.object({enabled:t,hubServer:ae.object({cluster:ae.object({name:ae.required().empty(null),network:ae.object({port:Yi,routes:y_}).required()}).required(),leafNodes:ae.object({network:ae.object({port:Yi}).required()}).required(),network:ae.object({port:Yi}).required()}).required(),leafServer:ae.object({network:ae.object({port:Yi,routes:y_}).required(),streams:ae.object({maxAge:Dt.min(120).allow(null).optional(),maxBytes:Dt.min(1).allow(null).optional(),maxMsgs:Dt.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ae.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Ie.optional(),databaseLevel:Ie.optional(),tls:ae.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ie.required(),verify:Ie.optional()}),user:Ir.optional().empty(null)}).required():_=ae.object({enabled:t,tls:ae.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ie.required()})}).required(),ae.object({authentication:ae.object({authorizeLocal:Ie,cacheTTL:Dt.required(),enableSessions:Ie}),analytics:ae.object({aggregatePeriod:Dt}),componentsRoot:s.optional(),clustering:_,localStudio:ae.object({enabled:t}).required(),logging:ae.object({auditAuthEvents:ae.object({logFailed:Ie,logSuccessful:Ie}),file:Ie.required(),level:ae.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ae.object({enabled:Ie.optional(),compress:Ie.optional(),interval:Ir.custom(BY).optional().empty(null),maxSize:Ir.custom(vY).optional().empty(null),path:Ir.optional().empty(null).default(Pc)}).required(),root:s,stdStreams:Ie.required(),auditLog:Ie.required()}).required(),operationsApi:ae.object({network:ae.object({cors:Ie.optional(),corsAccessList:Hm.optional(),headersTimeout:Dt.min(1).optional(),keepAliveTimeout:Dt.min(1).optional(),port:Dt.optional().empty(null),domainSocket:ae.optional().empty("hdb/operations-server").default(Pc),securePort:Dt.optional().empty(null),timeout:Dt.min(1).optional()}).optional(),tls:ae.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:Ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ae.object({network:ae.object({port:Yi,securePort:Yi,mtls:ae.alternatives([Ie.optional(),ae.object({user:Ir.optional(),certificateAuthority:n,required:Ie.optional()})])}).required(),webSocket:Ie.optional(),requireAuthentication:Ie.optional()}),http:ae.object({compressionThreshold:Dt.optional(),cors:Ie.optional(),corsAccessList:Hm.optional(),headersTimeout:Dt.min(1).optional(),port:Dt.min(0).optional().empty(null),securePort:Dt.min(0).optional().empty(null),mtls:ae.alternatives([Ie.optional(),ae.object({user:Ir.optional(),certificateAuthority:n,required:Ie.optional()})])}).required(),threads:ae.alternatives(r.optional(),ae.object({count:r.optional(),debug:Ie.optional()})),maxHeapMemory:Dt.min(0).optional(),storage:ae.object({writeAsync:Ie.required(),overlappingSync:Ie.optional(),caching:Ie.optional(),compression:Ie.optional(),noReadAhead:Ie.optional(),path:c,prefetchWrites:Ie.optional()}).required(),ignoreScripts:Ie.optional(),tls:ae.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:Ir.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(UY,"configValidator");function MY(e){return dy.existsSync(e)?null:`Specified path ${e} does not exist.`}a(MY,"doesPathExist");function PY(e,t){ae.assert(e,Ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=MY(e);if(r)return t.message(r)}a(PY,"validatePath");function vY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(yY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(IY):e}a(vY,"validateRotationMaxSize");function BY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(wY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(CY):e}a(BY,"validateRotationInterval");function HY(e,t){let r=t.state.path.join("."),s=AY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||uy();return i=Math.round(Math.min(i,uy())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),OY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(HY,"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,NY);case"logging.root":return $i.join(Ws,_y);case"clustering.leafServer.streams.path":return $i.join(Ws,"clustering","leaf");case"storage.path":let s=$i.join(Ws,ly.LEGACY_DATABASES_DIR_NAME);return dy.existsSync(s)?s:$i.join(Ws,ly.DATABASES_DIR_NAME);case"logging.rotation.path":return $i.join(Ws,_y);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 xY(e){let t=ae.object({routes:y_});return bY.validateBySchema({routes:e},t)}a(xY,"routesValidator")});var Lr=T((Cue,Ay)=>{"use strict";var Dr=L(),Lt=J(),Rt=V(),{configValidator:qY,routesValidator:Ey}=xm(),nr=require("fs-extra"),FY=require("yaml"),ys=require("path"),GY=require("is-number"),my=require("properties-reader"),kY=require("lodash"),{handleHDBError:VY}=re(),{HTTP_STATUS_CODES:$Y,HDB_ERROR_MSGS:w_}=Or(),Iue=require("minimist"),{server:YY}=(tr(),se(Mi)),{DATABASES_PARAM_CONFIG:vc,CONFIG_PARAMS:Cr,CONFIG_PARAM_MAP:ws}=Dr,KY="Unable to get config value because config is uninitialized",WY="Config successfully initialized",QY="Error backing up config file",zY="Empty parameter sent to getConfigValue",py=ys.join(Dr.PACKAGE_ROOT,"config","yaml",Dr.HDB_DEFAULT_CONFIG_FILE),JY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",hy={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_,At,C_;Ay.exports={createConfigFile:jY,getDefaultConfig:XY,getConfigValue:Ty,initConfig:Fm,flattenConfig:$o,updateConfigValue:gy,updateConfigObject:eK,getConfiguration:sK,setConfiguration:nK,readConfigFile:km,getClusteringRoutes:iK,initOldConfig:Ry,getConfigFromFile:oK,getConfigFilePath:Ki,addConfig:aK,deleteConfigFromFile:cK,getConfigObj:uK};function jY(e){let t=ri(py);I_=$o(t.toJSON());let r;for(let o in e){let c=ws[o.toLowerCase()];if(c===Cr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=qm(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){Rt.error(l)}}}r&&Sy(t,r),Gm(t);let s=t.toJSON();At=$o(s);let n=t.getIn(["rootPath"]),i=ys.join(n,Dr.HDB_CONFIG_FILE);nr.createFileSync(i),nr.writeFileSync(i,String(t)),Rt.trace(`Config file written to ${i}`)}a(jY,"createConfigFile");function Sy(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!Lt.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=[Cr.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=[Cr.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){Rt.error("Error parsing schemas CLI/env config arguments",s)}}a(Sy,"setSchemasConfig");function XY(e){if(I_===void 0){let r=ri(py);I_=$o(r.toJSON())}let t=ws[e.toLowerCase()];if(t!==void 0)return I_[t.toLowerCase()]}a(XY,"getDefaultConfig");function Ty(e){if(e==null){Rt.error(zY);return}if(At===void 0){Rt.trace(KY);return}let t=ws[e.toLowerCase()];if(t!==void 0)return At[t.toLowerCase()]}a(Ty,"getConfigValue");function Ki(e=Lt.getPropsFilePath()){let t=Lt.getEnvCliRootPath();return t?ys.join(t,Dr.HDB_CONFIG_FILE):my(e).get(Dr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ki,"getConfigFilePath");function Fm(e=!1){if(At===void 0||e){let t;if(!Lt.noBootFile()){t=Lt.getPropsFilePath();try{nr.accessSync(t,nr.constants.F_OK|nr.constants.R_OK)}catch(i){throw Rt.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{Ry(r);return}catch(i){if(i.code!==Dr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ri(r)}catch(i){if(i.code===Dr.NODE_ERROR_CODES.ENOENT){Rt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw Rt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}ZY(s,r),Gm(s);let n=s.toJSON();if(YY.config=n,At=$o(n),At.logging_rotation_rotate)for(let i in hy)At[i]&&Rt.error(`Config ${hy[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Rt.trace(WY)}}a(Fm,"initConfig");function ZY(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&&(Rt.trace("Updating config file with missing config params"),nr.writeFileSync(t,String(e)))}a(ZY,"checkForUpdatedConfig");function Gm(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t?.http?.threads&&(t.threads=t?.http?.threads);let r=qY(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(Gm,"validateConfig");function eK(e,t){At===void 0&&(At={});let r=ws[e.toLowerCase()];if(r===void 0){Rt.trace(`Unable to update config object because config param '${e}' does not exist`);return}At[r.toLowerCase()]=t}a(eK,"updateConfigObject");function gy(e,t,r=void 0,s=!1,n=!1,i=!1){At===void 0&&Fm();let o=Ty(ws.hdb_root),c=ys.join(o,Dr.HDB_CONFIG_FILE),u=ri(c),_;if(r===void 0&&e.toLowerCase()===Cr.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=qm(f,t);u.setIn([...E],h)}else for(let f in r){let E=ws[f.toLowerCase()];if(E===Cr.HTTP_SECUREPORT&&r[f]===At[Cr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Cr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===At[Cr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Cr.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Dr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=qm(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){Rt.error(A)}}}_&&Sy(u,_),Gm(u);let l=u.getIn(["rootPath"]),d=ys.join(l,Dr.HDB_CONFIG_FILE);s===!0&&tK(c,l),nr.writeFileSync(d,String(u)),n&&(At=$o(u.toJSON())),Rt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(gy,"updateConfigValue");function tK(e,t){try{let r=ys.join(t,"backup",`${Dr.HDB_CONFIG_FILE}.bak`);nr.copySync(e,r),Rt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Rt.error(QY),Rt.error(r)}}a(tK,"backupConfigFile");var rK=["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])&&!rK.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;!Cr[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 qm(e,t){if(e===Cr.CLUSTERING_NODENAME||e===Cr.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(GY(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(qm,"castConfigValue");function sK(){let e=Lt.getPropsFilePath(),t=Ki(e);return ri(t).toJSON()}a(sK,"getConfiguration");async function nK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return gy(void 0,void 0,n,!0),JY}catch(i){throw typeof i=="string"||i instanceof String?VY(i,i,$Y.BAD_REQUEST,void 0,void 0,!0):i}}a(nK,"setConfiguration");function km(){let e=Lt.getPropsFilePath();try{nr.accessSync(e,nr.constants.F_OK|nr.constants.R_OK)}catch(s){if(!Lt.noBootFile())throw Rt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ki(e);return ri(t).toJSON()}a(km,"readConfigFile");function ri(e){return FY.parseDocument(nr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ri,"parseYamlDoc");function iK(){let e=km(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Lt.isEmptyOrZeroLength(t)?[]:t;let r=Ey(t);if(r)throw w_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Lt.isEmptyOrZeroLength(s)?[]:s;let n=Ey(s);if(n)throw w_.CONFIG_VALIDATION(n.message);if(!Lt.isEmptyOrZeroLength(s)&&!Lt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.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 w_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(iK,"getClusteringRoutes");function Ry(e){let t=my(e);At={};for(let r in ws){let s=t.get(r.toUpperCase());if(Lt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=ws[r].toLowerCase();n===Cr.LOGGING_ROOT?At[n]=ys.dirname(s):At[n]=s}return At}a(Ry,"initOldConfig");function oK(e){let t=km();return kY.get(t,e.replaceAll("_","."))}a(oK,"getConfigFromFile");async function aK(e,t){let r=ri(Ki());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await nr.writeFile(Ki(),String(r))}a(aK,"addConfig");function cK(e){let t=Ki(Lt.getPropsFilePath()),r=ri(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=ys.join(s,Dr.HDB_CONFIG_FILE);nr.writeFileSync(n,String(r))}a(cK,"deleteConfigFromFile");function uK(){return C_||(Fm(),C_)}a(uK,"getConfigObj")});var by=T((Lue,Oy)=>{"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}},Vm=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}};Oy.exports={BaseLicense:L_,ExtendedLicense:Vm}});var Wi=T((Mue,Dy)=>{"use strict";var Ko=require("fs-extra"),yy=b_(),wy=require("crypto"),lK=require("moment"),_K=require("uuid").v4,Kt=V(),Ym=require("path"),dK=J(),si=L(),{totalmem:Ny}=require("os"),fK=by().ExtendedLicense,Yo="invalid license key format",EK="061183",hK="mofi25",mK="aes-256-cbc",pK=16,SK=32,Iy=Z();Iy.initSync();var $m;Dy.exports={validateLicense:Cy,generateFingerPrint:gK,licenseSearch:Qm,getLicense:OK,checkMemoryLimit:bK};function Km(){return Ym.join(Iy.getHdbBasePath(),si.LICENSE_KEY_DIR_NAME,si.LICENSE_FILE_NAME)}a(Km,"getLicenseDirPath");function TK(){let e=Km();return Ym.join(e,si.LICENSE_FILE_NAME)}a(TK,"getLicenseFilePath");function Wm(){let e=Km();return Ym.join(e,si.REG_KEY_FILE_NAME)}a(Wm,"getFingerPrintFilePath");async function gK(){let e=Wm();try{return await Ko.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await RK();throw Kt.error(`Error writing fingerprint file to ${e}`),Kt.error(t),new Error("There was an error generating the fingerprint")}}a(gK,"generateFingerPrint");async function RK(){let e=_K(),t=yy.hash(e),r=Wm();try{await Ko.mkdirp(Km()),await Ko.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Kt.error(`Error writing fingerprint file to ${r}`),Kt.error(s),new Error("There was an error generating the fingerprint")}return t}a(RK,"writeFingerprint");function Cy(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 Kt.error("empty license key passed to validate."),r;let s=Wm(),n=!1;try{n=Ko.statSync(s)}catch(i){Kt.error(i)}if(n){let i;try{i=Ko.readFileSync(s,"utf8")}catch{Kt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(hK),c=o[1];c=Buffer.concat([Buffer.from(c)],pK);let u=Buffer.concat([Buffer.from(i)],SK),_=wy.createDecipheriv(mK,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=AK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Yo),Kt.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),Kt.error(Yo),new Error(Yo)}else r.exp_date=l;r.exp_date<lK().valueOf()&&(r.valid_date=!1),yy.validate(o[1],`${EK}${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||Kt.error("Invalid licence"),r}a(Cy,"validateLicense");function AK(e,t){try{let r=wy.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Kt.warn("Check old license failed")}}a(AK,"checkOldLicense");function Qm(){let e=new fK,t=[];try{t=Ko.readFileSync(TK(),"utf-8").split(si.NEW_LINE)}catch(r){r.code==="ENOENT"?Kt.info("no license file found"):Kt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(dK.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=Cy(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){Kt.error("There was an error parsing the license string."),Kt.error(n),e.ram_allocation=si.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return $m=e,e}a(Qm,"licenseSearch");async function OK(){return $m||await Qm(),$m}a(OK,"getLicense");function bK(){let e=Qm().ram_allocation,t=process.constrainedMemory?.()||Ny();if(t=Math.round(Math.min(t,Ny())/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(bK,"checkMemoryLimit")});var ts=T((xue,Ky)=>{"use strict";var Py="username is required",vy="nothing to update, must supply active, role or password to update",By="password cannot be an empty string",Hy="If role is specified, it cannot be empty.",xy="active must be true or false";Ky.exports={addUser:MK,alterUser:PK,dropUser:BK,getSuperUser:FK,userInfo:HK,listUsers:M_,listUsersExternal:xK,setUsersToGlobal:Qo,findAndValidateUser:$y,getClusterUser:GK,USERNAME_REQUIRED:Py,ALTERUSER_NOTHING_TO_UPDATE:vy,EMPTY_PASSWORD:By,EMPTY_ROLE:Hy,ACTIVE_BOOLEAN:xy};var qy=wr(),NK=ti(),jm=b_(),Fy=ny(),Gy=es(),Xm=gn(),Ur=J(),ky=require("validate.js"),Te=V(),{promisify:yK}=require("util"),Zm=Sn(),Ly=L(),Uy=Ge(),wK=Lr(),vue=Z(),Bue=Wi(),IK=xi(),{table:Hue}=(Ae(),se(Fe)),{handleHDBError:Qs,hdb_errors:CK}=re(),{HTTP_STATUS_CODES:zs,AUTHENTICATION_ERROR_MSGS:zm,HDB_ERROR_MSGS:Wo}=CK,{UserEventMsg:ep}=Is(),Jm=require("lodash"),{server:tp}=(tr(),se(Mi)),DK=V();tp.getUser=(e,t)=>$y(e,t,t!=null);var Vy={username:!0,active:!0,role:!0,password:!0},My=new Map,U_=Gy.searchByValue,LK=Gy.searchByHash,UK=yK(NK.delete);async function MK(e){let t=ky.cleanAttributes(e,Vy),r=Fy.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=Zm.encrypt(t.password)),t.password=jm.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await qy.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],Xm.signalUserChange(new ep(process.pid)),`${c.username} successfully added`}a(MK,"addUser");async function PK(e){let t=ky.cleanAttributes(e,Vy);if(Ur.isEmptyOrZeroLength(t.username))throw new Error(Py);if(Ur.isEmptyOrZeroLength(t.password)&&Ur.isEmptyOrZeroLength(t.role)&&Ur.isEmptyOrZeroLength(t.active))throw new Error(vy);if(!Ur.isEmpty(t.password)&&Ur.isEmptyOrZeroLength(t.password.trim()))throw new Error(By);if(!Ur.isEmpty(t.active)&&!Ur.isBoolean(t.active))throw new Error(xy);let r=vK(t.username);if(!Ur.isEmpty(t.password)&&!Ur.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Zm.encrypt(t.password)),t.password=jm.hash(t.password)),t.role==="")throw new Error(Hy);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 qy.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 Xm.signalUserChange(new ep(process.pid)),n}a(PK,"alterUser");function vK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(vK,"isClusterUser");async function BK(e){try{let t=Fy.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Ur.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 UK(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 Xm.signalUserChange(new ep(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(BK,"dropUser");async function HK(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 LK(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(HK,"userInfo");async function xK(){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(xK,"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],qK(o.role),i.set(o.username,o);return i}catch(e){throw Te.error("got an error listing users"),Te.error(e),Ur.errorizeMessage(e)}return null}a(M_,"listUsers");function qK(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(IK)){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(qK,"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 $y(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,zm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw Qs(new Error,zm.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(My.get(t)===s.password)return n;if(jm.validate(s.password,t))My.set(t,s.password);else throw Qs(new Error,zm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}return n}a($y,"findAndValidateUser");async function FK(){global.hdb_users||await Qo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(FK,"getSuperUser");async function GK(){let e=await M_(),t=wK.getConfigFromFile(Ly.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Ur.isEmpty(r)&&r?.role?.role===Ly.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Zm.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+Uy.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+Uy.SERVER_SUFFIX.ADMIN,r}a(GK,"getClusterUser");var Yy=[];tp.invalidateUser=function(e){for(let t of Yy)try{t(e)}catch(r){DK.error("Error invalidating user",r)}};tp.onInvalidatedUser=function(e){Yy.push(e)}});var Hc=T((kue,Jy)=>{"use strict";var Qi=V(),Mr=L(),kK=NN(),Fue=Tn(),Gue=Xn(),VK=ts(),{validateEvent:Wy}=Is(),Bc=Ns(),$K=require("process"),{resetDatabases:YK}=(Ae(),se(Fe)),KK={[Mr.ITC_EVENT_TYPES.SCHEMA]:WK,[Mr.ITC_EVENT_TYPES.USER]:zy};async function WK(e){let t=Wy(e);if(t){Qi.error(t);return}Qi.trace("ITC schemaHandler received schema event:",e),await kK(e.message),await QK(e.message)}a(WK,"schemaHandler");async function QK(e){try{Bc.resetReadTxn(Mr.SYSTEM_SCHEMA_NAME,Mr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Bc.resetReadTxn(Mr.SYSTEM_SCHEMA_NAME,Mr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Bc.resetReadTxn(Mr.SYSTEM_SCHEMA_NAME,Mr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=YK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Qi.error(t)}}a(QK,"syncSchemaMetadata");var Qy=[];async function zy(e){try{try{Bc.resetReadTxn(Mr.SYSTEM_SCHEMA_NAME,Mr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Bc.resetReadTxn(Mr.SYSTEM_SCHEMA_NAME,Mr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Qi.warn(r)}let t=Wy(e);if(t){Qi.error(t);return}Qi.trace(`ITC userHandler ${Mr.HDB_ITC_CLIENT_PREFIX}${$K.pid} received user event:`,e),await VK.setUsersToGlobal();for(let r of Qy)r()}catch(t){Qi.error(t)}}a(zy,"userHandler");zy.addListener=function(e){Qy.push(e)};Jy.exports=KK});var Is=T((Que,Xy)=>{"use strict";var $ue=V(),rp=J(),zK=L(),{ITC_ERRORS:xc}=Or(),{parentPort:Yue,threadId:JK,isMainThread:jK,workerData:Kue}=require("worker_threads"),{onMessageFromWorkers:XK,broadcast:Wue,broadcastWithAcknowledgement:ZK}=Ke();Xy.exports={sendItcEvent:eW,validateEvent:jy,SchemaEventMsg:tW,UserEventMsg:rW};var P_;XK(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 eW(e){return!jK&&e.message&&(e.message.originator=JK),ZK(e)}a(eW,"sendItcEvent");function jy(e){if(typeof e!="object")return xc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||rp.isEmpty(e.type))return xc.MISSING_TYPE;if(!e.hasOwnProperty("message")||rp.isEmpty(e.message))return xc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||rp.isEmpty(e.message.originator))return xc.MISSING_ORIGIN;if(zK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return xc.INVALID_EVENT(e.type)}a(jy,"validateEvent");function tW(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(tW,"SchemaEventMsg");function rW(e){this.originator=e}a(rW,"UserEventMsg")});var gn=T((jue,rw)=>{"use strict";var Zy=L(),Jue=J(),v_=V(),ew=AN(),zo,{sendItcEvent:tw}=Is();function sW(e){try{v_.trace("signalSchemaChange called with message:",e),zo=zo||Hc();let t=new ew(Zy.ITC_EVENT_TYPES.SCHEMA,e);return zo.schema(t),tw(t)}catch(t){v_.error(t)}}a(sW,"signalSchemaChange");function nW(e){try{v_.trace("signalUserChange called with message:",e),zo=zo||Hc();let t=new ew(Zy.ITC_EVENT_TYPES.USER,e);return zo.user(t),tw(t)}catch(t){v_.error(t)}}a(nW,"signalUserChange");rw.exports={signalSchemaChange:sW,signalUserChange:nW}});var B_=T((Zue,nw)=>{"use strict";var sw=J(),iW=L(),oW=V(),aW=f_(),cW=d_(),uW=gn(),{SchemaEventMsg:lW}=Is(),_W="already exists in";nw.exports=dW;async function dW(e,t,r){if(sw.isEmptyOrZeroLength(r))return r;let s=[];sw.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 fW(e,t.schema,t.name,i)})),n}a(dW,"lmdbCheckForNewAttributes");async function fW(e,t,r,s){let n=new cW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await EW(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(_W))oW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(fW,"createNewAttribute");async function EW(e){let t;return t=await aW(e),uW.signalSchemaChange(new lW(process.pid,iW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(EW,"createAttribute")});var Jo=T((tle,iw)=>{"use strict";var sp=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}};iw.exports=sp});var aw=T((sle,ow)=>{"use strict";var hW=Jo(),mW=L().OPERATIONS_ENUM,np=class extends hW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(mW.INSERT,r,s,n,i),this.records=t}};ow.exports=np});var uw=T((ile,cw)=>{"use strict";var pW=Jo(),SW=L().OPERATIONS_ENUM,ip=class extends pW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(SW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};cw.exports=ip});var _w=T((ale,lw)=>{"use strict";var TW=Jo(),gW=L().OPERATIONS_ENUM,op=class extends TW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(gW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};lw.exports=op});var fw=T((ule,dw)=>{"use strict";var RW=Jo(),AW=L().OPERATIONS_ENUM,ap=class extends RW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(AW.DELETE,s,n,t,i),this.original_records=r}};dw.exports=ap});var qc=T((dle,pw)=>{"use strict";var _le=require("path"),Ew=We(),OW=aw(),bW=uw(),NW=_w(),yW=fw(),jo=dt(),hw=J(),{CONFIG_PARAMS:wW}=L(),mw=Z();mw.initSync();var H_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:IW}=Je();pw.exports=CW;async function CW(e,t){if(mw.get(wW.LOGGING_AUDITLOG)===!1)return;let r=IW(e.schema,e.table),s=await Ew.openEnvironment(r,e.table,!0),n=DW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){Ew.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),hw.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(CW,"writeTransaction");function DW(e,t){let r=hw.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===H_.INSERT)return new OW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.UPDATE)return new bW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.UPSERT)return new NW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.DELETE)return new yW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(DW,"createTransactionObject")});var cp=T((hle,Sw)=>{"use strict";var LW=wc(),Ele=Ic(),Fc=L(),UW=Uc(),MW=Go().insertRecords,PW=We(),vW=V(),BW=B_(),{getSchemaPath:HW}=Je(),xW=qc();Sw.exports=qW;async function qW(e){try{let{schema_table:t,attributes:r}=LW(e);UW(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 BW(e.hdb_auth_header,t,r),n=HW(e.schema,e.table),i=await PW.openEnvironment(n,e.table),o=await MW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await xW(e,o)}catch(c){vW.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(qW,"lmdbCreateRecords")});var Rw=T((ple,gw)=>{"use strict";var Tw=L(),FW=cp(),GW=Ic(),kW=require("fs-extra"),{getSchemaPath:VW}=Je();gw.exports=$W;async function $W(e){let t=[{name:e.schema,createddate:Date.now()}],r=new GW(Tw.SYSTEM_SCHEMA_NAME,Tw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await FW(r),await kW.mkdirp(VW(e.schema))}a($W,"lmdbCreateSchema")});var Ow=T((Tle,Aw)=>{"use strict";var up=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}};Aw.exports=up});var ww=T((ble,yw)=>{"use strict";var bw=We(),lp=br(),_p=Or().LMDB_ERRORS_ENUM,YW=dt(),Nw=V(),Rle=J(),KW=require("lmdb"),WW=Ow(),QW=L(),{OVERFLOW_MARKER:Ale,MAX_SEARCH_KEY_LENGTH:Ole}=YW,zW=QW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function JW(e,t,r,s){if(lp.validateEnv(e),t===void 0)throw new Error(_p.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(_p.IDS_REQUIRED):new Error(_p.IDS_MUST_BE_ITERABLE);try{let n=bw.listDBIs(e);bw.initializeDBIs(e,t,n);let i=new WW,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[zW]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,KW.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=lp.getIndexedValues(g);if(P)for(let H=0,v=P.length;H<v;H++)R.remove(P[H],o)}catch{Nw.warn(`cannot delete from attribute: ${A}, ${g}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){Nw.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=lp.getNextMonotonicTime(),i}catch(n){throw n}}a(JW,"deleteRecords");yw.exports={deleteRecords:JW}});var Gc=T((yle,Cw)=>{"use strict";var Xo=J(),jW=ww(),XW=We(),{getSchemaPath:ZW}=Je(),eQ=qc(),tQ=V();Cw.exports=rQ;async function rQ(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 Iw([],[]);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=ZW(e.schema,e.table),i=await XW.openEnvironment(n,e.table),o=await jW.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await eQ(e,o)}catch(c){tQ.error(`unable to write transaction due to ${c.message}`)}return Iw(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(rQ,"lmdbDeleteRecords");function Iw(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(Iw,"createDeleteResponse")});var fp=T((Cle,Dw)=>{"use strict";var sQ=L(),Ile=br();function dp(e,t){let r=Object.create(null);if(t.length===1&&sQ.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(dp,"parseRow");function nQ(e,t,r,s){let n=dp(r,e);s.push(n)}a(nQ,"searchAll");function iQ(e,t,r,s){let n=dp(r,e);s[t]=n}a(iQ,"searchAllToMap");function oQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(oQ,"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 aQ(e,t,r,s,n,i){t.toString().endsWith(e)&&zi(t,r,s,n,i)}a(aQ,"endsWith");function cQ(e,t,r,s,n,i){t.toString().includes(e)&&zi(t,r,s,n,i)}a(cQ,"contains");function uQ(e,t,r,s,n,i){t>e&&zi(t,r,s,n,i)}a(uQ,"greaterThanCompare");function lQ(e,t,r,s,n,i){t>=e&&zi(t,r,s,n,i)}a(lQ,"greaterThanEqualCompare");function _Q(e,t,r,s,n,i){t<e&&zi(t,r,s,n,i)}a(_Q,"lessThanCompare");function dQ(e,t,r,s,n,i){t<=e&&zi(t,r,s,n,i)}a(dQ,"lessThanEqualCompare");Dw.exports={parseRow:dp,searchAll:nQ,searchAllToMap:iQ,iterateDBI:oQ,endsWith:aQ,contains:cQ,greaterThanCompare:uQ,greaterThanEqualCompare:lQ,lessThanCompare:_Q,lessThanEqualCompare:dQ,pushResults:zi}});var Zo=T((Ple,Hw)=>{"use strict";var ni=We(),Lle=V(),Pr=br(),x_=dt(),ut=Or().LMDB_ERRORS_ENUM,Ule=J(),fQ=L(),q_=fp(),{parseRow:EQ}=q_,Mle=require("lmdb"),{OVERFLOW_MARKER:Lw,MAX_SEARCH_KEY_LENGTH:hQ}=x_;function Uw(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(Uw,"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 Mw(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(Lw)){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(Mw,"getOverflowCheck");function mQ(e,t,r,s=!1,n=void 0,i=void 0){if(Pr.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(_=>EQ(_.value,r))))}a(mQ,"searchAll");function pQ(e,t,r,s=!1,n=void 0,i=void 0){if(Pr.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 Uw(e,t,t,s,n,i))o.set(c,q_.parseRow(u,r));return o}a(pQ,"searchAllToMap");function SQ(e,t,r=!1,s=void 0,n=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=Uw(e,void 0,t,r,s,n),c=o.transaction,u=Mw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(SQ,"iterateDBI");function TQ(e,t){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);return ni.statDBI(e,t).entryCount}a(TQ,"countAll");function gQ(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=Pr.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(gQ,"equals");function RQ(e,t,r){return ii(e,t,r),ni.openDBI(e,t).getValuesCount(r)}a(RQ,"count");function AQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Ji(e,null,r,(c,u)=>{s=Pr.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(AQ,"startsWith");function OQ(e,t,r,s,n=!1,i=void 0,o=void 0){return Pw(e,t,r,s,n,i,o,!0)}a(OQ,"endsWith");function Pw(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=Mw(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(Lw)?_.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(Pw,"contains");function bQ(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(bQ,"greaterThan");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,!1,!1)}a(NQ,"greaterThanEqual");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="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),kc(e,t,r,u,s,n,i,o,!1,!0)}a(yQ,"lessThan");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,!1)}a(wQ,"lessThanEqual");function IQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(Pr.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=Pr.convertKeyValueToWrite(s),n=Pr.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(IQ,"between");function CQ(e,t,r,s){Pr.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(CQ,"searchByHash");function DQ(e,t,r){Pr.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(DQ,"checkHashExists");function LQ(e,t,r,s,n=[]){return Bw(e,t,r,s,n),vw(e,t,r,s,n).map(i=>i[1])}a(LQ,"batchSearchByHash");function UQ(e,t,r,s,n=[]){Bw(e,t,r,s,n);let i=new Map;for(let[o,c]of vw(e,t,r,s,n))i.set(o,c);return i}a(UQ,"batchSearchByHashToMap");function vw(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(vw,"batchHashSearch");function Bw(e,t,r,s,n){if(Pr.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(Bw,"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(Pr.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>hQ)throw new Error(ut.SEARCH_VALUE_TOO_LARGE)}a(ii,"validateComparisonFunctions");function Vc(e,t){return t.length===1&&fQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ni.listDBIs(e)),t}a(Vc,"setGetWholeRowAttributes");Hw.exports={searchAll:mQ,searchAllToMap:pQ,count:RQ,countAll:TQ,equals:gQ,startsWith:AQ,endsWith:OQ,contains:Pw,searchByHash:CQ,setGetWholeRowAttributes:Vc,batchSearchByHash:LQ,batchSearchByHashToMap:UQ,checkHashExists:DQ,iterateDBI:SQ,greaterThan:bQ,greaterThanEqual:NQ,lessThan:yQ,lessThanEqual:wQ,between:IQ}});var ea=T((Ble,kw)=>{var xw=require("lodash"),qw=je(),fe=require("joi"),MQ=J(),{hdb_schema_table:$c,checkValidTable:Fw,hdb_table:Gw,hdb_database:G_}=Ys(),{handleHDBError:PQ,hdb_errors:vQ}=re(),{getDatabases:BQ}=(Ae(),se(Fe)),{HTTP_STATUS_CODES:HQ}=vQ,xQ=fe.object({database:G_,schema:G_,table:Gw,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)}),qQ=fe.object({database:G_,schema:G_,table:Gw,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()});kw.exports=function(e,t){let r=null;switch(t){case"value":r=qw.validateBySchema(e,xQ);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(Fw("database",e.schema)),i(Fw("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=qw.validateBySchema(e,qQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=MQ.checkGlobalSchemaTable(e.schema,e.table);if(n)return PQ(new Error,n,HQ.NOT_FOUND);let o=BQ()[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 _=xw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!xw.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 Ep=T((xle,Vw)=>{"use strict";var FQ=We(),GQ=ea(),{getSchemaPath:kQ}=Je();Vw.exports=VQ;function VQ(e){let t=GQ(e,"hashes");if(t)throw t;let r=kQ(e.schema,e.table);return FQ.openEnvironment(r,e.table)}a(VQ,"initialize")});var hp=T((Fle,$w)=>{"use strict";var $Q=Zo(),YQ=Ep();$w.exports=KQ;async function KQ(e){let t=await YQ(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return $Q.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(KQ,"lmdbGetDataByHash")});var ta=T((kle,Yw)=>{"use strict";var mp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};Yw.exports=mp});var Ww=T((Yle,Kw)=>{"use strict";var $le=ta(),WQ=Zo(),QQ=Ep();Kw.exports=zQ;async function zQ(e){let t=await QQ(e),r=global.hdb_schema[e.schema][e.table];return WQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(zQ,"lmdbSearchByHash")});var Js=T((Wle,Qw)=>{"use strict";var pp=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}};Qw.exports=pp});var k_=T((zle,eI)=>{"use strict";var Wt=Zo(),JQ=We(),jQ=J(),Ee=dt(),ji=L(),XQ=xi(),zw=Or().LMDB_ERRORS_ENUM,{getSchemaPath:ZQ}=Je(),Rn=ji.SEARCH_WILDCARDS;async function ez(e,t,r){let s;e.schema===ji.SYSTEM_SCHEMA_NAME?s=XQ[e.table]:s=global.hdb_schema[e.schema][e.table];let n=Zw(e,s.hash_attribute,r,t);return jw(e,n,s.hash_attribute,r)}a(ez,"prepSearch");async function jw(e,t,r,s){let n=ZQ(e.schema,e.table),i=await JQ.openEnvironment(n,e.table),o=Xw(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(tz(e,r)===!1){let l=e.search_attribute;if(l===r)return s?Jw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?Jw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?Wt.batchSearchByHashToMap(c,r,e.get_attributes,_):Wt.batchSearchByHash(c,r,e.get_attributes,_)}a(jw,"executeSearch");function Xw(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=Wt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:n=Wt.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=Wt.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=Wt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Wt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Wt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Wt.searchAll(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Wt.searchAllToMap(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:n=Wt.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=Wt.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=Wt.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=Wt.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=Wt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(Xw,"searchByType");function Jw(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(Jw,"createMapFromIterable");function tz(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(tz,"checkToFetchMore");function Zw(e,t,r,s){if(jQ.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(zw.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(zw.UNKNOWN_SEARCH_TYPE)}}a(Zw,"createSearchTypeFromSearchObject");eI.exports={executeSearch:jw,createSearchTypeFromSearchObject:Zw,prepSearch:ez,searchByType:Xw}});var rI=T((Xle,tI)=>{"use strict";var jle=Js(),rz=ea(),sz=J(),nz=L(),iz=k_();tI.exports=oz;function oz(e,t){if(!sz.isEmpty(t)&&nz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=rz(e,"value");if(s)throw s;return iz.prepSearch(e,t,!0)}a(oz,"lmdbGetDataByValue")});var Yc=T((t_e,sI)=>{"use strict";var e_e=Js(),az=ea(),cz=J(),uz=L(),lz=k_();sI.exports=_z;async function _z(e,t){if(!cz.isEmpty(t)&&uz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=az(e,"value");if(s)throw s;return lz.prepSearch(e,t,!1)}a(_z,"lmdbSearchByValue")});var iI=T((n_e,nI)=>{"use strict";var s_e=dt(),Sp=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}},Tp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},gp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};nI.exports={SearchByConditionsObject:Sp,SearchCondition:Tp,SortAttribute:gp}});var lI=T((c_e,uI)=>{"use strict";var o_e=iI().SearchByConditionsObject,dz=Js(),fz=ea(),Rp=Zo(),V_=dt(),{Resource:a_e}=(As(),se(Ap)),cI=k_(),Ez=fp(),hz=require("lodash"),{getSchemaPath:mz}=Je(),oI=We(),{handleHDBError:pz,hdb_errors:Sz}=re(),{HTTP_STATUS_CODES:Tz}=Sz,gz=1e8;uI.exports=Rz;async function Rz(e){let t=fz(e,"conditions");if(t)throw pz(t,t.message,Tz.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=mz(e.schema,e.table),s=await oI.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)oI.openDBI(s,_.search_attribute);let i=hz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===V_.SEARCH_TYPES.EQUALS?_.estimated_count=Rp.count(s,_.search_attribute,_.search_value):l===V_.SEARCH_TYPES.CONTAINS||l===V_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=gz}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await aI(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(cI.filterByType),d=l.length,f=Rp.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=>Ez.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await aI(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=Rp.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Rz,"lmdbSearchByConditions");async function aI(e,t,r,s){let n=new dz(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,cI.searchByType(e,n,i,s).map(o=>o.value)}a(aI,"executeConditionSearch")});var ra=T((l_e,_I)=>{"use strict";var Az=L().OPERATIONS_ENUM,Op=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=Az.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};_I.exports=Op});var bp=T((d_e,TI)=>{"use strict";var hI=Js(),mI=ra(),pI=Yc(),SI=Gc(),ir=L(),dI=J(),fI=We(),{getTransactionAuditStorePath:Oz,getSchemaPath:bz}=Je(),EI=V();TI.exports=Nz;async function Nz(e){try{if(dI.isEmpty(global.hdb_schema[e.schema])||dI.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await yz(e),await wz(e);let t=bz(e.schema,e.table);try{await fI.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")EI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Oz(e.schema,e.table);await fI.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")EI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Nz,"lmdbDropTable");async function yz(e){let t=new hI(ir.SYSTEM_SCHEMA_NAME,ir.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ir.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ir.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await pI(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 mI(ir.SYSTEM_SCHEMA_NAME,ir.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await SI(n)}a(yz,"deleteAttributesFromSystem");async function wz(e){let t=new hI(ir.SYSTEM_SCHEMA_NAME,ir.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ir.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ir.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ir.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ir.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await pI(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 mI(ir.SYSTEM_SCHEMA_NAME,ir.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await SI(n)}catch(i){throw i}}a(wz,"dropTableFromSystem")});var RI=T((E_e,gI)=>{"use strict";var Iz=require("fs-extra"),Cz=Js(),Dz=ta(),Lz=ra(),Uz=bp(),Mz=Gc(),Pz=hp(),vz=Yc(),An=L(),{getSchemaPath:Bz}=Je(),{handleHDBError:Hz,hdb_errors:xz}=re(),{HDB_ERROR_MSGS:qz,HTTP_STATUS_CODES:Fz}=xz;gI.exports=Gz;async function Gz(e){let t;try{t=await kz(e.schema);let r=new Cz(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 vz(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await Uz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new Lz(An.SYSTEM_SCHEMA_NAME,An.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Mz(n);let i=Bz(t);await Iz.remove(i)}catch(r){throw r}}a(Gz,"lmdbDropSchema");async function kz(e){let t=new Dz(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 Pz(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw Hz(new Error,qz.SCHEMA_NOT_FOUND(e),Fz.NOT_FOUND,void 0,void 0,!0);return s}a(kz,"validateDropSchema")});var $_=T((m_e,AI)=>{"use strict";var Np=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};AI.exports=Np});var bI=T((T_e,OI)=>{"use strict";var Vz=require("fs-extra"),Y_=We(),{getTransactionAuditStorePath:$z}=Je(),yp=dt(),S_e=$_();OI.exports=Yz;async function Yz(e){let t;try{let r=$z(e.schema,e.table);await Vz.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,yp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Y_.createDBI(t,yp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Y_.createDBI(t,yp.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(Yz,"createTransactionsAuditEnvironment")});var II=T((R_e,wI)=>{"use strict";var wp=L(),NI=We(),Kz=Go(),{getSystemSchemaPath:Wz,getSchemaPath:Qz}=Je(),zz=xi(),Jz=f_(),Ip=d_(),jz=V(),Xz=bI(),Dp=zz.hdb_table,yI=[];for(let e=0;e<Dp.attributes.length;e++)yI.push(Dp.attributes[e].attribute);wI.exports=Zz;async function Zz(e,t){let r=Qz(t.schema,t.table),s=new Ip(t.schema,t.table,wp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Ip(t.schema,t.table,wp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Ip(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await NI.createEnvironment(r,t.table),e!==void 0){let o=await NI.openEnvironment(Wz(),wp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Kz.insertRecords(o,Dp.hash_attribute,yI,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Cp(s),await Cp(n),await Cp(i)}await Xz(t)}catch(o){throw o}}a(Zz,"lmdbCreateTable");async function Cp(e){try{await Jz(e)}catch(t){jz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Cp,"createAttribute")});var DI=T((O_e,CI)=>{"use strict";var eJ=wc(),tJ=Uc(),rJ=B_(),Kc=L(),sJ=Go().updateRecords,nJ=We(),{getSchemaPath:iJ}=Je(),oJ=qc(),aJ=V();CI.exports=cJ;async function cJ(e){try{let{schema_table:t,attributes:r}=eJ(e);tJ(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 rJ(e.hdb_auth_header,t,r),n=iJ(e.schema,e.table),i=await nJ.openEnvironment(n,e.table),o=await sJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await oJ(e,o)}catch(c){aJ.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(cJ,"lmdbUpdateRecords")});var UI=T((N_e,LI)=>{"use strict";var uJ=L().OPERATIONS_ENUM,Lp=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=uJ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};LI.exports=Lp});var PI=T((I_e,MI)=>{"use strict";var w_e=UI(),lJ=wc(),_J=Uc(),dJ=B_(),Wc=L(),fJ=Go().upsertRecords,EJ=We(),{getSchemaPath:hJ}=Je(),mJ=qc(),pJ=V(),{handleHDBError:SJ,hdb_errors:TJ}=re();MI.exports=gJ;async function gJ(e){let t;try{t=lJ(e)}catch(u){throw SJ(u,u.message,TJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;_J(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 dJ(e.hdb_auth_header,r,s),i=hJ(e.schema,e.table),o=await EJ.openEnvironment(i,e.table),c=await fJ(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await mJ(e,c)}catch(u){pJ.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(gJ,"lmdbUpsertRecords")});var BI=T((D_e,vI)=>{"use strict";var Up=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};vI.exports=Up});var xI=T((U_e,HI)=>{"use strict";var Mp=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}};HI.exports=Mp});var GI=T((v_e,FI)=>{"use strict";var Pp=We(),{getTransactionAuditStorePath:RJ}=Je(),P_e=BI(),Qc=dt(),AJ=J(),qI=xI(),OJ=require("util").promisify,bJ=OJ(setTimeout),NJ=1e4,yJ=100;FI.exports=wJ;async function wJ(e){let t=RJ(e.schema,e.table),r=await Pp.openEnvironment(t,e.table,!0),s=Pp.listDBIs(r);Pp.initializeDBIs(r,Qc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new qI;do n=await IJ(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 bJ(yJ);while(n.transactions_deleted>0);return i}a(wJ,"deleteAuditLogsBefore");async function IJ(e,t){let r=new qI;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];AJ.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>NJ)break}return await n,r}catch(s){throw s}}a(IJ,"deleteTransactions")});var VI=T((H_e,kI)=>{"use strict";var vp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};kI.exports=vp});var YI=T((F_e,$I)=>{"use strict";var CJ=Js(),DJ=ra(),q_e=VI(),js=L(),LJ=J(),Bp=We(),UJ=xi(),MJ=Yc(),PJ=Gc(),{getSchemaPath:vJ}=Je();$I.exports=BJ;async function BJ(e,t=!0){let r;e.schema===js.SYSTEM_SCHEMA_NAME?r=UJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await xJ(e),n=vJ(e.schema,e.table),i=await Bp.openEnvironment(n,e.table);return t===!0&&await HJ(e,i,r.hash_attribute),Bp.dropDBI(i,e.attribute),s}a(BJ,"lmdbDropAttribute");async function HJ(e,t,r){let s=Bp.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(HJ,"removeAttributeFromAllObjects");async function xJ(e){let t=new CJ(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 MJ(t)).filter(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(LJ.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 DJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return PJ(i)}a(xJ,"dropAttributeFromSystem")});var jI=T((V_e,JI)=>{"use strict";var Hp=We(),sa=dt(),k_e=br(),xp=L(),KI=J(),{getTransactionAuditStorePath:qJ}=Je(),FJ=Zo(),K_=Jo(),GJ=V();JI.exports=kJ;async function kJ(e){let t=qJ(e.schema,e.table),r=await Hp.openEnvironment(t,e.table,!0),s=Hp.listDBIs(r);Hp.initializeDBIs(r,sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case xp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return WI(r,e.search_values);case xp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,$J(r,e.search_values,n);case xp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return VJ(r,e.search_values);default:return WI(r)}}a(kJ,"readAuditLog");function WI(e,t=[0,Date.now()]){KI.isEmpty(t[0])&&(t[0]=0),KI.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(WI,"searchTransactionsByTimestamp");function VJ(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,zI(e,i))}return Object.fromEntries(r)}a(VJ,"searchTransactionsByUsername");function $J(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=FJ.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=zI(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);QI(u,"records",r,l,o),QI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a($J,"searchTransactionsByHashValues");function QI(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(QI,"loopRecords");function zI(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){GJ.warn(i)}return r}catch(s){throw s}}a(zI,"batchSearchTransactions")});var ZI=T((W_e,XI)=>{"use strict";var{getSchemaPath:Y_e}=Je(),K_e=We(),{database:YJ}=(Ae(),se(Fe));XI.exports={writeTransaction:KJ};async function KJ(e,t,r){return YJ({database:e,table:t}).transaction(r)}a(KJ,"writeTransaction")});var sC=T((z_e,rC)=>{"use strict";var{getSchemaPath:eC}=Je(),tC=We();rC.exports={flush:WJ,resetReadTxn:QJ};async function WJ(e,t){return(await tC.openEnvironment(eC(e,t),t.toString())).flushed}a(WJ,"flush");async function QJ(e,t){try{(await tC.openEnvironment(eC(e,t),t.toString())).resetReadTxn()}catch{}}a(QJ,"resetReadTxn")});var aC=T((j_e,oC)=>{"use strict";var{Readable:zJ}=require("stream"),{getDatabases:JJ}=(Ae(),se(Fe)),{readSync:jJ,openSync:XJ,createReadStream:nC}=require("fs"),{open:ZJ}=require("lmdb"),iC=r_(),e2=n_(),{AUDIT_STORE_OPTIONS:t2}=(Bi(),se(cC)),{INTERNAL_DBIS_NAME:r2,AUDIT_STORE_NAME:s2}=dt();oC.exports=i2;var qp=32768,n2=100;async function i2(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=ZJ({noSync:!0,maxDbs:e2.MAX_DBS}),f,E=d.openDB(r2,new iC(!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++%n2===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 iC(!H,H);await S(R,v)}e.include_audit&&await S(s2,Object.assign({},t2)),await f;let A=nC(d.path);return A.headers=u(),A.on("close",()=>{h.done(),d.close()}),A}let o=r[Object.keys(r)[0]].primaryStore,c=XJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(qp);jJ(c,_,0,qp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=nC(null,{fd:c,start:qp}),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",s),_}}a(i2,"getBackup")});var _C=T((Z_e,lC)=>{"use strict";var o2=V(),{handleHDBError:a2}=re(),c2=Nb(),u2=f_(),l2=cp(),_2=Rw(),d2=Gc(),f2=hp(),E2=Ww(),h2=rI(),m2=Yc(),p2=lI(),S2=RI(),T2=II(),g2=DI(),R2=PI(),A2=GI(),O2=bp(),b2=YI(),N2=jI(),y2=ZI(),uC=sC(),w2=aC(),Fp=class extends c2{static{a(this,"LMDBBridge")}async searchByConditions(t){return p2(t)}async getDataByHash(t){return await f2(t)}async searchByHash(t){return await E2(t)}async getDataByValue(t,r){return await h2(t,r)}async searchByValue(t){return await m2(t)}async createSchema(t){return await _2(t)}async dropSchema(t){return await S2(t)}async createTable(t,r){return await T2(t,r)}async dropTable(t){return await O2(t)}async createAttribute(t){return await u2(t)}async createRecords(t){return await l2(t)}async updateRecords(t){return await g2(t)}async upsertRecords(t){try{return await R2(t)}catch(r){throw a2(r,null,null,o2.ERR,r)}}async deleteRecords(t){return await d2(t)}async dropAttribute(t){return await b2(t)}async deleteAuditLogsBefore(t){return await A2(t)}async readAuditLog(t){return await N2(t)}writeTransaction(t,r,s){return y2.writeTransaction(t,r,s)}flush(t,r){return uC.flush(t,r)}resetReadTxn(t,r){return uC.resetReadTxn(t,r)}getBackup(t){return w2(t)}};lC.exports=Fp});function L2(){D2=setInterval(function(){for(let e of Gp)if(e.stale){let t=e[Oe]?.url;dC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},C2).unref()}var kp,dC,I2,Gp,Xi,W_,C2,D2,Vp=Re(()=>{kp=x(br()),dC=x(V());As();qo();I2=100,Gp=new Set,Xi=class{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===0)return this.readTxnsUsed=1,e_(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Gp.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&&(Gp.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");this.writes.push(t),this.open===1&&this.commit()}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,kp.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<I2>>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,kp.getNextMonotonicTime)())}getReadTxn(){}},C2=3e4;a(L2,"startMonitoringTxns");L2()});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 fC,Zi=Re(()=>{fC=require("../index");As();Vp();a(Xe,"transaction");(0,fC._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 AC={};Ye(AC,{ResourceBridge:()=>Kp});function Wp({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 hC(e,t){let r=Xs(e),s=Wp(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||M2,r=Ds()[t];if(!r)throw(0,Cs.handleHDBError)(new Error,U2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function mC(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*pC(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 SC,Q_,Cs,TC,gC,Ls,$p,Yp,RC,U2,M2,P2,v2,EC,Kp,OC=Re(()=>{"use strict";SC=x(_C()),Q_=x(ea()),Cs=x(re());Ae();TC=x(wc()),gC=x(Uc()),Ls=x(L()),$p=x(gn()),Yp=x(Is()),RC=x(J());Zi();J_();({HDB_ERROR_MSGS:U2}=Cs.hdb_errors),M2="data",P2=1e4,v2=10,Kp=class extends SC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),EC=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,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:Wp(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}),$p.signalSchemaChange(new Yp.SchemaEventMsg(process.pid,Ls.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Qp(t.schema),$p.signalSchemaChange(new Yp.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,EC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,TC.default)(t);(0,gC.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 mC(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,RC.async_set_timeout)(v2),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%P2===0&&await _();return u.length>0&&await _(),n?mC(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 hC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of hC(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:Wp(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 pC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return pC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Wp,"getSelect");a(hC,"getRecords");a(Xs,"getTable");a(mC,"createDeleteResponse");a(pC,"groupRecordsInHistory")});var Ns=T((hde,bC)=>{"use strict";var{ResourceBridge:B2}=(OC(),se(AC)),H2=Z();H2.initSync();var j_;function x2(){return j_||(j_=new B2,j_)}a(x2,"getBridge");bC.exports=x2()});var IC=T((pde,wC)=>{"use strict";var NC=require("lodash"),Jc=require("mathjs"),q2=require("jsonata"),yC=J();wC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?NC.uniqWith(e,NC.isEqual):e,searchJSON:F2,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 F2(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(yC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),yC.isEmpty(this.__ala__.res[r])){let s=q2(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(F2,"searchJSON")});var DC=T((Tde,CC)=>{"use strict";var Et=require("moment"),zp="YYYY-MM-DDTHH:mm:ss.SSSZZ";Et.suppressDeprecationWarnings=!0;CC.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(zp),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(zp),offset_utc:(e,t)=>Et(e).utc().utcOffset(t).format(zp)}});var PC=T((gde,MC)=>{"use strict";var G2=require("@turf/area"),k2=require("@turf/length"),V2=require("@turf/circle"),$2=require("@turf/difference"),Y2=require("@turf/distance"),K2=require("@turf/boolean-contains"),W2=require("@turf/boolean-equal"),Q2=require("@turf/boolean-disjoint"),z2=require("@turf/helpers"),LC=L(),pe=J(),On=V();MC.exports={geoArea:J2,geoLength:j2,geoCircle:X2,geoDifference:Z2,geoDistance:UC,geoNear:e4,geoContains:t4,geoEqual:r4,geoCrosses:s4,geoConvert:n4};function J2(e){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return G2.default(e)}catch(t){return On.trace(t,e),NaN}}a(J2,"geoArea");function j2(e,t){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return k2.default(e,{units:t||"kilometers"})}catch(r){return On.trace(r,e),NaN}}a(j2,"geoLength");function X2(e,t,r){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return V2.default(e,t,{units:r||"kilometers"})}catch(s){return On.trace(s,e,t),NaN}}a(X2,"geoCircle");function Z2(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 $2(e,t)}catch(r){return On.trace(r,e,t),NaN}}a(Z2,"geoDifference");function UC(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 Y2.default(e,t,{units:r||"kilometers"})}catch(s){return On.trace(s,e,t),NaN}}a(UC,"geoDistance");function e4(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 UC(e,t,s)<=r}catch(n){return On.trace(n,e,t),!1}}a(e4,"geoNear");function t4(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 K2.default(e,t)}catch(r){return On.trace(r,e,t),!1}}a(t4,"geoContains");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,"geoEqual");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,"geoCrosses");function n4(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(LC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(LC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=pe.autoCastJSON(e)),z2[t](e,r)}a(n4,"geoConvert")});var X_=T((Ade,vC)=>{var eo=IC(),vr=DC(),Zs=PC();vC.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=vr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=vr.current_time,e.fn.extract=e.fn.EXTRACT=vr.extract,e.fn.date=e.fn.DATE=vr.date,e.fn.date_format=e.fn.DATE_FORMAT=vr.date_format,e.fn.date_add=e.fn.DATE_ADD=vr.date_add,e.fn.date_sub=e.fn.DATE_SUB=vr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=vr.date_diff,e.fn.now=e.fn.NOW=vr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=vr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=vr.get_server_time,e.fn.getdate=e.fn.GETDATE=vr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=vr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=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 qC=T((Ode,xC)=>{"use strict";var Xc=require("lodash"),or=require("alasql");or.options.cache=!1;var i4=X_(),BC=require("clone"),Z_=require("recursive-iterator"),_e=V(),Ce=J(),na=Ns(),o4=L(),{hdb_errors:a4}=re(),{getDatabases:HC}=(Ae(),se(Fe)),c4="IS NULL",Us="There was a problem performing this search. Please check the logs and try again.";i4(or);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(BC(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=HC()[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 or.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 or.yy.LogicValue({value:i}):s instanceof or.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new or.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(o4.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 or.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(BC(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(c4)>-1&&this.tables.forEach(n=>{let i={columnid:HC()[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 or.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 or.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new or.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 or.yy.FuncValue:new or.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 or.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 or.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(a4.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)}};xC.exports=Jp});var es=T((Nde,FC)=>{"use strict";var u4=Ob();FC.exports={searchByConditions:_4,searchByHash:d4,searchByValue:f4,search:E4};var jp=Ns(),{transformReq:Xp}=J(),l4=qC();async function _4(e){return Xp(e),jp.searchByConditions(e)}a(_4,"searchByConditions");async function d4(e){Xp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of jp.searchByHash(e))r&&t.push(r);return t}a(d4,"searchByHash");async function f4(e){Xp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of jp.searchByValue(e))t.push(r);return t}a(f4,"searchByValue");function E4(e,t){try{let r=new u4(e);r.validate(),new l4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(E4,"search")});var ed=T((wde,GC)=>{"use strict";var h4=Ns();GC.exports={writeTransaction:m4};function m4(e,t,r){return h4.writeTransaction(e,t,r)}a(m4,"writeTransaction")});var YC=T((Dde,$C)=>{"use strict";var p4=es(),S4=Tn(),kC=V(),T4=wr(),Cde=ed(),g4=require("clone"),eS=require("alasql"),R4=X_(),VC=require("util"),A4=VC.promisify(S4.getTableSchema),O4=VC.promisify(p4.search),b4=L(),Zp=J();R4(eS);$C.exports={update:y4};var N4="There was a problem performing this update. Please check the logs and try again.";async function y4({statement:e,hdb_user:t}){let r=await A4(e.table.databaseid,e.table.tableid),s=w4(e.columns);Zp.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=g4(n),c=Zp.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=eS.parse(u).statements[0],l=await O4(_),d=I4(s,l);return C4(o,d,t)}a(y4,"update");function w4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=eS.compile(`SELECT ${r.expression.toString()} AS [${b4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw kC.error(t),new Error(N4)}}a(w4,"createUpdateRecord");function I4(e,t){return Zp.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(I4,"buildUpdateRecords");async function C4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await T4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){kC.error(`Error delete new_attributes from update response: ${i}`)}return n}a(C4,"updateRecords")});var WC=T((Pde,KC)=>{var D4=require("alasql"),L4=es(),U4=V(),M4=Ns(),rS=require("util"),tS=J(),P4=L(),v4=Tn(),Ude=ed(),Mde=wr(),B4="record",H4="successfully deleted",x4=rS.callbackify(k4),q4=rS.promisify(L4.search),F4=rS.promisify(v4.getTableSchema);KC.exports={convertDelete:x4};function G4(e){return`${e.deleted_hashes.length} ${B4}${e.deleted_hashes.length===1?"":"s"} ${H4}`}a(G4,"generateReturnMessage");async function k4({statement:e,hdb_user:t}){let r=await F4(e.table.databaseid,e.table.tableid);tS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=tS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=D4.parse(o).statements[0],u={operation:P4.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await q4(c);let _=await M4.deleteRecords(u);return tS.isEmptyOrZeroLength(_.message)&&(_.message=G4(_)),delete _.txn_time,_}catch(_){throw U4.error(_),_.hdb_code?_.message:_}}a(k4,"convertDelete")});var XC=T((Bde,jC)=>{"use strict";var V4=Xn(),{hdb_errors:QC}=re(),{getDatabases:zC}=(Ae(),se(Fe));jC.exports={checkSchemaExists:JC,checkSchemaTableExists:$4,schema_describe:V4};async function JC(e){if(!zC()[e])return QC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(JC,"checkSchemaExists");async function $4(e,t){let r=await JC(e);if(r)return r;if(!zC()[e][t])return QC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a($4,"checkSchemaTableExists")});var Zc=T((xde,Y4)=>{Y4.exports={name:"harperdb",version:"4.3.0-beta.5",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:()=>Br,recordActionBinary:()=>rs,setAnalyticsEnabled:()=>K4});function K4(e){cD=e}function Br(e,t,r,s,n){if(!cD)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||W4()}function rs(e,t,r,s,n){Br(!!e,t,r,s,n)}function ru(e){_D.push(e)}function W4(){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 dD){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 fD()}let s=process.memoryUsage();t.push({metric:"memory",threadId:to.threadId,byThread:!0,...s});for(let n of _D)n(t);sd=new Map,to.parentPort?to.parentPort.postMessage({type:lD,report:r}):mD({report:r})},uD).unref()}async function Q4(e,t=6e4){let r=iS(),s=ED(),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 It=ne[le];typeof It=="number"&&(ce[le]=(ce[le]*xe+It*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 fD()}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,It)=>le.value>It.value?1:-1);let A=S.count-1,R=[],g=0,P=0,H;for(let le of dD){let It=A*le;for(;g<It;)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-It)/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-ZC,active:E-eD,time:d,...process.memoryUsage()};s.primaryStore.put(h,p,{append:!0}).then(S=>{S||s.primaryStore.put(h,p)})}ZC=f,eD=E}async function tD(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function iS(){return rD||(rD=ct({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function ED(){return sD||(sD=ct({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function j4(){hD=!0;let e=(0,tu.get)(nS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await Q4(uD,e),await tD(iS(),z4),await tD(ED(),J4)},Math.min(e/2,2147483647)).unref()}function mD(e,t){let r=e.report;r.threadId=t?.threadId||to.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(nD+=s.mean*s.count);r.totalBytesProcessed=nD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(iD.get(t))}),iD.set(t,t.performance.eventLoopUtilization())),r.id=(0,rd.getNextMonotonicTime)(),iS().primaryStore.put(r.id,r),hD||j4(),X4&&(pD=e3(r))}async function e3(e){if(await pD,!oi){let r=(0,eu.dirname)((0,aD.getLogFilePath)());try{oi=await(0,sS.open)((0,eu.join)(r,"analytics.log"),"r+")}catch{oi=await(0,sS.open)((0,eu.join)(r,"analytics.log"),"w+")}}let t=(await oi.stat()).size;if(t>Z4){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(yD,"runCommand");async function O3(){try{await t3.access(cS)}catch{return!1}let e=await yD(`${cS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return r3.eq(t,R3)}a(O3,"checkNATSServerInstalled");async function dS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await AD.getClusterUser();if(io(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Hr.trace("create nats connection called");let i=await f3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:qt.get(Me.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:qt.get(Me.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:qt.get(Me.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Hr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Hr.error("Error with Nats client connection, connection closed",o),wD()}),i}a(dS,"createConnection");function wD(){ss=void 0,ro=void 0,so=void 0,no=void 0}a(wD,"clearClientCache");async function b3(){ss&&(await ss.drain(),ss=void 0,ro=void 0,so=void 0,no=void 0)}a(b3,"closeConnection");var ss,no;async function ad(){return no||(no=dS(qt.get(Me.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(Me.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 ID(){if(so)return so;io(ss)&&await ad();let{domain:e}=cu(Me.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(ID,"getJetStream");async function ar(){let e=ss||await ad(),t=ro||await au(),r=so||await ID();return{connection:e,jsm:t,js:r}}a(ar,"getNATSReferences");async function N3(e){let t=qt.get(Me.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await AD.getClusterUser(),n=await dS(t,r,s),i=_S(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=ND.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 uS.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(N3,"getServerList");async function fS(e,t){let{jsm:r}=await ar(),s=qt.get(Me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=qt.get(Me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=qt.get(Me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:OD.File,retention:bD.Limits,subjects:t,discard:E3.Old,max_msgs:n,max_bytes:i,max_age:s})}a(fS,"createLocalStream");async function CD(){let{jsm:e}=await ar(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(CD,"listStreams");async function y3(e){let{jsm:t}=await ar();await t.streams.delete(e)}a(y3,"deleteLocalStream");async function w3(e){let{connection:t}=await ar(),r=[],s=_S(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(ND.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(w3,"listRemoteStreams");async function I3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ar(),i=TD(),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=lS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Ne.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(I3,"viewStream");async function*C3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ar(),i=TD(),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=lS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(Ne.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(C3,"viewStreamIterator");async function D3(e,t,r,s){Hr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=DD(s,r);let{js:n}=await ar(),i=await uu(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:RD.encode(s);try{Hr.trace(`publishToStream publishing to subject: ${o}`),T3(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 PD(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Hr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await fS(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(D3,"publishToStream");function DD(e,t){t===void 0&&(t=m3());let r=qt.get(Me.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Ne.MSG_HEADERS.ORIGIN)&&r&&t.append(Ne.MSG_HEADERS.ORIGIN,r),t}a(DD,"addNatsMsgHeader");function cu(e){e=e.toLowerCase();let t=ou.join(qt.get(Me.CONFIG_PARAMS.ROOTPATH),g3);if(e===Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return io(aS)&&(aS={port:nu.getConfigFromFile(Me.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Me.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.HUB,config_file:Ne.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:ou.join(t,Ne.PID_FILES.HUB),hdb_nats_path:t}),aS;if(e===Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return io(oS)&&(oS={port:nu.getConfigFromFile(Me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Me.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,config_file:Ne.NATS_CONFIG_FILES.LEAF_SERVER,domain:nu.getConfigFromFile(Me.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,pid_file_path:ou.join(t,Ne.PID_FILES.LEAF),hdb_nats_path:t}),oS;Hr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(cu,"getServerConfig");async function L3(e){let{jsm:t}=await ar(),r=await uu();try{await t.streams.add({name:e.stream_name,storage:OD.File,retention:bD.Limits,max_age:_3,max_bytes:d3,subjects:[`${Ne.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(L3,"createWorkQueueStream");async function U3(){let{jsm:e}=await ar();(await e.consumers.info(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Hr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name),Hr.info("Adding pull consumer to ingest stream"),await e.consumers.add(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:id.Explicit,durable_name:Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:od.All,max_ack_pending:1e4}))}a(U3,"updateIngestStreamConsumer");async function LD(e,t,r){let{jsm:s}=await ar(),n=await s.streams.info(t),i=UD(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:`${Ne.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(LD,"addSourceToWorkStream");function UD(e){return e.split(".")[1]}a(UD,"extractServerName");async function MD(e,t,r){let{jsm:s}=await ar(),{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(MD,"removeSourceFromWorkStream");async function M3(e,t,r=6e4,s=_S()){if(!uS.isObject(t))throw new Error("data param must be an object");let n=RD.encode(t),{connection:i}=await ar(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return lS(c.data)}a(M3,"request");function ES(e){return new Promise(async(t,r)=>{let s=o3(cS,["--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(ES,"reloadNATS");async function P3(){let{pid_file_path:e}=cu(Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await ES(e)}a(P3,"reloadNATSHub");async function v3(){let{pid_file_path:e}=cu(Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await ES(e)}a(v3,"reloadNATSLeaf");function B3(e,t,r){let s;switch(e.code){case SD.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case SD.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(B3,"requestErrorHandler");async function H3(e,t){let r=t+Ne.SERVER_SUFFIX.LEAF;await PD(async()=>{e.subscribe===!0?await LD(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await MD(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(H3,"updateWorkStream");function PD(e){return a3.writeTransaction(Me.SYSTEM_SCHEMA_NAME,Me.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(PD,"exclusiveLock");async function vD(e,t){let r=nd.createNatsTableStreamName(e,t),s=await uu(),n=G3(e,t,s);await fS(r,[n])}a(vD,"createLocalTableStream");async function x3(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await vD(s,n)}}a(x3,"createTableStreams");async function BD(e,t,r=!1){if(qt.get(Me.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=nd.createNatsTableStreamName(e,t),{jsm:n}=await ar();r?await n.streams.purge(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name):await n.streams.purge(s)}catch(s){if(s.message==="stream not found")Hr.warn(s);else throw s}}a(BD,"purgeTableStream");async function q3(e,t){if(qt.get(Me.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await BD(e,t[r])}a(q3,"purgeSchemaTableStreams");async function F3(e){return(await au()).streams.info(e)}a(F3,"getStreamInfo");function G3(e,t,r){return`${Ne.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(G3,"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 k3(){let e=await au(),t=await uu(),r=await CD();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=V3(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Hr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Hr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Hr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}await e.streams.update(n.name,n)}}}a(k3,"updateLocalStreams");function V3(e){let{config:t}=e,r=!1;if(t.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=qt.get(Me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=qt.get(Me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=qt.get(Me.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(V3,"updateStreamLimits")});var lu=T((tfe,GD)=>{"use strict";var ia=__(),oa=XC(),$3=V(),Y3=require("uuid").v4,efe=require("clone"),ud=gn(),aa=L(),K3=require("util"),ai=Ns(),{handleHDBError:cr,hdb_errors:W3}=re(),{HDB_ERROR_MSGS:cd,HTTP_STATUS_CODES:ur}=W3,{SchemaEventMsg:ld}=Is(),xD=st(),{getDatabases:Q3}=(Ae(),se(Fe)),{transformReq:ca}=J();GD.exports={createSchema:z3,createSchemaStructure:qD,createTable:J3,createTableStructure:FD,createAttribute:tj,dropSchema:j3,dropTable:X3,dropAttribute:Z3,getBackup:rj};async function z3(e){let t=await qD(e);return ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema)),t}a(z3,"createSchema");async function qD(e){let t=ia.schema_object(e);if(t)throw cr(t,t.message,ur.BAD_REQUEST,void 0,void 0,!0);if(ca(e),!await oa.checkSchemaExists(e.schema))throw cr(new Error,cd.SCHEMA_EXISTS_ERR(e.schema),ur.BAD_REQUEST,aa.LOG_LEVELS.ERROR,cd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ai.createSchema(e),`database '${e.schema}' successfully created`}a(qD,"createSchemaStructure");async function J3(e){return ca(e),e.hash_attribute=e.primary_key??e.hash_attribute,await FD(e)}a(J3,"createTable");async function FD(e){let t=ia.create_table_object(e);if(t)throw cr(t,t.message,ur.BAD_REQUEST,void 0,void 0,!0);if(ia.validateTableResidence(e.residence),!await oa.checkSchemaTableExists(e.schema,e.table))throw cr(new Error,cd.TABLE_EXISTS_ERR(e.schema,e.table),ur.BAD_REQUEST,aa.LOG_LEVELS.ERROR,cd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:Y3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await ai.createTable(s,e);else throw cr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ur.BAD_REQUEST);else await ai.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(FD,"createTableStructure");async function j3(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 cr(s,s.message,ur.BAD_REQUEST,void 0,void 0,!0);ca(e);let n=await oa.checkSchemaExists(e.schema);if(n)throw cr(new Error,n,ur.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 xD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(j3,"dropSchema");async function X3(e){let t=ia.table_object(e);if(t)throw cr(t,t.message,ur.BAD_REQUEST,void 0,void 0,!0);ca(e);let r=await oa.checkSchemaTableExists(e.schema,e.table);if(r)throw cr(new Error,r,ur.NOT_FOUND,aa.LOG_LEVELS.ERROR,r,!0);return await ai.dropTable(e),await xD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(X3,"dropTable");async function Z3(e){let t=ia.attribute_object(e);if(t)throw cr(t,t.message,ur.BAD_REQUEST,void 0,void 0,!0);ca(e);let r=await oa.checkSchemaTableExists(e.schema,e.table);if(r)throw cr(new Error,r,ur.NOT_FOUND,aa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw cr(new Error,"You cannot drop a hash attribute",ur.BAD_REQUEST,void 0,void 0,!0);if(aa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw cr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ur.BAD_REQUEST,void 0,void 0,!0);try{return await ai.dropAttribute(e),ej(e),ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw $3.error(`Got an error deleting attribute ${K3.inspect(e)}.`),s}}a(Z3,"dropAttribute");function ej(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(ej,"dropAttributeFromGlobal");async function tj(e){ca(e);let t=Q3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw cr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,ur.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(tj,"createAttribute");function rj(e){return ai.getBackup(e)}a(rj,"getBackup")});var VD=T((sfe,kD)=>{"use strict";var{OPERATIONS_ENUM:sj}=L(),hS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=sj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};kD.exports=hS});var mS=T((ofe,QD)=>{"use strict";var nj=Ns(),ife=VD(),_d=J(),dd=L(),ij=Z(),{handleHDBError:$D,hdb_errors:oj}=re(),{HDB_ERROR_MSGS:YD,HTTP_STATUS_CODES:KD}=oj,aj=Object.values(dd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),WD="To use this operation audit log must be enabled in harperdb-config.yaml";QD.exports=cj;async function cj(e){if(_d.isEmpty(e.schema))throw new Error(YD.SCHEMA_REQUIRED_ERR);if(_d.isEmpty(e.table))throw new Error(YD.TABLE_REQUIRED_ERR);if(!ij.get(dd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw $D(new Error,WD,KD.BAD_REQUEST,dd.LOG_LEVELS.ERROR,WD,!0);let t=_d.checkSchemaTableExist(e.schema,e.table);if(t)throw $D(new Error,t,KD.NOT_FOUND,dd.LOG_LEVELS.ERROR,t,!0);if(!_d.isEmpty(e.search_type)&&aj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await nj.readAuditLog(e)}a(cj,"readAuditLog")});var JD=T((cfe,zD)=>{"use strict";var{OPERATIONS_ENUM:uj}=L(),pS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=uj.GET_BACKUP,this.schema=t,this.table=r}};zD.exports=pS});var ZD=T((dfe,XD)=>{"use strict";var lj=Ns(),lfe=JD(),SS=J(),_j=L(),_fe=Z(),{handleHDBError:dj,hdb_errors:fj}=re(),{HDB_ERROR_MSGS:jD,HTTP_STATUS_CODES:Ej}=fj;XD.exports=hj;async function hj(e){if(SS.isEmpty(e.schema))throw new Error(jD.SCHEMA_REQUIRED_ERR);if(SS.isEmpty(e.table))throw new Error(jD.TABLE_REQUIRED_ERR);let t=SS.checkSchemaTableExist(e.schema,e.table);if(t)throw dj(new Error,t,Ej.NOT_FOUND,_j.LOG_LEVELS.ERROR,t,!0);return await lj.getBackup(read_audit_log_object)}a(hj,"getBackup")});var iL=T((Efe,nL)=>{var ci=require("validate.js"),tL=je(),ua=L(),{handleHDBError:mj,hdb_errors:pj}=re(),{HDB_ERROR_MSGS:lt,HTTP_STATUS_CODES:Sj}=pj,TS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),Tj={STRUCTURE_USER:"structure_user"},eL=Object.values(ua.ROLE_TYPES_ENUM),gj="attribute_permissions",Rj="attribute_name",{PERMS_CRUD_ENUM:la}=ua,Aj=[gj,...Object.values(la)],rL=[la.READ,la.INSERT,la.UPDATE],Oj=[Rj,...rL];function bj(e){let t=TS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,sL(e,t)}a(bj,"addRoleValidation");function Nj(e){let t=TS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,sL(e,t)}a(Nj,"alterRoleValidation");function yj(e){let t=TS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,tL.validateObject(e,t)}a(yj,"dropRoleValidation");var wj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function sL(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)wj.includes(s[o])||n.push(s[o]);n.length>0&&ht(lt.INVALID_ROLE_JSON_KEYS(n),r);let i=tL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{ht(o,r)}),e.permission){let o=Ij(e);o&&ht(o,r),eL.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(eL.indexOf(o)<0){if(o===Tj.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=>{Aj.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=>{!Oj.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}rL.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 Cj(r)}a(sL,"customValidate");nL.exports={addRoleValidation:bj,alterRoleValidation:Nj,dropRoleValidation:yj};function Ij(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(Ij,"validateNoSUPerms");function Cj(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 mj(new Error,s,Sj.BAD_REQUEST)}else return null}a(Cj,"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 NS=T((mfe,uL)=>{"use strict";var oL=wr(),aL=es(),Dj=ti(),RS=iL(),AS=gn(),Lj=require("uuid").v4,Uj=require("util"),fd=L(),Mj=J(),OS=aL.searchByValue,Pj=aL.searchByHash,vj=Uj.promisify(Dj.delete),Bj=Js(),Hj=ta(),{hdb_errors:xj,handleHDBError:oo}=re(),{HDB_ERROR_MSGS:cL,HTTP_STATUS_CODES:_u}=xj,{UserEventMsg:bS}=Is();uL.exports={addRole:qj,alterRole:Fj,dropRole:Gj,listRoles:kj};function gS(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(gS,"scrubRoleDetails");async function qj(e){let t=RS.addRoleValidation(e);if(t)throw t;e=gS(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 OS(r)||[])}catch(i){throw oo(i)}if(s&&s.length>0)throw oo(new Error,cL.ROLE_ALREADY_EXISTS(e.role),_u.CONFLICT,void 0,void 0,!0);e.id||(e.id=Lj());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await oL.insert(n),AS.signalUserChange(new bS(process.pid)),e=gS(e),e}a(qj,"addRole");async function Fj(e){let t=RS.alterRoleValidation(e);if(t)throw t;e=gS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await oL.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 AS.signalUserChange(new bS(process.pid)),e}a(Fj,"alterRole");async function Gj(e){let t=RS.dropRoleValidation(e);if(t)throw oo(new Error,t,_u.BAD_REQUEST,void 0,void 0,!0);let r=new Hj(fd.SYSTEM_SCHEMA_NAME,fd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await Pj(r));if(s.length===0)throw oo(new Error,cL.ROLE_NOT_FOUND,_u.NOT_FOUND,void 0,void 0,!0);let n=new Bj(fd.SYSTEM_SCHEMA_NAME,fd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await OS(n)),o=!1;if(Mj.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 vj(c),AS.signalUserChange(new bS(process.pid)),`${s[0].role} successfully deleted`}a(Gj,"dropRole");async function kj(){return OS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(kj,"listRoles")});var fL=T((Sfe,dL)=>{"use strict";var Vj=Z(),ui=require("joi"),$j=je(),lL=require("moment"),Yj=require("fs-extra"),yS=require("path"),Kj=require("lodash"),du=L(),{LOG_LEVELS:ao}=L(),Wj="YYYY-MM-DD hh:mm:ss",Qj=yS.resolve(__dirname,"../logs");dL.exports=function(e){return $j.validateBySchema(e,zj)};var zj=ui.object({from:ui.custom(_L),until:ui.custom(_L),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 _L(e,t){if(lL(e,lL.ISO_8601).format(Wj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(_L,"validateDatetime");function Jj(e,t){if(Kj.invert(du.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Vj.get(du.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?du.LOG_NAMES.HDB:e,i=n===du.LOG_NAMES.INSTALL?yS.join(Qj,du.LOG_NAMES.INSTALL):yS.join(s,n);return Yj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Jj,"validateReadLogPath")});var IS=T((gfe,hL)=>{"use strict";var Ed=L(),jj=V(),Xj=Z(),Zj=fL(),wS=require("path"),EL=require("fs-extra"),{once:eX}=require("events"),{handleHDBError:tX,hdb_errors:rX}=re(),{PACKAGE_ROOT:sX}=L(),nX=wS.join(sX,"logs"),iX=1e3,oX=200;hL.exports=aX;async function aX(e){let t=Zj(e);if(t)throw tX(t,t.message,rX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Xj.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?wS.join(nX,Ed.LOG_NAMES.INSTALL):wS.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?iX:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(EL.statSync(n).size-(h+5)*oX,0));let S=EL.createReadStream(n,{start:p});S.on("error",v=>{jj.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 eX(S,"close"),R}a(aX,"readLog");function li(e,t,r){t==="desc"?cX(e,r):t==="asc"?uX(e,r):r.push(e)}a(li,"pushLineToResult");function cX(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(cX,"insertDescending");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,"insertAscending")});var hd=T((Nfe,TL)=>{"use strict";var CS=require("joi"),{string:fu,boolean:mL,date:lX}=CS.types(),_X=je(),{validateSchemaExists:Afe,validateTableExists:Ofe,validateSchemaName:bfe}=Ys(),dX=L(),fX=Ge(),pL=Z();pL.initSync();var EX=fu.invalid(pL.get(dX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(fX.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),SL={operation:fu.valid("add_node","update_node","set_node_replication"),node_name:EX,subscriptions:CS.array().items({table:fu.optional(),schema:fu.optional(),database:fu.optional(),subscribe:mL.required(),publish:mL.required().custom(mX),start_time:lX.iso()}).min(1).required()};function hX(e){return _X.validateBySchema(e,CS.object(SL))}a(hX,"addUpdateNodeValidator");function mX(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(mX,"checkForFalsy");TL.exports={addUpdateNodeValidator:hX,validation_schema:SL}});var RL=T((wfe,gL)=>{var pX=je(),SX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};gL.exports=function(e){return pX.validateObject(e,SX)}});var md=T((Ife,AL)=>{"use strict";var TX=L().OPERATIONS_ENUM,DS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=TX.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};AL.exports=DS});var bL=T((Dfe,OL)=>{"use strict";var gX={OPERATION:"operation",REFRESH:"refresh"},LS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},US=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};OL.exports={JWTTokens:LS,TOKEN_TYPE_ENUM:gX,JWTRSAKeys:US}});var mu=T((Ufe,IL)=>{"use strict";var hu=require("jsonwebtoken"),MS=require("fs-extra"),PS=J(),ns=L(),{handleHDBError:lr,hdb_errors:RX}=re(),{HTTP_STATUS_CODES:_r,AUTHENTICATION_ERROR_MSGS:dr}=RX,Eu=V(),NL=b_(),HS=ts(),AX=wr().update,OX=md(),bX=gn(),{UserEventMsg:NX}=Is(),_i=Z();_i.initSync();var vS=require("path"),{JWTTokens:yX,JWTRSAKeys:wX,TOKEN_TYPE_ENUM:pd}=bL(),IX=_i.get(ns.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?_i.get(ns.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",CX=_i.get(ns.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?_i.get(ns.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Sd="RS256",BS;IL.exports={createTokens:DX,validateOperationToken:UX,refreshOperationToken:LX,validateRefreshToken:wL};async function DX(e){if(PS.isEmpty(e)||typeof e!="object")throw lr(new Error,dr.INVALID_AUTH_OBJECT,_r.BAD_REQUEST,void 0,void 0,!0);if(PS.isEmpty(e.username))throw lr(new Error,dr.USERNAME_REQUIRED,_r.BAD_REQUEST,void 0,void 0,!0);if(PS.isEmpty(e.password))throw lr(new Error,dr.PASSWORD_REQUIRED,_r.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await HS.findAndValidateUser(e.username,e.password),!t)throw lr(new Error,dr.INVALID_CREDENTIALS,_r.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Eu.error(f),lr(new Error,dr.INVALID_CREDENTIALS,_r.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 yL(i,r.private_key,r.passphrase),c=await hu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:CX,algorithm:Sd,subject:pd.REFRESH}),u=NL.hash(c),_=new OX(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await AX(_)}catch(f){Eu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw lr(new Error,dr.REFRESH_TOKEN_SAVE_FAILED,_r.INTERNAL_SERVER_ERROR);return bX.signalUserChange(new NX(process.pid)),new yX(o,c)}a(DX,"createTokens");async function yL(e,t,r){return await hu.sign(e,{key:t,passphrase:r},{expiresIn:IX,algorithm:Sd,subject:pd.OPERATION})}a(yL,"signOperationToken");async function Td(){if(BS===void 0)try{let e=vS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PASSPHRASE_NAME),t=vS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=vS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await MS.readFile(e)).toString(),n=(await MS.readFile(t)).toString(),i=(await MS.readFile(r)).toString();BS=new wX(i,n,s)}catch(e){throw Eu.error(e),lr(new Error,dr.NO_ENCRYPTION_KEYS,_r.INTERNAL_SERVER_ERROR)}return BS}a(Td,"getJWTRSAKeys");async function LX(e){if(!e)throw lr(new Error,dr.INVALID_BODY,_r.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw lr(new Error,dr.REFRESH_TOKEN_REQUIRED,_r.BAD_REQUEST,void 0,void 0,!0);await wL(e.refresh_token);let t=await Td(),r=await hu.decode(e.refresh_token);return{operation_token:await yL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(LX,"refreshOperationToken");async function UX(e){try{let t=await Td(),r=await hu.verify(e,t.public_key,{algorithms:Sd,subject:pd.OPERATION});return await HS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Eu.warn(t),t.name&&t.name==="TokenExpiredError"?lr(new Error,dr.TOKEN_EXPIRED,_r.FORBIDDEN):lr(new Error,dr.INVALID_TOKEN,_r.UNAUTHORIZED)}}a(UX,"validateOperationToken");async function wL(e){let t;try{let r=await Td(),s=await hu.verify(e,r.public_key,{algorithms:Sd,subject:pd.REFRESH});t=await HS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Eu.warn(r),r.name&&r.name==="TokenExpiredError"?lr(new Error,dr.TOKEN_EXPIRED,_r.FORBIDDEN):lr(new Error,dr.INVALID_TOKEN,_r.UNAUTHORIZED)}if(!NL.validate(t.refresh_token,e))throw lr(new Error,dr.INVALID_TOKEN,_r.UNAUTHORIZED);return t}a(wL,"validateRefreshToken")});var xS=T((vfe,LL)=>{"use strict";var MX=RL(),_a=require("passport"),PX=require("passport-local").Strategy,vX=require("passport-http").BasicStrategy,BX=require("util"),HX=ts(),DL=BX.callbackify(HX.findAndValidateUser),Pfe=Or(),xX=L(),CL=mu();_a.use(new PX(function(e,t,r){DL(e,t,r)}));_a.use(new vX(function(e,t,r){DL(e,t,r)}));_a.serializeUser(function(e,t){t(null,e)});_a.deserializeUser(function(e,t){t(null,e)});function qX(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===xX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?CL.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):CL.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(qX,"authorize");function FX(e,t){let r=MX(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(FX,"checkPermissions");LL.exports={authorize:qX,checkPermissions:FX}});var di=T((Hfe,UL)=>{"use strict";var qS=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},FS=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};UL.exports={Node:qS,NodeSubscription:FS}});var PL=T((qfe,ML)=>{"use strict";var GX=L().OPERATIONS_ENUM,GS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=GX.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};ML.exports=GS});var pu=T((Gfe,vL)=>{"use strict";var kS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},VS=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)}};vL.exports={RemotePayloadObject:kS,RemotePayloadSubscription:VS}});var HL=T((Vfe,BL)=>{"use strict";var $S=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}};BL.exports=$S});var FL=T((Qfe,qL)=>{"use strict";var kX=HL(),Yfe=dt(),xL=We(),VX=V(),{getSchemaPath:Kfe,getTransactionAuditStorePath:Wfe}=Je(),{getDatabases:$X}=(Ae(),se(Fe));qL.exports=YX;async function YX(e){let t=new kX;try{let r=$X()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await xL.environmentDataSize(schema_path,e.name),o=await xL.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){VX.warn(`unable to stat table dbi due to ${r}`)}return t}a(YX,"lmdbGetTableSize")});var kL=T((Jfe,GL)=>{"use strict";var YS=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}};GL.exports=YS});var da=T((eEe,KL)=>{"use strict";var KX=require("fs-extra"),WX=require("path"),Qt=require("systeminformation"),fi=V(),QX=st(),KS=Ge(),Rd=L(),zX=FL(),YL=Xn(),{getThreadInfo:VL}=Ke(),rT=Z();rT.initSync();var JX=kL(),{openEnvironment:Xfe}=We(),{getSchemaPath:Zfe}=Je(),{database:jX}=(Ae(),se(Fe)),gd;KL.exports={getHDBProcessInfo:JS,getNetworkInfo:XS,getDiskInfo:jS,getMemoryInfo:zS,getCPUInfo:QS,getTimeInfo:WS,getSystemInformation:ZS,systemInformation:XX,getTableSize:eT,getMetrics:tT};function WS(){return Qt.time()}a(WS,"getTimeInfo");async function QS(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Qt.cpu();l.cpu_speed=await Qt.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 Qt.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(QS,"getCPUInfo");async function zS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Qt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return fi.error(`error in getMemoryInfo: ${e}`),{}}}a(zS,"getMemoryInfo");async function JS(){let e={core:[],clustering:[]};try{let t=await Qt.processes(),r;try{r=Number.parseInt(await KX.readFile(WX.join(rT.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 jS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Qt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Qt.fsStats();return e.read_write=_,e.size=await Qt.fsSize(),e}catch(t){return fi.error(`error in getDiskInfo: ${t}`),e}}a(jS,"getDiskInfo");async function XS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Qt.networkInterfaceDefault(),e.latency=await Qt.inetChecksite("google.com"),(await Qt.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 Qt.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(XS,"getNetworkInfo");async function ZS(){if(gd!==void 0)return gd;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Qt.osInfo();e=c;let u=await Qt.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(ZS,"getSystemInformation");async function eT(){let e=[],t=await YL.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await zX(s));return e}a(eT,"getTableSize");async function tT(){let e=await YL.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=jX({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(tT,"getMetrics");async function $L(){if(rT.get(Rd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await QX.getNATSReferences(),r=await t.streams.info(KS.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(KS.WORK_QUEUE_CONSUMER_NAMES.stream_name,KS.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($L,"getNatsStreamInfo");async function XX(e){let t=new JX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await ZS(),t.time=WS(),t.cpu=await QS(),t.memory=await zS(),t.disk=await jS(),t.network=await XS(),t.harperdb_processes=await JS(),t.table_size=await eT(),t.metrics=await tT(),t.threads=await VL(),t.replication=await $L(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await ZS();break;case"time":t.time=WS();break;case"cpu":t.cpu=await QS();break;case"memory":t.memory=await zS();break;case"disk":t.disk=await jS();break;case"network":t.network=await XS();break;case"harperdb_processes":t.harperdb_processes=await JS();break;case"table_size":t.table_size=await eT();break;case"database_metrics":case"metrics":t.metrics=await tT();break;case"threads":t.threads=await VL();break;case"replication":t.replication=await $L();break;default:break}return t}a(XX,"systemInformation")});var Od=T((rEe,WL)=>{"use strict";WL.exports={version:ZX,printVersion:eZ};var Ad=Zc();function ZX(){if(Ad)return Ad.version}a(ZX,"version");function eZ(){Ad&&console.log(`HarperDB Version ${Ad.version}`)}a(eZ,"printVersion")});var is=T((oEe,jL)=>{"use strict";var tZ=wr(),sT=J(),rZ=require("util"),co=L(),QL=Z();QL.initSync();var sZ=xS(),zL=es(),{Node:nEe,NodeSubscription:iEe}=di(),nZ=ta(),iZ=PL(),{RemotePayloadObject:oZ,RemotePayloadSubscription:aZ}=pu(),{handleHDBError:cZ,hdb_errors:uZ}=re(),{HTTP_STATUS_CODES:lZ,HDB_ERROR_MSGS:_Z}=uZ,dZ=Js(),fZ=da(),EZ=Od(),{getDatabases:hZ}=(Ae(),se(Fe)),mZ=rZ.promisify(sZ.authorize),pZ=zL.searchByHash,SZ=zL.searchByValue;jL.exports={authHeaderToUser:TZ,isEmpty:gZ,getNodeRecord:RZ,upsertNodeRecord:AZ,buildNodePayloads:OZ,checkClusteringEnabled:bZ,getAllNodeRecords:NZ,getSystemInfo:yZ,reverseSubscription:JL};async function TZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await mZ(t,null),e}a(TZ,"authHeaderToUser");function gZ(e){return e==null}a(gZ,"isEmpty");async function RZ(e){let t=new nZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return pZ(t)}a(RZ,"getNodeRecord");async function AZ(e){let t=new iZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return tZ.upsert(t)}a(AZ,"upsertNodeRecord");function JL(e){if(sT.isEmpty(e.subscribe)||sT.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(JL,"reverseSubscription");function OZ(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=sT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=JL(c),E=hZ()[u]?.[_],h=new aZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new oZ(r,t,n,s)}a(OZ,"buildNodePayloads");function bZ(){if(!QL.get(co.CONFIG_PARAMS.CLUSTERING_ENABLED))throw cZ(new Error,_Z.CLUSTERING_NOT_ENABLED,lZ.BAD_REQUEST,void 0,void 0,!0)}a(bZ,"checkClusteringEnabled");async function NZ(){let e=new dZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await SZ(e))}a(NZ,"getAllNodeRecords");async function yZ(){let e=await fZ.getSystemInformation();return{hdb_version:EZ.version(),node_version:e.node_version,platform:e.platform}}a(yZ,"getSystemInfo")});var nT=T((cEe,iU)=>{"use strict";var bd=st(),XL=J(),ZL=Ge(),eU=L(),Nd=V(),tU=lu(),wZ=$_(),{RemotePayloadObject:IZ}=pu(),{handleHDBError:rU,hdb_errors:CZ}=re(),{HTTP_STATUS_CODES:sU}=CZ,{NodeSubscription:nU}=di();iU.exports=DZ;async function DZ(e,t){let r;try{r=await bd.request(`${t}.${ZL.REQUEST_SUFFIX}`,new IZ(eU.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 rU(new Error,c,sU.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===ZL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw rU(new Error,o,sU.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===eU.SYSTEM_SCHEMA_NAME){await bd.createLocalTableStream(u,c);let h=new nU(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=XL.doesSchemaExist(u),l=s[u]!==void 0,d=c?XL.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 tU.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 wZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await tU.createTable(h)}await bd.createLocalTableStream(u,c);let E=new nU(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(DZ,"reviewSubscriptions")});var Id=T((lEe,cU)=>{"use strict";var{handleHDBError:yd,hdb_errors:LZ}=re(),{HTTP_STATUS_CODES:wd}=LZ,{addUpdateNodeValidator:UZ}=hd(),Su=V(),aU=L(),oU=Ge(),MZ=J(),iT=st(),Tu=is(),PZ=Z(),vZ=nT(),{Node:BZ,NodeSubscription:HZ}=di(),{broadcast:xZ}=Ke(),qZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",FZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",GZ=PZ.get(aU.CONFIG_PARAMS.CLUSTERING_NODENAME);cU.exports=kZ;async function kZ(e,t=!1){Su.trace("addNode called with:",e),Tu.checkClusteringEnabled();let r=UZ(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(!MZ.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 vZ(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=qZ,o;let c=Tu.buildNodePayloads(n,GZ,aU.OPERATIONS_ENUM.ADD_NODE,await Tu.getSystemInfo());Su.trace("addNode sending remote payload:",c);let u;try{u=await iT.request(`${s}.${oU.REQUEST_SUFFIX}`,c)}catch(d){Su.error(`addNode received error from request: ${d}`);let f=iT.requestErrorHandler(d,"add_node",s);throw yd(new Error,f,wd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===oU.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 iT.updateWorkStream(E,s),n[d].start_time===void 0&&delete n[d].start_time,_.push(new HZ(E.schema,E.table,E.publish,E.subscribe))}let l=new BZ(s,_,u.system_info);return await Tu.upsertNodeRecord(l),xZ({type:"nats_update"}),i.length>0?o.message=FZ:o.message=`Successfully added '${s}' to manifest`,o}a(kZ,"addNode")});var uT=T((fEe,_U)=>{"use strict";var{handleHDBError:oT,hdb_errors:VZ}=re(),{HTTP_STATUS_CODES:aT}=VZ,{addUpdateNodeValidator:$Z}=hd(),gu=V(),lU=L(),uU=Ge(),dEe=J(),cT=st(),Ru=is(),YZ=Z(),{cloneDeep:KZ}=require("lodash"),WZ=nT(),{Node:QZ,NodeSubscription:zZ}=di(),{broadcast:JZ}=Ke(),jZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",XZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",ZZ=YZ.get(lU.CONFIG_PARAMS.CLUSTERING_NODENAME);_U.exports=e5;async function e5(e){gu.trace("updateNode called with:",e),Ru.checkClusteringEnabled();let t=$Z(e);if(t)throw oT(t,t.message,aT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await Ru.getNodeRecord(r);n.length>0&&(s=KZ(n));let{added:i,skipped:o}=await WZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=jZ,c;let u=Ru.buildNodePayloads(i,ZZ,lU.OPERATIONS_ENUM.UPDATE_NODE,await Ru.getSystemInfo());gu.trace("updateNode sending remote payload:",u);let _;try{_=await cT.request(`${r}.${uU.REQUEST_SUFFIX}`,u)}catch(l){gu.error(`updateNode received error from request: ${l}`);let d=cT.requestErrorHandler(l,"update_node",r);throw oT(new Error,d,aT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===uU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw oT(new Error,l,aT.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 cT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return s||(s=[new QZ(r,[],_.system_info)]),await t5(s[0],i,_.system_info),o.length>0?c.message=XZ:c.message=`Successfully updated '${r}'`,c}a(e5,"updateNode");async function t5(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 zZ(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Ru.upsertNodeRecord(s),JZ({type:"nats_update"})}a(t5,"updateNodeTable")});var mU=T((hEe,hU)=>{"use strict";var EU=require("joi"),{string:dU}=EU.types(),r5=je(),fU=L(),s5=Z(),n5=Ge();hU.exports=i5;function i5(e){let t=dU.invalid(s5.get(fU.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(n5.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=EU.object({operation:dU.valid(fU.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return r5.validateBySchema(e,r)}a(i5,"removeNodeValidator")});var Dd=T((pEe,AU)=>{"use strict";var{handleHDBError:pU,hdb_errors:o5}=re(),{HTTP_STATUS_CODES:SU}=o5,a5=mU(),Au=V(),TU=is(),c5=J(),Cd=L(),gU=Ge(),RU=st(),u5=Z(),{RemotePayloadObject:l5}=pu(),{NodeSubscription:_5}=di(),d5=ra(),f5=ti(),{broadcast:E5}=Ke(),h5=u5.get(Cd.CONFIG_PARAMS.CLUSTERING_NODENAME);AU.exports=m5;async function m5(e){Au.trace("removeNode called with:",e),TU.checkClusteringEnabled();let t=a5(e);if(t)throw pU(t,t.message,SU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await TU.getNodeRecord(r);if(c5.isEmptyOrZeroLength(s))throw pU(new Error,`Node '${r}' was not found.`,SU.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new l5(Cd.OPERATIONS_ENUM.REMOVE_NODE,h5,[]),i,o=!1;try{i=await RU.request(`${r}.${gU.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 _5(l.schema,l.table,!1,!1);await RU.updateWorkStream(d,r)}let c=new d5(Cd.SYSTEM_SCHEMA_NAME,Cd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await f5.deleteRecord(c),E5({type:"nats_update"}),i?.status===gU.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(m5,"removeNode")});var NU=T((TEe,bU)=>{"use strict";var OU=require("joi"),{string:p5,array:S5}=OU.types(),T5=je(),g5=hd();bU.exports=R5;function R5(e){let t=OU.object({operation:p5.valid("configure_cluster").required(),connections:S5.items(g5.validation_schema).required()});return T5.validateBySchema(e,t)}a(R5,"configureClusterValidator")});var lT=T((REe,DU)=>{"use strict";var A5=L(),Ld=V(),O5=J(),b5=Dd(),N5=Id(),yU=is(),y5=NU(),{handleHDBError:wU,hdb_errors:w5}=re(),{HTTP_STATUS_CODES:IU}=w5,I5="Configure cluster complete.",C5="Failed to configure the cluster. Check the logs for more details.",D5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";DU.exports=L5;async function L5(e){Ld.trace("configure cluster called with:",e),yU.checkClusteringEnabled();let t=y5(e);if(t)throw wU(t,t.message,IU.BAD_REQUEST,void 0,void 0,!0);let r=await yU.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(CU(b5,{operation:A5.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(CU(N5,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(O5.isEmptyOrZeroLength(u))return{message:I5,connections:_};if(l)return{message:D5,failed_nodes:u,connections:_};throw wU(new Error,C5,IU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(L5,"configureCluster");async function CU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(CU,"functionWrapper")});var UU=T((OEe,LU)=>{"use strict";var Ud=require("joi"),U5=je(),{validateSchemaExists:M5,validateTableExists:P5,validateSchemaName:v5}=Ys(),B5=Ud.object({operation:Ud.string().valid("purge_stream"),schema:Ud.string().custom(M5).custom(v5).required(),table:Ud.string().custom(P5).required()});function H5(e){return U5.validateBySchema(e,B5)}a(H5,"purgeStreamValidator");LU.exports=H5});var _T=T((NEe,MU)=>{"use strict";var{handleHDBError:x5,hdb_errors:q5}=re(),{HTTP_STATUS_CODES:F5}=q5,G5=UU(),k5=st(),V5=is();MU.exports=$5;async function $5(e){if(e.purge_ingest!==!0){let n=G5(e);if(n)throw x5(n,n.message,F5.BAD_REQUEST,void 0,void 0,!0)}V5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await k5.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a($5,"purgeStream")});var ET=T((wEe,qU)=>{"use strict";var fT=is(),Y5=st(),BU=Z(),Md=L(),uo=Ge(),K5=J(),dT=V(),{RemotePayloadObject:W5}=pu(),{ErrorCode:PU}=require("nats"),vU=BU.get(Md.CONFIG_PARAMS.CLUSTERING_ENABLED),HU=BU.get(Md.CONFIG_PARAMS.CLUSTERING_NODENAME);qU.exports={clusterStatus:Q5,buildNodeStatus:xU};async function Q5(){let e={node_name:HU,is_enabled:vU,connections:[]};if(!vU)return e;let t=await fT.getAllNodeRecords();if(K5.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(xU(t[s],e.connections));return await Promise.allSettled(r),e}a(Q5,"clusterStatus");async function xU(e,t){let r=e.name,s=new W5(Md.OPERATIONS_ENUM.CLUSTER_STATUS,HU,void 0,await fT.getSystemInfo()),n,i,o=uo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await Y5.request(uo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===uo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=uo.CLUSTER_STATUS_STATUSES.CLOSED,dT.error(`Error getting node status from ${r} `,n))}catch(u){dT.warn(`Error getting node status from ${r}`,u),u.code===PU.NoResponders?o=uo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===PU.Timeout?o=uo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=uo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new z5(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 fT.upsertNodeRecord(u)}catch(u){dT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(xU,"buildNodeStatus");function z5(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(z5,"NodeStatusObject")});var mT=T((CEe,FU)=>{"use strict";var{handleHDBError:J5,hdb_errors:j5}=re(),{HTTP_STATUS_CODES:X5}=j5,Z5=st(),e8=is(),hT=J(),Pd=require("joi"),t8=je(),r8=2e3,s8=Pd.object({timeout:Pd.number().min(1),connected_nodes:Pd.boolean(),routes:Pd.boolean()});FU.exports=n8;async function n8(e){e8.checkClusteringEnabled();let t=t8.validateBySchema(e,s8);if(t)throw J5(t,t.message,X5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||hT.autoCastBoolean(s),o=n===void 0||hT.autoCastBoolean(n),c={nodes:[]},u=await Z5.getServerList(r??r8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:hT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(n8,"clusterNetwork")});var $U=T((LEe,VU)=>{"use strict";var pT=require("joi"),GU=je(),{route_constraints:kU}=xm();VU.exports={setRoutesValidator:i8,deleteRoutesValidator:o8};function i8(e){let t=pT.object({server:pT.valid("hub","leaf").required(),routes:kU.required()});return GU.validateBySchema(e,t)}a(i8,"setRoutesValidator");function o8(e){let t=pT.object({routes:kU.required()});return GU.validateBySchema(e,t)}a(o8,"deleteRoutesValidator")});var TT=T((MEe,QU)=>{"use strict";var lo=Lr(),ST=J(),vd=L(),YU=$U(),{handleHDBError:KU,hdb_errors:a8}=re(),{HTTP_STATUS_CODES:WU}=a8,c8="cluster routes successfully set",u8="cluster routes successfully deleted";QU.exports={setRoutes:l8,getRoutes:_8,deleteRoutes:d8};function l8(e){let t=YU.setRoutesValidator(e);if(t)throw KU(t,t.message,WU.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=ST.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:c8,set:o,skipped:i}}a(l8,"setRoutes");function _8(){let e=lo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(_8,"getRoutes");function d8(e){let t=YU.deleteRoutesValidator(e);if(t)throw KU(t,t.message,WU.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=ST.isEmptyOrZeroLength(s)?null:s,lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=ST.isEmptyOrZeroLength(n)?null:n,lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:u8,deleted:i,skipped:o}}a(d8,"deleteRoutes")});var JU=T((vEe,zU)=>{"use strict";var Ou=require("alasql"),_o=require("recursive-iterator"),Ms=V(),f8=J(),bu=L(),gT=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,h8(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=E8(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 E8(e){return e.filter(t=>t[bu.PERMS_CRUD_ENUM.READ])}a(E8,"filterReadRestrictedAttrs");function h8(e,t,r,s,n){m8(e,t,r,s,n)}a(h8,"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 m8(e,t,r,s,n){if(!e){Ms.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Ou.yy.Insert?g8(e,t,r):e instanceof Ou.yy.Select?p8(e,t,r,s,n):e instanceof Ou.yy.Update?S8(e,t,r):e instanceof Ou.yy.Delete?T8(e,t,r):Ms.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(m8,"getRecordAttributesAST");function p8(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(f8.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(p8,"getSelectAttributes");function S8(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&&RT(e.table.tableid,n,i.columnid,t,r)}a(S8,"getUpdateAttributes");function T8(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&&RT(e.table.tableid,n,i.columnid,t,r)}a(T8,"getDeleteAttributes");function g8(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&&RT(e.into.tableid,n,i.columnid,t,r)}a(g8,"getInsertAttributes");function RT(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(RT,"pushAttribute");zU.exports=gT});var bT=T((HEe,eM)=>{var Bd=Wi(),jU=require("chalk"),xr=V(),XU=require("prompt"),{promisify:R8}=require("util"),AT=L(),A8=require("fs-extra"),O8=require("path"),b8=J(),N8=Od(),ZU=Z();ZU.initSync();var y8=require("moment"),w8=R8(XU.get),I8=O8.join(ZU.getHdbBasePath(),AT.LICENSE_KEY_DIR_NAME,AT.LICENSE_FILE_NAME,AT.LICENSE_FILE_NAME);eM.exports={getFingerprint:D8,setLicense:C8,parseLicense:OT,register:L8,getRegistrationInfo:M8};async function C8(e){if(e&&e.key&&e.company){try{xr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await OT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw xr.error(r),xr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(C8,"setLicense");async function D8(){let e={};try{e=await Bd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw xr.error(r),xr.error(t),new Error(r)}return e}a(D8,"getFingerprint");async function OT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");xr.info("Validating license input...");let r=Bd.validateLicense(e,t);if(xr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(xr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(xr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{xr.info("writing license to disk"),await A8.writeFile(I8,JSON.stringify({license_key:e,company:t}))}catch(s){throw xr.error("Failed to write License"),s}return"Registration successful."}a(OT,"parseLicense");async function L8(){let e=await U8();return OT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(L8,"register");async function U8(){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{XU.start()}catch(s){xr.error(s)}let r;try{r=await w8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(U8,"promptForRegistration");async function M8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Bd.getLicense()}catch(r){throw xr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(b8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=N8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=y8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(M8,"getRegistrationInfo")});var rM=T((qEe,tM)=>{"use strict";var P8=Ge(),NT=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+P8.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"}};tM.exports=NT});var iM=T((GEe,nM)=>{"use strict";var sM=Ge(),yT=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+sM.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+sM.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"}};nM.exports=yT});var aM=T((VEe,oM)=>{"use strict";var wT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};oM.exports=wT});var uM=T((YEe,cM)=>{"use strict";var v8=Ge(),IT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+v8.SERVER_SUFFIX.ADMIN,this.password=r}};cM.exports=IT});var LT=T((WEe,dM)=>{"use strict";var fa=require("path"),qd=require("fs-extra"),B8=rM(),H8=iM(),x8=aM(),q8=uM(),CT=ts(),ha=J(),fr=Lr(),xd=L(),yu=Ge(),{CONFIG_PARAMS:_t}=xd,wu=V(),Iu=Z(),lM=Sn(),DT=st(),Ea="clustering",F8=1e4,_M=5;dM.exports={generateNatsConfig:k8,removeNatsConfig:V8,getHubConfigPath:G8};function G8(){let e=Iu.get(_t.ROOTPATH);return fa.join(e,Ea,yu.NATS_CONFIG_FILES.HUB_SERVER)}a(G8,"getHubConfigPath");async function k8(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=fr.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=fr.getConfigFromFile(_t.CLUSTERING_TLS_CERTIFICATE),_=fr.getConfigFromFile(_t.CLUSTERING_TLS_PRIVATEKEY),l=fr.getConfigFromFile(_t.CLUSTERING_TLS_CERT_AUTH),d=fr.getConfigFromFile(_t.CLUSTERING_TLS_INSECURE),f=fr.getConfigFromFile(_t.CLUSTERING_TLS_VERIFY),E=fr.getConfigFromFile(_t.CLUSTERING_NODENAME),h=fr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await DT.checkNATSServerInstalled()||Fd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await CT.listUsers(),S=fr.getConfigFromFile(_t.CLUSTERING_USER),A=await CT.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 q8(ne.username,lM.decrypt(ne.hash))),g.push(new x8(ne.username,lM.decrypt(ne.hash))));let P=[],{hub_routes:H}=fr.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 B8(fr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,fr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_CLUSTER_NAME),fr.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 H8(fr.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(k8,"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 V8(e){let{port:t,config_file:r}=DT.getServerConfig(e),{username:s,decrypt_hash:n}=await CT.getClusterUser(),i=0,o=2e3;for(;i<_M;){try{let _=await DT.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>=_M)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(F8),u=fa.join(Iu.get(_t.ROOTPATH),Ea,r);await qd.writeFile(u,c),await qd.remove(u),wu.notify(e,"started.")}a(V8,"removeNatsConfig")});var SM=T((zEe,pM)=>{"use strict";var qr=Z(),$8=Wi(),he=L(),Cu=Ge(),Nn=require("path"),{PACKAGE_ROOT:kd}=L(),fM=Z(),Gd=J(),ma="/dev/null",Y8=Nn.join(kd,"launchServiceScripts"),EM=Nn.join(kd,"utility/scripts"),K8=Nn.join(EM,he.HDB_RESTART_SCRIPT),hM=Nn.resolve(kd,"dependencies",`${process.platform}-${process.arch}`,Cu.NATS_BINARY_NAME);function mM(){let t=$8.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(mM,"generateMainServerConfig");var W8=9930;function Q8(){qr.initSync(!0);let e=qr.get(he.CONFIG_PARAMS.ROOTPATH),t=Nn.join(e,"clustering",Cu.NATS_CONFIG_FILES.HUB_SERVER),r=Nn.join(qr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=fM.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=Cu.LOG_LEVEL_FLAGS[qr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==W8?"-"+s:""),script:hM,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 qr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ma,i.error_file=ma),i}a(Q8,"generateNatsHubServerConfig");var z8=9940;function J8(){qr.initSync(!0);let e=qr.get(he.CONFIG_PARAMS.ROOTPATH),t=Nn.join(e,"clustering",Cu.NATS_CONFIG_FILES.LEAF_SERVER),r=Nn.join(qr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=fM.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=Cu.LOG_LEVEL_FLAGS[qr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==z8?"-"+s:""),script:hM,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 qr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ma,i.error_file=ma),i}a(J8,"generateNatsLeafServerConfig");function j8(){qr.initSync();let e=Nn.join(qr.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:Y8,autorestart:!1};return qr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ma,t.error_file=ma),t}a(j8,"generateClusteringUpgradeV4ServiceConfig");function X8(){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:EM},script:K8}}a(X8,"generateRestart");function Z8(){return{apps:[mM()]}}a(Z8,"generateAllServiceConfigs");pM.exports={generateAllServiceConfigs:Z8,generateMainServerConfig:mM,generateRestart:X8,generateNatsHubServerConfig:Q8,generateNatsLeafServerConfig:J8,generateClusteringUpgradeV4ServiceConfig:j8}});var UM=T((XEe,LM)=>{"use strict";var Pe=L(),e6=J(),yn=LT(),Du=st(),en=Ge(),Ei=SM(),Vd=Z(),hi=V(),t6=is(),{startWorker:TM,onMessageFromWorkers:r6}=Ke(),s6=da(),jEe=require("util"),n6=require("child_process"),i6=require("fs"),{execFile:o6}=n6,ye;LM.exports={enterPM2Mode:a6,start:mi,stop:UT,reload:RM,restart:AM,list:MT,describe:bM,connect:wn,kill:d6,startAllServices:f6,startService:PT,getUniqueServicesList:NM,restartAllServices:E6,isServiceRegistered:yM,reloadStopStart:wM,restartHdb:OM,deleteProcess:l6,startClusteringProcesses:CM,startClusteringThreads:DM,isHdbRestartRunning:_6,isClusteringRunning:m6,stopClustering:h6,reloadClustering:p6};var Lu=!1;r6(e=>{e.type==="restart"&&Vd.initSync(!0)});function a6(){Lu=!0}a(a6,"enterPM2Mode");function wn(){return ye||(ye=require("pm2")),new Promise((e,t)=>{ye.connect((r,s)=>{hi.setupConsoleLogging(),r&&t(r),e(s)})})}a(wn,"connect");var Er,c6=10,gM;function mi(e,t=!1){if(Lu)return u6(e);let r=o6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Er.indexOf(r);o>-1&&Er.splice(o,1),!gM&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<c6&&(i6.existsSync(yn.getHubConfigPath())?mi(e):(await yn.generateNatsConfig(!0),mi(e),await new Promise(c=>setTimeout(c,3e3)),await yn.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await yn.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=Vd.get(Pe.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(),Er=[],!Er&&!t){let i=a(()=>{gM=!0,Er&&(Er.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)}Er.push(r)}a(mi,"start");function u6(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}ye.start(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(u6,"startWithPM2");function UT(e){if(!Lu){for(let t of Er||[])t.name===e&&(Er.splice(Er.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}ye.stop(e,async(s,n)=>{s&&(ye.disconnect(),r(s)),ye.delete(e,(i,o)=>{i&&(ye.disconnect(),r(s)),ye.disconnect(),t(o)})})})}a(UT,"stop");function RM(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}ye.reload(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(RM,"reload");function AM(e){if(!Lu)for(let t of Er||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}ye.restart(e,(s,n)=>{ye.disconnect(),t(n)})})}a(AM,"restart");function l6(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}ye.delete(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(l6,"deleteProcess");async function OM(){await mi(Ei.generateRestart())}a(OM,"restartHdb");async function _6(){let e=await MT();for(let t in e)if(e[t].name===Pe.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(_6,"isHdbRestartRunning");function MT(){return new Promise(async(e,t)=>{try{await wn()}catch(r){t(r)}ye.list((r,s)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(s)})})}a(MT,"list");function bM(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}ye.describe(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(bM,"describe");function d6(){if(!Lu){for(let e of Er||[])e.kill();Er=[];return}return new Promise(async(e,t)=>{try{await wn()}catch(r){t(r)}ye.killDaemon((r,s)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(s)})})}a(d6,"kill");async function f6(){try{await CM(),await DM(),await mi(Ei.generateAllServiceConfigs())}catch(e){throw ye?.disconnect(),e}}a(f6,"startAllServices");async function PT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Pe.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ei.generateMainServerConfig();break;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ei.generateNatsIngestServiceConfig();break;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ei.generateNatsReplyServiceConfig();break;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ei.generateNatsHubServerConfig(),await mi(r,t),await yn.removeNatsConfig(e);return;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ei.generateNatsLeafServerConfig(),await mi(r,t),await yn.removeNatsConfig(e);return;case Pe.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 ye?.disconnect(),r}}a(PT,"startService");async function NM(){try{let e=await MT(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw ye?.disconnect(),e}}a(NM,"getUniqueServicesList");async function E6(e=[]){try{let t=!1,r=await NM();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Pe.PROCESS_DESCRIPTORS.HDB?t=!0:await AM(o))}t&&await wM(Pe.PROCESS_DESCRIPTORS.HDB)}catch(t){throw ye?.disconnect(),t}}a(E6,"restartAllServices");async function yM(e){if(Er?.find(r=>r.name===e))return!0;let t=await s6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(yM,"isServiceRegistered");async function wM(e){let t=Vd.get(Pe.CONFIG_PARAMS.THREADS_COUNT)??Vd.get(Pe.CONFIG_PARAMS.THREADS),r=await bM(e),s=e6.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await UT(e),await PT(e)):e===Pe.PROCESS_DESCRIPTORS.HDB?await OM():await RM(e)}a(wM,"reloadStopStart");var IM;async function CM(e=!1){for(let t in Pe.CLUSTERING_PROCESSES){let r=Pe.CLUSTERING_PROCESSES[t];await PT(r,e)}}a(CM,"startClusteringProcesses");async function DM(){IM=TM(Pe.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Pe.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Du.createWorkQueueStream(en.WORK_QUEUE_CONSUMER_NAMES),await Du.updateIngestStreamConsumer(),await Du.updateLocalStreams();let e=await t6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Pe.PRE_4_0_0_VERSION){hi.info("Starting clustering upgrade 4.0.0 process"),TM(Pe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(DM,"startClusteringThreads");async function h6(){for(let e in Pe.CLUSTERING_PROCESSES)if(e!==Pe.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Pe.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await IM.terminate();else{let t=Pe.CLUSTERING_PROCESSES[e];await UT(t)}}a(h6,"stopClustering");async function m6(){for(let e in Pe.CLUSTERING_PROCESSES){let t=Pe.CLUSTERING_PROCESSES[e];if(await yM(t)===!1)return!1}return!0}a(m6,"isClusteringRunning");async function p6(){await yn.generateNatsConfig(!0),await Du.reloadNATSHub(),await Du.reloadNATSLeaf(),await yn.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await yn.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(p6,"reloadClustering")});var Wd=T((ehe,qM)=>{"use strict";var S6=require("minimist"),{isMainThread:HT,parentPort:vM}=require("worker_threads"),nt=L(),{PROCESS_DESCRIPTORS_VALIDATE:Uu}=nt,tn=V(),xT=J(),$d=LT(),pa=st(),vT=Ge(),BM=Lr(),rn=UM(),MM=da(),T6=_h(),{restartWorkers:Yd,onMessageByType:g6}=Ke(),{handleHDBError:R6,hdb_errors:A6}=re(),{HTTP_STATUS_CODES:O6}=A6,Kd=Z();Kd.initSync();var Mu=`Restarting HarperDB. This may take up to ${nt.RESTART_TIMEOUT_MS/1e3} seconds.`,b6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",PM="Clustering is not enabled so cannot be restarted",N6="Invalid service",Sa,os;qM.exports={restart:HM,restartService:qT};HT&&g6(nt.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?qT({service:e.workerType}):HM({operation:"restart"})});async function HM(e){os=Object.keys(e).length===0,Sa=await rn.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR);let t=S6(process.argv);if(t.service){await qT(t);return}if(os&&!Sa){console.error(b6);return}if(os&&console.log(Mu),Sa){rn.enterPM2Mode(),tn.notify(Mu);let r=T6(Object.keys(nt.CONFIG_PARAM_MAP),!0);return xT.isEmptyOrZeroLength(Object.keys(r))||BM.updateConfigValue(void 0,void 0,r,!0,!0),w6(),Mu}return HT?(tn.notify(Mu),setTimeout(()=>{Yd()},50)):vM.postMessage({type:nt.ITC_EVENT_TYPES.RESTART}),Mu}a(HM,"restart");async function qT(e){let{service:t}=e;if(nt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw R6(new Error,N6,O6.BAD_REQUEST,void 0,void 0,!0);if(Sa=await rn.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR),!HT)return vM.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=PM;break}os&&console.log("Restarting clustering"),tn.notify("Restarting clustering"),await xM();break;case Uu.clustering_config:case Uu["clustering config"]:if(!Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=PM;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(qT,"restartService");async function y6(){await pa.publishToStream(`${vT.SUBJECT_PREFIXES.TXN}.${vT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,vT.WORK_QUEUE_CONSUMER_NAMES.stream_name,pa.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(y6,"postDummyNatsMsg");async function w6(){await xM(),await rn.restart(nt.HDB_PROC_DESCRIPTOR),await xT.async_set_timeout(2e3),Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await BT(),os&&(await pa.closeConnection(),process.exit(0))}a(w6,"restartPM2Mode");async function xM(){if(!BM.getConfigFromFile(nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await MM.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 BT(),os&&await pa.closeConnection();else{await y6(),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 MM.getHDBProcessInfo()).clustering.forEach(n=>{tn.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await xT.async_set_timeout(3e3),await BT(),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(xM,"restartClustering");async function BT(){await $d.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await $d.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(BT,"removeNatsConfig")});var JM=T((she,zM)=>{"use strict";var rhe=require("lodash"),hr=L(),{handleHDBError:FM,hdb_errors:I6}=re(),{HDB_ERROR_MSGS:C6,HTTP_STATUS_CODES:D6}=I6,FT=V();zM.exports={getRolePermissions:U6};var fo=Object.create(null),L6=a(e=>({key:e,perms:{}}),"perms_template_obj"),$M=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),YM=a((e=!1,t=!1,r=!1,s=!1)=>({[hr.PERMS_CRUD_ENUM.READ]:e,[hr.PERMS_CRUD_ENUM.INSERT]:t,[hr.PERMS_CRUD_ENUM.UPDATE]:r,[hr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),GT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...YM(t,r,s,n)}),"table_perms_template"),GM=a((e,t=YM())=>({attribute_name:e,describe:QM(t),[Pu]:t[Pu],[kT]:t[kT],[VT]:t[VT]}),"attr_perms_template"),kM=a((e,t=!1)=>({attribute_name:e,describe:t,[Pu]:t}),"timestamp_attr_perms_template"),{READ:Pu,INSERT:kT,UPDATE:VT}=hr.PERMS_CRUD_ENUM,KM=Object.values(hr.PERMS_CRUD_ENUM),WM=[Pu,kT,VT];function U6(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[hr.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=M6(e,r);return fo[t]?fo[t].key=s:fo[t]=L6(s),fo[t].perms=n,n}catch(r){if(!e[hr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[hr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<hr.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 FT.error(s),FT.debug(r),FM(new Error,C6.OUTDATED_PERMS_TRANSLATION_ERROR,D6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
-
${r.stack}`;throw FT.error(s),FM(new Error)}}}a(U6,"getRolePermissions");function M6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[hr.SYSTEM_SCHEMA_NAME]=s[hr.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]=P6(t[i]);return}r[i]=$M(),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],_=v6(c,u);r[i].describe||KM.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=GT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=GT()})}),r}a(M6,"translateRolePermissions");function P6(e){let t=$M(!0);return Object.keys(e).forEach(r=>{t.tables[r]=GT(!0,!0,!0,!0,!0)}),t}a(P6,"createStructureUserPermissions");function v6(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 hr.TIME_STAMP_NAMES.includes(d)&&(f=kM(d,l[Pu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=GM(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=QM(l),n.attribute_permissions.push(l),c||B6(l,u)}else if(_!==o){let l;hr.TIME_STAMP_NAMES.includes(_)?l=kM(_):l=GM(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=VM(n),n}else return e.describe=VM(e),e}a(v6,"getTableAttrPerms");function VM(e){return KM.filter(t=>e[t]).length>0}a(VM,"getSchemaTableDescribePerm");function QM(e){return WM.filter(t=>e[t]).length>0}a(QM,"getAttributeDescribePerm");function B6(e,t){WM.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(B6,"checkForHashPerms")});var jM={};Ye(jM,{Resources:()=>Qd,keyArrayToString:()=>Ta,resetResources:()=>H6,resources:()=>pi});function H6(){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(H6,"resetResources");a(Ta,"keyArrayToString")});var XM={};Ye(XM,{Headers:()=>Si,appendHeader:()=>$T});function $T(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($T,"appendHeader")});var Hu={};Ye(Hu,{authentication:()=>oP,bypassAuth:()=>$6,login:()=>K6,logout:()=>W6,start:()=>Y6});function $6(){iP=!0}async function oP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?G6?F6:[]:q6?x6:[];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 eP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new jd.AuthAuditLog(E,h,Ft.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===Ft.AUTH_AUDIT_STATUS.SUCCESS?ZM.notify(S):ZM.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 V6&&(Eo.get(h)||(Eo.set(h,h),l(p,Ft.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ti({error:A.message},e)})}Eo.set(s,d),k6&&l(d.username,Ft.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await tt.getUser(_.user,null,e):(iP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,rP.getSuperUser)());zd&&(e.session.update=function(E){if(!u){u=(0,sP.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,eP.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 Y6({server:e,port:t}){e.request(oP,{port:t||"all"}),tP||(tP=!0,setInterval(()=>{Eo=new Map},as.get(Ft.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),nP.user.addListener(()=>{Eo=new Map}))}async function K6(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 W6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var rP,Jd,sP,as,Ft,jd,nP,ZM,x6,q6,F6,G6,eP,zd,iP,k6,V6,Eo,tP,Xd=Re(()=>{rP=x(ts());tr();vu();Jd=x(mu());Ae();sP=require("uuid"),as=x(Z()),Ft=x(L()),jd=x(V()),nP=x(Hc());Bu();ga();ZM=(0,jd.loggerWithTag)("auth-event");as.initSync();x6=as.get(Ft.CONFIG_PARAMS.HTTP_CORSACCESSLIST),q6=as.get(Ft.CONFIG_PARAMS.HTTP_CORS),F6=as.get(Ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),G6=as.get(Ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),eP=ct({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),zd=as.get(Ft.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,iP=as.get(Ft.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,k6=as.get(Ft.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,V6=as.get(Ft.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Eo=new Map;tt.onInvalidatedUser(()=>{Eo=new Map});a($6,"bypassAuth");a(oP,"authentication");a(Y6,"start");a(K6,"login");a(W6,"logout")});var fP=T((Ehe,dP)=>{"use strict";var we=require("joi"),aP=require("fs-extra"),cP=require("path"),Cn=je(),uP=Z(),lP=L(),_P=V(),{hdb_errors:Q6}=re(),{HDB_ERROR_MSGS:zt}=Q6,In=/^[a-zA-Z0-9-_]+$/;dP.exports={getDropCustomFunctionValidator:J6,setCustomFunctionValidator:j6,addComponentValidator:t9,dropCustomFunctionProjectValidator:r9,packageComponentValidator:s9,deployComponentValidator:n9,setComponentFileValidator:X6,getComponentFileValidator:e9,dropComponentFileValidator:Z6};function Zd(e,t,r){try{let s=uP.get(lP.CONFIG_PARAMS.COMPONENTSROOT),n=cP.join(s,t);return aP.existsSync(n)?e?t:r.message(zt.PROJECT_EXISTS):e?r.message(zt.NO_PROJECT):t}catch(s){return _P.error(s),r.message(zt.VALIDATION_ERR)}}a(Zd,"checkProjectExists");function xu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(xu,"checkFilePath");function z6(e,t,r,s){try{let n=uP.get(lP.CONFIG_PARAMS.COMPONENTSROOT),i=cP.join(n,e,t,r+".js");return aP.existsSync(i)?r:s.message(zt.NO_FILE)}catch(n){return _P.error(n),s.message(zt.VALIDATION_ERR)}}a(z6,"checkFileExists");function J6(e){let t=we.object({project:we.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().pattern(In).custom(z6.bind(null,e.project,e.type)).custom(xu).required().messages({"string.pattern.base":zt.BAD_FILE_NAME})});return Cn.validateBySchema(e,t)}a(J6,"getDropCustomFunctionValidator");function j6(e){let t=we.object({project:we.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().custom(xu).required(),function_content:we.string().required()});return Cn.validateBySchema(e,t)}a(j6,"setCustomFunctionValidator");function X6(e){let t=we.object({project:we.string().pattern(In).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME}),file:we.string().custom(xu).required(),payload:we.string().allow("").optional(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(X6,"setComponentFileValidator");function Z6(e){let t=we.object({project:we.string().pattern(In).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME}),file:we.string().custom(xu).optional()});return Cn.validateBySchema(e,t)}a(Z6,"dropComponentFileValidator");function e9(e){let t=we.object({project:we.string().required(),file:we.string().custom(xu).required(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(e9,"getComponentFileValidator");function t9(e){let t=we.object({project:we.string().pattern(In).custom(Zd.bind(null,!1)).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(t9,"addComponentValidator");function r9(e){let t=we.object({project:we.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(r9,"dropCustomFunctionProjectValidator");function s9(e){let t=we.object({project:we.string().pattern(In).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME}),skip_node_modules:we.boolean()});return Cn.validateBySchema(e,t)}a(s9,"packageComponentValidator");function n9(e){let t=we.object({project:we.string().pattern(In).required().messages({"string.pattern.base":zt.BAD_PROJECT_NAME}),payload:we.string().optional().messages({"string.pattern.base":zt.BAD_PACKAGE}),package:we.string().optional()});return Cn.validateBySchema(e,t)}a(n9,"deployComponentValidator")});var sf=T((mhe,gP)=>{"use strict";var ef=require("joi"),tf=require("path"),EP=require("fs-extra"),{exec:i9}=require("child_process"),o9=require("util"),hP=o9.promisify(i9),qu=L(),{handleHDBError:Ra,hdb_errors:a9}=re(),{HTTP_STATUS_CODES:Aa}=a9,Fu=Z(),c9=je(),Oa=V();Fu.initSync();var YT=Fu.get(qu.CONFIG_PARAMS.COMPONENTSROOT),mP="npm install --omit=dev --json",u9=`${mP} --dry-run`;gP.exports={installModules:f9,auditModules:E9,installAllRootModules:l9,uninstallRootModule:_9,linkHarperdb:d9};async function l9(e=!1){await rf(),await Gu(e?"npm install --ignore-scripts":"npm install",Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(l9,"installAllRootModules");async function _9(e){await Gu(`npm uninstall ${e}`,Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(_9,"uninstallRootModule");async function d9(){await rf(),await Gu(`npm link ${qu.PACKAGE_ROOT}`,Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(d9,"linkHarperdb");async function Gu(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await hP(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(pP,"parseNPMStdErr");async function E9(e){Oa.info(`starting auditModules for request: ${e}`);let t=TP(e);if(t)throw Ra(t,t.message,Aa.BAD_REQUEST);let{projects:r}=e;await rf(),await SP(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=tf.join(YT,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=pP(u.stderr)}}return Oa.info(`finished auditModules with response ${s}`),s}a(E9,"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 SP(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(YT,i.toString());if(!await EP.pathExists(o)){t.push(i);continue}let u=tf.join(o,"package.json");await EP.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(SP,"checkProjectPaths");function TP(e){let t=ef.object({projects:ef.array().min(1).items(ef.string()).required(),dry_run:ef.boolean().default(!1)});return c9.validateBySchema(e,t)}a(TP,"modulesValidator")});var WT=T((She,NP)=>{"use strict";var ba=require("fs-extra"),KT=require("path"),nf=V(),RP=J(),of=L(),bP=Z(),h9=Lr();NP.exports=m9;async function m9(){let e=p9(),t=bP.get(of.CONFIG_PARAMS.ROOTPATH),r=KT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+of.PACKAGE_ROOT}},n=KT.join(t,"node_modules");await ba.ensureDir(n);let i,o=!0,c=!1;try{i=await ba.readJson(r)}catch(u){if(RP.isEmptyOrZeroLength(e))return;if(u.code!==of.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!RP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await AP(_);s.dependencies[u]=l+_}if(!o){nf.notify("Installing components"),await OP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await AP(_);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 OP(r,s,i))}a(m9,"installComponents");function p9(){let e=h9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(p9,"getComponentsConfig");async function AP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":KT.extname(e)||await ba.pathExists(e)?"file:":"github:"}a(AP,"getPkgPrefix");async function OP(e,t,r){nf.trace("npm installing components package.json",t),await ba.writeFile(e,JSON.stringify(t,null," "));try{await sf().installAllRootModules(bP.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(OP,"installPackages")});var JT=T((Rhe,CP)=>{"use strict";var ke=require("fs-extra"),QT=require("fast-glob"),Se=require("path"),wP=require("tar-fs"),ghe=require("uuid").v4,zT=require("normalize-path"),sn=fP(),Ot=V(),Qe=L(),mt=Z(),ku=Lr(),S9=J(),{PACKAGE_ROOT:T9}=L(),{handleHDBError:Ut,hdb_errors:g9}=re(),{basename:R9}=require("path"),A9=WT(),IP=Z(),O9=L(),{Readable:b9}=require("stream"),{isMainThread:N9}=require("worker_threads"),{HDB_ERROR_MSGS:ho,HTTP_STATUS_CODES:Mt}=g9,y9=Se.join(T9,"application-template"),yP=Se.join(mt.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function w9(){Ot.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 Ut(new Error,ho.FUNCTION_STATUS,Mt.INTERNAL_SERVER_ERROR,Ot.ERR,t)}return e}a(w9,"customFunctionsStatus");function I9(){Ot.trace("getting custom api endpoints");let e={},t=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{QT.sync(zT(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:QT.sync(zT(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:QT.sync(zT(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Ut(new Error,ho.GET_FUNCTIONS,Mt.INTERNAL_SERVER_ERROR,Ot.ERR,r)}return e}a(I9,"getCustomFunctions");function C9(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 Ut(t,t.message,Mt.BAD_REQUEST);Ot.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 Ut(new Error,ho.GET_FUNCTION,Mt.INTERNAL_SERVER_ERROR,Ot.ERR,c)}}a(C9,"getCustomFunction");function D9(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 Ut(t,t.message,Mt.BAD_REQUEST);Ot.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 Ut(new Error,ho.SET_FUNCTION,Mt.INTERNAL_SERVER_ERROR,Ot.ERR,c)}}a(D9,"setCustomFunction");function L9(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 Ut(t,t.message,Mt.BAD_REQUEST);Ot.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 Ut(new Error,ho.DROP_FUNCTION,Mt.INTERNAL_SERVER_ERROR,Ot.ERR,o)}}a(L9,"dropCustomFunction");function U9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.addComponentValidator(e);if(t)throw Ut(t,t.message,Mt.BAD_REQUEST);Ot.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(y9,n),`Successfully added project: ${s}`}catch(n){throw Ut(new Error,ho.ADD_FUNCTION,Mt.INTERNAL_SERVER_ERROR,Ot.ERR,n)}}a(U9,"addComponent");function M9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.dropCustomFunctionProjectValidator(e);if(t)throw Ut(t,t.message,Mt.BAD_REQUEST);Ot.trace("dropping custom function project");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=mt.get(Qe.CONFIG_PARAMS.APPS);if(!S9.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 Ut(new Error,ho.DROP_FUNCTION_PROJECT,Mt.INTERNAL_SERVER_ERROR,Ot.ERR,i)}}a(M9,"dropCustomFunctionProject");async function P9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.packageComponentValidator(e);if(t)throw Ut(t,t.message,Mt.BAD_REQUEST);let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;Ot.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(yP);let i=Se.join(yP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Se.join(n,"node_modules"))}),wP.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(P9,"packageComponent");async function v9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.deployComponentValidator(e);if(t)throw Ut(t,t.message,Mt.BAD_REQUEST);let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(Ot.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=b9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(wP.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 A9();let f=IP.get(O9.CONFIG_PARAMS.ROOTPATH);o=Se.join(f,"node_modules",s)}if(N9)return;let c=new Map;c.isWorker=!0;let u=(cf(),se(af)),_;u.setErrorReporter(f=>_=f);let l=R9(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Ot.info("Installed component"),`Successfully deployed: ${s}`}a(v9,"deployComponent");async function B9(){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 Ot.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(B9,"getComponents");async function H9(e){let t=sn.getComponentFileValidator(e);if(t)throw Ut(t,t.message,Mt.BAD_REQUEST);let s=ku.getConfigObj()[e.project]||e.project==="harperdb"?Se.join(IP.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(H9,"getComponentFile");async function x9(e){let t=sn.setComponentFileValidator(e);if(t)throw Ut(t,t.message,Mt.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(x9,"setComponentFile");async function q9(e){let t=sn.dropComponentFileValidator(e);if(t)throw Ut(t,t.message,Mt.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(q9,"dropComponent");CP.exports={customFunctionsStatus:w9,getCustomFunctions:I9,getCustomFunction:C9,setCustomFunction:D9,dropCustomFunction:L9,addComponent:U9,dropCustomFunctionProject:M9,packageComponent:P9,deployComponent:v9,getComponents:B9,getComponentFile:H9,setComponentFile:x9,dropComponent:q9}});var jT=T((Ohe,LP)=>{"use strict";var nn=require("joi"),DP=je();LP.exports={readTransactionLogValidator:F9,deleteTransactionLogsBeforeValidator:G9};function F9(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 DP.validateBySchema(e,t)}a(F9,"readTransactionLogValidator");function G9(e){let t=nn.object({schema:nn.string().required(),table:nn.string().required(),timestamp:nn.date().timestamp().required()});return DP.validateBySchema(e,t)}a(G9,"deleteTransactionLogsBeforeValidator")});var lf=T((Nhe,BP)=>{"use strict";var XT=L(),uf=st(),UP=J(),MP=Z(),PP=Sn(),{handleHDBError:Na,hdb_errors:k9}=re(),{HTTP_STATUS_CODES:ya}=k9,{readTransactionLogValidator:V9,deleteTransactionLogsBeforeValidator:$9}=jT(),vP="This operation relies on clustering and cannot run with it disable.",Y9="Logs successfully deleted from transaction log.",K9="All logs successfully deleted from transaction log.";BP.exports={readTransactionLog:W9,deleteTransactionLogsBefore:Q9};async function*W9(e){let t=V9(e);if(t)throw Na(t,t.message,ya.BAD_REQUEST,void 0,void 0,!0);if(!MP.get(XT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Na(new Error,vP,ya.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=UP.checkSchemaTableExist(r,s);if(n)throw Na(new Error,n,ya.NOT_FOUND,void 0,void 0,!0);let i=PP.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===XT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(W9,"readTransactionLog");async function Q9(e){let t=$9(e);if(t)throw Na(t,t.message,ya.BAD_REQUEST,void 0,void 0,!0);if(!MP.get(XT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Na(new Error,vP,ya.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=UP.checkSchemaTableExist(r,s);if(i)throw Na(new Error,i,ya.NOT_FOUND,void 0,void 0,!0);let o=PP.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=Y9,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=K9):d=(await uf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(Q9,"deleteTransactionLogsBefore")});var xP=T((whe,HP)=>{"use strict";var ZT=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}};HP.exports=ZT});var FP=T((Che,qP)=>{"use strict";var eg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};qP.exports=eg});var rg=T((Lhe,kP)=>{"use strict";var GP=xP(),z9=FP(),{HDB_ERROR_MSGS:J9}=Or(),tg=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 GP(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new z9(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 GP(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}};kP.exports=tg});var Ef=T((Mhe,nv)=>{"use strict";var sg=wr(),_f=es(),us=lu(),Yu=Xn(),ng=ti(),j9=mS(),X9=ZD(),Ku=ts(),df=NS(),bt=V(),Z9=IS(),e7=Id(),t7=uT(),r7=Dd(),s7=lT(),n7=_T(),i7=ET(),o7=mT(),ig=TT(),Dn=J(),a7=JU(),og=bT(),YP=Wd(),cs=L(),KP=JM(),c7=da(),WP=mu(),QP=(Xd(),se(Hu)),zP=Lr(),Fr=JT(),u7=require("alasql"),JP=lf(),jP=sf(),XP=rg(),{handleHDBError:mr,hdb_errors:ZP}=re(),{HDB_ERROR_MSGS:Gt,HTTP_STATUS_CODES:Vu}=ZP,k=new Map,ev="delete",gi="insert",Ln="read",mo="update",$u="describe",VP=Yu.describeSchema.name,$P=Yu.describeTable.name,tv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},l7="catchup",_7="handleGetJob",d7="handleGetJobsByStartDate",ff={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},f7=[us.createTable.name,us.createAttribute.name,us.dropTable.name,us.dropAttribute.name],rv={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(sg.insert.name,new Q(!1,[gi]));k.set(sg.update.name,new Q(!1,[mo]));k.set(sg.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(ng.deleteRecord.name,new Q(!1,[ev]));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(Z9.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(ig.setRoutes.name,new Q(!0,[]));k.set(ig.getRoutes.name,new Q(!0,[]));k.set(ig.deleteRoutes.name,new Q(!0,[]));k.set(zP.setConfiguration.name,new Q(!0,[]));k.set(i7.clusterStatus.name,new Q(!0,[]));k.set(o7.name,new Q(!0,[]));k.set(og.getFingerprint.name,new Q(!0,[]));k.set(og.setLicense.name,new Q(!0,[]));k.set(ng.deleteFilesBefore.name,new Q(!0,[]));k.set(ng.deleteAuditLogsBefore.name,new Q(!0,[]));k.set(YP.restart.name,new Q(!0,[]));k.set(YP.restartService.name,new Q(!0,[]));k.set(j9.name,new Q(!0,[]));k.set(X9.name,new Q(!0,[Ln]));k.set(c7.systemInformation.name,new Q(!0,[]));k.set(zP.getConfiguration.name,new Q(!0,[]));k.set(JP.readTransactionLog.name,new Q(!0,[]));k.set(JP.deleteTransactionLogsBefore.name,new Q(!0,[]));k.set(jP.installModules.name,new Q(!0,[]));k.set(jP.auditModules.name,new Q(!0,[]));k.set(WP.createTokens.name,new Q(!1,[]));k.set(WP.refreshOperationToken.name,new Q(!1,[]));k.set(QP.login.name,new Q(!1,[]));k.set(QP.logout.name,new Q(!1,[]));k.set(Fr.customFunctionsStatus.name,new Q(!0,[]));k.set(Fr.getCustomFunctions.name,new Q(!0,[]));k.set(Fr.getComponents.name,new Q(!0,[]));k.set(Fr.getComponentFile.name,new Q(!0,[]));k.set(Fr.setComponentFile.name,new Q(!0,[]));k.set(Fr.dropComponent.name,new Q(!0,[]));k.set(Fr.getCustomFunction.name,new Q(!0,[]));k.set(Fr.setCustomFunction.name,new Q(!0,[]));k.set(Fr.dropCustomFunction.name,new Q(!0,[]));k.set(Fr.addComponent.name,new Q(!0,[]));k.set(Fr.dropCustomFunctionProject.name,new Q(!0,[]));k.set(Fr.packageComponent.name,new Q(!0,[]));k.set(Fr.deployComponent.name,new Q(!0,[]));k.set(og.getRegistrationInfo.name,new Q(!1,[]));k.set(Ku.userInfo.name,new Q(!1,[]));k.set(Yu.describeAll.name,new Q(!1,[]));k.set(_7,new Q(!1,[]));k.set(d7,new Q(!0,[]));k.set(l7,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(rv.EXPORT_TO_S3,new Q(!0,[]));k.set(rv.EXPORT_LOCAL,new Q(!0,[]));k.set(cs.VALID_SQL_OPS_ENUM.DELETE,new Q(!1,[ev]));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]));nv.exports={verifyPerms:h7,verifyPermsAst:E7,verifyBulkLoadAttributePerms:p7};function E7(e,t,r){if(Dn.isEmptyOrZeroLength(e))throw bt.info("verify_perms_ast has an empty user parameter"),mr(new Error);if(Dn.isEmptyOrZeroLength(t))throw bt.info("verify_perms_ast has an empty user parameter"),mr(new Error);if(Dn.isEmptyOrZeroLength(r))throw bt.info("verify_perms_ast has a null operation parameter"),mr(new Error);try{let s=new XP,n=new a7(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw bt.info("No schemas defined in verifyPermsAst(), will not continue."),mr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&tv[r])throw mr(new Error,Gt.DROP_SYSTEM,Vu.FORBIDDEN);if(c&&!u)return null;let _=KP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof u7.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=sv(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=cg(t.role.permission,f,d[E]);ag(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw mr(s)}}a(E7,"verifyPermsAst");function h7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw bt.info("null required parameter in verifyPerms"),mr(new Error,Gt.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 XP;if(Dn.isEmptyOrZeroLength(e.hdb_user.role)||Dn.isEmptyOrZeroLength(e.hdb_user.role.permission))return bt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Gt.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&&tv[r])throw mr(new Error,Gt.DROP_SYSTEM,Vu.FORBIDDEN);if(u&&!l||_===!0&&(r===us.createSchema.name||r===us.dropSchema.name))return null;if(f7.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=KP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===VP||r===$P){if(n===cs.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Gt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===VP&&(!d[n]||!d[n][$u]))return c.handleInvalidItem(Gt.SCHEMA_NOT_FOUND(n));if(r===$P&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][$u]))return c.handleInvalidItem(Gt.TABLE_NOT_FOUND(n,i))}}let f=sv(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=m7(e),h=cg(e.hdb_user.role.permission,n,i);return ag(E,h,r,i,n,c,s),c.getPermsResponse()}a(h7,"verifyPerms");function sv(e,t,r,s,n){if(Dn.arrayHasEmptyValues([e,t,r]))throw bt.info("hasPermissions has an invalid parameter"),mr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||k.get(t).requires_su))return null;if(!k.get(t))throw bt.info(`operation ${t} not found.`),mr(new Error,Gt.OP_NOT_FOUND(t),Vu.BAD_REQUEST);if(k.get(t)&&k.get(t).requires_su)return bt.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Gt.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(Gt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(Gt.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(Gt.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)&&(bt.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=Gt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw bt.error(E),bt.error(f),mr(ZP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(sv,"hasPermissions");function ag(e,t,r,s,n,i,o){if(!e||!t)throw bt.info("no attributes specified in checkAttributePerms."),mr(new Error);let c=k.get(r).perms;if(!c||c==="")throw bt.info(`no permissions found for ${r} in checkAttributePerms().`),mr(new Error);if(Dn.isEmptyOrZeroLength(t))return bt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[$u]===!1){i.addInvalidItem(Gt.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 mr(new Error,Gt.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(Gt.ATTR_NOT_FOUND(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(ag,"checkAttributePerms");function m7(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){bt.info(r)}return t}a(m7,"getRecordAttributes");function cg(e,t,r){let s=new Map;if(Dn.isEmpty(e))return bt.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{bt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(cg,"getAttributePermissions");function p7(e,t,r,s,n,i,o){let c=new Set(i),u=cg(e,s,n);ag(c,u,t,n,s,o,r)}a(p7,"verifyBulkLoadAttributePerms")});var mf=T((vhe,uv)=>{"use strict";uv.exports={evaluateSQL:D7,processAST:cv,convertSQLToAST:av,checkASTPermissions:ov};var S7=wr(),iv=require("util"),T7=iv.callbackify(S7.insert),g7=es().search,R7=YC().update,A7=iv.callbackify(R7),O7=WC().convertDelete,Ri=require("alasql"),b7=Ef(),hf=V(),N7=X_(),y7=J(),Wu=L(),{hdb_errors:w7,handleHDBError:ug}=re(),{HTTP_STATUS_CODES:lg}=w7;N7(Ri);var I7=403,C7="There was a problem performing this insert. Please check the logs and try again.",_g=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function D7(e,t){let r=e.parsed_sql_object;if(!r){r=av(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)&&y7.isEmptyOrZeroLength(s))return t("No schema specified",null)}cv(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(D7,"evaluateSQL");function ov(e,t){let r;try{r=b7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(ov,"checkASTPermissions");function av(e){let t=new _g;if(!e)throw ug(new Error,"The 'sql' parameter is missing from the request body",lg.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]?ug(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,lg.BAD_REQUEST):ug(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",lg.BAD_REQUEST)}return t}a(av,"convertSQLToAST");function cv(e,t,r){try{let s=L7;if(!e.bypass_auth&&!t.permissions_checked){let i=ov(e,t);if(i&&i.length>0)return r(I7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Wu.VALID_SQL_OPS_ENUM.SELECT:s=g7,n=t.ast.statements[0];break;case Wu.VALID_SQL_OPS_ENUM.INSERT:s=U7;break;case Wu.VALID_SQL_OPS_ENUM.UPDATE:s=A7;break;case Wu.VALID_SQL_OPS_ENUM.DELETE:s=O7;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(cv,"processAST");function L7(e,t){hf.info(e),t("unknown sql statement")}a(L7,"nullFunction");function U7({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=M7(i,e.values)}catch(o){return r(o)}T7(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(U7,"convertInsert");function M7(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(C7)}}a(M7,"createDataObjects")});var dg=T((Hhe,_v)=>{"use strict";var{S3:P7,GetObjectCommand:v7}=require("@aws-sdk/client-s3");_v.exports={getFileStreamFromS3:B7,getS3AuthObj:lv};async function B7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await lv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new v7(r))).Body}a(B7,"getFileStreamFromS3");function lv(e,t,r){return new P7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(lv,"getS3AuthObj")});var pf=T((qhe,gv)=>{"use strict";var Eg=es(),H7=mf(),x7=dg(),{AsyncParser:q7,Transform:F7}=require("json2csv"),zu=require("stream"),Gr=J(),fg=require("fs-extra"),G7=require("path"),ls=V(),{promisify:Ev}=require("util"),Qu=J(),{handleHDBError:pt,hdb_errors:k7}=re(),{HDB_ERROR_MSGS:pr,HTTP_STATUS_CODES:St}=k7,{streamAsJSON:V7}=(Uh(),se(lb)),{Upload:$7}=require("@aws-sdk/lib-storage"),dv=["search_by_value","search_by_hash","sql","search_by_conditions"],fv=["json","csv"],hv="json",mv="csv",Y7="Successfully exported JSON locally.",K7="Successfully exported CSV locally.",W7=1e3,Q7=Eg.searchByHash,z7=Eg.searchByValue,J7=Ev(H7.evaluateSQL),j7=Ev(zu.finished);gv.exports={export_to_s3:tee,export_local:X7,toCsvStream:pv};async function X7(e){ls.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=Sv(e);if(!Gr.isEmpty(t))throw ls.error(t),pt(new Error,t,St.BAD_REQUEST,void 0,void 0,!0);if(Gr.isEmpty(e.path))throw ls.error(pr.MISSING_VALUE("path")),pt(new Error,pr.MISSING_VALUE("path"),St.BAD_REQUEST,void 0,void 0,!0);let r=(Gr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(G7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Gr.buildFolderPath(e.path,r);await Z7(e.path);let n=await Tv(e);return await eee(s,e.format,n)}a(X7,"export_local");async function Z7(e){if(ls.trace("in confirmPath"),Gr.isEmptyOrZeroLength(e))throw pt(new Error,`Invalid path: ${e}`,St.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await fg.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(Z7,"confirmPath");async function eee(e,t,r){if(ls.trace("in saveToLocal"),Qu.isEmptyOrZeroLength(e))throw pt(new Error,pr.INVALID_VALUE("file_path"),St.BAD_REQUEST,void 0,void 0,!0);if(Qu.isEmptyOrZeroLength(t))throw pt(new Error,pr.INVALID_VALUE("Source format"),St.BAD_REQUEST,void 0,void 0,!0);if(Qu.isEmpty(r))throw pt(new Error,pr.NOT_FOUND("Data"),St.BAD_REQUEST,void 0,void 0,!0);if(t===hv){let s=fg.createWriteStream(e);return V7(r).pipe(s),await j7(s),{message:Y7,path:e}}else if(t===mv){let s=fg.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 q7(i,c).fromInput(n).toOutput(s).promise(!1),{message:K7,path:e}}throw pt(new Error,pr.INVALID_VALUE("format"),St.BAD_REQUEST)}a(eee,"saveToLocal");async function tee(e){if(!e.s3||Object.keys(e.s3).length===0)throw pt(new Error,pr.MISSING_VALUE("S3 object"),St.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw pt(new Error,pr.MISSING_VALUE("aws_access_key_id"),St.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw pt(new Error,pr.MISSING_VALUE("aws_secret_access_key"),St.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.bucket))throw pt(new Error,pr.MISSING_VALUE("bucket"),St.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.key))throw pt(new Error,pr.MISSING_VALUE("key"),St.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.region))throw pt(new Error,pr.MISSING_VALUE("region"),St.BAD_REQUEST);let t=Sv(e);if(!Gr.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 Tv(e)}catch(u){throw ls.error(u),u}let s,n=await x7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new zu.PassThrough;if(e.format===mv){i=e.s3.key+".csv";let u=pv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===hv){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%W7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw pt(new Error,pr.INVALID_VALUE("format"),St.BAD_REQUEST);return new $7({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(tee,"export_to_s3");function pv(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 F7(s,n);return r.pipe(i)}a(pv,"toCsvStream");function Sv(e){if(ls.trace("in exportCoreValidation"),Gr.isEmpty(e.format))return"format missing";if(fv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${fv.join(", ")}`;let t=e.search_operation.operation;if(Gr.isEmpty(t))return"search_operation.operation missing";if(dv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${dv.join(", ")}`}a(Sv,"exportCoreValidation");async function Tv(e){ls.trace("in getRecords");let t,r;if(Qu.isEmpty(e.search_operation)||Qu.isEmptyOrZeroLength(e.search_operation.operation))throw pt(new Error,pr.INVALID_VALUE("Search operation"),St.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=z7;break;case"search_by_hash":t=Q7;break;case"search_by_conditions":t=Eg.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(Tv,"getRecords")});var Iv={};Ye(Iv,{contentTypes:()=>Tg,findBestSerializer:()=>Tf,getDeserializer:()=>So,registerContentHandlers:()=>gg,serialize:()=>gf,serializeMessage:()=>Ti});function ree(e){try{return e?.[0]===123?Sg(e):e}catch{return e}}function gg(e){e.register(nee,{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,hg.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=Pt.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(Pt.keys()).join(", "))}};s=Pt.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function gf(e,t,r){let s=Av&&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>Av?(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 iee(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=Pt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=Pt.get(e)?.deserialize||Ov(e,s);return o=>iee(o).then(i)}return e&&Pt.get(e)?.deserialize||Ov(e,s)}function Ov(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 Sg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function oee(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 hg,on,po,Un,Sf,bv,mg,pg,Nv,yv,Ju,Sg,ju,Pt,Tg,Rv,wv,see,nee,Av,ga=Re(()=>{Uh();hg=x(pf()),on=require("msgpackr"),po=require("cbor-x"),Un=require("zlib"),Sf=require("stream");tr();bv=require("../index"),mg=x(Z()),pg=x(L()),Nv=x(require("yaml")),yv=mg.default.get(pg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Ju=yv?Pi:JSON.stringify,Sg=yv?Lh:JSON.parse,ju={useRecords:!1,useToJSON:!0},Pt=new Map,Tg=Pt;tt.contentTypes=Tg;(0,bv._assignPackageExport)("contentTypes",Tg);Pt.set("application/json",{serializeStream:mc,serialize:Ju,deserialize:Sg,q:.8});Rv=new po.Encoder(ju);Pt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new po.EncoderStream(ju).end(e)},serialize:Rv.encode,deserialize:Rv.decode,q:1});Pt.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});Pt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,hg.toCsvStream)(e,e?.getColumns?.())},q:.1});Pt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});Pt.set("text/yaml",{serialize(e){return Nv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Pt.set("text/event-stream",{serializeStream:function(e){return Sf.Readable.from(oee(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});Pt.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()}});wv={type:"application/json",serializeStream:mc,serialize:Ju,deserialize:ree,q:.8};Pt.set("*/*",wv);Pt.set("",wv);a(ree,"tryJSONParse");a(gg,"registerContentHandlers");see=require("fastify-plugin"),nee=see(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");Av=mg.default.get(pg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(gf,"serialize");a(Ti,"serializeMessage");a(iee,"streamToBuffer");a(So,"getDeserializer");a(Ov,"deserializerUnknownType");a(oee,"transformIterable")});function Og(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?Og(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=Ng(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=hee(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 kr.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=_ee(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=dee(v,g,P.primaryStore,H,U)):v=v.flatMap(U)}return v}else if(o.length===1)o=o[0];else throw new kr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(bg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=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 kr.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 kr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(n===!1&&E)throw new kr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new kr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new kr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Ng(e),!S)throw new kr.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 _ee(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 dee(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 Ng(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=Ng({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()),bg[o]||o){case Rg.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 kr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!n&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&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=bg[s]||s,s===Rg.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=uee*Mn(e.primaryStore)+1:s==="between"?r.estimated_count=cee*Mn(e.primaryStore)+1:s==="sort"?r.estimated_count=Mn(e.primaryStore)+1:r.estimated_count=aee*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,fee.test(e))try{let t=Xu(new Ia,"");if(Sr!==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 ${Sr} 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);){Sr=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=Cv}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=lee[d],u=Ag[i]?Cv: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"&&Dv(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=Sr;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=Lv(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Oi[Sr]===","?r.lastIndex=++Sr: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=Sr,f=Xu([],"}"),f.name=l,e.push(f),Oi[Sr]===","?r.lastIndex=++Sr:o=!0;break;case"[":wa.lastIndex=Sr,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[Sr]===","?r.lastIndex=++Sr: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"&&Dv(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?Eee:wa,r.lastIndex=Sr),Sr===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 Cv(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new kr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function Dv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new kr.ClientError("wildcard can only be used at the end of a string")}function Lv(e){let t=Uv(e[0]);return e.length>1&&(t.next=Lv(e.slice(1))),t}function Uv(e){if(Array.isArray(e)){let t=Uv(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 hee(e,t,r){return t*r/Mn(e)}var kr,Rg,an,Ai,aee,cee,uee,lee,Ag,bg,fee,wa,Eee,Sr,Oi,Ia,bf=Re(()=>{kr=x(re()),Rg=x(dt()),an=require("ordered-binary"),Ai=require("lmdb"),aee=.3,cee=.1,uee=.05,lee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Ag={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Og,"executeConditions");a(Ca,"searchByIndex");a(Pn,"findAttribute");a(_ee,"joinTo");a(dee,"joinFrom");bg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Ng,"filterByType");a(Af,"estimateCondition");fee=/[()[\]|!<>.]|(=\w*=)/,wa=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Eee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Of,"parseQuery");a(Xu,"parseBlock");a(Rf,"assignOperator");a(Zu,"decodeProperty");a(Cv,"typedDecoding");a(Dv,"wildcardDecoding");a(Lv,"toSortObject");a(Uv,"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(hee,"intersectionEstimate")});function Hv(e){let t={openapi:mee,info:{title:"HarperDB HTTP REST interface",version:(0,Bv.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 Cg(yg[z.type],z.type)}),t.components.schemas[Y.type]=new vv(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 Cg(yg[H.type],H.type)}:g==="Any"||g=="ID"?_[P]={format:g}:_[P]=new Cg(yg[g],g)}l.push(new Dg(P,"query",_[P]))}let d=Object.keys(_),f=new Dg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Dg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new vv(_);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 pee(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new wg(l,r,{200:new Ig({$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 Pv(l,r,"delete all the records that match the provided query",{204:new Mv})),R="/"+n+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new wg([f],r,{200:new Ig({$ref:bi+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new See([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 Pv([f],r,"delete a record with the given primary key",{204:new Mv})),S&&E.schema.enum.length>0&&(R="/"+n+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new wg([f,E],r,{200:new Ig({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function pee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:bi+e}}}},this.security=t,this.responses={200:{description:Lg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function wg(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.responses=r}function Ig(e){this.description=Lg,this.content={"application/json":{schema:e}}}function Mv(){this.description="successfully processed request, no content returned to client"}function See(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:Lg}}}function Pv(e,t,r,s){this.description=r,this.parameters=e,this.security=t,this.responses=s}function vv(e){this.type="object",this.properties=e}function Cg(e,t){this.type=e,this.format=t}function Dg(e,t,r){this.name=e,this.in=t,this.schema=r}var Bv,mee,yg,bi,Lg,xv=Re(()=>{Bv=x(Od()),mee="3.0.3",yg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},bi="#/components/schemas/",Lg="successful operation";a(Hv,"generateJsonApi");a(pee,"Post");a(wg,"Get");a(Ig,"Response200");a(Mv,"Response204");a(See,"Put");a(Pv,"Delete");a(vv,"ResourceSchema");a(Cg,"Type");a(Dg,"Parameter")});var yf={};Ye(yf,{start:()=>Ree});async function gee(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!==qv){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===qv&&s==="GET"){if(e?.user?.role?.permission?.super_user)return Hv(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,Ug.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){Tee[0]=d;let h=String.fromCharCode(34,(kt[0]&63)+62,(kt[0]>>6)+(kt[1]<<2&63)+62,(kt[1]>>4)+(kt[2]<<4&63)+62,(kt[2]>>2)+62,(kt[3]&63)+62,(kt[3]>>6)+(kt[4]<<2&63)+62,(kt[4]>>4)+(kt[5]<<4&63)+62,(kt[5]>>2)+62,(kt[6]&63)+62,(kt[6]>>6)+(kt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):n.setIfNone("ETag",h),Ug.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 Ree(e){Ug=e,!Fv&&(Fv=!0,Nf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return gee(t,r)}),e.server.ws(async(t,r,s)=>{el++;let n=new Rs;Gv||(Gv=!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,Br(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),Br(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var To,Da,kt,Tee,Ug,qv,Fv,Nf,Gv,el,kv=Re(()=>{ga();bn();To=x(V()),Da=x(re());bf();Ec();Zi();Bu();xv();kt=new Uint8Array(8),Tee=new Float64Array(kt.buffer,0,1),Ug={},qv="openapi";a(gee,"http");el=0;a(Ree,"start")});var Mg=T((sme,Vv)=>{var{recordAction:wf,recordActionBinary:Aee}=(bn(),se(su)),Oee=require("fastify-plugin"),bee=200;Vv.exports=Oee(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),Aee(n.raw.statusCode<400,"success",_,d,l);let f=bee;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 qg=T((ome,Wv)=>{var Lf=require("clone"),Uf=je(),Nee=J(),Cf=L(),nme=V(),Pg=require("fs"),Bg=require("joi"),{string:Df}=Bg.types(),{hdb_errors:yee,handleHDBError:If}=re(),{HDB_ERROR_MSGS:ime,HTTP_STATUS_CODES:vg}=yee,{common_validators:La}=Ys(),$v=" is required",wee=["insert","update","upsert"],Hg={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:wee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Iee={schema:Df.required(),table:Df.required(),action:Df.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Cee,AWS_SECRET:Dee,AWS_BUCKET:Lee,AWS_FILE_KEY:Uee,REGION:Mee}=Cf.S3_BUCKET_AUTH_KEYS,Pee={s3:{presence:!0},[`s3.${Cee}`]:{presence:!0,type:"String"},[`s3.${Dee}`]:{presence:!0,type:"String"},[`s3.${Lee}`]:{presence:!0,type:"String"},[`s3.${Uee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Mee}`]:{presence:!0,type:"String"}},Yv=Lf(Hg);Yv.data.presence={message:$v};var Kv=Lf(Hg);Kv.file_path.presence={message:$v};var vee=Object.assign(Lf(Hg),Pee),xg=Lf(Iee);xg.csv_url=Df.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();xg.passthrough_headers=Bg.object();function Bee(e){let t=Uf.validateObject(e,Yv);return Mf(e,t)}a(Bee,"dataObject");function Hee(e){let t=Uf.validateBySchema(e,Bg.object(xg));return Mf(e,t)}a(Hee,"urlObject");function xee(e){let t=Uf.validateObject(e,Kv);return Mf(e,t)}a(xee,"fileObject");function qee(e){let t=Uf.validateObject(e,vee);return Mf(e,t)}a(qee,"s3FileObject");function Mf(e,t){if(!t){let r=Nee.checkGlobalSchemaTable(e.schema,e.table);if(r)return If(new Error,r,vg.BAD_REQUEST);if(e.operation===Cf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Pg.accessSync(e.file_path,Pg.constants.R_OK|Pg.constants.F_OK)}catch(s){return s.code===Cf.NODE_ERROR_CODES.ENOENT?If(s,`No such file or directory ${s.path}`,vg.BAD_REQUEST):s.code===Cf.NODE_ERROR_CODES.EACCES?If(s,`Permission denied ${s.path}`,vg.BAD_REQUEST):If(s)}}return t}a(Mf,"postValidateChecks");Wv.exports={dataObject:Bee,urlObject:Hee,fileObject:xee,s3FileObject:qee}});var Fg=T((cme,Qv)=>{"use strict";var tl=V(),Pf=L();async function Fee(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(Fee,"callOperationFunctionAsAwait");Qv.exports={callOperationFunctionAsAwait:Fee}});var Jv=T((lme,zv)=>{"use strict";var Gg=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}},kg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};zv.exports={BulkLoadFileObject:Gg,BulkLoadDataObject:kg}});var Xv=T((dme,jv)=>{"use strict";var Vg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};jv.exports=Vg});var zg=T((Sme,h0)=>{"use strict";var vf=wr(),Hf=qg(),Gee=require("needle"),vs=L(),Eme=Ge(),Ua=J(),{handleHDBError:it,hdb_errors:a0}=re(),{HTTP_STATUS_CODES:Vt,HDB_ERROR_MSGS:Nt,CHECK_LOGS_WRAPPER:Ro}=a0,Ma=V(),$g=require("papaparse");Ua.promisifyPapaParse();var Bs=require("fs-extra"),kee=require("path"),{chain:Zv}=require("stream-chain"),e0=require("stream-json/streamers/StreamArray"),t0=require("stream-json/utils/Batch"),r0=require("stream-chain/utils/comp"),{finished:s0}=require("stream"),Vee=Z(),c0=Fg(),$ee=dg(),{BulkLoadFileObject:Kg,BulkLoadDataObject:Yee}=Jv(),Wg=rg(),{verifyBulkLoadAttributePerms:u0}=Ef(),hme=Xv(),mme=st(),pme=Sn(),{databases:Kee}=(Ae(),se(Fe)),{coerceType:Wee}=(xf(),se(Jg)),n0="No records parsed from csv file.",go=`${Vee.get("HDB_ROOT")}/tmp`,{schema_regex:Qee}=Ys(),i0=1024*1024*2,o0=5e3,zee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};h0.exports={csvDataLoad:Jee,csvURLLoad:jee,csvFileLoad:Xee,importFromS3:Zee};async function Jee(e,t){let r=Hf.dataObject(e);if(r)throw it(r,r.message,Vt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=d0(e.schema,e.table),i=$g.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Yg.bind(null,n),dynamicTyping:!1}),o=new Wg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&u0(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,Vt.BAD_REQUEST,void 0,void 0,!0);let u=new Yee(e.action,e.schema,e.table,i.data);return s=await c0.callOperationFunctionAsAwait(f0,u,null),s.message===n0?n0:E0(s.records,s.number_written)}catch(n){throw Ao(n)}}a(Jee,"csvDataLoad");async function jee(e){let t=Hf.urlObject(e);if(t)throw it(t,t.message,Vt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${go}/${r}`;try{await ete(e,r)}catch(n){throw Ma.error(Nt.DOWNLOAD_FILE_ERR(r)+" - "+n),it(n,Ro(Nt.DOWNLOAD_FILE_ERR(r)))}try{let n=new Kg(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 Qg(n);return await Bf(s),i}catch(n){throw await Bf(s),Ao(n)}}a(jee,"csvURLLoad");async function Xee(e){let t=Hf.fileObject(e);if(t)throw it(t,t.message,Vt.BAD_REQUEST,void 0,void 0,!0);let r=new Kg(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 Qg(r)}catch(s){throw Ao(s)}}a(Xee,"csvFileLoad");async function Zee(e){let t=Hf.s3FileObject(e);if(t)throw it(t,t.message,Vt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=kee.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${go}/${n}`;let i=new Kg(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await tte(n,e);let o=await Qg(i);return await Bf(r),o}catch(s){throw await Bf(r),Ao(s)}}a(Zee,"importFromS3");async function ete(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Gee("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)}ste(r,e.csv_url),await rte(t,r.raw)}a(ete,"downloadCSVFile");async function tte(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 $ee.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(Nt.S3_DOWNLOAD_ERR+" - "+r),it(r,Ro(Nt.S3_DOWNLOAD_ERR))}}a(tte,"downloadFileFromS3");async function rte(e,t){try{await Bs.mkdirp(go),await Bs.writeFile(`${go}/${e}`,t)}catch(r){throw Ma.error(Nt.WRITE_TEMP_FILE_ERR),it(r,Ro(Nt.DEFAULT_BULK_LOAD_ERR))}}a(rte,"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 ste(e,t){if(e.statusCode!==a0.HTTP_STATUS_CODES.OK)throw it(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Vt.BAD_REQUEST);if(!zee[e.headers["content-type"]])throw it(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Vt.BAD_REQUEST);if(!e.raw)throw it(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Vt.BAD_REQUEST)}a(ste,"validateURLResponse");async function Qg(e){try{let t;switch(e.file_type){case vs.VALID_S3_FILE_TYPES.CSV:t=await nte(e);break;case vs.VALID_S3_FILE_TYPES.JSON:t=await ite(e);break;default:throw it(new Error,Nt.DEFAULT_BULK_LOAD_ERR,Vt.BAD_REQUEST,vs.LOG_LEVELS.ERROR,Nt.INVALID_FILE_EXT_ERR(e))}return E0(t.records,t.number_written)}catch(t){throw Ao(t)}}a(Qg,"fileLoad");async function l0(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&&u0(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(l0,"validateChunk");async function _0(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 c0.callOperationFunctionAsAwait(f0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=it(c,Ro(Nt.INSERT_CSV_ERR),Vt.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,Nt.INSERT_CSV_ERR+" - "+c);r(u)}}a(_0,"insertChunk");async function nte(e){let t={records:0,number_written:0},r=d0(e.schema,e.table);try{let s=new Wg,n=Bs.createReadStream(e.file_path,{highWaterMark:i0});n.setEncoding("utf8"),await $g.parsePromise(n,l0.bind(null,e,s),Yg.bind(null,r));let i=s.getPermsResponse();if(i)throw it(new Error,i,Vt.BAD_REQUEST);return n=Bs.createReadStream(e.file_path,{highWaterMark:i0}),n.setEncoding("utf8"),await $g.parsePromise(n,_0.bind(null,e,t),Yg.bind(null,r)),n.destroy(),t}catch(s){throw it(s,Ro(Nt.PAPA_PARSE_ERR),Vt.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,Nt.PAPA_PARSE_ERR+s)}}a(nte,"callPapaParse");function d0(e,t){let r=Kee[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>Wee(i,n));return s}a(d0,"createTransformMap");function Yg(e,t,r){let s=e.get(r);return s?s(t):Ua.autoCast(t)}a(Yg,"typeFunction");async function ite(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Wg,n=Zv([Bs.createReadStream(e.file_path,{encoding:"utf-8"}),e0.withParser(),c=>c.value,new t0({batchSize:o0}),r0(async c=>{await l0(e,s,r,c)})]);await new Promise((c,u)=>{s0(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw it(new Error,i,Vt.BAD_REQUEST);let o=Zv([Bs.createReadStream(e.file_path,{encoding:"utf-8"}),e0.withParser(),c=>c.value,new t0({batchSize:o0}),r0(async c=>{await _0(e,t,r,c)})]);return await new Promise((c,u)=>{s0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw it(s,Ro(Nt.INSERT_JSON_ERR),Vt.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,Nt.INSERT_JSON_ERR+s)}}a(ite,"insertJson");async function f0(e){let t={};try{e.data&&e.data.length>0&&ote(e.data[0])?t=await ate(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(f0,"callBulkFileLoad");function ote(e){let t=Object.keys(e);for(let r of t)if(!Qee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(ote,"validateColumnNames");async function ate(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,Nt.INVALID_ACTION_PARAM_ERR(s),Vt.BAD_REQUEST,vs.LOG_LEVELS.ERROR,Nt.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(ate,"bulkFileLoad");function E0(e,t){return`successfully loaded ${t} of ${e} records`}a(E0,"buildResponseMsg");function Ao(e){return it(e,Ro(Nt.DEFAULT_BULK_LOAD_ERR),Vt.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,Nt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Ao,"buildTopLevelErrMsg")});var p0=T((gme,m0)=>{"use strict";var jg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};m0.exports=jg});var g0=T((Ame,T0)=>{"use strict";var cte=L(),S0=require("moment"),ute=require("uuid").v4,Xg=class{static{a(this,"JobObject")}constructor(){this.id=ute(),this.type=void 0,this.start_datetime=S0().valueOf(),this.created_datetime=S0().valueOf(),this.end_datetime=void 0,this.status=cte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};T0.exports=Xg});var Zg=T((bme,y0)=>{"use strict";var lte=require("uuid").v4,O0=wr(),b0=es(),_te=Js(),dte=ta(),fte=p0(),ot=L(),Ete=g0(),hte=md(),_s=V(),mte=Ic(),Pa=J(),{promisify:pte}=require("util"),Oo=require("moment"),Ste=mf(),qf=qg(),R0=wm(),{deleteTransactionLogsBeforeValidator:Tte}=jT(),{handleHDBError:gte,hdb_errors:Rte}=re(),{HTTP_STATUS_CODES:Ate}=Rte,A0=b0.searchByValue,Ote=b0.searchByHash,bte=O0.insert,Nte=pte(Ste.evaluateSQL),yte=O0.update;y0.exports={addJob:Cte,updateJob:Lte,handleGetJob:wte,handleGetJobsByStartDate:Ite,getJobById:N0};async function wte(e){try{let t=await N0(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(wte,"handleGetJob");async function Ite(e){try{let t=await Dte(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(Ite,"handleGetJobsByStartDate");async function Cte(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=R0(e,"date");break;case ot.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=R0(e,"timestamp");break;case ot.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=Tte(e);break;default:break}if(s)throw gte(s,s.message,Ate.BAD_REQUEST,void 0,void 0,!0);let n=new Ete;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 _te(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await A0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return _s.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=lte();try{o=await A0(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 mte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await bte(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(Cte,"addJob");async function Dte(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 fte(s,e.hdb_user);try{return await Nte(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(Dte,"getJobsInDateRange");async function N0(e){if(Pa.isEmptyOrZeroLength(e))return Pa.errorizeMessage("Invalid job ID specified.");let t=new dte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Ote(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(N0,"getJobById");async function Lte(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 hte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await yte(t),r}a(Lte,"updateJob")});var U0=T((yme,L0)=>{"use strict";var w0=J(),Tr=L(),Ute=require("moment"),Ff=zg(),Gf=V(),I0=Zg(),C0=pf(),D0=ti(),Mte=Ke(),Pte=lf(),eR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function vte(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(w0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(w0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Tr.JOB_TYPE_ENUM.csv_file_load:await vn(e,Ff.csvFileLoad);break;case Tr.JOB_TYPE_ENUM.csv_url_load:await vn(e,Ff.csvURLLoad);break;case Tr.JOB_TYPE_ENUM.csv_data_load:await vn(e,Ff.csvDataLoad);break;case Tr.JOB_TYPE_ENUM.import_from_s3:await vn(e,Ff.importFromS3);break;case Tr.JOB_TYPE_ENUM.empty_trash:break;case Tr.JOB_TYPE_ENUM.export_local:await vn(e,C0.export_local);break;case Tr.JOB_TYPE_ENUM.export_to_s3:await vn(e,C0.export_to_s3);break;case Tr.JOB_TYPE_ENUM.delete_files_before:case Tr.JOB_TYPE_ENUM.delete_records_before:await vn(e,D0.deleteFilesBefore);break;case Tr.JOB_TYPE_ENUM.delete_audit_logs_before:await vn(e,D0.deleteAuditLogsBefore);break;case Tr.JOB_TYPE_ENUM.delete_transaction_logs_before:await vn(e,Pte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(vte,"parseMessage");async function vn(e,t){try{e.job.status=Tr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Ute().valueOf(),await I0.updateJob(e.job),await Bte(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=Tr.JOB_STATUS_ENUM.ERROR;try{await I0.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 Bte(e){Gf.trace("launching job thread:",e),Mte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Tr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Bte,"launchJobThread");L0.exports={parseMessage:vte,RunnerMessage:eR}});var P0=T((Ime,M0)=>{"use strict";var tR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};M0.exports=tR});var j0=T((Dme,aR)=>{"use strict";var Yf=es(),nR=mf(),kf=zg(),Bn=lu(),Vf=Xn(),sl=ti(),Hte=mS(),rl=ts(),$f=NS(),$t=JT(),yt=V(),xte=IS(),qte=Id(),v0=uT(),Fte=Dd(),Gte=lT(),kte=_T(),Vte=ET(),$te=mT(),rR=TT(),B0=pf(),Yte=Ef(),iR=Zg(),q=L(),{hdb_errors:il,handleHDBError:nl}=re(),{HTTP_STATUS_CODES:H0}=il,sR=bT(),x0=Wd(),W0=require("util"),va=wr(),Kte=Tn(),Wte=da(),q0=U0(),F0=mu(),G0=(Xd(),se(Hu)),k0=Lr(),V0=lf(),$0=sf(),{setServerUtilities:Qte}=(xf(),se(Jg)),{CONTEXT:zte}=(As(),se(Ap)),{_assignPackageExport:Jte}=require("../index"),{transformReq:jte}=J(),{server:Xte}=(tr(),se(Mi)),Zte=Fg(),Y0=Yf.searchByHash,ere=Yf.searchByValue,tre=W0.promisify(Yf.search),rre=W0.promisify(nR.evaluateSQL),sre={[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},$=P0();async function Q0(e,t){try{if(e.body.operation!=="read_log"&&(yt.log_level===q.LOG_LEVELS.INFO||yt.log_level===q.LOG_LEVELS.DEBUG||yt.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;yt.info(o)}}catch(s){yt.error(s)}let r=await Zte.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return sre[e.body.operation]&&Kte.setSchemaDataToGlobal(s=>{s&&yt.error(s)}),r}a(Q0,"processLocalTransaction");var K0=ire();aR.exports={chooseOperation:z0,getOperationFunction:J0,operation:oR,processLocalTransaction:Q0};Qte(aR.exports);Xte.operation=oR;function z0(e){let t;try{t=J0(e)}catch(n){throw yt.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=nR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=nR.checkASTPermissions(e,i);if(o)throw yt.error(`${H0.FORBIDDEN} from operation ${e.operation}`),yt.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=Yte.verifyPerms(i,n);if(o)throw yt.error(`${H0.FORBIDDEN} from operation ${e.operation}`),yt.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(z0,"chooseOperation");function J0(e){if(yt.trace(`getOperationFunction with operation: ${e.operation}`),K0.has(e.operation))return K0.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(J0,"getOperationFunction");Jte("operation",oR);function oR(e,t){e.hdb_user=this[zte]?.user,e.bypass_auth=!t;let r=z0(e);return Q0({body:e},r)}a(oR,"operation");async function nre(e){yt.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:yt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){yt.info("Invalid operation in transaction"),yt.error(o)}}a(nre,"catchup");async function cn(e){jte(e);let t,r;try{r=await iR.addJob(e),t=r.createdJob,yt.info("addJob result",r);let s=new q0.RunnerMessage(t,e);return await q0.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 yt.error(n),nl(s,n)}}a(cn,"executeJob");function ire(){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 $(Y0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new $(Y0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(ere)),e.set(q.OPERATIONS_ENUM.SEARCH,new $(tre)),e.set(q.OPERATIONS_ENUM.SQL,new $(rre)),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 $(xte)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new $(qte)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new $(v0)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(v0)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new $(Fte)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(Gte)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new $(kte)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new $(k0.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new $(Vte.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new $($te)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(rR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(rR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(rR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new $(cn,B0.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,B0.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(iR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new $(iR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new $(sR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new $(sR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new $(sR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new $(x0.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new $(x0.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new $(nre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $(Wte.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(cn,sl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(Hte)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(F0.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(F0.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new $(G0.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new $(G0.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new $(k0.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $($t.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $($t.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $($t.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new $($t.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $($t.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new $($t.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $($t.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $($t.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $($t.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $($t.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new $($t.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $($t.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $($t.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $($t.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $($t.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $($t.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(V0.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(cn,V0.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $($0.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $($0.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new $(Bn.getBackup)),e}a(ire,"initializeOperationFunctionMap")});var Wf=T((Ume,eB)=>{"use strict";var cR=L(),ore=J(),ol=V(),{handleHDBError:uR,hdb_errors:Kf}=re(),{isMainThread:are}=require("worker_threads"),{Readable:cre}=require("stream"),X0=require("os"),ure=require("util"),lre=xS(),_re=ure.promisify(lre.authorize),Z0=j0(),{createGzip:dre,constants:fre}=require("zlib");function Ere(e){let t=`Found an uncaught exception with message: ${e.message}. ${X0.EOL}Stack: ${e.stack} ${X0.EOL}Terminating ${are?"HDB":"thread"}.`;console.error(t),ol.fatal(t),process.exit(1)}a(Ere,"handleServerUncaughtException");function hre(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(hre,"serverErrorHandler");function mre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=uR(new Error,"Invalid JSON.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(ore.isEmpty(e.body.operation)){let s=uR(new Error,"Request body must include an 'operation' property.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(mre,"reqBodyValidationHandler");function pre(e,t,r){let s;e.body.operation!==cR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==cR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==cR.OPERATIONS_ENUM.LOGOUT?_re(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(uR(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(pre,"authHandler");async function Sre(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=Z0.chooseOperation(e.body);let n=await Z0.processLocalTransaction(e,s);if(n instanceof cre&&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(dre({level:fre.Z_BEST_SPEED})))}return n}catch(n){throw ol.error(n),n}}a(Sre,"handlePostRequest");eB.exports={authHandler:pre,handlePostRequest:Sre,handleServerUncaughtException:Ere,serverErrorHandler:hre,reqBodyValidationHandler:mre}});var nB=T((Pme,sB)=>{"use strict";var Tre=require("fastify-plugin"),{handlePostRequest:tB,authHandler:gre,reqBodyValidationHandler:Rre}=Wf();async function Are(e){e.decorate("hdbCore",{preValidation:[Rre,gre],request:t=>rB(tB(t,response)),requestWithoutAuthentication:(t,r)=>rB(tB(t,r,!0))})}a(Are,"hdbCore");async function rB(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(rB,"convertAsyncIterators");sB.exports=Tre(Are)});var aB=T((Hme,oB)=>{"use strict";var Bme=require("fs"),lR=Z();lR.initSync();var{CONFIG_PARAMS:iB}=L(),Ore=1024*1024*1024;function bre(e){let t=lR.get(iB.HTTP_TIMEOUT),r=lR.get(iB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Ore,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(bre,"getServerOptions");oB.exports=bre});var lB=T((qme,uB)=>{"use strict";var _R=Z();_R.initSync();var{CONFIG_PARAMS:cB}=L();function Nre(){let e=_R.get(cB.HTTP_CORSACCESSLIST),t=_R.get(cB.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(Nre,"getCORSOptions");uB.exports=Nre});var fB=T((Gme,dB)=>{"use strict";var _B=Z();_B.initSync();var yre=L();function wre(){return _B.get(yre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(wre,"getHeaderTimeoutConfig");dB.exports=wre});var fR={};Ye(fR,{customFunctionsServer:()=>Dre,ready:()=>IB,start:()=>Cre});function Cre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){Hn||(Hn=wB(t),tt.http((await Hn).server));let o=await Hn,c=(0,dR.dirname)(n),u=(0,dR.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!EB.has(c)){EB.add(c);try{o.register(Ure(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:IB}}async function Dre(){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 Lre();let e=gB.get(RB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Hn=await wB(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 Lre(){try{Ve.info("Custom Functions starting configuration."),await AB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function Ure(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,hB.existsSync)(e)&&r.register(TB.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 wB(e){Ve.info("Custom Functions starting buildServer.");let t=(0,OB.default)(e),r=(0,mB.default)(t);r.server.headersTimeout=(0,NB.default)(),r.setErrorHandler(yB.serverErrorHandler);let s=(0,bB.default)();return s&&r.register(pB.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(SB.default),await r.register(Ire),await r.after(),gg(r),Ve.info("Custom Functions completed buildServer."),r}function IB(){if(Hn)return Hn.then?Hn.then(e=>e.ready()):Hn.ready()}var dR,hB,mB,pB,SB,TB,gB,RB,Ve,Ire,AB,OB,bB,NB,yB,Hn,EB,CB=Re(()=>{dR=require("path"),hB=require("fs"),mB=x(require("fastify")),pB=x(require("@fastify/cors")),SB=x(Mg()),TB=x(require("@fastify/autoload")),gB=x(Z()),RB=x(L()),Ve=x(V()),Ire=x(nB()),AB=x(ts()),OB=x(aB()),bB=x(lB()),NB=x(fB()),yB=x(Wf());ga();tr();EB=new Set;a(Cre,"start");a(Dre,"customFunctionsServer");a(Lre,"setUp");a(Ure,"buildRouteFolder");a(wB,"buildServer");a(IB,"ready")});var ER={};Ye(ER,{start:()=>Mre});function Mre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,PB.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){LB||(LB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=DB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,UB.default)(n,(0,MB.realpathSync)(o))}}return i(n)},{runFirst:!0})),DB.set(r,s)}}}var UB,MB,PB,DB,LB,vB=Re(()=>{UB=x(require("send")),MB=require("fs"),PB=x(require("serve-static")),DB=new Map;a(Mre,"start")});function Bre(e,t=1,r){if(hR++,(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)});vre.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)qB[c.localPort](null,c)}}}),r){let s=setInterval(()=>{mR?mR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,bo.shutdownWorkers)(),hR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function FB(e=0,t){if(typeof e=="string")try{(0,jf.existsSync)(e)&&(0,jf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Hre:r=xre(t):r=SR;let s=(0,xa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=qB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),mR=!0,r(o,(c,u)=>{if(!c){if(BB){let l=o._socket||new xa.Socket({handle:o,writable:!0,readable:!0});BB.deliverSocket(l,e,u),l.resume()}else hR>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"),Bre(0));Br(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new xa.Socket({handle:o,writable:!0,readable:!0});kre(l,c,e)}Br(!0,"socket-routed")})};let n=Zc();pR.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 SR(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 Hre(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);SR(e,o=>{qa.set(s,{worker:o,lastUsed:i}),t(o)})}function xre(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);SR(s,d=>{qa.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function Fre(){Qf=0;for(let e of Ba)e.expectedIdle=e.recentELU.idle+qre,e.requests=1;Ba.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function kre(e,t,r){let s=Gre++;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,pR,jf,xB,Pre,Ba,Ha,qB,BB,hR,vre,mR,Qf,HB,qa,qre,zf,Gre,GB=Re(()=>{bo=x(Ke()),xa=require("net"),Jf=x(L()),pR=x(V()),jf=require("fs");bn();xB=require("worker_threads"),Pre=x(Wi()),Ba=[],Ha=[],qB=[],hR=0,vre=[];xB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Bre,"startHTTPWorker");a(FB,"startSocketServer");Qf=0;a(SR,"findMostIdleWorker");HB=36e5,qa=new Map;a(Hre,"findByRemoteAddressAffinity");a(xre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of qa)r.lastUsed+HB<e&&qa.delete(t)},HB).unref();qre=1e3;a(Fre,"updateWorkerIdleness");(0,bo.setMonitorListener)(Fre);zf=new Map,Gre=1;a(kre,"proxySocket")});var AR={};Ye(AR,{Request:()=>TR,createReuseportFd:()=>Xf});var kB,TR,gR,RR,Xf,Zf=Re(()=>{kB=require("os"),TR=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 RR(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 gR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},gR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},RR=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,kB.platform)()!="win32"&&(Xf=require("node-unix-socket").createReuseportFd)});var KB=T((rpe,YB)=>{"use strict";var Vre=require("cluster"),No=Z();No.initSync();var $B=L(),jme=require("util"),xn=V(),Xme=require("fs"),$re=require("fastify"),Zme=Zc(),Yre=require("@fastify/cors"),Kre=require("@fastify/compress"),Wre=require("@fastify/static"),Qre=Mg(),zre=require("path"),{PACKAGE_ROOT:Jre}=L(),jre=Tn(),Xre=J(),Zre=ts(),ese=Wi(),{server:tse}=(tr(),se(Mi)),{node_request_key:epe}=(Zf(),se(AR)),{authHandler:rse,handlePostRequest:sse,serverErrorHandler:nse,reqBodyValidationHandler:ise}=Wf(),tpe=require("net"),{registerContentHandlers:ose}=(ga(),se(Iv)),ase=6e4,cse=1024*1024*1024,use="TRUE",{CONFIG_PARAMS:al}=$B,Fa;YB.exports={hdbServer:VB,start:VB};async function VB(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=Vre.isMaster,await lse();let t=e.securePort>0;Fa=_se(t),await Fa.ready(),e||(e={}),e.isOperationsServer=!0;try{tse.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(VB,"operationsServer");async function lse(){xn.trace("Configuring HarperDB process."),jre.setSchemaDataToGlobal(),await Zre.setUsersToGlobal(),await ese.getLicense()}a(lse,"setUp");function _se(e){xn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=dse(e),r=$re(t);r.server.headersTimeout=Ese(),r.setErrorHandler(nse);let s=fse();s&&r.register(Yre,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Qre),r.register(Kre),r.register(Wre,{root:zre.join(Jre,"studio/build-local")}),ose(r);let n=No.get($B.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Xre.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[ise,rse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),sse(i,o)}),r.get("/health",()=>"HarperDB is running."),xn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(_se,"buildServer");function dse(e){let t=No.get(al.OPERATIONSAPI_NETWORK_TIMEOUT),r=No.get(al.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:cse,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(dse,"getServerOptions");function fse(){let e=No.get(al.OPERATIONSAPI_NETWORK_CORS),t=No.get(al.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===use)&&(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(fse,"getCORSOpts");function Ese(){return No.get(al.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??ase}a(Ese,"getHeaderTimeoutConfig")});var rH=T((ape,tH)=>{"use strict";var{decode:hse}=require("msgpackr"),{isMainThread:npe,parentPort:mse,threadId:ipe}=require("worker_threads"),bR=st(),qn=Ge(),pse=L(),Ni=V(),WB=Z(),zB=L();Ke();var Sse=Sn(),{recordAction:Tse,recordActionBinary:gse}=(bn(),se(su)),{publishToStream:Rse}=bR,{ConsumerEvents:Ase}=require("nats"),ope={durable:qn.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qn.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Ose,bse,Nse,JB,jB;tH.exports={initialize:NR,workQueueListener:eH,setSubscription:yse,setIgnoreOrigin:Ise,getDatabaseSubscriptions:wse};async function NR(){jB=!0,Ni.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await bR.getNATSReferences();Ose=e,bse=e.info.server_name,Nse=t,JB=r}a(NR,"initialize");var tE=new Map;function yse(e,t,r){let s=tE.get(e);s||tE.set(e,s=new Map),s.set(t,r),jB||NR().then(eH)}a(yse,"setSubscription");function wse(){return tE}a(wse,"getDatabaseSubscriptions");var XB;function Ise(e){XB=e}a(Ise,"setIgnoreOrigin");var ZB=100,QB=new Array(ZB),eE=0;async function eH(){let e=await JB.consumers.get(qn.WORK_QUEUE_CONSUMER_NAMES.stream_name,qn.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(mse?.on("message",async s=>{let{type:n}=s;n===zB.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===Ase.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 QB[eE],QB[eE]=Cse(s).catch(n=>{Ni.error(n)}),++eE>=ZB&&(eE=0)}catch(s){Ni.error("Error consuming clustering ingest, restarting consumer",s)}bR.clearClientCache(),await NR()}}a(eH,"workQueueListener");async function Cse(e){let t=hse(e.data);Tse(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,s=!1,n=WB.get(pse.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&&!XB),gse(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:OR(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:OR(o),value:P,expiresAt:E,id:d?.[H],table:_}));for(;u;)g.push({type:OR(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})}WB.get(zB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Rse(e.subject.split(".").slice(0,-1).join("."),Sse.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ni.error(o)}e.ack()}a(Cse,"messageProcessor");function OR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(OR,"convertOperation")});var LR={};Ye(LR,{disableNATS:()=>Lse,publishToStream:()=>oE,setNATSReplicator:()=>yR,setPublishToStream:()=>Use,setSubscription:()=>DR,start:()=>Dse});function Dse(){sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Pse()}function Lse(e=!0){aH=e}function Use(e,t){oE=e,DR=t}function Pse(){if(aH||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];yR(n,r,i)}}UR((r,s)=>{yR(r.tableName,r.databaseName,r),s&&uH(r)}),!sH&&(sH=!0)}function yR(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 Ht{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[De],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[De]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[De],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[De],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[De]})}static defineSchema(i){uH(i)}static subscribe(){let i=new Rs;return DR(t,e,i),i}static subscribeOnThisThread(i){return i<Mse}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=cH;return i}a(s,"getNATSTransaction")}function uH(e){let t=sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);oE(`${IR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,CR.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 nH,IR,CR,iH,oH,sE,nE,iE,aH,oE,DR,Mse,cH,sH,rE,wR,lH=Re(()=>{Ae();As();nH=x(st()),IR=x(Ge()),CR=x(Sn());Ec();iH=x(rH()),oH=x(br()),sE=x(Z()),nE=x(L()),iE=x(V());a(Dse,"start");a(Lse,"disableNATS");oE=nH.publishToStream,DR=iH.setSubscription;a(Use,"setPublishToStream");Mse=2;a(Pse,"assignReplicationSource");a(yR,"setNATSReplicator");a(uH,"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(`${IR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,CR.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)}},wR=class extends rE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,oH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};cH=new wR});var OH=T(yo=>{"use strict";var{isMainThread:vse,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:_H,existsSync:Gse}=require("fs"),Vr=V(),He=Z(),Jt=L(),{server:lE}=(tr(),se(Mi)),{WebSocketServer:kse}=require("ws"),{createServer:Vse}=require("tls"),{getTicketKeys:$se,restartNumber:Yse,getWorkerIndex:vR}=Ke(),{Headers:mH,appendHeader:Kse}=(Bu(),se(XM)),{recordAction:cl,recordActionBinary:Wse}=(bn(),se(su)),{Request:pH,createReuseportFd:dH}=(Zf(),se(AR)),{checkMemoryLimit:Qse}=Wi(),SH=require("tls"),fH=SH.createSecureContext;SH.createSecureContext=function(e){if(!e.cert||!e.key)return fH(e);let t={...e};delete t.key,delete t.cert;let r=fH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var MR=He.get(Jt.CONFIG_PARAMS.THREADS_DEBUG);if(MR){let e=(typeof MR=="number"?MR:9229)+(vR()??-1)+1;try{require("inspector").open(e)}catch(t){Vr.trace(`Could not start debugging on port ${e}, you may already be debugging:`,t.message)}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){Yse<=1&&Vr.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}=Jt;He.initSync();var Jse=He.get(zse.HTTP_SESSIONAFFINITY),un={};yo.registerServer=qR;yo.httpServer=FR;yo.deliverSocket=xR;yo.startServers=TH;yo.when_components_loaded=null;lE.http=FR;lE.request=ene;lE.socket=tne;lE.ws=rne;var PR={},cE={},jse,yi={},uE={},Xse=[],BR=[];function TH(){return yo.when_components_loaded=GR().loadRootComponents(!0).then(()=>{ul?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)xR(s,r,n);else if(t.requestId)Zse(t);else if(t.type===Jt.ITC_EVENT_TYPES.SHUTDOWN){Vr.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?Vr.info(`Closing ${E.length} idle connections`):f&&Vr.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(
|
|
30
|
-
`)}a(hH,"defaultNotFound")});async function wH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await kR.getResource(e,{});n=new YR(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await kR.get(e);i&&i.delete()}n=new dE(e,t)}return s&&(s.id=e,s.user={username:t?.username},ll.put(s)),n}function VR(){return _E++,_E>65500&&(_E=1),_E}function $R(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 bH,wi,NH,yH,kR,ll,_E,dE,YR,IH=Re(()=>{Ae();vu();bH=x(br()),wi=x(V());Zi();NH=x(Ke()),yH=x(OH());tr();kR=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,NH.getWorkerIndex)()===0&&(async()=>{await yH.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{$R(r,t)}catch{(0,wi.warn)("Failed to publish will",t)}ll.delete(e.id,r)})}})();a(wH,"getSession");_E=1;a(VR,"getNextMessageId");dE=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=VR());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=VR();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,$R(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 $R(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($R,"publish");YR=class extends dE{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=VR(),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,bH.getNextMonotonicTime)()),(0,wi.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),kR.put(this.sessionRecord)),t.qos}}});var KR={};Ye(KR,{bypassAuth:()=>sne,start:()=>nne});function sne(){MH=!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}=LH(_,(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,gr.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,gr.error)(E)}else if(u.required)return(0,gr.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&MH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,UH.getSuperUser)());let{onMessage:d,onClose:f}=LH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,gr.info)("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function LH(e,t,r,s,n){DH||(DH=!0,ru(d=>{fE>0&&d.push({metric:"mqtt-connections",connections:fE,byThread:!0})}));let i;fE++;let o,c={protocolVersion:4},u=(0,hE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){fE--,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,EE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&CH.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,EE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&CH.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=wH({user:s,...d}),o=await o,n.sessions.add(o)}catch(g){return(0,gr.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,gr.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,gr.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,gr.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,gr.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,hE.generate)(h,c);t(S),Br(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 hE,UH,EE,ln,gr,CH,MH,DH,fE,PH=Re(()=>{hE=require("mqtt-packet");IH();UH=x(ts());ga();bn();tr();EE=x(Z()),ln=x(L()),gr=x(V()),CH=(0,gr.loggerWithTag)("auth-event"),MH=(0,EE.get)(ln.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(sne,"bypassAuth");a(nne,"start");fE=0;a(LH,"onSocket")});var af={};Ye(af,{component_errors:()=>Va,loadComponent:()=>mE,loadComponentDirectories:()=>VH,setErrorReporter:()=>cne});function VH(e,t){t&&(QR=t),e&&(zR=e);let r=[];if((0,Hs.existsSync)(WR)){let n=(0,Hs.readdirSync)(WR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Tt.join)(WR,o);r.push(mE(c,QR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(mE(s,QR,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{kH=!0})}function cne(e){dl=e}async function mE(e,t,r,s,n,i){if(!BH.has(e)){BH.set(e,!0),n&&(zR=n);try{let o;s&&(Va=new Map);let c=(0,Tt.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Hs.existsSync)(c)?o=s?(0,GH.getConfigObj)():(0,HH.parseDocument)((0,Hs.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=JR;let u=[],_=s;for(let l in o){let d=o[l];if(Va.set(s?l:(0,Tt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let R=e,g;for(;!(0,Hs.existsSync)(g=(0,Tt.join)(R,"node_modules",l));)if(R=(0,Tt.dirname)(R),R.length<(0,FH.getHdbBasePath)().length){g=null;break}if(g)f=await mE(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&&!vH.includes(R)){let g=jR.get(XR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&_l.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!Xf)&&(vH.push(R),FB(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),zR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,qH.handleHDBError)("Can not reference parent directories");let R=(0,Tt.join)(e,d.files).replace(/\\/g,"/"),g=R.indexOf("/*");if(g>-1&&d.files!==JR[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,Tt.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,Tt.join)(e,z)}else(Y=R.indexOf("/*"))>-1&&(U=R.slice(0,Y+1),v=(0,Tt.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,xH.default)(R,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:me}=z;_=!0;let ce=(0,Tt.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,Tt.basename)(e),le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Tt.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,Tt.basename)(e),h.message)}}if(ka.isMainThread&&!kH&&i&&(0,$a.watchDir)(e,async()=>VH()),o.extensionModule)return await Ql((0,Tt.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,Tt.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,Tt,ka,HH,jR,XR,xH,$a,_l,qH,FH,ine,GH,one,WR,zR,kH,QR,Va,ane,JR,vH,BH,dl,fl,cf=Re(()=>{Hs=require("fs"),Tt=require("path"),ka=require("worker_threads"),HH=require("yaml"),jR=x(Z()),XR=x(L());XO();rb();sb();kv();CB();vB();xH=x(require("fast-glob")),$a=x(Ke()),_l=x(V());Nh();tr();qH=x(re());As();Ae();GB();FH=x(Z()),ine=x(KB());Xd();lH();PH();GH=x(Lr());Zf();({readFile:one}=Hs.promises),WR=jR.get(XR.CONFIG_PARAMS.COMPONENTSROOT),zR=new Map,Va=new Map;a(VH,"loadComponentDirectories");ane={REST:yf,rest:yf,graphqlSchema:bh,jsResource:wh,fastifyRoutes:fR,login:Ch,static:ER,operationsApi:ine,customFunctions:{},http:{},clustering:LR,authentication:Hu,mqtt:KR},JR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(JR,"static",{value:{files:"web/**"}});vH=[],BH=new Map;a(cne,"setErrorReporter");a(mE,"loadComponent");fl=class extends Ht{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 GR=T((Fpe,YH)=>{var{isMainThread:$H}=require("worker_threads"),{getTables:une}=(Ae(),se(Fe)),{loadComponentDirectories:lne,loadComponent:_ne}=(cf(),se(af)),{resetResources:dne}=(vu(),se(jM)),fne=WT(),Ene=Lr(),{dirname:hne}=require("path"),{getConnection:mne}=st(),pne=Z(),Sne=L(),ZR=new Map;async function Tne(e=!1){!$H&&pne.get(Sne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&mne();try{$H&&await fne()}catch(s){console.error(s)}let t=dne();une(),t.isWorker=e,await _ne(hne(Ene.getConfigFilePath()),t,"hdb",!0,ZR),await lne(ZR,t);let r=[];for(let[s]of ZR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Tne,"loadRootComponents");YH.exports.loadRootComponents=Tne});var Ke=T((kpe,Ci)=>{"use strict";var{Worker:gne,MessageChannel:Rne,parentPort:_n,isMainThread:nA,threadId:Ane,workerData:Fn}=require("worker_threads"),{PACKAGE_ROOT:One}=L(),{join:zH,isAbsolute:bne,extname:Nne}=require("path"),{server:JH}=(tr(),se(Mi)),{watch:yne,readdir:wne}=require("fs/promises"),{totalmem:KH}=require("os"),El=L(),jH=Z(),Gn=V(),{randomBytes:Ine}=require("crypto"),{_assignPackageExport:Cne}=require("../index"),Dne=L(),WH=1024*1024,Ii=[],ds=[],Lne=50,iA=1e4,Une="restart",XH="request_thread_info",ZH="resource_report",ex="thread_info",tx="added-port",Mne="ack",eA;Cne("threads",ds);Ci.exports={startWorker:tA,restartWorkers:aA,shutdownWorkers:xne,workers:Ii,setMonitorListener:Kne,onMessageFromWorkers:qne,onMessageByType:cx,broadcast:Gne,broadcastWithAcknowledgement:Vne,setChildListenerByType:Hne,getWorkerIndex:rx,getWorkerCount:sx,getTicketKeys:ix,setMainIsWorker:vne,setTerminateTimeout:Pne,restartNumber:Fn?.restartNumber||1};ds.onMessageByType=cx;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 oA;function Pne(e){iA=e}a(Pne,"setTerminateTimeout");function rx(){return Fn?Fn.workerIndex:oA?0:void 0}a(rx,"getWorkerIndex");function sx(){return Fn?Fn.workerCount:oA?1:void 0}a(sx,"getWorkerCount");function vne(e){oA=e}a(vne,"setMainIsWorker");var nx=1,pE;function ix(){return pE||(pE=nA?Ine(48):Fn.ticketKeys,pE)}a(ix,"getTicketKeys");Object.defineProperty(JH,"workerIndex",{get(){return rx()}});Object.defineProperty(JH,"workerCount",{get(){return sx()}});var ox={[XH](e,t){$ne(t)},[ZH](e,t){Yne(t,e)}};function tA(e,t={}){let r=process.constrainedMemory?.()||KH();r=Math.min(r,KH(),2e4*WH);let s=jH.get(El.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/WH/(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:zH(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:nx=t.threadCount,name:t.name,restartNumber:Ci.exports.restartNumber,ticketKeys:ix()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:tx,port:u,threadId:c.threadId},[u]);return TE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>tA(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,tA(e,t)):Gn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{ox[u.type]?.(u,c)}),Ii.push(c),Qne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(tA,"startWorker");var Bne=[El.THREAD_TYPES.HTTP];async function aA(e=null,t=Math.max(nx>3,1),r=!0){if(nA){if(r){let{loadRootComponents:o}=GR();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(),iA*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)&&jH.get(El.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else _n.postMessage({type:Une,workerType:e})}a(aA,"restartWorkers");function Hne(e,t){ox[e]=t}a(Hne,"setChildListenerByType");function xne(e){return aA(e,1/0,!1)}a(xne,"shutdownWorkers");var ax=[];function qne(e){ax.push(e)}a(qne,"onMessageFromWorkers");var rA=new Map;function cx(e,t){let r=rA.get(e);r||rA.set(e,r=[]),r.push(t)}a(cx,"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 SE=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(()=>{SE.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,SE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of SE)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:ex,workers:ux()})}a($ne,"sendThreadInfo");function ux(){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(ux,"getChildWorkerInfo");function Yne(e,t){e.resources=t,e.resources.updated=Date.now()}a(Yne,"recordResourceReport");var sA;function Kne(e){sA=e}a(Kne,"setMonitorListener");var Wne=1e3,QH=!1;function Qne(){QH||(QH=!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}sA&&sA()},Wne).unref())}a(Qne,"startMonitoring");var zne=1e3;if(_n){TE(_n);for(let e=0,t=Fn.addPorts.length;e<t;e++){let r=Fn.addPorts[e];r.threadId=Fn.addThreadIds[e],TE(r)}setInterval(()=>{let e=process.memoryUsage();_n.postMessage({type:ZH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},zne).unref(),eA=a(()=>new Promise((e,t)=>{_n.on("message",r),_n.postMessage({type:XH});function r(s){s.type===ex&&(_n.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else eA=ux;Ci.exports.getThreadInfo=eA;function TE(e,t){ds.push(e),e.on("message",r=>{if(r.type===tx)r.port.threadId=r.threadId,TE(r.port);else if(r.type===Mne){let s=SE.get(r.id);s&&s()}else{for(let n of ax)n(r,e);let s=rA.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(TE,"addPort");if(nA){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(zH(s,i.name));try{for await(let{filename:i}of yne(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await aA(),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)},iA).unref())})});var cC={};Ye(cC,{AUDIT_STORE_OPTIONS:()=>Tx,createAuditEntry:()=>Zl,openAuditStore:()=>OE,readAuditEntry:()=>Ct,setAuditRetention:()=>jne,transactionKeyEncoder:()=>Sx});function OE(e){let t=e.auditStore=e.openDB(hx.AUDIT_STORE_NAME,Tx);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=gE){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()-cA})){if((_[0]&15)===_A){let l=Ct(_),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,cA/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,AE.getWorkerIndex)()===(0,AE.getWorkerCount)()-1&&n(gE),t}function jne(e,t=gE){cA=e,gE=t}function Zl(e,t,r,s,n,i,o){let c=gx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?Ya.setFloat64(0,s):Es.set(Kh),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?(fA.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 Ct(e){try{let t=e.dataView||(e.dataView=new dA(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:gx[s&7],tableId:i,get recordId(){return Ex(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Ex(e,l,d):void 0},getValue(f,E,h){if(s&uA||s&lA&&!E)return f.decoder.decode(e.subarray(t.position));if(s&lA&&h)return EA(f.getEntry(this.recordId),h,f)}}}catch{return fA.error("Reading audit entry error",e),{}}}function Ex(e,t,r){let s=e.subarray(t,r);return(0,Ka.readKey)(s,0,r-t)}var Ka,RE,hx,mx,AE,px,fA,Es,Ya,Sx,Tx,cA,Jne,gE,uA,lA,lx,_A,_x,dx,fx,gx,dA,Bi=Re(()=>{Ka=require("ordered-binary"),RE=x(Z()),hx=x(dt()),mx=x(L()),AE=x(Ke()),px=x(J());qo();fA=x(V());bE();(0,RE.initSync)();Es=Buffer.alloc(1024),Ya=new DataView(Es.buffer,Es.byteOffset,1024),Sx={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)}},Tx={encoding:"binary",keyEncoder:Sx},cA=(0,px.convertToMS)((0,RE.get)(mx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Jne=1e3,gE=1e4;a(OE,"openAuditStore");a(jne,"setAuditRetention");uA=16,lA=32,lx=1,_A=2,_x=3,dx=4,fx=5,gx={put:lx|uA,[lx]:"put",delete:_A,[_A]:"delete",message:_x|uA,[_x]:"message",invalidate:dx,[dx]:"invalidate",patch:fx|lA,[fx]:"patch"};a(Zl,"createAuditEntry");a(Ct,"readAuditEntry");dA=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(Ex,"readKeySafely")});var hA={};Ye(hA,{add:()=>NE,applyReverse:()=>Rx,getRecordAtTime:()=>EA,rebuildUpdateBefore:()=>yE});function NE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function yE(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,NE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function Rx(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]=Ax}}function EA(e,t,r){let s=r.rootStore.auditStore,n=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=s.get(i),_=Ct(u);switch(_.type){case"put":n=_.getValue(r);break;case"patch":Rx(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===Ax&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=s.get(i),_=Ct(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,Ax,bE=Re(()=>{Bi();a(NE,"add");NE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Xne={add:NE};a(yE,"rebuildUpdateBefore");a(Rx,"applyReverse");Ax={};a(EA,"getRecordAtTime")});function $r(e){return e[wt]||(e[wt]=Object.create(null))}function LE(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[wt];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=bx(d,o);if(f)return l||(l=this[wt]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,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[wt];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[wt],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 bx(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}},LE(r,t)),new r(e)):new wE(e);case Array:let s=new CE(e.length);s[de]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=bx(o,t?.elements)),s[n]=o}return s;default:return e}}function z_(e){let t=e[wt],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[wt]){let r;if(Ox.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=hA[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):Ox.call(e,de)?e[de]:e}function IE(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(IE(i))return!0}else return!0}}else{let r=e[wt];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(IE(n))return!0}else return!0}else return!0}}return!1}var hs,wt,wE,Ox,wo,CE,DE,J_=Re(()=>{As();hs=x(re());bE();wt=Symbol("own-data");a($r,"getChanges");a(LE,"assignTrackedAccessors");a(bx,"trackObject");wE=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}};LE(wE,{});a(z_,"collapseData");Ox=Object.prototype.hasOwnProperty;a(Io,"deepFreeze");a(IE,"hasChanges");wo=Symbol.for("has-array-changes"),CE=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()}};CE.prototype.constructor=Array;DE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Ap={};Ye(Ap,{CONTEXT:()=>Oe,ID_PROPERTY:()=>De,IS_COLLECTION:()=>ms,RECORD_PROPERTY:()=>de,Resource:()=>Ht,snake_case:()=>eie,transformForSelect:()=>ME});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 Nx(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 pA;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[De]??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 UE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new UE(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 Ix.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 mA(e,t,r){let s=e[de];if(s){let n=e[wt];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 ME(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):mA(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(mA(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(mA(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]=ME(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var yx,wx,Ix,Oe,De,ms,de,Zne,Ht,UE,hl,pA,As=Re(()=>{yx=require("crypto");Ec();wx=require("../index"),Ix=x(re());J_();Zi();bf();Oe=Symbol.for("context"),De=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"},Ht=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[De]=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 _=ME(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,yx.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[De]!=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[De]!=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=ME(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[De],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:Nx(t,this),isCollection:hl}}let i=Nx(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(_=>_[De]===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[De],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[De]}getContext(){return this[Oe]}};Ht.prototype[Oe]=null;(0,wx._assignPackageExport)("Resource",Ht);a(eie,"snake_case");UE=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(Nx,"pathToId");pA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Yr,"transactional");a(Kr,"missingMethod");a(mA,"selectFromObject");a(ME,"transformForSelect")});function Dx(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;Wa||((0,PE.onMessageByType)(Cx,l=>{Lx(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 TA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function Lx(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=Ct(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,SA.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,SA.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 Ux(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,PE.broadcast)({type:Cx,path:n}),Lx(n,!0)})}}var SA,PE,Cx,Wa,lSe,TA,Mx=Re(()=>{SA=x(V()),PE=x(Ke());Ec();vu();Bi();Cx="transaction",lSe=Buffer.alloc(4096);a(Dx,"addSubscription");TA=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(Lx,"notifyFromTransactionData");a(Ux,"listenToCommits")});var Jg={};Ye(Jg,{coerceType:()=>vE,makeTable:()=>xE,setServerUtilities:()=>uie,updateResource:()=>BE});function xE(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=[]),Ux(i,u);let S=zh(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={},It=864e5,Ul,Ml,$n,FA=!1,th,Hq=i.getRange({start:!1,end:!1}).constructor,xq=10,qq=6;E&&VA();class ze extends Ht{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 Ue of F.writes)try{ee.push(y(Ue,F))}catch(oe){throw oe.message+=" writing "+JSON.stringify(Ue)+" of event "+JSON.stringify(F),oe}return Promise.all(ee)}else if(F.type==="define_schema"){let ee=this.attributes.slice(0),Ue;for(let oe of F.attributes)ee.find(qe=>qe.name===oe.name)||(ee.push(oe),Ue=!0);Ue&&(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(ie){Ze.error("error in subscription handler",ie)}}}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 rh(m,O,{transaction:y},b,M=>{if(M?BE(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=sh(m,M,O,N);if(G)return D?.disregardReadTxn(),N[gA]=!0,AA(G,C=>(BE(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=sh(this[De],this[Wr],this[Oe]);if(m)return this[gA]=!0,AA(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,It=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");It=It||(d+f)/4,ih()}static enableAuditing(m=!0){E=m,m&&VA(),ze.audit=m}static coerceId(m){return m===""?null:vE(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[De]===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||FA&&b){if(O||(O={}),b){let D=N?.length>0&&RA(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=RA(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=RA(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[wt]=m):(N=this[wt],N&&(m=Object.assign(N,m)),this[wt]=N=m)),this._writeUpdate(this[wt],O),this}addTo(m,O){if(typeof O=="number")this[ml]===vx?this.set(m,(+this.getProperty(m)||0)+O):(this[ml]||this.update(),this.set(m,new DE(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[De];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,Gx.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[De];Za(D);let y=this[Wr];this[ml]=O?vx:oie;let M={key:D,store:i,entry:y,nodeName:N?.nodeName,validate:G=>{m||(m=this[wt]),O||m&&IE(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[wt]=m,this[gl]=G;let F=C?.value,ie=m;if(this[ml]=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=Ct(te);if(qe=j.version,qe>G){if(j.type==="patch"){let ge=j.getValue(i);ie=yE(ie,ge)}else if(j.type==="put"||j.type==="delete")return}else if(qe===G)return;oe=j.previousLocalTime}}else{if(O)return;ie=yE(ie,F)}let be;if(O?be=ie:(this[de]=F,be=O?ie:Io(this,ie)),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 Ue=O?"put":"patch";S(D,be,C,G,0,E,N,N.expiresAt||(d?d+Date.now():0),Ue,!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[De];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),BE(this,D)),!(D?.version>b)&&(Pl(this[De],M),Ze.trace("Write delete entry",w,b),E||h?(S(w,null,this[Wr],b,0,E,this[Oe],0,"delete"),E||ih()):i.remove(this[De]))}}),!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[De]&&(N=[{attribute:null,comparator:"prefix",value:this[De]}].concat(N));let b,D={};function y(j,ge){let ve;switch(ge){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');ve=!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=ve&&{},Yn;for(let $e of j){if($e.conditions){$e.conditions=y($e.conditions,$e.operator);continue}let vt=$e[0]??$e.attribute,jr=vt==null?P:Pn(p,vt);if(jr){if(ve){let Gs=Ps(vt),Bt=Fs[Gs];Bt?(Bt.push($e),Yn=!0):Fs[Gs]=[$e]}(jr.type||Ag[$e.comparator])&&($e[1]===void 0?$e.value=G($e.value,jr):$e[1]=G($e[1],jr))}else if(vt!=null)throw(0,ps.handleHDBError)(new Error,`${vt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(Yn)for(let $e in Fs){let vt=Fs[$e],jr=vt.length;if(jr>1)for(let Gs=0;Gs<jr;Gs++){let Bt=vt[Gs];if(Bt.comparator==="ge"||Bt.comparator==="greater_than_equal")for(let Kn=0;Kn<jr;Kn++){let Po=vt[Kn];(Po.comparator==="le"||Po.comparator==="less_than_equal")&&(Bt.comparator="between",Bt.value=[Bt.value,Po.value],j.splice(j.indexOf(Po),1))}if(Bt.comparator==="equals"||!Bt.comparator){for(let Kn=0;Kn<jr;Kn++)if(Kn!==Gs){let Po=vt[Kn];j.splice(j.indexOf(Po),1)}break}}}return j}a(y,"prepareConditions");function M(j,ge){if(m.enforceExecutionOrder)return j;for(let ve of j)ve.conditions&&(ve.conditions=M(ve.conditions,ve.operator));return j.length>1&&ge!=="or"?(0,Fx.sortBy)(j,Af(ze)):j}a(M,"orderConditions");function G(j,ge){return Array.isArray(j)?j.map(ve=>vE(ve,ge)):vE(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 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=Og(N,C,ze,be,m,O,(j,ge)=>GA(j,ie,O,be,ge),D),Ue=m.ensureLoaded!==!1;F||(ee=te(ee));let oe=ze.transformEntryForSelect(ie,O,be,D,Ue,!0),qe=ze.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 ge of ie)ge==="*"?j.push(...p.map(ve=>ve.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 Hq;if(w){m=GA(m,O,N,b,null);let M;y.iterate=function(){let C,B=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),F,ie=w.dbOrderedAttribute,be,ee,Ue=!0;function oe(te){let j=te.next&&oe(te.next),ge=te.descending;return(ve,Fs)=>{let Yn=nh(ve,te.attribute,N),$e=nh(Fs,te.attribute,N),vt=ge?(0,Lo.compareKeys)($e,Yn):(0,Lo.compareKeys)(Yn,$e);return vt===0?j?.(ve,Fs)||0:vt}}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)};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),ie){let ge=nh(j,ie,N);if(Ue)Ue=!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],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&&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(th=C,B=C.value||C.deref?.(),!B&&(C.key===void 0||C.deref)){if(C=rh(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=sh(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,ie=a((ee,Ue)=>{let oe;typeof ee=="object"?oe=ee.name:oe=ee;let qe=$n?.[oe],te;if(qe){let j=N?.[oe];if(j)if(j.hasMappings){let ve=qe.from?B[qe.from]:Ps(C.key);te=j.get(ve),te||(te=[])}else te=j.fromRecord?.(B);else te=qe(B,O,C);let ge=a(ve=>{if(ve&&typeof ve=="object"){let Fs=qe.definition?.tableClass||ze;M||(M={});let Yn=M[oe]||(M[oe]=Fs.transformEntryForSelect(oe===ee?null:ee.select||(Array.isArray(ee)?ee:null),O,w,j,b));if(Array.isArray(ve)){let $e=[],vt=Fs.transformToOrderedSelect(ve,ee.select,typeof ee.sort=="object"&&ee.sort,O,w,Yn)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),jr=a(Bt=>{for(;!Bt.done;){if(Bt?.then)return Bt.then(jr);$e.push(Bt.value),Bt=vt.next()}Ue($e,oe)},"nextValue"),Gs=jr(vt.next());Gs&&(F||(F=[]),F.push(Gs));return}else if(ve=Yn.call(this,ve),ve?.then){F||(F=[]),F.push(ve.then($e=>Ue($e,oe)));return}}Ue(ve,oe)},"handleResolvedValue");te?.then?(F||(F=[]),F.push(te.then(ge))):ge(te);return}else te=B[oe],te&&typeof te=="object"&&oe!==ee&&(te=ze.transformEntryForSelect(ee.select||ee,O,w,null)({value:te}));Ue(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,Ue)=>{ee==="*"?m[Ue]=B:ie(ee,oe=>be[Ue]=oe)});else{be={};let ee=m.forceNulls;for(let Ue of m)if(Ue==="*")for(let oe in B)be[oe]=B[oe];else ie(Ue,(oe,qe)=>{oe===void 0&&ee&&(oe=null),be[qe]=oe})}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=Dx(ze,this[De]??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[De],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=Ct(M);if(G.tableId!==s)continue;let C=G.recordId;(N==null||xx(N,C))&&w.send({id:C,timestamp:y,...G}),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=Ct(G);if(C.tableId!==s)continue;let B=C.recordId;if(N==null||xx(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,version:G,timestamp:C,value:M})}else{b&&!D&&(D=0);let y=this[Wr]?.localTime;if(y===Qh&&(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=Ct(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,version:this[gl],timestamp:y,value:this})}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[De]||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&&ih(),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[gA]: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:Ue}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Ue!=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),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(){$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)"),FA=!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(qx)):G.filter(qx):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[De]||y[w.tableClass.primaryKey]);N[O.from]=D}else{let D=b[De]||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`)}LE(this,this)}static async deleteHistory(m=0){let O;for(let{key:w,value:N}of u.getRange({start:0,end:m}))await Tl(),Ct(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=Ct(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=Ct(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 Fq=ze.prototype;return Fq[iie]=!0,d&&ze.setTTLExpiration(d/1e3),Y&&Gq(),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){Px&&b.prefetch(C.map(B=>({key:B,value:W})),Hx);for(let B=0,F=C.length;B<F;B++)b.remove(C[B],W)}if(C=(0,Rl.getIndexedValues)(y,G),C){Px&&b.prefetch(C.map(B=>({key:B,value:W})),Hx);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>Bx)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)>Bx)throw new Error("Primary key size is too large: "+W.length);return!0}a(Za,"checkValidId");function rh(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>qq&&(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<xq&&ce++}a(M,"prefetch");function G(){try{D(b())}catch(C){y(C)}}a(G,"load")})}a(rh,"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 sh(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=kA(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(sh,"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 nh(W,m,O){if(!W)return;th=W;let w=W.value||W.deref?.()||(th=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(nh,"getAttributeValue");function GA(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 ie=N[B].idFilter;if(ie){if(!ie(C))return Co.SKIP;y||(y=[]),y.push(B)}}return rh(C,O,D,!1,M)});return Array.isArray(W)&&(G=G.filter(C=>C!==Co.SKIP)),G.hasEntries=!0,G}return W}a(GA,"transformToEntries");async function kA(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(kA(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;AA(Xe(M,async ie=>{let be=performance.now(),ee,Ue,oe;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;oe=w&pl;let te=M.lastModified||oe&&N;Ue=oe||te>N||!y,te||(te=(0,Rl.getNextMonotonicTime)());let j=performance.now()-be;if(Br(j,"cache-resolution",n),G&&$T(G,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),ie.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&&Ue||null,M,M.expiresAt,"put",!!oe)):(le.delete?.(M,W),E||h?S(W,null,j,te,0,E&&Ue||null,M,0,"delete",!!oe):i.remove(W,N))}})}),()=>{i.unlock(W,N)},ie=>{i.unlock(W,N),F&&Ze.error("Error committing cache update",ie)})})}a(kA,"getFromSource");function ih(){if(It!==Ul&&(Ul=It,(0,Do.getWorkerIndex)()===(0,Do.getWorkerCount)()-1)){if(Ml&&clearTimeout(Ml),!It)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())/It)*It+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+It,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(ie=>{Ze.error("Cleanup error",ie)}),++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(ih,"scheduleCleanup");function VA(){K=u?.addDeleteRemovalCallback(s,W=>{let m=i.getEntry(W);m?.value===null&&i.remove(W,m.version)})}a(VA,"addDeleteRemoval");function Gq(){(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(Gq,"runRecordExpirationEviction")}function RA(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 Hx(){}function uie(e){Gx=e}function vE(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,HE.autoCast)(e):e}function xx(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 AA(e,t,r){return e?.then?e.then(t,r):t(e)}function BE(e,t){e[Wr]=t,e[de]=t?.value??null,e[gl]=t?.version}function qx(e){return e!=null}function xs(e){try{return JSON.stringify(e)}catch{return e}}var qs,Co,Rl,Fx,bl,ps,Al,Ol,Ze,Lo,Do,HE,tie,Gx,rie,sie,Px,nie,gl,iie,Wr,ml,vx,oie,gA,Qa,pl,Sl,aie,Bx,cie,ISe,lie,Tl,xf=Re(()=>{qs=x(L()),Co=require("lmdb"),Rl=x(br()),Fx=require("lodash");As();Vp();bl=x(Z());Mx();ps=x(re()),Al=x(gn()),Ol=x(Is());Ae();bf();Ze=x(V());J_();Zi();Lo=require("ordered-binary"),Do=x(Ke());Bi();HE=x(J());qo();bn();bE();Bu();tie=new Uint8Array(9);tie[8]=192;rie=6e4,sie=864e5;bl.initSync();Px=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"),vx=1,oie=2,gA=Symbol("loaded-from-source"),Qa={isNotification:!0,ensureLoaded:!1},pl=1,Sl=8,aie=Buffer.allocUnsafeSlow(8192),Bx=1978,cie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},ISe=(0,HE.convertToMS)(bl.get(qs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(xE,"makeTable");a(RA,"attributesAsObject");a(Hx,"noop");a(uie,"setServerUtilities");lie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(vE,"coerceType");a(xx,"isDescendantId");Tl=a(()=>new Promise(setImmediate),"rest");a(AA,"when");a(BE,"updateResource");a(qx,"exists");a(xs,"stringify")});var Fe={};Ye(Fe,{database:()=>zc,databases:()=>rt,dropDatabase:()=>Qp,dropTableMeta:()=>mie,getDatabases:()=>Ds,getTables:()=>_ie,onUpdatedTable:()=>UR,readMetaDb:()=>Nl,resetDatabases:()=>die,table:()=>ct,tables:()=>Nr});function _ie(){return VE||Ds(),Nr||{}}function Ds(){if(VE)return rt;VE=!0,ja=new Map;let e=(0,jt.getHdbBasePath)()&&(0,et.join)((0,jt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),t=(0,jt.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,jt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Qr.existsSync)(e)?e:(0,et.join)((0,jt.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 Nr)delete Nr[n];delete Nr[$E]}}return ja=null,rt}}function die(){VE=!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=NA,s,n){let i=new OA.default(e,!1);try{let o=Di.get(e);o?o.needsDeletion=!1:(o=(0,FE.open)(i),Di.set(e,o));let c=new Uo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(qE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,Qr.existsSync)(s)&&(i.path=s,_=(0,FE.open)(i),_.isLegacy=!0):_=OE(o));let l=Yx(r),d=l[$E],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,jt.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=Kx(l,E,xE({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 yA)z(A)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Yx(e){let t=rt[e];if(t||(e==="data"?t=rt[e]=Nr: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[$E]=r,ja.set(e,r)}return t}function Kx(e,t,r){return e[t]=r,r}function zc({database:e,table:t}){e||(e=NA),Ds();let r=Yx(e),s=(0,et.join)((0,jt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),n=(0,jt.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,jt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||((0,Qr.existsSync)(s)?s:(0,et.join)((0,jt.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 OA.default(o,!1);c=(0,FE.open)(u),Di.set(o,c)}return c}async function Qp(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 kx.remove(n.path))}if(e==="data"){for(let r in Nr)delete Nr[r];delete Nr[$E]}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=NA);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=OE(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,jt.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(qE.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=Kx(d,e,xE({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(qE.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&&GE.signalSchemaChange(new kE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,R)for(let U of yA)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 GE.signalSchemaChange(new kE.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,Vx.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!==$x.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 GE.signalSchemaChange(new kE.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 UR(e){yA.push(e)}var jt,qE,FE,et,Qr,Ja,Uo,OA,zr,kx,bA,Vx,GE,kE,yl,Ss,$x,NA,$E,Nr,rt,za,yA,VE,Di,ja,fie,Eie,Ae=Re(()=>{jt=x(Z()),qE=x(dt()),FE=require("lmdb"),et=require("path"),Qr=require("fs"),Ja=x(Je());xf();Uo=x(r_()),OA=x(n_()),zr=x(L()),kx=x(require("fs-extra")),bA=require("../index"),Vx=x(br()),GE=x(gn()),kE=x(Is()),yl=require("worker_threads"),Ss=x(V()),$x=x(Ke());Bi();qo();NA="data",$E=Symbol("defined-tables");(0,jt.initSync)();Nr=Object.create(null),rt=Object.create(null);(0,bA._assignPackageExport)("databases",rt);(0,bA._assignPackageExport)("tables",Nr);za=Symbol.for("next-table-id"),yA=[],Di=new Map;a(_ie,"getTables");a(Ds,"getDatabases");a(die,"resetDatabases");a(Nl,"readMetaDb");a(Yx,"ensureDB");a(Kx,"setTable");a(zc,"database");a(Qp,"dropDatabase");a(ct,"table");fie=1e3,Eie=10;a(hie,"runIndexing");a(mie,"dropTableMeta");a(UR,"onUpdatedTable")});var J=T((HSe,oq)=>{"use strict";var Li=require("path"),jx=require("fs-extra"),Rr=V(),Wx=require("fs-extra"),YE=require("os"),pie=require("net"),Sie=require("recursive-iterator"),at=L(),Tie=AO(),Qx=require("papaparse"),KE=require("moment"),{inspect:gie}=require("util"),zx=require("is-number"),BSe=require("lodash"),Rie=require("minimist"),Aie=require("https"),Oie=require("http"),{hdb_errors:WE}=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)))$/,Xx=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};oq.exports={isEmpty:Jr,isEmptyOrZeroLength:dn,arrayHasEmptyValues:Lie,arrayHasEmptyOrZeroLengthValues:Uie,buildFolderPath:Mie,isBoolean:Zx,errorizeMessage:Cie,stripFileExtension:vie,autoCast:Bie,autoCastJSON:eq,autoCastJSONDeep:IA,removeDir:Hie,compareVersions:xie,isCompatibleDataVersion:qie,escapeRawValue:Fie,unescapeValue:Gie,stringifyProps:kie,timeoutPromise:$ie,isClusterOperation:Kie,getClusterUser:Qie,checkGlobalSchemaTable:Wie,getHomeDir:rq,getPropsFilePath:Vie,promisifyPapaParse:zie,removeBOM:sq,createEventPromise:Jie,checkProcessRunning:jie,checkSchemaTableExist:Xie,checkSchemaExists:nq,checkTableExists:iq,getStartOfTomorrowInSeconds:Zie,getLimitKey:eoe,isObject:Pie,isNotEmptyAndHasValue:Die,autoCasterIsNumberCheck:tq,backtickASTSchemaItems:toe,isPortTaken:Yie,createForkArgs:roe,autoCastBoolean:soe,async_set_timeout:Xx,getTableHashAttribute:noe,doesSchemaExist:ioe,doesTableExist:ooe,stringifyObj:aoe,ms_to_time:coe,changeExtension:uoe,getEnvCliRootPath:CA,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===""||Zx(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 Zx(e){return Jr(e)?!1:e===!0||e===!1}a(Zx,"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]:tq(e)===!0?Number(e):bie.test(e)?new Date(e):e}a(Bie,"autoCast");function eq(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(eq,"autoCastJSON");function IA(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=IA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=IA(r);s!==r&&(e[t]=s)}return e}else return eq(e)}a(IA,"autoCastJSONDeep");function tq(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(tq,"autoCasterIsNumberCheck");async function Hie(e){if(dn(e))throw new Error(`Directory path: ${e} does not exist`);try{await Wx.emptyDir(e),await Wx.remove(e)}catch(t){throw Rr.error(`Error removing files in ${e} -- ${t}`),t}}a(Hie,"removeDir");function xie(e,t){if(dn(e)){Rr.info("Invalid current version sent as parameter.");return}if(dn(t)){Rr.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 Rr.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+YE.EOL}!dn(s)&&s[0]===";"?r+=" "+s+n+YE.EOL:dn(s)||(r+=s+"="+n+YE.EOL)}catch{Rr.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(kie,"stringifyProps");function rq(){let e;try{e=YE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(rq,"getHomeDir");function Vie(){let e=Li.join(rq(),at.HDB_HOME_DIR_NAME,at.BOOT_PROPS_FILE_NAME);return jx.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){Rr.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 WE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return WE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Wie,"checkGlobalSchemaTable");function Qie(e,t){if(Jr(t)){Rr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Jr(e)||dn(e)){Rr.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){Rr.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Rr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Qie,"getClusterUser");function zie(){Qx.parsePromise=function(e,t,r){return new Promise(function(s,n){Qx.parse(e,{header:!0,transformHeader:sq,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(zie,"promisifyPapaParse");function sq(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(sq,"removeBOM");function Jie(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Rr.info(`Got cluster status event response: ${gie(n)}`);try{i.cancel()}catch{Rr.error("Error trying to cancel timeout.")}s(n)})})}a(Jie,"createEventPromise");async function jie(e){let t=!0,r=0;do await Xx(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=nq(e);if(r)return r;let s=iq(e,t);if(s)return s}a(Xie,"checkSchemaTableExist");function nq(e){let{getDatabases:t}=(Ae(),se(Fe));if(!t()[e])return WE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(nq,"checkSchemaExists");function iq(e,t){let{getDatabases:r}=(Ae(),se(Fe));if(!r()[e][t])return WE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(iq,"checkTableExists");function Zie(){let e=KE().utc().add(1,at.MOMENT_DAYS_TAG).startOf(at.MOMENT_DAYS_TAG).unix(),t=KE().utc().unix();return e-t}a(Zie,"getStartOfTomorrowInSeconds");function eoe(){return KE().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){Rr.error("Got an error back ticking items."),Rr.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=KE.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 CA(){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(CA,"getEnvCliRootPath");var wA;function loe(){if(wA)return wA;let e=CA();CA()&&jx.pathExistsSync(Li.join(e,at.HDB_CONFIG_FILE))&&(wA=!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,lq)=>{"use strict";var DA=require("fs-extra"),Mo=require("path"),aq=require("os"),Eoe=require("properties-reader"),Il=V(),wl=J(),ue=L(),QE=Lr(),hoe="Error initializing environment manager",zE="BOOT_PROPS_FILE_PATH",cq=!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={};lq.exports={BOOT_PROPS_FILE_PATH:zE,getHdbBasePath:poe,setHdbBasePath:Soe,get:uq,initSync:goe,setProperty:Le,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 uq(e){let t=QE.getConfigValue(e);return t===void 0?kn[e]:t}a(uq,"get");function Le(e,t){moe[e]&&(kn[e]=t),QE.updateConfigObject(e,t)}a(Le,"setProperty");function Toe(){let e;try{e=wl.getPropsFilePath(),DA.accessSync(e,DA.constants.F_OK|DA.constants.R_OK),cq=!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[zE]=e,!0}catch{return Il.trace(`Environment manager found no properties file at ${e}`),!1}}a(Toe,"doesPropFileExist");function goe(e=!1){try{(cq||Toe()||wl.noBootFile())&&(QE.initConfig(e),kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=QE.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[zE]=Mo.join(u,"hdb_boot_properties.file"),Le(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Mo.join(u,"settings.test")),Le(ue.HDB_SETTINGS_NAMES.INSTALL_USER,aq.userInfo()?aq.userInfo().username:void 0),Le(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Le(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Mo.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,Mo.join(u,"envDir")),Le(ue.CONFIG_PARAMS.STORAGE_PATH,Mo.join(u,"envDir")),n&&(Le(ue.CONFIG_PARAMS.HTTP_SECUREPORT,uq(ue.CONFIG_PARAMS.HTTP_PORT)),Le(ue.CONFIG_PARAMS.HTTP_PORT,null)),Le(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Le(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Le(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,wl.isEmpty(i)?!1:i),Le(ue.CONFIG_PARAMS.HTTP_CORS,wl.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,Mo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Le(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,wl.isEmpty(c)?!1:c),o&&(Le("CORS_ACCESSLIST",o),Le(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Le(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Le(ue.CONFIG_PARAMS.HTTP_TIMEOUT,s)),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 ${zE}. Please check your boot props and settings files`;Il.fatal(r),Il.error(t)}}a(Roe,"initTestEnvironment")});var hq=T((GSe,Eq)=>{"use strict";var fq=require("joi"),{string:Cl,boolean:_q,array:Aoe}=fq.types(),dq=L(),Ooe=je();Eq.exports=boe;function boe(e){let t=fq.object({operation:Cl.valid(dq.OPERATIONS_ENUM.ADD_NODE,dq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Cl.required(),subscriptions:Aoe.items({schema:Cl.required(),table:Cl.optional(),hash_attribute:Cl.optional(),subscribe:_q.required(),publish:_q.required()}).min(1).required()});return Ooe.validateBySchema(e,t)}a(boe,"updateRemoteSourceValidator")});var Dl=T((VSe,mq)=>{"use strict";var LA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};mq.exports=LA});var Rq=T((YSe,gq)=>{"use strict";var Noe=hq(),Vn=V(),UA=Ge(),pq=L(),MA=is(),PA=st(),Sq=lu(),yoe=$_(),{Node:woe,NodeSubscription:Tq}=di(),vA=Dl(),BA=J(),Ioe=Z(),{cloneDeep:Coe}=require("lodash"),{broadcast:Doe}=Ke();gq.exports=Loe;async function Loe(e){try{let t=Noe(e);if(t)return Vn.error(`Validation error in updateRemoteSource: ${t.message}`),new vA(UA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=Coe(await MA.getNodeRecord(s)),c=!BA.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(!BA.doesSchemaExist(f)){Vn.trace(`updateRemoteSource creating schema: ${f}`);try{await Sq.createSchema({operation:"create_schema",schema:f})}catch(h){Vn.error(h)}}if(E&&!BA.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 Sq.createTable(h)}catch(p){Vn.error(p)}Vn.trace(`Creating local stream for ${f}.${E}`),await PA.createLocalTableStream(f,E)}if(f===pq.SYSTEM_SCHEMA_NAME&&await PA.createLocalTableStream(f,E),await PA.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 Tq(f,E,d.publish,d.subscribe))}else i.push(new Tq(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 MA.upsertNodeRecord(u),Doe({type:"nats_update"}),new vA(UA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Ioe.get(pq.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await MA.getSystemInfo())}catch(t){Vn.error(t);let r=t.message?t.message:t;return new vA(UA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Loe,"updateRemoteSource")});var Nq=T((WSe,bq)=>{"use strict";var Oq=require("joi"),{string:Aq}=Oq.types(),Uoe=L(),Moe=je();bq.exports=Poe;function Poe(e){let t=Oq.object({operation:Aq.valid(Uoe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:Aq.required()});return Moe.validateBySchema(e,t)}a(Poe,"removeRemoteSourceValidator")});var wq=T((zSe,yq)=>{"use strict";var voe=Nq(),JE=V(),jE=Ge(),HA=L(),Boe=is(),Hoe=J(),xoe=st(),qoe=Z(),XE=Dl(),{NodeSubscription:Foe}=di(),Goe=ra(),koe=ti(),{broadcast:Voe}=Ke(),$oe=qoe.get(HA.CONFIG_PARAMS.CLUSTERING_NODENAME);yq.exports=Yoe;async function Yoe(e){try{let t=voe(e);if(t)return JE.error(`Validation error in removeRemoteSource: ${t.message}`),new XE(jE.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 XE(jE.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(HA.SYSTEM_SCHEMA_NAME,HA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await koe.deleteRecord(n),Voe({type:"nats_update"}),new XE(jE.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 XE(jE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Yoe,"removeRemoteSource")});var Uq=T((jSe,Lq)=>{"use strict";var ZE=V(),eh=L(),Iq=Ge(),Cq=Z(),Koe=J(),Dq=Dl(),Woe=is(),Qoe=md(),zoe=wr();Lq.exports=Joe;async function Joe(e){try{ZE.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Koe.ms_to_time(t),s=new joe(Cq.get(eh.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),Cq.get(eh.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT),r,await Woe.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new Qoe(eh.SYSTEM_SCHEMA_NAME,eh.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await zoe.update(i)}catch(n){ZE.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return ZE.trace("getRemoteSourceConfig response:",s),new Dq(Iq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){ZE.error(t);let r=t.message?t.message:t;return new Dq(Iq.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 Bq=T((ZSe,vq)=>{"use strict";var Mq=Z();Mq.initSync();var Pq=st(),Ll=V(),Xa=L(),xA=Ge(),Xoe=Rq(),Zoe=wq(),eae=Uq(),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),qA=Mq.get(Xa.CONFIG_PARAMS.CLUSTERING_NODENAME);vq.exports=_ae;async function _ae(){try{Ll.notify("Starting reply service."),await lae();let e=await Pq.getConnection(),t=`${qA}.__request__`,r=e.subscribe(t,{queue:qA});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 '${qA}' reply service received unrecognized request operation`;Ll.error(n),s=new tae(xA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}Ll.trace(s),t.respond(rae(s))}}a(dae,"handleRequest");async function fae(){try{return{status:xA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await iae.describeAll()}}catch(e){return Ll.error(e),{status:xA.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&&Pq.closeConnection()})});var Eae=Bq();(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)}})();
|