harperdb 4.3.0-beta.3 → 4.3.0-beta.5
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 +56 -56
- package/bin/lite.js +19 -19
- package/config/yaml/defaultConfig.yaml +3 -1
- package/launchServiceScripts/launchInstallNATSServer.js +2 -2
- package/launchServiceScripts/launchNatsIngestService.js +19 -19
- package/launchServiceScripts/launchNatsReplyService.js +19 -19
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +19 -19
- package/npm-shrinkwrap.json +65 -68
- package/package.json +2 -2
- package/resources/DatabaseTransaction.d.ts +7 -2
- package/resources/Table.d.ts +2 -2
- package/resources/databases.d.ts +2 -2
- package/server/jobs/jobProcess.js +19 -19
- package/server/serverHelpers/Headers.d.ts +12 -0
- 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.f2d1cee1.js → main.1b4b013e.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -19
- /package/studio/build-local/static/js/{main.f2d1cee1.js.LICENSE.txt → main.1b4b013e.js.LICENSE.txt} +0 -0
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
"use strict";var qq=Object.create;var Xa=Object.defineProperty;var Fq=Object.getOwnPropertyDescriptor;var Gq=Object.getOwnPropertyNames;var kq=Object.getPrototypeOf,Vq=Object.prototype.hasOwnProperty;var a=(e,t)=>Xa(e,"name",{value:t,configurable:!0});var Oe=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ve=(e,t)=>{for(var r in t)Xa(e,r,{get:t[r],enumerable:!0})},FA=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Gq(t))!Vq.call(e,n)&&n!==r&&Xa(e,n,{get:()=>t[n],enumerable:!(s=Fq(t,n))||s.enumerable});return e};var x=(e,t,r)=>(r=e!=null?qq(kq(e)):{},FA(t||!e||!e.__esModule?Xa(r,"default",{value:e,enumerable:!0}):r,e)),te=e=>FA(Xa({},"__esModule",{value:!0}),e);var VA=T((fae,kA)=>{var $q=require("fast-glob"),{statSync:ih,existsSync:oh,readFileSync:Yq,writeFileSync:Kq}=require("fs"),{spawnSync:Wq,spawn:Qq,execFileSync:dae}=require("child_process"),{isMainThread:zq}=require("worker_threads"),{join:Kn,relative:GA}=require("path"),{PACKAGE_ROOT:Ts}=L(),{tmpdir:Jq,platform:jq}=require("os");require("source-map-support").install();var Xq=["resources","server","dataLayer","components"],Za="ts-build",ah,Zq=__filename.endsWith("tsBuild.js");if(Zq){if(zq){let r;try{ih(Kn(Ts,Za)),r=!0}catch{}if(r)for(let s of $q.sync(Xq.map(n=>n+"/**/*.ts"),{cwd:Ts})){let n=0,i=0;try{n=ih(Kn(Ts,s)).mtimeMs-5e3,i=ih(Kn(Ts,Za,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."),ah=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),ah=!0;if(ah){let s=Kn(Ts,"node_modules/.bin/tsc");jq()==="win32"&&(s+=".cmd");let n=Wq(s,{cwd:Ts});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Kn(Jq(),"harperdb-tsc.pid"),o;if(oh(i))try{process.kill(+Yq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Qq(s,["--watch"],{cwd:Ts,detached:!0,stdio:"ignore"});Kq(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(Ts)&&!s[0].includes("node_modules")){let i=GA(Ts,s[0]),o;i.startsWith(Za)?o=Kn(Ts,GA(Za,i)):o=Kn(Ts,Za,i);let c=Kn(o,r),u=c+".js";if(oh(u))return u;if(c.includes(".")&&oh(c))return c}return t(r,s,n)}}});var L=T((mae,sO)=>{"use strict";var jr=require("path"),eF=require("fs"),{relative:Eae,join:hae}=jr,{existsSync:tF}=eF;function rF(){let e=__dirname;for(;!tF(jr.join(e,"package.json"));){let t=jr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(rF,"getHDBPackageRoot");var Wn=rF(),$A="js",vl=$A,sF="harperdb-config.yaml",nF="defaultConfig.yaml",iF="hdb",YA=`harperdb.${vl}`,KA=`customFunctionsServer.${vl}`,oF=`restartHdb.${vl}`,uh="HarperDB",Pl="Custom Functions",Bl="Clustering Hub",Hl="Clustering Leaf",aF="Clustering Ingest Service",cF="Clustering Reply Service",uF="foreground.pid",lF="hdb.pid",_F="data",dF={HDB:uh,CLUSTERING_HUB:Bl,CLUSTERING_LEAF:Hl,CLUSTERING_INGEST_SERVICE:aF,CLUSTERING_REPLY_SERVICE:cF,CUSTOM_FUNCTIONS:Pl,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"},fF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},EF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},hF={harperdb:uh,"clustering hub":Bl,"clustering leaf":Hl,"custom functions":Pl,custom_functions:Pl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},mF={CLUSTERING_HUB_PROC_DESCRIPTOR:Bl,CLUSTERING_LEAF_PROC_DESCRIPTOR:Hl},ch={HDB:jr.join(Wn,"server/harperdb"),CUSTOM_FUNCTIONS:jr.join(Wn,"server/customFunctions"),CLUSTERING_HUB:jr.join(Wn,"server/nats"),CLUSTERING_LEAF:jr.join(Wn,"server/nats")},pF={HDB:jr.join(ch.HDB,YA),CUSTOM_FUNCTIONS:jr.join(ch.CUSTOM_FUNCTIONS,KA)},SF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:jr.join(Wn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:jr.join(Wn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:jr.join(Wn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},TF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},WA="support@harperdb.io",gF="customer-success@harperdb.io",QA=1,RF=4141,zA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",AF="https://www.harperdb.io/product",OF=`For support, please submit a request at ${zA} or contact ${WA}`,JA=`For license support, please contact ${gF}`,bF="None of the specified records were found.",NF="hash attribute not found",yF=`Your current license only supports ${QA} role. ${JA}`,wF="Your current license only supports 3 connections to a node.",IF="127.0.0.1",CF=1,DF=/^\.$/,LF=/^\.\.$/,MF="U+002E",UF=/\//g,PF="U+002F",vF=/U\+002F/g,BF=/^U\+002E$/,HF=/^U\+002EU\+002E$/,xF="d",qF=999999,FF="*",GF="--max-old-space-size=",kF="system",VF="__hdb_hash",$F=".harperdb",YF=".hdb",KF="keys",WF="hdb_boot_properties.file",QF=".updateConfig.json",zF="SIGTSTP",JF=24,jF=6e4,XF=448,ZF="blob",eG="trash",tG="database",rG="schema",sG="transactions",nG=".count",iG="id",oG="PROCESS_NAME",jA={SETTINGS_PATH_KEY:"settings_path"},XA=require("lodash"),aG={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"},cG={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},uG={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},lG={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"},_G={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"},Or="hdb_internal:",dG={CREATE_SCHEMA:Or+"create_schema",CREATE_TABLE:Or+"create_table",CREATE_ATTRIBUTE:Or+"create_attribute",ADD_USER:Or+"add_user",ALTER_USER:Or+"alter_user",DROP_USER:Or+"drop_user",HDB_NODES:Or+"hdb_nodes",HDB_USERS:Or+"hdb_users",HDB_WORKERS:Or+"hdb_workers",CATCHUP:Or+"catchup",SCHEMA_CATCHUP:Or+"schema_catchup",WORKER_ROOM:Or+"cluster_workers"},fG={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"},EG="060493.ks",hG=".license",mG={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},j={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"},pG={CSV:".csv",JSON:".json"},SG={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},TG={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},ec={};ec[j.INSERT]=j.INSERT;ec[j.UPDATE]=j.UPDATE;ec[j.UPSERT]=j.UPSERT;ec[j.DELETE]=j.DELETE;var Be=Object.create(null);Be[j.DESCRIBE_ALL]=j.DESCRIBE_ALL;Be[j.DESCRIBE_TABLE]=j.DESCRIBE_TABLE;Be[j.DESCRIBE_SCHEMA]=j.DESCRIBE_SCHEMA;Be[j.READ_LOG]=j.READ_LOG;Be[j.ADD_NODE]=j.ADD_NODE;Be[j.LIST_USERS]=j.LIST_USERS;Be[j.LIST_ROLES]=j.LIST_ROLES;Be[j.USER_INFO]=j.USER_INFO;Be[j.SQL]=j.SQL;Be[j.GET_JOB]=j.GET_JOB;Be[j.SEARCH_JOBS_BY_START_DATE]=j.SEARCH_JOBS_BY_START_DATE;Be[j.DELETE_FILES_BEFORE]=j.DELETE_FILES_BEFORE;Be[j.EXPORT_LOCAL]=j.EXPORT_LOCAL;Be[j.EXPORT_TO_S3]=j.EXPORT_TO_S3;Be[j.CLUSTER_STATUS]=j.CLUSTER_STATUS;Be[j.REMOVE_NODE]=j.REMOVE_NODE;Be[j.RESTART]=j.RESTART;Be[j.CUSTOM_FUNCTIONS_STATUS]=j.CUSTOM_FUNCTIONS_STATUS;Be[j.GET_CUSTOM_FUNCTIONS]=j.GET_CUSTOM_FUNCTIONS;Be[j.GET_CUSTOM_FUNCTION]=j.GET_CUSTOM_FUNCTION;Be[j.SET_CUSTOM_FUNCTION]=j.SET_CUSTOM_FUNCTION;Be[j.DROP_CUSTOM_FUNCTION]=j.DROP_CUSTOM_FUNCTION;Be[j.ADD_CUSTOM_FUNCTION_PROJECT]=j.ADD_CUSTOM_FUNCTION_PROJECT;Be[j.DROP_CUSTOM_FUNCTION_PROJECT]=j.DROP_CUSTOM_FUNCTION_PROJECT;Be[j.PACKAGE_CUSTOM_FUNCTION_PROJECT]=j.PACKAGE_CUSTOM_FUNCTION_PROJECT;Be[j.DEPLOY_CUSTOM_FUNCTION_PROJECT]=j.DEPLOY_CUSTOM_FUNCTION_PROJECT;var gG={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"},RG={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},ZA={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"},AG=XA.invert(ZA),OG={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"},C={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",MAXHEAPMEMORY:"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"},eO={settings_path:jA.SETTINGS_PATH_KEY,hdb_root_key:C.ROOTPATH,hdb_root:C.ROOTPATH,rootpath:C.ROOTPATH,server_port_key:C.OPERATIONSAPI_NETWORK_PORT,server_port:C.OPERATIONSAPI_NETWORK_PORT,cert_key:C.TLS_CERTIFICATE,certificate:C.TLS_CERTIFICATE,private_key_key:C.TLS_PRIVATEKEY,private_key:C.TLS_PRIVATEKEY,http_secure_enabled_key:C.OPERATIONSAPI_NETWORK_HTTPS,https_on:C.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:C.OPERATIONSAPI_NETWORK_CORS,cors_on:C.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:C.LOGGING_LEVEL,log_level:C.LOGGING_LEVEL,log_path_key:C.LOGGING_ROOT,log_path:C.LOGGING_ROOT,clustering_node_name_key:C.CLUSTERING_NODENAME,node_name:C.CLUSTERING_NODENAME,clustering_enabled_key:C.CLUSTERING_ENABLED,clustering:C.CLUSTERING_ENABLED,max_http_threads:C.THREADS,max_hdb_processes:C.THREADS,server_timeout_key:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:C.LOGGING_AUDITLOG,disable_transaction_log:C.LOGGING_AUDITLOG,operation_token_timeout_key:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:C.HTTP_PORT,custom_functions_port:C.HTTP_PORT,custom_functions_directory_key:C.COMPONENTSROOT,custom_functions_directory:C.COMPONENTSROOT,max_custom_function_processes:C.THREADS,log_to_file:C.LOGGING_FILE,log_to_stdstreams:C.LOGGING_STDSTREAMS,local_studio_on:C.LOCALSTUDIO_ENABLED,clustering_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:C.CLUSTERING_USER,clustering_enabled:C.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:C.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:C.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:C.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:C.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:C.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:C.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:C.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:C.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:C.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:C.CLUSTERING_NODENAME,clustering_tls_certificate:C.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:C.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:C.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:C.CLUSTERING_TLS_INSECURE,clustering_tls_verify:C.CLUSTERING_TLS_VERIFY,clustering_loglevel:C.CLUSTERING_LOGLEVEL,clustering_republishmessages:C.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:C.CLUSTERING_DATABASELEVEL,customfunctions_network_port:C.HTTP_PORT,customfunctions_tls_certificate:C.TLS_CERTIFICATE,customfunctions_network_cors:C.HTTP_CORS,customfunctions_network_corsaccesslist:C.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:C.HTTP_HEADERSTIMEOUT,customfunctions_network_https:C.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:C.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:C.HTTP_TIMEOUT,http_threads:C.THREADS,threads:C.THREADS,maxheapmemory:C.MAXHEAPMEMORY,http_session_affinity:C.HTTP_SESSIONAFFINITY,http_compressionthreshold:C.HTTP_COMPRESSIONTHRESHOLD,http_cors:C.HTTP_CORS,http_corsaccesslist:C.HTTP_CORSACCESSLIST,http_headerstimeout:C.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,http_timeout:C.HTTP_TIMEOUT,http_port:C.HTTP_PORT,http_secureport:C.HTTP_SECUREPORT,http_mtls:C.HTTP_MTLS,http_mtls_user:C.HTTP_MTLS_USER,http_mtls_required:C.HTTP_MTLS_REQUIRED,customfunctions_processes:C.THREADS,customfunctions_root:C.COMPONENTSROOT,localstudio_enabled:C.LOCALSTUDIO_ENABLED,logging_file:C.LOGGING_FILE,logging_level:C.LOGGING_LEVEL,logging_root:C.LOGGING_ROOT,logging_rotation_enabled:C.LOGGING_ROTATION_ENABLED,logging_rotation_compress:C.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:C.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:C.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:C.LOGGING_ROTATION_PATH,logging_stdstreams:C.LOGGING_STDSTREAMS,logging_auditlog:C.LOGGING_AUDITLOG,logging_auditretention:C.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:C.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:C.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:C.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:C.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:C.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:C.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:C.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:C.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:C.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:C.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:C.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:C.ROOTPATH,databases:C.DATABASES,storage_path:C.STORAGE_PATH,ignorescripts:C.IGNORE_SCRIPTS,mqtt_network_port:C.MQTT_NETWORK_PORT,mqtt_websocket:C.MQTT_WEBSOCKET,mqtt_network_secureport:C.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:C.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:C.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:C.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:C.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:C.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:C.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:C.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:C.AUTHENTICATION_CACHETTL,authentication_enablesessions:C.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:C.COMPONENTSROOT,tls_certificate:C.TLS_CERTIFICATE,tls_privatekey:C.TLS_PRIVATEKEY,tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,tls_ciphers:C.TLS_CIPHERS};for(let e in C){let t=C[e];eO[t.toLowerCase()]=t}var bG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},NG={csv_file_load:"csv_file_load",csv_data_load:j.CSV_DATA_LOAD,csv_url_load:j.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"},yG={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"},wG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},IG={VERSION_DEFAULT:"2.2.0"},CG={DEVELOPMENT:8192,DEFAULT:512},DG={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"},LG={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"},MG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},tO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},UG=Symbol("metadata"),PG="__clustering__",vG=Object.values(tO),BG=15984864e5,rO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},HG=XA.invert(rO),xG={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"},qG=111,FG=`\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:Tk.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(Ok,"findPs")});var _t=T((bae,gO)=>{"use strict";var bk="__dbis__",Nk="__txns__",yk="__environment_name__",wk="__dbi_defintion__",Ik={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"},Ck=["__createdtime__","__updatedtime__"],Dk="\uFFFF",TO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},Lk=Object.values(TO);gO.exports={AUDIT_STORE_NAME:Nk,INTERNAL_DBIS_NAME:bk,DBI_DEFINITION_NAME:wk,SEARCH_TYPES:Ik,TIMESTAMP_NAMES:Ck,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:yk,TRANSACTIONS_DBI_NAMES_ENUM:TO,TRANSACTIONS_DBIS:Lk,OVERFLOW_MARKER:Dk}});var br=T((Nae,CO)=>{"use strict";var RO=L(),AO=_t(),OO={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},bO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),NO={500:bO("There was an error processing your request."),400:"Invalid request"},Mk=NO[OO.INTERNAL_SERVER_ERROR],Uk={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.`},Pk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},vk={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"},Bk={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 ${AO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${AO.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"},Hk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${RO.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 ${RO.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"},yO={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"},xk={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."},qk={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`},Fk={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"},Gk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},kk={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},wO={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.`},IO={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}`},Vk={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."},$k={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Yk={...yO,...vk,...Uk,...xk,...qk,...Fk,...Gk,...kk,...Hk,...wO,...IO,...Vk,...$k,...Pk};CO.exports={CHECK_LOGS_WRAPPER:bO,HDB_ERROR_MSGS:Yk,DEFAULT_ERROR_MSGS:NO,DEFAULT_ERROR_RESP:Mk,HTTP_STATUS_CODES:OO,LMDB_ERRORS_ENUM:Bk,AUTHENTICATION_ERROR_MSGS:yO,VALIDATION_ERROR_MSGS:wO,ITC_ERRORS:IO}});var ee=T((wae,MO)=>{"use strict";var vo=br(),Kk=V(),Wk=L(),kl=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,DO),this.statusCode=s||vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(vo.DEFAULT_ERROR_MSGS[s]?vo.DEFAULT_ERROR_MSGS[s]:vo.DEFAULT_ERROR_MSGS[vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&Kk[n](i)}},Sh=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}},Th=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function DO(e,t,r,s=Wk.LOG_LEVELS.ERROR,n=null,i=!1){if(LO(e))return e;let o=new kl(e,t,r,s,n);return i&&delete o.stack,o}a(DO,"handleHDBError");function LO(e){return e.__proto__.constructor.name===kl.name}a(LO,"isHDBError");MO.exports={isHDBError:LO,handleHDBError:DO,ClientError:Sh,ServerError:Th,hdb_errors:vo}});var We=T((Cae,qO)=>{"use strict";var lc=L(),Qk=J(),jt=X(),_c=require("path"),zk=require("minimist"),UO=require("fs-extra"),PO=require("lodash");jt.initSync();var{CONFIG_PARAMS:Qn,DATABASES_PARAM_CONFIG:oc,SYSTEM_SCHEMA_NAME:Vl}=lc,ac,cc,uc;function vO(){if(ac!==void 0)return ac;if(jt.getHdbBasePath()!==void 0)return ac=jt.get(Qn.STORAGE_PATH)||_c.join(jt.getHdbBasePath(),lc.DATABASES_DIR_NAME),ac}a(vO,"getBaseSchemaPath");function BO(){if(cc!==void 0)return cc;if(jt.getHdbBasePath()!==void 0)return cc=xO(Vl),cc}a(BO,"getSystemSchemaPath");function HO(){if(uc!==void 0)return uc;if(jt.getHdbBasePath()!==void 0)return uc=jt.get(lc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||_c.join(jt.getHdbBasePath(),lc.TRANSACTIONS_DIR_NAME),uc}a(HO,"getTransactionAuditStoreBasePath");function Jk(e,t){let r=jt.get(Qn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||_c.join(HO(),e.toString())}a(Jk,"getTransactionAuditStorePath");function xO(e,t){e=e.toString(),t=t&&t.toString();let r=jt.get(lc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||_c.join(vO(),e)}a(xO,"getSchemaPath");function jk(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,zk(process.argv));let s=r[Qn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!Qk.isObject(s))throw o;i=s}for(let o of i){let c=o[Vl];if(!c)continue;let u=jt.get(Qn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[oc.PATH];if(_)return PO.set(u,[Vl,oc.TABLES,t,oc.PATH],_),jt.setProperty(Qn.DATABASES,u),_;let l=c?.[oc.PATH];if(l)return PO.set(u,[Vl,oc.PATH],l),jt.setProperty(Qn.DATABASES,u),l}}let n=r[Qn.STORAGE_PATH.toUpperCase()];if(n){if(!UO.pathExistsSync(n))throw new Error(n+" does not exist");let i=_c.join(n,e);return UO.mkdirsSync(i),jt.setProperty(Qn.STORAGE_PATH,n),i}return BO()}a(jk,"initSystemSchemaPaths");function Xk(){ac=void 0,cc=void 0,uc=void 0}a(Xk,"resetPaths");qO.exports={getBaseSchemaPath:vO,getSystemSchemaPath:BO,getTransactionAuditStorePath:Jk,getTransactionAuditStoreBasePath:HO,getSchemaPath:xO,initSystemSchemaPaths:jk,resetPaths:Xk}});var Nr=T((Uae,$O)=>{"use strict";var Zk=br().LMDB_ERRORS_ENUM,Lae=require("lmdb"),eV=_t(),Mae=require("buffer").Buffer,{OVERFLOW_MARKER:FO,MAX_SEARCH_KEY_LENGTH:$l}=eV,GO=["number","string","symbol","boolean","bigint"];function tV(e){if(e=e?.primaryStore||e,!e)throw new Error(Zk.ENV_REQUIRED)}a(tV,"validateEnv");function rV(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(rV,"stringifyData");function sV(e){return e instanceof Date?e.valueOf():e}a(sV,"convertKeyValueToWrite");function nV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(GO.includes(typeof e))return e.length>$l?[e.slice(0,$l)+FO]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if(GO.includes(typeof i))i.length>$l?r.push(i.slice(0,$l)+FO):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(nV,"getIndexedValues");var Yl=0,kO=0;function VO(){kO=Date.now()-performance.now()}a(VO,"adjustStartTime");VO();var iV=6e4;setInterval(VO,iV).unref();function oV(){let e=performance.now()+kO;return e>Yl?(Yl=e,e):(Yl+=488e-6,Yl)}a(oV,"getNextMonotonicTime");$O.exports={validateEnv:tV,stringifyData:rV,convertKeyValueToWrite:sV,getNextMonotonicTime:oV,getIndexedValues:nV}});var YO,gs,gh,dc=Oe(()=>{YO=require("events"),gs=class extends YO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new gh;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)}},gh=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 Di={};Ve(Di,{server:()=>et});var KO,et,Xt=Oe(()=>{KO=require("../index"),et={};(0,KO._assignPackageExport)("server",et)});var Oh={};Ve(Oh,{loadGQLSchema:()=>uV,start:()=>Ah,startOnMainThread:()=>cV});function Ah({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 W=H(v.type);return W.nullable=!1,W}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 O=S.name.value,g=[],R={table:null,database:null,properties:g};f.set(O,R);for(let v of S.directives){if(v.name.value==="table"){for(let U of v.arguments)R[U.name.value]=U.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=O),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(v.name.value==="sealed"&&(R.sealed=!0),v.name.value==="export"){R.export=!0;for(let U of v.arguments)U.name.value==="name"&&(R.export={name:U.value.value})}}let B=!1;for(let v of S.fields){let U=H(v.type);U.name=v.name.value,g.push(U);for(let Y of v.directives)if(Y.name.value==="primaryKey")B?console.warn("Can not define two attributes as a primary key"):(U.isPrimaryKey=!0,B=!0);else if(Y.name.value==="indexed")U.indexed=!0;else if(Y.name.value==="relationship"){let W={};for(let z of Y.arguments)W[z.name.value]=z.value.value;U.relationship=W}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 W=U.authorizedRoles=[];for(let z of Y.arguments)z.name.value==="role"&&W.push(z.value.value)}}R.type=O,O==="Query"&&(h=R)}function p(S){let O=f.get(S.type);O?(Object.defineProperty(S,"properties",{value:O.properties}),Object.defineProperty(S,"definition",{value:O})):S.type==="array"?p(S.elements):aV.includes(S.type)||(0,WO.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 O of S.properties)p(O);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Rh.dirname)(s),S.tableClass):i.set((0,Rh.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass))}}var Rh,WO,aV,cV,uV,QO=Oe(()=>{Rh=require("path");be();WO=x($e()),aV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Ah,"start");cV=Ah,uV=Ah({ensureTable:at}).handleFile});async function Kl(e){return lV?(fc||(fc=_V(fV)),(await(await fc).import(e)).namespace):import(e)}async function _V(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),fc=new Compartment({console,Math,Date,fetch:dV,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,JO.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:vt,tables:yr,databases:tt})}};let s=await(0,zO.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),fc}function dV(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 fV(){return{Resource:vt,tables:yr}}var zO,JO,lV,fc,bh=Oe(()=>{Rs();be();zO=require("fs/promises"),JO=require("path"),lV=!1;a(Kl,"secureImport");a(_V,"getCompartment");a(dV,"secureOnlyFetch");a(fV,"getGlobalVars")});var yh={};Ve(yh,{handleFile:()=>EV});async function EV(e,t,r,s){let n=new Map,i=(0,jO.pathToFileURL)(r).toString(),o=await Kl(i);u(o.default)&&s.set((0,Nh.dirname)(t),o.default),c(o,(0,Nh.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 jO,Nh,XO=Oe(()=>{jO=require("url");bh();Nh=require("path");a(EV,"handleFile")});var Ih={};Ve(Ih,{start:()=>hV});function hV({resources:e}){e.set("login",wh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var wh,ZO=Oe(()=>{Rs();a(hV,"start");wh=class extends vt{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 ob={};Ve(ob,{parse:()=>Dh,streamAsJSON:()=>Ec,stringify:()=>Li});function Ec(e){return new Ch({value:e})}function eb(e){return console.error(e),JSON.stringify(e.toString())}function tb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Li(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===nb)return ib(e);if(t.resolution)return t.resolution.then(()=>Li(e));throw t}}function ib(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+=ib(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+Li(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Dh(e){return SV.test(e)?mV.parse(e):JSON.parse(e)}var rb,sb,mV,pV,nb,Ch,SV,Lh=Oe(()=>{rb=require("stream"),sb=x(require("json-bigint-fixes")),mV=(0,sb.default)({useNativeBigInt:!0}),pV=1e4,nb={};BigInt.prototype.toJSON=function(){throw nb};a(Ec,"streamAsJSON");Ch=class extends rb.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),eb)}catch(n){yield eb(n)}else yield Li(t)}else yield Li(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);tb(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>pV?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 tb(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(eb,"handleError");a(tb,"when");a(Li,"stringify");a(ib,"jsStringify");SV=/-?\d{16,}/;a(Dh,"parse")});var Tb=T((zae,Sb)=>{"use strict";var Mh=require("recursive-iterator"),TV=require("alasql"),Uh=require("clone"),ab=J(),{handleHDBError:cb,hdb_errors:gV}=ee(),{HDB_ERROR_MSGS:ub,HTTP_STATUS_CODES:lb}=gV,{getDatabases:RV}=(be(),te(qe)),AV=["DISTINCT_ARRAY"],_b=Symbol("validateTables"),Ph=Symbol("validateTable"),Qae=Symbol("getAllColumns"),db=Symbol("validateAllColumns"),Wl=Symbol("findColumn"),fb=Symbol("validateOrderBy"),hc=Symbol("validateSegment"),vh=Symbol("validateColumn"),Eb=Symbol("setColumnsForTable"),hb=Symbol("checkColumnsForAsterisk"),mb=Symbol("validateGroupBy"),pb=Symbol("hasColumns"),Bh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[_b](),this[hb](),this[db]()}[_b](){if(this[pb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Ph](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Ph](t.table)})}}[pb](){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}[Ph](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=RV();if(!r[t.databaseid])throw cb(new Error,ub.SCHEMA_NOT_FOUND(t.databaseid),lb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw cb(new Error,ub.TABLE_NOT_FOUND(t.databaseid,t.tableid),lb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=Uh(n);i.table=Uh(t),this.attributes.push(i)})}[Wl](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)}[hb](){let t=new Mh(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Eb](r.tableid)}[Eb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new TV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[db](){this[hc](this.statement.columns,!1),this[hc](this.statement.joins,!1),this[hc](this.statement.where,!1),this[mb](this.statement.group,!1),this[hc](this.statement.order,!0)}[hc](t,r){if(!t)return;let s=new Mh(t),n=[];for(let{node:i,path:o}of s)!ab.isEmpty(i)&&!ab.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[fb](i):n.push(this[vh](i)));return n}[mb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&AV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Uh(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Wl](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[Wl](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`}[fb](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[vh](t)}[vh](t){let r=this[Wl](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]}};Sb.exports=Bh});var Rb=T((jae,gb)=>{"use strict";var Hh=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")}};gb.exports=Hh});var Ob=T((Zae,Ab)=>{"use strict";var xh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Ab.exports=xh});var wb={};Ve(wb,{HAS_EXPIRATION:()=>Kh,LAST_TIMESTAMP_PLACEHOLDER:()=>Sc,LOCAL_TIMESTAMP:()=>OV,METADATA:()=>mc,NO_TIMESTAMP:()=>Fh,PENDING_LOCAL_TIME:()=>Wh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Yh,RecordEncoder:()=>Vh,TIMESTAMP_ASSIGN_LAST:()=>NV,TIMESTAMP_ASSIGN_NEW:()=>Nb,TIMESTAMP_ASSIGN_PREVIOUS:()=>yb,TIMESTAMP_PLACEHOLDER:()=>Ql,TIMESTAMP_RECORD_PREVIOUS:()=>Gh,fromResource:()=>Xl,getUpdateRecord:()=>Qh,handleLocalTimeForGets:()=>Zl});function wV(){return pc[0]=pc[0]^64,bV.getFloat64(0)}function Xl(e){$h=!0;try{return e()}finally{$h=!1}}function Zl(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?.[mc];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?.[mc]>=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[mc];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,Mi.push(new WeakRef(this))),!$h)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<Mi.length;u++){let _=Mi[u].deref();(!_||_.isDone||_.isCommitted)&&Mi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Qh(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Bo=i?.localTime?Gh|yb:Fh:Bo=u?i?.localTime?Gh|16384:Nb|16384:Fh,l>0&&(c|=Kh),Jl=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:Bo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(u){let O=_?.user?.username;if(E&&(zl=e.encoder.encode(E)),f&&i?.localTime){let g=i?.localTime,R=r.get(g);if(R){let B=Ct(R).previousLocalTime;return r.put(g,jl(o,t,s,B,O,d,zl),{ifVersion:p}),S}}r.put(Sc,jl(o,t,s,i?.localTime?1:0,O,d,zl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var bb,qh,Ql,Sc,Yh,OV,mc,pc,bV,Fh,Nb,NV,yb,Gh,Kh,Wh,yV,zl,Bo,Jl,kh,Vh,rce,$h,Mi,Ho=Oe(()=>{bb=require("msgpackr");Ui();qh=x(V()),Ql=new Uint8Array([1,1,1,1,4,64,0,0]),Sc=new Uint8Array([1,1,1,1,1,0,0,0]),Yh=new Uint8Array([1,1,1,1,3,64,0,0]),OV=Symbol("local-timestamp"),mc=Symbol("metadata"),pc=new Uint8Array(8),bV=new DataView(pc.buffer,0,8),Fh=0,Nb=0,NV=1,yb=3,Gh=4,Kh=16,Wh=1,Bo=0,Jl=-1,kh=0,Vh=class extends bb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){if(Bo||Jl>=0){let i=0,o=Bo;o&&(i+=8,Bo=0);let c=Jl,u=kh;c>=0&&(i+=2,Jl=-1,u&&(i+=8,kh=0));let _=yV=r.call(this,s,n|2048|i);zl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Ql[4]=o,Ql[5]=o>>8,_.set(Ql,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(pc,0,c),c+=8;else for(let d=0;d<8;d++)pc[d]=t[c++];u=wV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Kh&&(_=(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,[mc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(wV,"getTimestamp");rce=Map.prototype.get;a(Xl,"fromResource");a(Zl,"handleLocalTimeForGets");Mi=[];setInterval(()=>{for(let e=0;e<Mi.length;e++){let t=Mi[e].deref();!t||t.isDone||t.isCommitted?Mi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(qh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):qh.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(Qh,"getUpdateRecord")});var e_=T((nce,Ib)=>{"use strict";var Jh=X(),jh=L(),{RecordEncoder:IV}=(Ho(),te(wb));Jh.initSync();var CV=Jh.get(jh.CONFIG_PARAMS.STORAGE_COMPRESSION),DV=Jh.get(jh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,LV=jh.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=CV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=DV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:IV},this.alwaysLazyProperty=s=>s===LV)}};Ib.exports=zh});var r_=T((oce,Db)=>{"use strict";var xo=X(),Tc=L();xo.initSync();var MV=xo.get(Tc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||xo.get(Tc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||xo.get(Tc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Cb=xo.get(Tc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),UV=xo.get(Tc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),t_=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=MV,this.noFSAccess=!0,Cb!==void 0&&(this.overlappingSync=Cb),this.noReadAhead=UV}};Db.exports=t_;t_.MAX_DBS=1e4});var Ye=T((cce,Fb)=>{"use strict";var Zh=require("lmdb"),As=require("fs-extra"),wr=require("path"),s_=Nr(),Ub=V(),Zt=br().LMDB_ERRORS_ENUM,n_=Ob(),em=e_(),Pb=r_(),zn=_t(),Lb=L(),{table:PV,resetDatabases:vV}=(be(),te(qe)),Mb=X(),Os=zn.INTERNAL_DBIS_NAME,vb=zn.DBI_DEFINITION_NAME,BV="data.mdb",HV="lock.mdb",gc=".mdb",xV="-lock",Xh=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=Xr(t,r),this.key_type=this.dbi[zn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[zn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new Zh.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function i_(e,t){if(e===void 0)throw new Error(Zt.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Zt.ENV_NAME_REQUIRED)}a(i_,"pathEnvNameValidation");async function tm(e,t,r=!0){try{await As.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Zt.INVALID_BASE_PATH):s}try{let s=wr.join(e,t+gc);return await As.access(s,As.constants.R_OK|As.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await As.access(wr.join(e,t,BV),As.constants.R_OK|As.constants.F_OK),wr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Zt.INVALID_ENVIRONMENT)}else throw new Error(Zt.INVALID_ENVIRONMENT);throw s}}a(tm,"validateEnvironmentPath");function o_(e,t){if(s_.validateEnv(e),t===void 0)throw new Error(Zt.DBI_NAME_REQUIRED)}a(o_,"validateEnvDBIName");async function qV(e,t,r=!1,s=!1){i_(e,t);let n=wr.basename(e);t=t.toString();let i=Mb.get(Lb.CONFIG_PARAMS.DATABASES);i||Mb.setProperty(Lb.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await tm(e,t,s),Bb(e,t,r)}catch(o){if(o.message===Zt.INVALID_ENVIRONMENT){let c=wr.join(e,t);await As.mkdirp(s?c:e);let u=new Pb(s?c:c+gc,!1),_=Zh.open(u);_.dbis=Object.create(null);let l=new em(!1);_.openDB(Os,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=rm(e,t,r);return _[zn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(qV,"createEnvironment");async function FV(e,t,r,s=!0){i_(e,t),t=t.toString();let n=wr.join(e,t);return PV({table:t,database:wr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(FV,"copyEnvironment");async function Bb(e,t,r=!1){i_(e,t),t=t.toString();let s=rm(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 tm(e,t),i=wr.join(e,t+gc),o=n!=i,c=new Pb(n,o),u=Zh.open(c);u.dbis=Object.create(null);let _=xb(u);for(let l=0;l<_.length;l++)Xr(u,_[l]);return u[zn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(Bb,"openEnvironment");async function GV(e,t,r=!1){i_(e,t),t=t.toString();let s=wr.join(e,t+gc),n=await tm(e,t);if(global.lmdb_map!==void 0){let i=rm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Hb(o),delete global.lmdb_map[i]}}await As.remove(n),await As.remove(n===s?n+xV:wr.join(wr.dirname(n),HV))}a(GV,"deleteEnvironment");async function Hb(e){s_.validateEnv(e);let t=e[zn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Hb,"closeEnvironment");function rm(e,t,r=!1){let n=`${wr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(rm,"getCachedEnvironmentName");function kV(e){s_.validateEnv(e);let t=Object.create(null),r=Xr(e,Os);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==Os)try{t[s]=Object.assign(new n_,n)}catch{Ub.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(kV,"listDBIDefinitions");function xb(e){s_.validateEnv(e);let t=[],r=Xr(e,Os);for(let{key:s}of r.getRange({start:!1}))s!==Os&&t.push(s);return t}a(xb,"listDBIs");function VV(e,t){let s=Xr(e,Os).getEntry(t),n=new n_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Ub.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(VV,"getDBIDefinition");function qb(e,t,r,s=!r){if(o_(e,t),t=t.toString(),t===Os)throw new Error(Zt.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Xr(e,t)}catch(n){if(n.message===Zt.DBI_DOES_NOT_EXIST){let i=new em(r,s===!0),o=e.openDB(t,i),c=new n_(r===!0,s);return o[vb]=c,Xr(e,Os).putSync(t,c),e.dbis[t]=o,o}throw n}}a(qb,"createDBI");function Xr(e,t){if(o_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Os?r=VV(e,t):r=new n_,r===void 0)throw new Error(Zt.DBI_DOES_NOT_EXIST);let s;try{let n=new em(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(Zt.DBI_DOES_NOT_EXIST):n}return s[vb]=r,e.dbis[t]=s,s}a(Xr,"openDBI");function $V(e,t){o_(e,t),t=t.toString();let r=Xr(e,t),s=r.getStats();return r[zn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a($V,"statDBI");async function YV(e,t){try{let r=wr.join(e,t+gc);return(await As.stat(r)).size}catch{throw new Error(Zt.INVALID_ENVIRONMENT)}}a(YV,"environmentDataSize");function KV(e,t){if(o_(e,t),t=t.toString(),t===Os)throw new Error(Zt.CANNOT_DROP_INTERNAL_DBIS_NAME);Xr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Xr(e,Os).removeSync(t)}a(KV,"dropDBI");function WV(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{Xr(e,i)}catch(o){if(o.message===Zt.DBI_DOES_NOT_EXIST)qb(e,i,i!==t,i===t),s=!0;else throw o}}s&&vV()}a(WV,"initializeDBIs");Fb.exports={openDBI:Xr,openEnvironment:Bb,createEnvironment:qV,listDBIs:xb,listDBIDefinitions:kV,createDBI:qb,dropDBI:KV,statDBI:$V,deleteEnvironment:GV,initializeDBIs:WV,TransactionCursor:Xh,environmentDataSize:YV,copyEnvironment:FV,closeEnvironment:Hb}});var kb=T((lce,Gb)=>{"use strict";var sm=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};Gb.exports=sm});var $b=T((dce,Vb)=>{"use strict";var nm=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}};Vb.exports=nm});var Kb=T((Ece,Yb)=>{"use strict";var im=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};Yb.exports=im});var qo=T((Tce,zb)=>{"use strict";var QV=Ye(),zV=kb(),JV=$b(),jV=Kb(),ks=Nr(),Rc=br().LMDB_ERRORS_ENUM,XV=_t(),hn=L(),ZV=J(),e$=require("uuid"),mce=require("lmdb"),{handleHDBError:t$,hdb_errors:r$}=ee(),{OVERFLOW_MARKER:pce,MAX_SEARCH_KEY_LENGTH:Sce}=XV,Wb=X();Wb.initSync();var a_=Wb.get(hn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),om=hn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Pi=hn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function s$(e,t,r,s,n=ks.getNextMonotonicTime()){lm(e,t,r,s),am(e,t,r);let i=new zV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];Qb(_,!0,n);let l=n$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return cm(o,c,s,i,n)}a(s$,"insertRecords");function n$(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][hn.FUNC_VAL],s[o]=c)}let u=ks.getIndexedValues(c),_=e.dbis[o];if(u){a_&&_.prefetch(u.map(l=>({key:l,value:n})),c_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}a_&&e.dbis[t].prefetch([n],c_),e.dbis[t].put(n,s,s[Pi])})}a(n$,"insertRecord");function i$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(i$,"removeSkippedRecords");function Qb(e,t,r){let s=r>0;(s||!Number.isInteger(e[Pi]))&&(e[Pi]=r||(r=ks.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[om]))&&(e[om]=r||ks.getNextMonotonicTime()):delete e[om]}a(Qb,"setTimestamps");function am(e,t,r){r.indexOf(hn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(hn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(hn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(hn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),QV.initializeDBIs(e,t,r)}a(am,"initializeTransaction");async function o$(e,t,r,s,n=ks.getNextMonotonicTime()){lm(e,t,r,s),am(e,t,r);let i=new JV,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=um(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return cm(c,u,s,i,n,o)}a(o$,"updateRecords");async function a$(e,t,r,s,n=ks.getNextMonotonicTime()){try{lm(e,t,r,s)}catch(u){throw t$(u,u.message,r$.HTTP_STATUS_CODES.BAD_REQUEST)}am(e,t,r);let i=new jV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;ZV.isEmpty(_[t])?(l=e$.v4(),_[t]=l):l=_[t];let d=um(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return cm(o,c,s,i,n)}a(a$,"upsertRecords");async function cm(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||ks.getNextMonotonicTime(),i$(r,i),s}a(cm,"finalizeWrite");function um(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(Qb(r,!l,o),Number.isInteger(r[Pi])&&_[Pi]>r[Pi])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 O=_[h];if(typeof p=="function"){let R=p([[_]]);Array.isArray(R)&&(p=R[0][hn.FUNC_VAL],r[h]=p)}if(p===O)continue;let g=ks.getIndexedValues(O);if(g){a_&&S.prefetch(g.map(R=>({key:R,value:s})),c_);for(let R=0,B=g.length;R<B;R++)S.remove(g[R],s)}if(g=ks.getIndexedValues(p),g){a_&&S.prefetch(g.map(R=>({key:R,value:s})),c_);for(let R=0,B=g.length;R<B;R++)S.put(g[R],s)}}let E=Object.assign({},_,r);c.put(s,E,E[Pi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:um(e,t,r,s,n,i,o))}a(um,"updateUpsertRecord");function c$(e,t,r){if(ks.validateEnv(e),t===void 0)throw new Error(Rc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Rc.WRITE_ATTRIBUTES_REQUIRED):new Error(Rc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(c$,"validateBasic");function lm(e,t,r,s){if(c$(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Rc.RECORDS_REQUIRED):new Error(Rc.RECORDS_MUST_BE_ARRAY)}a(lm,"validateWrite");function c_(){}a(c_,"noop");zb.exports={insertRecords:s$,updateRecords:o$,upsertRecords:a$}});var vi=T((Rce,u$)=>{u$.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 $s=T((Ace,Xb)=>{"use strict";var jb=J(),Jb=L(),Fo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Vs=require("joi"),Jn={schema_format:{pattern:Fo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},l$=Vs.alternatives(Vs.string().min(1).max(Jn.schema_length.maximum).pattern(Fo).messages({"string.pattern.base":"{:#label} "+Jn.schema_format.message}),Vs.number(),Vs.array()).required(),_$=Vs.alternatives(Vs.string().min(1).max(Jn.schema_length.maximum).pattern(Fo).messages({"string.pattern.base":"{:#label} "+Jn.schema_format.message}),Vs.number()),d$=Vs.alternatives(Vs.string().min(1).max(Jn.schema_length.maximum).pattern(Fo).messages({"string.pattern.base":"{:#label} "+Jn.schema_format.message}),Vs.number()).required();function f$(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`:Fo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(f$,"checkValidTable");function E$(e,t){return jb.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(E$,"validateSchemaExists");function h$(e,t){let r=t.state.ancestors[0].schema;return jb.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(h$,"validateTableExists");function m$(e,t){return e.toLowerCase()===Jb.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Jb.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(m$,"validateSchemaName");Xb.exports={common_validators:Jn,schema_regex:Fo,hdb_schema_table:l$,validateSchemaExists:E$,validateTableExists:h$,validateSchemaName:m$,checkValidTable:f$,hdb_database:_$,hdb_table:d$}});var Qe=T((bce,Zb)=>{"use strict";var er=require("validate.js");er.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||er.validators.type.checks[t](e)?null:` must be a '${t}' value`};er.validators.type.checks={Object:function(e){return er.isObject(e)&&!er.isArray(e)},Array:er.isArray,Integer:er.isInteger,Number:er.isNumber,String:er.isString,Date:er.isDate,Boolean:function(e){return typeof e=="boolean"}};er.validators.hasValidFileExt=function(e,t){return er.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};Zb.exports={validateObject:p$,validateObjectAsync:S$,validateBySchema:T$};function p$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=er(e,t,{format:"flat"});return r?new Error(r):null}a(p$,"validateObject");async function S$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await er.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(S$,"validateObjectAsync");function T$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(T$,"validateBySchema")});var u_=T((yce,eN)=>{var{common_validators:Ys}=$s(),Oc=Qe(),Ac="is required",dt={database:{presence:!1,format:Ys.schema_format,length:Ys.schema_length},schema:{presence:!1,format:Ys.schema_format,length:Ys.schema_length},table:{presence:!0,format:Ys.schema_format,length:Ys.schema_length},attribute:{presence:!0,format:Ys.schema_format,length:Ys.schema_length},hash_attribute:{presence:!0,format:Ys.schema_format,length:Ys.schema_length}};function bc(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(bc,"makeAttributesStrings");function g$(e){return e=bc(e),dt.table.presence=!1,dt.attribute.presence=!1,dt.hash_attribute.presence=!1,Oc.validateObject(e,dt)}a(g$,"schema_object");function R$(e){return e=bc(e),dt.table.presence={message:Ac},dt.attribute.presence=!1,dt.hash_attribute.presence=!1,Oc.validateObject(e,dt)}a(R$,"table_object");function A$(e){return e=bc(e),dt.table.presence={message:Ac},dt.attribute.presence=!1,Oc.validateObject(e,dt)}a(A$,"create_table_object");function O$(e){return e=bc(e),dt.table.presence={message:Ac},dt.attribute.presence={message:Ac},dt.hash_attribute.presence=!1,Oc.validateObject(e,dt)}a(O$,"attribute_object");function b$(e){return e=bc(e),dt.table.presence={message:Ac},dt.attribute.presence=!1,dt.hash_attribute.presence=!1,Oc.validateObject(e,dt)}a(b$,"describe_table");function N$(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(N$,"validateTableResidence");eN.exports={schema_object:g$,create_table_object:A$,table_object:R$,attribute_object:O$,describe_table:b$,validateTableResidence:N$}});var rN=T((Ice,tN)=>{"use strict";var y$=require("uuid"),_m=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||y$.v4(),this.schema_table=`${this.schema}.${this.table}`}};tN.exports=_m});var l_=T((Dce,sN)=>{"use strict";var w$=rN(),dm=class extends w${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}};sN.exports=dm});var iN=T((Mce,nN)=>{"use strict";nN.exports=C$;var I$="inserted";function C$(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===I$?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(C$,"returnObject")});var __=T((Pce,lN)=>{"use strict";var D$=L(),fm=Ye(),L$=qo(),{getSystemSchemaPath:M$,getSchemaPath:U$}=We(),P$=vi(),v$=u_(),B$=l_(),H$=iN(),{handleHDBError:oN,hdb_errors:cN}=ee(),aN=J(),{HTTP_STATUS_CODES:x$}=cN,Em=P$.hdb_attribute,uN=[];for(let e=0;e<Em.attributes.length;e++)uN.push(Em.attributes[e].attribute);var q$="inserted";lN.exports=F$;async function F$(e){let t=v$.attribute_object(e);if(t)throw oN(new Error,t.message,cN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&aN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw oN(new Error,r,x$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=aN.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 B$(e.schema,e.table,e.attribute,e.id);try{let i=await fm.openEnvironment(U$(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}`);fm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await fm.openEnvironment(M$(),D$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await L$.insertRecords(o,Em.hash_attribute,uN,[n]);return H$(q$,c,{records:[n]},u)}catch(i){throw i}}a(F$,"lmdbCreateAttribute")});var mm=T((Bce,dN)=>{var{hdb_table:G$,hdb_database:_N}=$s(),k$=Qe(),hm=require("joi"),V$={undefined:"undefined",null:"null"},$$=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||V$[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"),Y$=hm.object({database:_N,schema:_N,table:G$,records:hm.array().items(hm.object().custom($$)).required()});dN.exports=function(e){return k$.validateBySchema(e,Y$)}});var Nc=T((qce,EN)=>{"use strict";var mn=J(),fN=V(),xce=mm(),{getDatabases:K$}=(be(),te(qe)),{ClientError:Bi}=ee();EN.exports=W$;function W$(e){if(mn.isEmpty(e))throw new Bi("invalid update parameters defined.");if(mn.isEmptyOrZeroLength(e.schema))throw new Bi("invalid schema specified.");if(mn.isEmptyOrZeroLength(e.table))throw new Bi("invalid table specified.");if(!Array.isArray(e.records))throw new Bi("records must be an array");let t=K$()[e.schema]?.[e.table];if(mn.isEmpty(t))throw new Bi(`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&&mn.isEmptyOrZeroLength(o[r]))throw fN.error("a valid hash attribute must be provided with update record:",o),new Bi("a valid hash attribute must be provided with update record, check log for more info");if(!mn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw fN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Bi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!mn.isEmpty(o[r])&&o[r]!==""&&s.has(mn.autoCast(o[r]))&&(o.skip=!0),s.add(mn.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(W$,"insertUpdateValidate")});var yc=T((Gce,hN)=>{"use strict";var Q$=L().OPERATIONS_ENUM,pm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=Q$.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};hN.exports=pm});var Dc=T(($ce,mN)=>{"use strict";var Vce=yc(),d_=L(),Tm=J(),Sm=V(),z$=require("uuid"),{handleHDBError:wc,hdb_errors:J$}=ee(),{HDB_ERROR_MSGS:Ic,HTTP_STATUS_CODES:Cc}=J$;mN.exports=j$;function j$(e,t,r){for(let n=0;n<t.length;n++)X$(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];Z$(i,r,e.operation)}}a(j$,"processRows");function X$(e){if(Buffer.byteLength(String(e))>d_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw wc(new Error,Ic.ATTR_NAME_LENGTH_ERR(e),Cc.BAD_REQUEST,void 0,void 0,!0);if(Tm.isEmptyOrZeroLength(e)||Tm.isEmpty(e.trim()))throw wc(new Error,Ic.ATTR_NAME_NULLISH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(X$,"validateAttribute");function Z$(e,t,r){if(!e.hasOwnProperty(t)||Tm.isEmptyOrZeroLength(e[t])){if(r===d_.OPERATIONS_ENUM.INSERT||r===d_.OPERATIONS_ENUM.UPSERT){e[t]=z$.v4();return}throw Sm.error("Update transaction aborted due to record with no hash value:",e),wc(new Error,Ic.RECORD_MISSING_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>d_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Sm.error(e),wc(new Error,Ic.HASH_VAL_LENGTH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Sm.error(e),wc(new Error,Ic.INVALID_FORWARD_SLASH_IN_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(Z$,"validateHash")});var SN=T((Kce,pN)=>{"use strict";var gm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};pN.exports=gm});var RN=T((Qce,gN)=>{"use strict";var Rm=Ye(),e1=V(),TN=br().LMDB_ERRORS_ENUM;gN.exports=t1;async function t1(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 Rm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==TN.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Rm.closeEnvironment(global.lmdb_map[s]),await Rm.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==TN.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){e1.error(t)}}a(t1,"cleanLMDBMap")});var pn=T((Jce,NN)=>{"use strict";var Lc=require("crypto"),r1=X(),{CONFIG_PARAMS:s1}=L(),ON="aes-256-cbc",n1=32,i1=16,Am=64,bN=32,o1=Am+bN,AN=new Map;NN.exports={encrypt:a1,decrypt:c1,createNatsTableStreamName:u1};function a1(e){let t=Lc.randomBytes(n1),r=Lc.randomBytes(i1),s=Lc.createCipheriv(ON,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(a1,"encrypt");function c1(e){let t=e.substr(0,Am),r=e.substr(Am,bN),s=e.substr(o1,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Lc.createDecipheriv(ON,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(c1,"decrypt");function u1(e,t){let r=r1.get(s1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=AN.get(r);return s||(s=Lc.createHash("md5").update(r).digest("hex"),AN.set(r,s)),s}a(u1,"createNatsTableStreamName")});var jn=T((Zce,wN)=>{"use strict";var Xce=Zr(),f_=V(),yN=u_(),l1=pn(),E_=J(),{handleHDBError:h_,hdb_errors:_1}=ee(),{HDB_ERROR_MSGS:m_,HTTP_STATUS_CODES:Om}=_1,d1=X();d1.initSync();var{getDatabases:bm}=(be(),te(qe));wN.exports={describeAll:f1,describeTable:p_,describeSchema:E1};async function f1(e){try{let t=E_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=bm(),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 p_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await p_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){f_.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 f_.error("Got an error in describeAll"),f_.error(t),h_(new Error,m_.DESCRIBE_ALL_ERR)}}a(f1,"describeAll");async function p_(e,t){E_.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=yN.describe_table(e);if(i)throw i;let c=bm()[r];if(!c)throw h_(new Error,m_.SCHEMA_NOT_FOUND(e.schema),Om.NOT_FOUND);let u=c[s];if(!u)throw h_(new Error,m_.TABLE_NOT_FOUND(e.schema,e.table),Om.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=l1.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){f_.warn(`unable to stat table dbi due to ${f}`)}return d}a(p_,"descTable");async function E1(e){E_.transformReq(e);let t=yN.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=bm()[s];if(!i)throw h_(new Error,m_.SCHEMA_NOT_FOUND(e.schema),Om.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),E_.isEmpty(u)||u.describe){let _=await p_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(E1,"describeSchema")});var Sn=T((sue,MN)=>{var h1=vi(),{callbackify:CN,promisify:m1}=require("util"),{getDatabases:DN}=(be(),te(qe));MN.exports={setSchemaDataToGlobal:IN,getTableSchema:p1,getSystemSchema:S1,setSchemaDataToGlobalAsync:m1(IN)};var LN=jn(),tue=CN(LN.describeAll),rue=CN(LN.describeTable);function IN(e){global.hdb_schema=DN(),e&&e()}a(IN,"setSchemaDataToGlobal");function p1(e,t,r){let s=DN()[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(p1,"getTableSchema");function S1(){return h1}a(S1,"getSystemSchema")});var Ir=T((iue,BN)=>{"use strict";var T_=mm(),Bt=J(),T1=require("util"),g_=bs(),g1=Sn(),UN=V(),{handleHDBError:Hi,hdb_errors:R1}=ee(),{HTTP_STATUS_CODES:xi}=R1,A1=T1.promisify(g1.getTableSchema),O1="updated",PN="inserted",vN="upserted";BN.exports={insert:N1,update:y1,upsert:w1,validation:b1,flush:I1};async function b1(e){if(Bt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Bt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Bt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await A1(e.schema,e.table),r=T_(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&&Bt.isEmptyOrZeroLength(c[s]))throw UN.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(!Bt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw UN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Bt.isEmpty(c[s])&&c[s]!==""&&n.has(Bt.autoCast(c[s]))&&(c.skip=!0),n.add(Bt.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(b1,"validation");async function N1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=T_(e);if(t)throw Hi(new Error,t.message,xi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw Hi(new Error,r,xi.BAD_REQUEST);let s=await g_.createRecords(e);return S_(PN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(N1,"insertData");async function y1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=T_(e);if(t)throw Hi(new Error,t.message,xi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw Hi(new Error,r,xi.BAD_REQUEST);let s=await g_.updateRecords(e);return Bt.isEmpty(s.existing_rows)?S_(O1,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):S_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(y1,"updateData");async function w1(e){if(e.operation!=="upsert")throw Hi(new Error,"invalid operation, must be upsert",xi.INTERNAL_SERVER_ERROR);let t=T_(e);if(t)throw Hi(new Error,t.message,xi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw Hi(new Error,r,xi.BAD_REQUEST);let s=await g_.upsertRecords(e);return S_(vN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(w1,"upsertData");function S_(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===PN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===vN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(S_,"returnObject");function I1(e){return Bt.transformReq(e),g_.flush(e.schema,e.table)}a(I1,"flush")});var ym=T((aue,qN)=>{var C1=Qe(),Nm=require("joi"),{hdb_table:D1,hdb_database:HN}=$s(),xN={schema:HN,database:HN,table:D1},L1={date:Nm.date().iso().required()},M1={timestamp:Nm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};qN.exports=function(e,t){let r=t==="timestamp"?{...xN,...M1}:{...xN,...L1},s=Nm.object(r);return C1.validateBySchema(e,s)}});var kN=T((cue,GN)=>{var U1=Qe(),wm=require("joi"),{hdb_table:P1,hdb_database:FN}=$s(),v1=wm.object({schema:FN,database:FN,table:P1,hash_values:wm.array().required(),ids:wm.array()});GN.exports=function(e){return U1.validateBySchema(e,v1)}});var $N=T((uue,VN)=>{"use strict";var Im=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}},Cm=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}},Dm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};VN.exports={InsertObject:Im,NoSQLSeachObject:Cm,DeleteResponseObject:Dm}});var ei=T((_ue,zN)=>{"use strict";var KN=ym(),B1=kN(),qi=J(),YN=require("moment"),WN=V(),{promisify:H1,callbackify:x1}=require("util"),Fi=L(),q1=Sn(),Lm=H1(q1.getTableSchema),Mm=bs(),{DeleteResponseObject:F1}=$N(),{handleHDBError:Xn,hdb_errors:G1}=ee(),{HDB_ERROR_MSGS:R_,HTTP_STATUS_CODES:Zn}=G1,k1="records successfully deleted",V1=x1(QN);zN.exports={delete:V1,deleteRecord:QN,deleteFilesBefore:$1,deleteAuditLogsBefore:Y1};async function $1(e){let t=KN(e,"date");if(t)throw Xn(t,t.message,Zn.BAD_REQUEST,void 0,void 0,!0);if(qi.transformReq(e),!YN(e.date,YN.ISO_8601).isValid())throw Xn(new Error,R_.INVALID_DATE,Zn.BAD_REQUEST,Fi.LOG_LEVELS.ERROR,R_.INVALID_DATE,!0);let s=qi.checkSchemaTableExist(e.schema,e.table);if(s)throw Xn(new Error,s,Zn.NOT_FOUND,Fi.LOG_LEVELS.ERROR,s,!0);let n=await Mm.deleteRecordsBefore(e);if(await Lm(e.schema,e.table),WN.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a($1,"deleteFilesBefore");async function Y1(e){let t=KN(e,"timestamp");if(t)throw Xn(t,t.message,Zn.BAD_REQUEST,void 0,void 0,!0);if(qi.transformReq(e),isNaN(e.timestamp))throw Xn(new Error,R_.INVALID_VALUE("Timestamp"),Zn.BAD_REQUEST,Fi.LOG_LEVELS.ERROR,R_.INVALID_VALUE("Timestamp"),!0);let r=qi.checkSchemaTableExist(e.schema,e.table);if(r)throw Xn(new Error,r,Zn.NOT_FOUND,Fi.LOG_LEVELS.ERROR,r,!0);let s=await Mm.deleteAuditLogsBefore(e);return await Lm(e.schema,e.table),WN.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(Y1,"deleteAuditLogsBefore");async function QN(e){e.ids&&(e.hash_values=e.ids);let t=B1(e);if(t)throw Xn(t,t.message,Zn.BAD_REQUEST,void 0,void 0,!0);qi.transformReq(e);let r=qi.checkSchemaTableExist(e.schema,e.table);if(r)throw Xn(new Error,r,Zn.NOT_FOUND,Fi.LOG_LEVELS.ERROR,r,!0);try{await Lm(e.schema,e.table);let s=await Mm.deleteRecords(e);return qi.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${k1}`),s}catch(s){if(s.message===Fi.SEARCH_NOT_FOUND_MESSAGE){let n=new F1;return n.message=Fi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(QN,"deleteRecord")});var A_=T((fue,XN)=>{var K1=require("crypto"),JN=9;function W1(e){let t=z1(JN),r=jN(e+t);return t+r}a(W1,"createHash");function Q1(e,t){let r=e?.substr(0,JN),s=r+jN(t+r);return e===s}a(Q1,"validateHash");function z1(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(z1,"generateSalt");function jN(e){return K1.createHash("md5").update(e).digest("hex")}a(jN,"md5");XN.exports={hash:W1,validate:Q1}});var ey=T((hue,ZN)=>{var Um=Qe(),Vt={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 J1(e){return Vt.password.presence=!0,Vt.username.presence=!0,Vt.role.presence=!0,Vt.active.presence=!0,Um.validateObject(e,Vt)}a(J1,"addUserValidation");function j1(e){return Vt.password.presence=!1,Vt.username.presence=!0,Vt.role.presence=!1,Vt.active.presence=!1,Um.validateObject(e,Vt)}a(j1,"alterUserValidation");function X1(e){return Vt.password.presence=!1,Vt.username.presence=!0,Vt.role.presence=!1,Vt.active.presence=!1,Um.validateObject(e,Vt)}a(X1,"dropUserValidation");ZN.exports={addUserValidation:J1,alterUserValidation:j1,dropUserValidation:X1}});var Fe=T((Sue,ry)=>{"use strict";var{platform:pue}=require("os"),Z1="nats-server.zip",Pm="nats-server",eY=process.platform==="win32"?`${Pm}.exe`:Pm,vm="HDB",tY=/^[^\s.,*>]+$/,ty="__request__",rY=a(e=>`${e}.${ty}`,"REQUEST_SUBJECT"),sY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},nY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},iY={HUB:"hub.pid",LEAF:"leaf.pid"},oY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},aY={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:vm,deliver_subject:"__HDB__.WORKQUEUE"},cY={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:vm,deliver_subject:"HDB.SCHEMAQUEUE"},uY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:vm,deliver_subject:"HDB.USERQUEUE"},lY={SUCCESS:"success",ERROR:"error"},_Y={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},dY={TXN:"txn",MSGID:"msgid"},Go={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},fY={[Go.ERR]:1,[Go.WRN]:2,[Go.INF]:3,[Go.DBG]:4,[Go.TRC]:5},EY={debug:"-D",trace:"-DVV"};ry.exports={NATS_SERVER_ZIP:Z1,NATS_SERVER_NAME:Pm,NATS_BINARY_NAME:eY,PID_FILES:iY,NATS_CONFIG_FILES:nY,SERVER_SUFFIX:oY,WORK_QUEUE_CONSUMER_NAMES:aY,SCHEMA_QUEUE_CONSUMER_NAMES:cY,USER_QUEUE_CONSUMER_NAMES:uY,NATS_TERM_CONSTRAINTS_RX:tY,REQUEST_SUFFIX:ty,UPDATE_REMOTE_RESPONSE_STATUSES:lY,CLUSTER_STATUS_STATUSES:_Y,REQUEST_SUBJECT:rY,SUBJECT_PREFIXES:dY,MSG_HEADERS:sY,LOG_LEVELS:Go,LOG_LEVEL_FLAGS:EY,LOG_LEVEL_HIERARCHY:fY}});var ny=T((gue,sy)=>{"use strict";var hY={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 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
|
+
`,$G={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},YG=["*","%"],KG="unauthorized_access",WG="func_val",QG={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"},JG={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"},jG={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},XG={HTTP:"http"},ZG={STOPPED:"stopped",ONLINE:"online"},ek="3.x.x",tk={SUCCESS:"success",FAILURE:"failure"},rk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};aO.exports={LOCAL_HARPERDB_OPERATIONS:Be,HDB_SUPPORT_ADDRESS:jA,HDB_SUPPORT_URL:ZA,HDB_PRICING_URL:NF,SUPPORT_HELP_MSG:yF,LICENSE_HELP_MSG:eO,HDB_PROC_NAME:zA,HDB_PROC_DESCRIPTOR:lh,CLUSTERING_LEAF_PROC_DESCRIPTOR:ql,CLUSTERING_HUB_PROC_DESCRIPTOR:xl,SYSTEM_SCHEMA_NAME:YF,HASH_FOLDER_NAME:KF,HDB_HOME_DIR_NAME:WF,UPDATE_FILE_NAME:jF,LICENSE_KEY_DIR_NAME:zF,BOOT_PROPS_FILE_NAME:JF,JOB_TYPE_ENUM:IG,JOB_STATUS_ENUM:TG,SYSTEM_TABLE_NAMES:fG,SYSTEM_TABLE_HASH_ATTRIBUTES:EG,OPERATIONS_ENUM:X,VALID_S3_FILE_TYPES:gG,S3_BUCKET_AUTH_KEYS:RG,VALID_SQL_OPS_ENUM:AG,GEO_CONVERSION_ENUM:bG,HDB_SETTINGS_NAMES:sO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:NG,SERVICE_ACTIONS_ENUM:OG,CLUSTER_MESSAGE_TYPE_ENUM:CG,CLUSTER_CONNECTION_DIRECTION_ENUM:DG,CLUSTER_EVENTS_DEFS_ENUM:MG,PERIOD_REGEX:MF,DOUBLE_PERIOD_REGEX:PF,UNICODE_PERIOD:vF,FORWARD_SLASH_REGEX:BF,UNICODE_FORWARD_SLASH:HF,ESCAPED_FORWARD_SLASH_REGEX:xF,ESCAPED_PERIOD_REGEX:qF,ESCAPED_DOUBLE_PERIOD_REGEX:FF,REG_KEY_FILE_NAME:pG,RESTART_TIMEOUT_MS:eG,HDB_FILE_PERMISSIONS:tG,DATABASES_DIR_NAME:nG,LEGACY_DATABASES_DIR_NAME:iG,TRANSACTIONS_DIR_NAME:oG,LIMIT_COUNT_NAME:aG,ID_ATTRIBUTE_STRING:cG,INSERT_MODULE_ENUM:_G,UPGRADE_JSON_FIELD_NAMES_ENUM:dG,RESTART_CODE:XF,RESTART_CODE_NUM:ZF,CLUSTER_OPERATIONS:rc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:mG,HDB_INTERNAL_SC_CHANNEL_PREFIX:Ar,INTERNAL_SC_CHANNELS:hG,CLUSTERING_MESSAGE_TYPES:GG,HDB_FILE_SUFFIX:QF,BLOB_FOLDER_NAME:rG,HDB_TRASH_DIR:sG,ORIGINATOR_SET_VALUE:kG,LICENSE_VALUES:LG,RAM_ALLOCATION_ENUM:UG,TIME_STAMP_NAMES_ENUM:iO,TIME_STAMP_NAMES:xG,PERMS_UPDATE_RELEASE_TIMESTAMP:qG,SEARCH_NOT_FOUND_MESSAGE:wF,SEARCH_ATTRIBUTE_NOT_FOUND:IF,LICENSE_ROLE_DENIED_RESPONSE:CF,LICENSE_MAX_CONNS_REACHED:DF,BASIC_LICENSE_MAX_NON_CU_ROLES:XA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:bF,VALUE_SEARCH_COMPARATORS:oO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:FG,LICENSE_FILE_NAME:SG,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:PG,NEW_LINE:VG,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:UF,MOMENT_DAYS_TAG:GF,API_TURNOVER_SEC:kF,LOOPBACK:LF,CODE_EXTENSION:Hl,WILDCARD_SEARCH_VALUE:VF,NODE_ERROR_CODES:vG,JAVASCRIPT_EXTENSION:QA,PERMS_CRUD_ENUM:$G,UNAUTHORIZED_PERMISSION_NAME:KG,SEARCH_WILDCARDS:YG,FUNC_VAL:WG,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:QG,JWT_ENUM:zG,CLUSTERING_FLAG:HG,ITC_EVENT_TYPES:JG,CUSTOM_FUNCTION_PROC_NAME:JA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Bl,SERVICES:jG,THREAD_TYPES:XG,MEM_SETTING_KEY:$F,HDB_RESTART_SCRIPT:uF,PROCESS_DESCRIPTORS:hF,SERVICE_SERVERS:gF,SERVICE_SERVERS_CWD:uh,PROCESS_DESCRIPTORS_VALIDATE:SF,LAUNCH_SERVICE_SCRIPTS:RF,LOG_LEVELS:pF,PROCESS_NAME_ENV_PROP:uG,LOG_NAMES:mF,PM2_PROCESS_STATUSES:ZG,CONFIG_PARAM_MAP:nO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:oF,HDB_DEFAULT_CONFIG_FILE:aF,ROLE_TYPES_ENUM:AF,BOOT_PROP_PARAMS:tO,INSTALL_PROMPTS:lG,HDB_ROOT_DIR_NAME:cF,CLUSTERING_PROCESSES:TF,FOREGROUND_PID_FILE:dF,PACKAGE_ROOT:Qn,PRE_4_0_0_VERSION:ek,DATABASES_PARAM_CONFIG:wG,METADATA_PROPERTY:BG,AUTH_AUDIT_STATUS:tk,AUTH_AUDIT_TYPES:rk,HDB_PID_FILE:fF,DEFAULT_DATABASE_NAME:EF,LEGACY_CONFIG_PARAMS:yG};WA()});var _h=T((Aae,lO)=>{"use strict";var cO=require("minimist");lO.exports=sk;function sk(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=uO(process.env),s=uO(cO(process.argv))):(r=process.env,s=cO(process.argv));let n={};for(let i=0,o=e.length;i<o;i++){let c=e[i];s[c]!==void 0?n[c]=s[c].toString().trim():r[c]!==void 0&&(n[c]=r[c].toString().trim())}return n}a(sk,"assignCMDENVVariables");function uO(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(uO,"objKeysToLowerCase")});var V=T((bae,Sh)=>{"use strict";var Ui=require("fs-extra"),{workerData:nk,threadId:ik}=require("worker_threads"),En=require("path"),fO=require("yaml"),EO=require("properties-reader"),gt=L(),_O=_h(),ok=require("os"),{PACKAGE_ROOT:fh}=L(),{_assignPackageExport:ak}=require("../index"),nc={};for(let e in console)nc[e]||(nc[e]=console[e]);var Zt={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},hO={STDOUT:"stdOut",STDERR:"stdErr"},ck=En.join(fh,"logs"),uk=En.join(fh,"config/yaml/",gt.HDB_DEFAULT_CONFIG_FILE),lk=1e4,fn,ks,Xt,Fl,Gl,ic,Bo,sc;sc===void 0&&mO();Sh.exports={notify:TO,fatal:gO,error:oc,warn:ph,info:kl,debug:mh,trace:hh,setLogLevel:pk,log_level:Xt,loggerWithTag:_k,suppressLogging:dk,initLogSettings:mO,setupConsoleLogging:pO,logCustomLevel:hk,closeLogFile:Eh,getLogFilePath:()=>ic,OUTPUTS:hO,AuthAuditLog:gk};ak("logger",Sh.exports);function mO(e=!1){try{if(sc===void 0||e){Eh();let t=mk(),r=_O(["ROOTPATH"]);try{sc=EO(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!Ui.pathExistsSync(En.join(r.ROOTPATH,gt.HDB_CONFIG_FILE)))throw s}({level:Xt,config_log_path:Gl,to_file:fn,to_stream:ks}=Sk(r.ROOTPATH?En.join(r.ROOTPATH,gt.HDB_CONFIG_FILE):sc.get("settings_path"))),Fl=gt.LOG_NAMES.HDB,ic=En.join(Gl,Fl)}}catch(t){if(sc=void 0,t.code===gt.NODE_ERROR_CODES.ENOENT){let r=_O(Object.keys(gt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=gt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===gt.CONFIG_PARAMS.LOGGING_LEVEL){Xt=u;continue}if(c===gt.CONFIG_PARAMS.LOGGING_STDSTREAMS){ks=u;continue}c===gt.CONFIG_PARAMS.LOGGING_FILE&&(fn=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=Tk();fn=fn===void 0?n:fn,fn=dO(fn),ks=ks===void 0?i:ks,ks=dO(ks),Xt=Xt===void 0?s:Xt,Gl=ck,Fl=gt.LOG_NAMES.INSTALL,ic=En.join(Gl,Fl);return}throw oc("Error initializing log settings"),oc(t),t}process.env.DEV_MODE&&(ks=!0),pO()}a(mO,"initLogSettings");var dh=!0;function pO(){vo("error",oc),vo("warn",ph),vo("log",kl),vo("info",kl),vo("debug",mh),vo("trace",hh)}a(pO,"setupConsoleLogging");function vo(e,t){console[e]=function(...r){if(dh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return nc[e](...r)}}a(vo,"logConsole");function _k(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(TO),fatal:r(gO),error:r(oc),warn:r(ph),info:r(kl),debug:r(mh),trace:r(hh)};function r(s){return function(...n){return s(t,...n)}}}a(_k,"loggerWithTag");function dk(e){try{dh=!1,e()}finally{dh=!0}}a(dk,"suppressLogging");var fk=nk?.name?.replace(/ /g,"-")||"main";function hn(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-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||fk+"/"+ik);c<n;c++){let _=t[c];_ instanceof Error&&_.stack?s+=_.stack:typeof _=="object"?s+=JSON.stringify(_):s+=_,c<i&&(s+=" ")}return`${r} [${o.join("] [")}]: ${s}
|
|
3
|
+
`}a(hn,"createLogRecord");function ac(e){fn&&SO(e),ks&&process.stdout.write(e)}a(ac,"logStdOut");function Vl(e){fn&&SO(e),ks&&process.stderr.write(e)}a(Vl,"logStdErr");function SO(e){Ek(),Bo?Ui.appendFileSync(Bo,e):nc.log(e)}a(SO,"logToFile");function Eh(){try{Ui.closeSync(Bo)}catch{}Bo=null}a(Eh,"closeLogFile");function Ek(){if(!Bo){try{if(!ic)debugger;Bo=Ui.openSync(ic,"a")}catch(e){nc.error(e)}setTimeout(()=>{Eh()},lk).unref()}}a(Ek,"openLogFile");function kl(...e){Zt[Xt]<=Zt.info&&ac(hn("info",e))}a(kl,"info");function hh(...e){Zt[Xt]<=Zt.trace&&ac(hn("trace",e))}a(hh,"trace");function oc(...e){Zt[Xt]<=Zt.error&&Vl(hn("error",e))}a(oc,"error");function mh(...e){Zt[Xt]<=Zt.debug&&ac(hn("debug",e))}a(mh,"debug");function TO(...e){Zt[Xt]<=Zt.notify&&ac(hn("notify",e))}a(TO,"notify");function gO(...e){Zt[Xt]<=Zt.fatal&&Vl(hn("fatal",e))}a(gO,"fatal");function ph(...e){Zt[Xt]<=Zt.warn&&Vl(hn("warn",e))}a(ph,"warn");function hk(e,t,...r){t===hO.STDERR?Vl(hn(e,r)):ac(hn(e,r))}a(hk,"logCustomLevel");function mk(){let e;try{e=ok.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=En.join(e,gt.HDB_HOME_DIR_NAME,gt.BOOT_PROPS_FILE_NAME);return Ui.existsSync(t)||(t=En.join(fh,"utility/hdb_boot_properties.file")),t}a(mk,"getPropsFilePath");function pk(e){Xt=e}a(pk,"setLogLevel");function dO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(dO,"autoCastBoolean");function Sk(e){try{if(e.includes("config/settings.js")){let o=EO(e);return{level:o.get(gt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:En.dirname(o.get(gt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(gt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(gt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=fO.parseDocument(Ui.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),s=t.getIn(["logging","root"]),n=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:s,to_file:n,to_stream:i}}catch(t){if(t.code===gt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Sk,"getLogConfig");function Tk(){try{let e=fO.parseDocument(Ui.readFileSync(uk,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),s=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:s}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(Tk,"getDefaultConfig");function gk(e,t,r,s,n,i){this.username=e,this.status=t,this.type=r,this.originating_ip=s,this.request_method=n,this.path=i}a(gk,"AuthAuditLog")});var AO=T((yae,RO)=>{"use strict";var Rk=require("util"),Ak=require("path"),Ok=require("child_process"),bk=Rk.promisify(Ok.execFile),Nk=1e3*1e3*10;RO.exports={findPs:yk};async function yk(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await bk("ps",["wwxo",`pid,${r}`],{maxBuffer:Nk});for(let n of s.trim().split(`
|
|
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
|
|
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
|
-
`)},mY="certificate.pem",pY="privateKey.pem",SY="ca.pem";sy.exports={CERTIFICATE_VALUES:hY,CERTIFICATE_PEM_NAME:mY,PRIVATEKEY_PEM_NAME:pY,CA_PEM_NAME:SY}});var Hm=T((Aue,uy)=>{"use strict";var cy=require("fs-extra"),ue=require("joi"),TY=require("os"),{boolean:De,string:Cr,number:Dt,array:Bm}=ue.types(),{totalmem:iy}=require("os"),Gi=require("path"),gY=V(),O_=J(),Rue=ny(),oy=L(),RY=Qe(),ay="log",AY="components",OY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",bY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",NY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",yY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",wY="rootPath config parameter is undefined",IY="clustering.enabled config parameter is undefined",ki=Dt.min(0).required(),b_=Bm.items({host:Cr.required(),port:ki}).empty(null),Ks;uy.exports={configValidator:CY,routesValidator:vY,route_constraints:b_};function CY(e){if(Ks=e.rootPath,O_.isEmpty(Ks))throw wY;let t=De.required(),r=Dt.min(0).max(1e3).empty(null).default(PY),s=Cr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Mc),n=Cr.optional().empty(null),i=Cr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ue.string().empty(null).default(Mc),c=ue.custom(LY).empty(null).default(Mc),u=e.clustering?.enabled;if(O_.isEmpty(u))throw IY;let _;return u===!0?_=ue.object({enabled:t,hubServer:ue.object({cluster:ue.object({name:ue.required().empty(null),network:ue.object({port:ki,routes:b_}).required()}).required(),leafNodes:ue.object({network:ue.object({port:ki}).required()}).required(),network:ue.object({port:ki}).required()}).required(),leafServer:ue.object({network:ue.object({port:ki,routes:b_}).required(),streams:ue.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:ue.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:De.optional(),databaseLevel:De.optional(),tls:ue.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:De.required(),verify:De.optional()}),user:Cr.optional().empty(null)}).required():_=ue.object({enabled:t,tls:ue.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:De.required()})}).required(),ue.object({authentication:ue.object({authorizeLocal:De,cacheTTL:Dt.required(),enableSessions:De}),analytics:ue.object({aggregatePeriod:Dt}),componentsRoot:s.optional(),clustering:_,localStudio:ue.object({enabled:t}).required(),logging:ue.object({auditAuthEvents:ue.object({logFailed:De,logSuccessful:De}),file:De.required(),level:ue.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ue.object({enabled:De.optional(),compress:De.optional(),interval:Cr.custom(UY).optional().empty(null),maxSize:Cr.custom(MY).optional().empty(null),path:Cr.optional().empty(null).default(Mc)}).required(),root:s,stdStreams:De.required(),auditLog:De.required()}).required(),operationsApi:ue.object({network:ue.object({cors:De.optional(),corsAccessList:Bm.optional(),headersTimeout:Dt.min(1).optional(),keepAliveTimeout:Dt.min(1).optional(),port:Dt.optional().empty(null),domainSocket:ue.optional().empty("hdb/operations-server").default(Mc),securePort:Dt.optional().empty(null),timeout:Dt.min(1).optional()}).optional(),tls:ue.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:Cr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ue.object({network:ue.object({port:ki,securePort:ki,mtls:ue.alternatives([De.optional(),ue.object({user:Cr.optional(),certificateAuthority:n,required:De.optional()})])}).required(),webSocket:De.optional(),requireAuthentication:De.optional()}),http:ue.object({compressionThreshold:Dt.optional(),cors:De.optional(),corsAccessList:Bm.optional(),headersTimeout:Dt.min(1).optional(),port:Dt.min(0).optional().empty(null),securePort:Dt.min(0).optional().empty(null),mtls:ue.alternatives([De.optional(),ue.object({user:Cr.optional(),certificateAuthority:n,required:De.optional()})])}).required(),threads:r.optional(),maxHeapMemory:Dt.min(0).optional(),storage:ue.object({writeAsync:De.required(),overlappingSync:De.optional(),caching:De.optional(),compression:De.optional(),noReadAhead:De.optional(),path:c,prefetchWrites:De.optional()}).required(),ignoreScripts:De.optional(),tls:ue.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:Cr.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(CY,"configValidator");function DY(e){return cy.existsSync(e)?null:`Specified path ${e} does not exist.`}a(DY,"doesPathExist");function LY(e,t){ue.assert(e,Cr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=DY(e);if(r)return t.message(r)}a(LY,"validatePath");function MY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(OY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(NY):e}a(MY,"validateRotationMaxSize");function UY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(bY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(yY):e}a(UY,"validateRotationInterval");function PY(e,t){let r=t.state.path.join("."),s=TY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||iy();return i=Math.round(Math.min(i,iy())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),gY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(PY,"setDefaultThreads");function Mc(e,t){let r=t.state.path.join(".");if(!O_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(O_.isEmpty(Ks))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Gi.join(Ks,AY);case"logging.root":return Gi.join(Ks,ay);case"clustering.leafServer.streams.path":return Gi.join(Ks,"clustering","leaf");case"storage.path":let s=Gi.join(Ks,oy.LEGACY_DATABASES_DIR_NAME);return cy.existsSync(s)?s:Gi.join(Ks,oy.DATABASES_DIR_NAME);case"logging.rotation.path":return Gi.join(Ks,ay);case"operationsApi.network.domainSocket":return r==null?null:Gi.join(Ks,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Mc,"setDefaultRoot");function vY(e){let t=ue.object({routes:b_});return RY.validateBySchema({routes:e},t)}a(vY,"routesValidator")});var Mr=T((Nue,Sy)=>{"use strict";var Lr=L(),Lt=J(),Rt=V(),{configValidator:BY,routesValidator:ly}=Hm(),tr=require("fs-extra"),HY=require("yaml"),Ns=require("path"),xY=require("is-number"),dy=require("properties-reader"),qY=require("lodash"),{handleHDBError:FY}=ee(),{HTTP_STATUS_CODES:GY,HDB_ERROR_MSGS:N_}=br(),bue=require("minimist"),{server:kY}=(Xt(),te(Di)),{DATABASES_PARAM_CONFIG:Uc,CONFIG_PARAMS:Dr,CONFIG_PARAM_MAP:ys}=Lr,VY="Unable to get config value because config is uninitialized",$Y="Config successfully initialized",YY="Error backing up config file",KY="Empty parameter sent to getConfigValue",fy=Ns.join(Lr.PACKAGE_ROOT,"config","yaml",Lr.HDB_DEFAULT_CONFIG_FILE),WY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",_y={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"},y_,At,w_;Sy.exports={createConfigFile:QY,getDefaultConfig:zY,getConfigValue:hy,initConfig:qm,flattenConfig:ko,updateConfigValue:my,updateConfigObject:jY,getConfiguration:eK,setConfiguration:tK,readConfigFile:Gm,getClusteringRoutes:rK,initOldConfig:py,getConfigFromFile:sK,getConfigFilePath:Vi,addConfig:nK,deleteConfigFromFile:iK,getConfigObj:oK};function QY(e){let t=ti(fy);y_=ko(t.toJSON());let r;for(let o in e){let c=ys[o.toLowerCase()];if(c===Dr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=xm(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){Rt.error(l)}}}r&&Ey(t,r),Fm(t);let s=t.toJSON();At=ko(s);let n=t.getIn(["rootPath"]),i=Ns.join(n,Lr.HDB_CONFIG_FILE);tr.createFileSync(i),tr.writeFileSync(i,String(t)),Rt.trace(`Config file written to ${i}`)}a(QY,"createConfigFile");function Ey(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(Uc.TABLES))for(let i in s[n][Uc.TABLES])for(let o in s[n][Uc.TABLES][i]){let c=s[n][Uc.TABLES][i][o],u=[Dr.DATABASES,n,Uc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Dr.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){Rt.error("Error parsing schemas CLI/env config arguments",s)}}a(Ey,"setSchemasConfig");function zY(e){if(y_===void 0){let r=ti(fy);y_=ko(r.toJSON())}let t=ys[e.toLowerCase()];if(t!==void 0)return y_[t.toLowerCase()]}a(zY,"getDefaultConfig");function hy(e){if(e==null){Rt.error(KY);return}if(At===void 0){Rt.trace(VY);return}let t=ys[e.toLowerCase()];if(t!==void 0)return At[t.toLowerCase()]}a(hy,"getConfigValue");function Vi(e=Lt.getPropsFilePath()){let t=Lt.getEnvCliRootPath();return t?Ns.join(t,Lr.HDB_CONFIG_FILE):dy(e).get(Lr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Vi,"getConfigFilePath");function qm(e=!1){if(At===void 0||e){let t;if(!Lt.noBootFile()){t=Lt.getPropsFilePath();try{tr.accessSync(t,tr.constants.F_OK|tr.constants.R_OK)}catch(i){throw Rt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Vi(t),s;if(r.includes("config/settings.js"))try{py(r);return}catch(i){if(i.code!==Lr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ti(r)}catch(i){if(i.code===Lr.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}`)}JY(s,r),Fm(s);let n=s.toJSON();if(kY.config=n,At=ko(n),At.logging_rotation_rotate)for(let i in _y)At[i]&&Rt.error(`Config ${_y[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Rt.trace($Y)}}a(qm,"initConfig");function JY(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Ns.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Ns.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Ns.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"),tr.writeFileSync(t,String(e)))}a(JY,"checkForUpdatedConfig");function Fm(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=BY(t);if(r.error)throw N_.CONFIG_VALIDATION(r.error.message);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(Fm,"validateConfig");function jY(e,t){At===void 0&&(At={});let r=ys[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(jY,"updateConfigObject");function my(e,t,r=void 0,s=!1,n=!1,i=!1){At===void 0&&qm();let o=hy(ys.hdb_root),c=Ns.join(o,Lr.HDB_CONFIG_FILE),u=ti(c),_;if(r===void 0&&e.toLowerCase()===Dr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=ys[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=xm(f,t);u.setIn([...E],h)}else for(let f in r){let E=ys[f.toLowerCase()];if(E===Dr.HTTP_SECUREPORT&&r[f]===At[Dr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Dr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===At[Dr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Dr.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Lr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=xm(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(O){Rt.error(O)}}}_&&Ey(u,_),Fm(u);let l=u.getIn(["rootPath"]),d=Ns.join(l,Lr.HDB_CONFIG_FILE);s===!0&&XY(c,l),tr.writeFileSync(d,String(u)),n&&(At=ko(u.toJSON())),Rt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(my,"updateConfigValue");function XY(e,t){try{let r=Ns.join(t,"backup",`${Lr.HDB_CONFIG_FILE}.bak`);tr.copySync(e,r),Rt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Rt.error(YY),Rt.error(r)}}a(XY,"backupConfigFile");var ZY=["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)),w_=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])&&!ZY.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Dr[u.toUpperCase()]&&ys[u]&&(n[ys[u].toLowerCase()]=o[c]),n[u]=o[c]}}s[i]!==void 0&&(n[i.toLowerCase()]=s[i])}return n}a(r,"squashObj")}a(ko,"flattenConfig");function xm(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(xY(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(xm,"castConfigValue");function eK(){let e=Lt.getPropsFilePath(),t=Vi(e);return ti(t).toJSON()}a(eK,"getConfiguration");async function tK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return my(void 0,void 0,n,!0),WY}catch(i){throw typeof i=="string"||i instanceof String?FY(i,i,GY.BAD_REQUEST,void 0,void 0,!0):i}}a(tK,"setConfiguration");function Gm(){let e=Lt.getPropsFilePath();try{tr.accessSync(e,tr.constants.F_OK|tr.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=Vi(e);return ti(t).toJSON()}a(Gm,"readConfigFile");function ti(e){return HY.parseDocument(tr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ti,"parseYamlDoc");function rK(){let e=Gm(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Lt.isEmptyOrZeroLength(t)?[]:t;let r=ly(t);if(r)throw N_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Lt.isEmptyOrZeroLength(s)?[]:s;let n=ly(s);if(n)throw N_.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 N_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(rK,"getClusteringRoutes");function py(e){let t=dy(e);At={};for(let r in ys){let s=t.get(r.toUpperCase());if(Lt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=ys[r].toLowerCase();n===Dr.LOGGING_ROOT?At[n]=Ns.dirname(s):At[n]=s}return At}a(py,"initOldConfig");function sK(e){let t=Gm();return qY.get(t,e.replaceAll("_","."))}a(sK,"getConfigFromFile");async function nK(e,t){let r=ti(Vi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await tr.writeFile(Vi(),String(r))}a(nK,"addConfig");function iK(e){let t=Vi(Lt.getPropsFilePath()),r=ti(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Ns.join(s,Lr.HDB_CONFIG_FILE);tr.writeFileSync(n,String(r))}a(iK,"deleteConfigFromFile");function oK(){return w_||(qm(),w_)}a(oK,"getConfigObj")});var gy=T((wue,Ty)=>{"use strict";var I_=L(),C_=class{static{a(this,"BaseLicense")}constructor(t=0,r=I_.RAM_ALLOCATION_ENUM.DEFAULT,s=I_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},km=class extends C_{static{a(this,"ExtendedLicense")}constructor(t=0,r=I_.RAM_ALLOCATION_ENUM.DEFAULT,s=I_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};Ty.exports={BaseLicense:C_,ExtendedLicense:km}});var $i=T((Cue,yy)=>{"use strict";var $o=require("fs-extra"),Ay=A_(),Oy=require("crypto"),aK=require("moment"),cK=require("uuid").v4,$t=V(),$m=require("path"),uK=J(),ri=L(),{totalmem:Ry}=require("os"),lK=gy().ExtendedLicense,Vo="invalid license key format",_K="061183",dK="mofi25",fK="aes-256-cbc",EK=16,hK=32,by=X();by.initSync();var Vm;yy.exports={validateLicense:Ny,generateFingerPrint:pK,licenseSearch:Wm,getLicense:gK,checkMemoryLimit:RK};function Ym(){return $m.join(by.getHdbBasePath(),ri.LICENSE_KEY_DIR_NAME,ri.LICENSE_FILE_NAME)}a(Ym,"getLicenseDirPath");function mK(){let e=Ym();return $m.join(e,ri.LICENSE_FILE_NAME)}a(mK,"getLicenseFilePath");function Km(){let e=Ym();return $m.join(e,ri.REG_KEY_FILE_NAME)}a(Km,"getFingerPrintFilePath");async function pK(){let e=Km();try{return await $o.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await SK();throw $t.error(`Error writing fingerprint file to ${e}`),$t.error(t),new Error("There was an error generating the fingerprint")}}a(pK,"generateFingerPrint");async function SK(){let e=cK(),t=Ay.hash(e),r=Km();try{await $o.mkdirp(Ym()),await $o.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw $t.error(`Error writing fingerprint file to ${r}`),$t.error(s),new Error("There was an error generating the fingerprint")}return t}a(SK,"writeFingerprint");function Ny(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ri.RAM_ALLOCATION_ENUM.DEFAULT,version:ri.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return $t.error("empty license key passed to validate."),r;let s=Km(),n=!1;try{n=$o.statSync(s)}catch(i){$t.error(i)}if(n){let i;try{i=$o.readFileSync(s,"utf8")}catch{$t.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(dK),c=o[1];c=Buffer.concat([Buffer.from(c)],EK);let u=Buffer.concat([Buffer.from(i)],hK),_=Oy.createDecipheriv(fK,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=TK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Vo),$t.error(Vo),new Error(Vo)}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(Vo),$t.error(Vo),new Error(Vo)}else r.exp_date=l;r.exp_date<aK().valueOf()&&(r.valid_date=!1),Ay.validate(o[1],`${_K}${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||$t.error("Invalid licence"),r}a(Ny,"validateLicense");function TK(e,t){try{let r=Oy.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{$t.warn("Check old license failed")}}a(TK,"checkOldLicense");function Wm(){let e=new lK,t=[];try{t=$o.readFileSync(mK(),"utf-8").split(ri.NEW_LINE)}catch(r){r.code==="ENOENT"?$t.info("no license file found"):$t.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(uK.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=Ny(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){$t.error("There was an error parsing the license string."),$t.error(n),e.ram_allocation=ri.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Vm=e,e}a(Wm,"licenseSearch");async function gK(){return Vm||await Wm(),Vm}a(gK,"getLicense");function RK(){let e=Wm().ram_allocation,t=process.constrainedMemory?.()||Ry();if(t=Math.round(Math.min(t,Ry())/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(RK,"checkMemoryLimit")});var es=T((Pue,ky)=>{"use strict";var Dy="username is required",Ly="nothing to update, must supply active, role or password to update",My="password cannot be an empty string",Uy="If role is specified, it cannot be empty.",Py="active must be true or false";ky.exports={addUser:DK,alterUser:LK,dropUser:UK,getSuperUser:HK,userInfo:PK,listUsers:L_,listUsersExternal:vK,setUsersToGlobal:Ko,findAndValidateUser:Fy,getClusterUser:xK,USERNAME_REQUIRED:Dy,ALTERUSER_NOTHING_TO_UPDATE:Ly,EMPTY_PASSWORD:My,EMPTY_ROLE:Uy,ACTIVE_BOOLEAN:Py};var vy=Ir(),AK=ei(),Jm=A_(),By=ey(),Hy=Zr(),jm=Tn(),Ur=J(),xy=require("validate.js"),Ae=V(),{promisify:OK}=require("util"),Xm=pn(),wy=L(),Iy=Fe(),bK=Mr(),Lue=X(),Mue=$i(),NK=vi(),{table:Uue}=(be(),te(qe)),{handleHDBError:Ws,hdb_errors:yK}=ee(),{HTTP_STATUS_CODES:Qs,AUTHENTICATION_ERROR_MSGS:Qm,HDB_ERROR_MSGS:Yo}=yK,{UserEventMsg:Zm}=ws(),zm=require("lodash"),{server:ep}=(Xt(),te(Di)),wK=V();ep.getUser=(e,t)=>Fy(e,t,t!=null);var qy={username:!0,active:!0,role:!0,password:!0},Cy=new Map,D_=Hy.searchByValue,IK=Hy.searchByHash,CK=OK(AK.delete);async function DK(e){let t=xy.cleanAttributes(e,qy),r=By.addUserValidation(t);if(r)throw Ws(new Error,r.message,Qs.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 D_(s),n=n&&Array.from(n)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!n||n.length<1)throw Ws(new Error,Yo.ROLE_NAME_NOT_FOUND(t.role),Qs.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw Ws(new Error,Yo.DUP_ROLES_FOUND(t.role),Qs.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Xm.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 vy.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await Ko()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw Ws(new Error,Yo.USER_ALREADY_EXISTS(t.username),Qs.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],jm.signalUserChange(new Zm(process.pid)),`${c.username} successfully added`}a(DK,"addUser");async function LK(e){let t=xy.cleanAttributes(e,qy);if(Ur.isEmptyOrZeroLength(t.username))throw new Error(Dy);if(Ur.isEmptyOrZeroLength(t.password)&&Ur.isEmptyOrZeroLength(t.role)&&Ur.isEmptyOrZeroLength(t.active))throw new Error(Ly);if(!Ur.isEmpty(t.password)&&Ur.isEmptyOrZeroLength(t.password.trim()))throw new Error(My);if(!Ur.isEmpty(t.active)&&!Ur.isBoolean(t.active))throw new Error(Py);let r=MK(t.username);if(!Ur.isEmpty(t.password)&&!Ur.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Xm.encrypt(t.password)),t.password=Jm.hash(t.password)),t.role==="")throw new Error(Uy);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 D_(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=Yo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),Ws(new Error,c,Qs.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Yo.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),Ws(new Error,c,Qs.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 vy.update(s)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await Ko()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return jm.signalUserChange(new Zm(process.pid)),n}a(LK,"alterUser");function MK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(MK,"isClusterUser");async function UK(e){try{let t=By.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 Ws(new Error,Yo.USER_NOT_EXIST(e.username),Qs.NOT_FOUND,void 0,void 0,!0);let s;try{s=await CK(r)}catch(n){throw Ae.error("Got an error deleting a user."),Ae.error(n),n}Ae.debug(s);try{await Ko()}catch(n){throw Ae.error("Got an error setting users to global."),Ae.error(n),n}return jm.signalUserChange(new Zm(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(UK,"dropUser");async function PK(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:["*"]},s;try{s=await IK(r)}catch(n){throw Ae.error("Got an error searching for a role."),Ae.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(PK,"userInfo");async function vK(){let e;try{e=await L_()}catch(t){throw Ae.error("Got an error listing users."),Ae.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(vK,"listUsersExternal");async function L_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await D_(e)}catch(o){throw Ae.error("Got an error searching for roles."),Ae.error(o),o}let r={};for(let o of t)r[o.id]=zm.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 D_(s)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of n)o=zm.cloneDeep(o),o.role=r[o.role],BK(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),Ur.errorizeMessage(e)}return null}a(L_,"listUsers");function BK(e){try{if(!e){Ae.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(NK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ae.error("Got an error trying to set system permissions."),Ae.error(t)}}a(BK,"appendSystemTablesToRole");async function Ko(){try{let e=await L_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(Ko,"setUsersToGlobal");async function Fy(e,t,r=!0){global.hdb_users||await Ko();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw Ws(new Error,Qm.GENERIC_AUTH_FAIL,Qs.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw Ws(new Error,Qm.USER_INACTIVE,Qs.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(Cy.get(t)===s.password)return n;if(Jm.validate(s.password,t))Cy.set(t,s.password);else throw Ws(new Error,Qm.GENERIC_AUTH_FAIL,Qs.UNAUTHORIZED,void 0,void 0,!0)}return n}a(Fy,"findAndValidateUser");async function HK(){global.hdb_users||await Ko();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(HK,"getSuperUser");async function xK(){let e=await L_(),t=bK.getConfigFromFile(wy.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Ur.isEmpty(r)&&r?.role?.role===wy.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Xm.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+Iy.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+Iy.SERVER_SUFFIX.ADMIN,r}a(xK,"getClusterUser");var Gy=[];ep.invalidateUser=function(e){for(let t of Gy)try{t(e)}catch(r){wK.error("Error invalidating user",r)}};ep.onInvalidatedUser=function(e){Gy.push(e)}});var vc=T((xue,Ky)=>{"use strict";var Yi=V(),Pr=L(),qK=RN(),Bue=Sn(),Hue=jn(),FK=es(),{validateEvent:Vy}=ws(),Pc=bs(),GK=require("process"),{resetDatabases:kK}=(be(),te(qe)),VK={[Pr.ITC_EVENT_TYPES.SCHEMA]:$K,[Pr.ITC_EVENT_TYPES.USER]:Yy};async function $K(e){let t=Vy(e);if(t){Yi.error(t);return}Yi.trace("ITC schemaHandler received schema event:",e),await qK(e.message),await YK(e.message)}a($K,"schemaHandler");async function YK(e){try{Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=kK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Yi.error(t)}}a(YK,"syncSchemaMetadata");var $y=[];async function Yy(e){try{try{Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Yi.warn(r)}let t=Vy(e);if(t){Yi.error(t);return}Yi.trace(`ITC userHandler ${Pr.HDB_ITC_CLIENT_PREFIX}${GK.pid} received user event:`,e),await FK.setUsersToGlobal();for(let r of $y)r()}catch(t){Yi.error(t)}}a(Yy,"userHandler");Yy.addListener=function(e){$y.push(e)};Ky.exports=VK});var ws=T(($ue,Qy)=>{"use strict";var Fue=V(),tp=J(),KK=L(),{ITC_ERRORS:Bc}=br(),{parentPort:Gue,threadId:WK,isMainThread:QK,workerData:kue}=require("worker_threads"),{onMessageFromWorkers:zK,broadcast:Vue,broadcastWithAcknowledgement:JK}=$e();Qy.exports={sendItcEvent:jK,validateEvent:Wy,SchemaEventMsg:XK,UserEventMsg:ZK};var M_;zK(async(e,t)=>{M_=M_||vc(),Wy(e),M_[e.type]&&await M_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function jK(e){return!QK&&e.message&&(e.message.originator=WK),JK(e)}a(jK,"sendItcEvent");function Wy(e){if(typeof e!="object")return Bc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||tp.isEmpty(e.type))return Bc.MISSING_TYPE;if(!e.hasOwnProperty("message")||tp.isEmpty(e.message))return Bc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||tp.isEmpty(e.message.originator))return Bc.MISSING_ORIGIN;if(KK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Bc.INVALID_EVENT(e.type)}a(Wy,"validateEvent");function XK(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(XK,"SchemaEventMsg");function ZK(e){this.originator=e}a(ZK,"UserEventMsg")});var Tn=T((Wue,Xy)=>{"use strict";var zy=L(),Kue=J(),U_=V(),Jy=SN(),Wo,{sendItcEvent:jy}=ws();function eW(e){try{U_.trace("signalSchemaChange called with message:",e),Wo=Wo||vc();let t=new Jy(zy.ITC_EVENT_TYPES.SCHEMA,e);return Wo.schema(t),jy(t)}catch(t){U_.error(t)}}a(eW,"signalSchemaChange");function tW(e){try{U_.trace("signalUserChange called with message:",e),Wo=Wo||vc();let t=new Jy(zy.ITC_EVENT_TYPES.USER,e);return Wo.user(t),jy(t)}catch(t){U_.error(t)}}a(tW,"signalUserChange");Xy.exports={signalSchemaChange:eW,signalUserChange:tW}});var P_=T((zue,ew)=>{"use strict";var Zy=J(),rW=L(),sW=V(),nW=__(),iW=l_(),oW=Tn(),{SchemaEventMsg:aW}=ws(),cW="already exists in";ew.exports=uW;async function uW(e,t,r){if(Zy.isEmptyOrZeroLength(r))return r;let s=[];Zy.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 lW(e,t.schema,t.name,i)})),n}a(uW,"lmdbCheckForNewAttributes");async function lW(e,t,r,s){let n=new iW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await _W(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(cW))sW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(lW,"createNewAttribute");async function _W(e){let t;return t=await nW(e),oW.signalSchemaChange(new aW(process.pid,rW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(_W,"createAttribute")});var Qo=T((jue,tw)=>{"use strict";var rp=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}};tw.exports=rp});var sw=T((Zue,rw)=>{"use strict";var dW=Qo(),fW=L().OPERATIONS_ENUM,sp=class extends dW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(fW.INSERT,r,s,n,i),this.records=t}};rw.exports=sp});var iw=T((tle,nw)=>{"use strict";var EW=Qo(),hW=L().OPERATIONS_ENUM,np=class extends EW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(hW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};nw.exports=np});var aw=T((sle,ow)=>{"use strict";var mW=Qo(),pW=L().OPERATIONS_ENUM,ip=class extends mW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(pW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};ow.exports=ip});var uw=T((ile,cw)=>{"use strict";var SW=Qo(),TW=L().OPERATIONS_ENUM,op=class extends SW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(TW.DELETE,s,n,t,i),this.original_records=r}};cw.exports=op});var Hc=T((cle,fw)=>{"use strict";var ale=require("path"),lw=Ye(),gW=sw(),RW=iw(),AW=aw(),OW=uw(),zo=_t(),_w=J(),{CONFIG_PARAMS:bW}=L(),dw=X();dw.initSync();var v_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:NW}=We();fw.exports=yW;async function yW(e,t){if(dw.get(bW.LOGGING_AUDITLOG)===!1)return;let r=NW(e.schema,e.table),s=await lw.openEnvironment(r,e.table,!0),n=wW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){lw.initializeDBIs(s,zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,zo.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),_w.isEmpty(n.user_name)||s.dbis[zo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[zo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(yW,"writeTransaction");function wW(e,t){let r=_w.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===v_.INSERT)return new gW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===v_.UPDATE)return new RW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===v_.UPSERT)return new AW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===v_.DELETE)return new OW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(wW,"createTransactionObject")});var ap=T((_le,Ew)=>{"use strict";var IW=Nc(),lle=yc(),xc=L(),CW=Dc(),DW=qo().insertRecords,LW=Ye(),MW=V(),UW=P_(),{getSchemaPath:PW}=We(),vW=Hc();Ew.exports=BW;async function BW(e){try{let{schema_table:t,attributes:r}=IW(e);CW(e,r,t.hash_attribute),e.schema!==xc.SYSTEM_SCHEMA_NAME&&(r.includes(xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await UW(e.hdb_auth_header,t,r),n=PW(e.schema,e.table),i=await LW.openEnvironment(n,e.table),o=await DW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await vW(e,o)}catch(c){MW.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(BW,"lmdbCreateRecords")});var pw=T((fle,mw)=>{"use strict";var hw=L(),HW=ap(),xW=yc(),qW=require("fs-extra"),{getSchemaPath:FW}=We();mw.exports=GW;async function GW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new xW(hw.SYSTEM_SCHEMA_NAME,hw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await HW(r),await qW.mkdirp(FW(e.schema))}a(GW,"lmdbCreateSchema")});var Tw=T((hle,Sw)=>{"use strict";var cp=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}};Sw.exports=cp});var Ow=T((gle,Aw)=>{"use strict";var gw=Ye(),up=Nr(),lp=br().LMDB_ERRORS_ENUM,kW=_t(),Rw=V(),ple=J(),VW=require("lmdb"),$W=Tw(),YW=L(),{OVERFLOW_MARKER:Sle,MAX_SEARCH_KEY_LENGTH:Tle}=kW,KW=YW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function WW(e,t,r,s){if(up.validateEnv(e),t===void 0)throw new Error(lp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(lp.IDS_REQUIRED):new Error(lp.IDS_MUST_BE_ITERABLE);try{let n=gw.listDBIs(e);gw.initializeDBIs(e,t,n);let i=new $W,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[KW]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,VW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let O=n[S];if(!h.hasOwnProperty(O)||O===t)continue;let g=e.dbis[O],R=h[O];if(R!=null)try{let B=up.getIndexedValues(R);if(B)for(let H=0,v=B.length;H<v;H++)g.remove(B[H],o)}catch{Rw.warn(`cannot delete from attribute: ${O}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){Rw.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=up.getNextMonotonicTime(),i}catch(n){throw n}}a(WW,"deleteRecords");Aw.exports={deleteRecords:WW}});var qc=T((Ale,Nw)=>{"use strict";var Jo=J(),QW=Ow(),zW=Ye(),{getSchemaPath:JW}=We(),jW=Hc(),XW=V();Nw.exports=ZW;async function ZW(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Jo.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Jo.isEmptyOrZeroLength(e.hash_values)&&!Jo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Jo.isEmpty(u)||e.hash_values.push(u)}}if(Jo.isEmptyOrZeroLength(e.hash_values))return bw([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Jo.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=JW(e.schema,e.table),i=await zW.openEnvironment(n,e.table),o=await QW.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await jW(e,o)}catch(c){XW.error(`unable to write transaction due to ${c.message}`)}return bw(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(ZW,"lmdbDeleteRecords");function bw(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(bw,"createDeleteResponse")});var dp=T((Nle,yw)=>{"use strict";var eQ=L(),ble=Nr();function _p(e,t){let r=Object.create(null);if(t.length===1&&eQ.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(_p,"parseRow");function tQ(e,t,r,s){let n=_p(r,e);s.push(n)}a(tQ,"searchAll");function rQ(e,t,r,s){let n=_p(r,e);s[t]=n}a(rQ,"searchAllToMap");function sQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(sQ,"iterateDBI");function Ki(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(Ki,"pushResults");function nQ(e,t,r,s,n,i){t.toString().endsWith(e)&&Ki(t,r,s,n,i)}a(nQ,"endsWith");function iQ(e,t,r,s,n,i){t.toString().includes(e)&&Ki(t,r,s,n,i)}a(iQ,"contains");function oQ(e,t,r,s,n,i){t>e&&Ki(t,r,s,n,i)}a(oQ,"greaterThanCompare");function aQ(e,t,r,s,n,i){t>=e&&Ki(t,r,s,n,i)}a(aQ,"greaterThanEqualCompare");function cQ(e,t,r,s,n,i){t<e&&Ki(t,r,s,n,i)}a(cQ,"lessThanCompare");function uQ(e,t,r,s,n,i){t<=e&&Ki(t,r,s,n,i)}a(uQ,"lessThanEqualCompare");yw.exports={parseRow:_p,searchAll:tQ,searchAllToMap:rQ,iterateDBI:sQ,endsWith:nQ,contains:iQ,greaterThanCompare:oQ,greaterThanEqualCompare:aQ,lessThanCompare:cQ,lessThanEqualCompare:uQ,pushResults:Ki}});var jo=T((Dle,Uw)=>{"use strict";var si=Ye(),wle=V(),vr=Nr(),B_=_t(),ct=br().LMDB_ERRORS_ENUM,Ile=J(),lQ=L(),H_=dp(),{parseRow:_Q}=H_,Cle=require("lmdb"),{OVERFLOW_MARKER:ww,MAX_SEARCH_KEY_LENGTH:dQ}=B_;function Iw(e,t,r,s=!1,n=void 0,i=void 0){return Wi(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(Iw,"iterateFullIndex");function Fc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Wi(e,t,r,(l,d,f,E)=>{let g={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?(g.values=!1,d.getRange(g).map(R=>({value:R}))):d.getRange(g)})}a(Fc,"iterateRangeBetween");function Wi(e,t,r,s){let n=e.database||e,i=si.openDBI(n,r);i[B_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&si.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(Wi,"setupTransaction");function Cw(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(ww)){if(!n)if(r)n=si.openDBI(e,r);else{let u=si.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=si.openDBI(e,u[_]),!n[B_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(Cw,"getOverflowCheck");function fQ(e,t,r,s=!1,n=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ct.HASH_ATTRIBUTE_REQUIRED);return Wi(e,t,t,(o,c,u)=>(x_(r),r=Gc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>_Q(_.value,r))))}a(fQ,"searchAll");function EQ(e,t,r,s=!1,n=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ct.HASH_ATTRIBUTE_REQUIRED);x_(r),r=Gc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of Iw(e,t,t,s,n,i))o.set(c,H_.parseRow(u,r));return o}a(EQ,"searchAllToMap");function hQ(e,t,r=!1,s=void 0,n=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ct.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=Iw(e,void 0,t,r,s,n),c=o.transaction,u=Cw(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(hQ,"iterateDBI");function mQ(e,t){if(vr.validateEnv(e),t===void 0)throw new Error(ct.HASH_ATTRIBUTE_REQUIRED);return si.statDBI(e,t).entryCount}a(mQ,"countAll");function pQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ni(e,r,s),Wi(e,t,r,(c,u,_,l)=>(s=vr.convertKeyValueToWrite(s),l===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(pQ,"equals");function SQ(e,t,r){return ni(e,t,r),si.openDBI(e,t).getValuesCount(r)}a(SQ,"count");function TQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ni(e,r,s),Wi(e,null,r,(c,u)=>{s=vr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(TQ,"startsWith");function gQ(e,t,r,s,n=!1,i=void 0,o=void 0){return Dw(e,t,r,s,n,i,o,!0)}a(gQ,"endsWith");function Dw(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ni(e,r,s),Wi(e,null,r,(u,_,l,d)=>{let f=Cw(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(ww)?_.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))?_[B_.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(Dw,"contains");function RQ(e,t,r,s,n=!1,i=void 0,o=void 0){ni(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Fc(e,t,r,s,u,n,i,o,!0,!1)}a(RQ,"greaterThan");function AQ(e,t,r,s,n=!1,i=void 0,o=void 0){ni(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Fc(e,t,r,s,u,n,i,o,!1,!1)}a(AQ,"greaterThanEqual");function OQ(e,t,r,s,n=!1,i=void 0,o=void 0){ni(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Fc(e,t,r,u,s,n,i,o,!1,!0)}a(OQ,"lessThan");function bQ(e,t,r,s,n=!1,i=void 0,o=void 0){ni(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Fc(e,t,r,u,s,n,i,o,!1,!1)}a(bQ,"lessThanEqual");function NQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(vr.validateEnv(e),r===void 0)throw new Error(ct.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ct.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ct.END_VALUE_REQUIRED);if(s=vr.convertKeyValueToWrite(s),n=vr.convertKeyValueToWrite(n),s>n)throw new Error(ct.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Fc(e,t,r,s,n,i,o,c)}a(NQ,"between");function yQ(e,t,r,s){vr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ct.HASH_ATTRIBUTE_REQUIRED);if(x_(r),r=Gc(n,r),s===void 0)throw new Error(ct.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=H_.parseRow(c,r)),o}a(yQ,"searchByHash");function wQ(e,t,r){vr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ct.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ct.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(wQ,"checkHashExists");function IQ(e,t,r,s,n=[]){return Mw(e,t,r,s,n),Lw(e,t,r,s,n).map(i=>i[1])}a(IQ,"batchSearchByHash");function CQ(e,t,r,s,n=[]){Mw(e,t,r,s,n);let i=new Map;for(let[o,c]of Lw(e,t,r,s,n))i.set(o,c);return i}a(CQ,"batchSearchByHashToMap");function Lw(e,t,r,s,n=[]){return Wi(e,t,t,(i,o,c)=>{r=Gc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,H_.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(Lw,"batchHashSearch");function Mw(e,t,r,s,n){if(vr.validateEnv(e),t===void 0)throw new Error(ct.HASH_ATTRIBUTE_REQUIRED);if(x_(r),s==null)throw new Error(ct.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ct.IDS_MUST_BE_ITERABLE)}a(Mw,"initializeBatchSearchByHash");function x_(e){if(!Array.isArray(e))throw e===void 0?new Error(ct.FETCH_ATTRIBUTES_REQUIRED):new Error(ct.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(x_,"validateFetchAttributes");function ni(e,t,r){if(vr.validateEnv(e),t===void 0)throw new Error(ct.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ct.SEARCH_VALUE_REQUIRED);if(r?.length>dQ)throw new Error(ct.SEARCH_VALUE_TOO_LARGE)}a(ni,"validateComparisonFunctions");function Gc(e,t){return t.length===1&&lQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=si.listDBIs(e)),t}a(Gc,"setGetWholeRowAttributes");Uw.exports={searchAll:fQ,searchAllToMap:EQ,count:SQ,countAll:mQ,equals:pQ,startsWith:TQ,endsWith:gQ,contains:Dw,searchByHash:yQ,setGetWholeRowAttributes:Gc,batchSearchByHash:IQ,batchSearchByHashToMap:CQ,checkHashExists:wQ,iterateDBI:hQ,greaterThan:RQ,greaterThanEqual:AQ,lessThan:OQ,lessThanEqual:bQ,between:NQ}});var Xo=T((Mle,xw)=>{var Pw=require("lodash"),vw=Qe(),me=require("joi"),DQ=J(),{hdb_schema_table:kc,checkValidTable:Bw,hdb_table:Hw,hdb_database:q_}=$s(),{handleHDBError:LQ,hdb_errors:MQ}=ee(),{getDatabases:UQ}=(be(),te(qe)),{HTTP_STATUS_CODES:PQ}=MQ,vQ=me.object({database:q_,schema:q_,table:Hw,search_attribute:kc,search_value:me.any().required(),get_attributes:me.array().min(1).items(me.alternatives(kc,me.object())).optional(),desc:me.bool(),limit:me.number().integer().min(1),offset:me.number().integer().min(0)}),BQ=me.object({database:q_,schema:q_,table:Hw,operator:me.string().valid("and","or").default("and").lowercase(),offset:me.number().integer().min(0),limit:me.number().integer().min(1),get_attributes:me.array().min(1).items(me.alternatives(kc,me.object())).optional(),sort:me.object({attribute:me.alternatives(kc,me.array().min(1)),descending:me.bool().optional()}).optional(),conditions:me.array().min(1).items(me.alternatives(me.object({operator:me.string().valid("and","or").default("and").lowercase(),conditions:me.array()}),me.object({search_attribute:me.alternatives(kc,me.array().min(1)),search_type:me.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:me.when("search_type",{switch:[{is:"equals",then:me.any()},{is:"between",then:me.array().items(me.alternatives([me.string(),me.number()])).length(2)}],otherwise:me.alternatives(me.string(),me.number())}).required()}))).required()});xw.exports=function(e,t){let r=null;switch(t){case"value":r=vw.validateBySchema(e,vQ);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(Bw("database",e.schema)),i(Bw("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=vw.validateBySchema(e,BQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=DQ.checkGlobalSchemaTable(e.schema,e.table);if(n)return LQ(new Error,n,PQ.NOT_FOUND);let o=UQ()[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 _=Pw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!Pw.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 fp=T((Ple,qw)=>{"use strict";var HQ=Ye(),xQ=Xo(),{getSchemaPath:qQ}=We();qw.exports=FQ;function FQ(e){let t=xQ(e,"hashes");if(t)throw t;let r=qQ(e.schema,e.table);return HQ.openEnvironment(r,e.table)}a(FQ,"initialize")});var Ep=T((Ble,Fw)=>{"use strict";var GQ=jo(),kQ=fp();Fw.exports=VQ;async function VQ(e){let t=await kQ(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return GQ.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(VQ,"lmdbGetDataByHash")});var Zo=T((xle,Gw)=>{"use strict";var hp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};Gw.exports=hp});var Vw=T((Gle,kw)=>{"use strict";var Fle=Zo(),$Q=jo(),YQ=fp();kw.exports=KQ;async function KQ(e){let t=await YQ(e),r=global.hdb_schema[e.schema][e.table];return $Q.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(KQ,"lmdbSearchByHash")});var zs=T((Vle,$w)=>{"use strict";var mp=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}};$w.exports=mp});var F_=T((Yle,Jw)=>{"use strict";var Yt=jo(),WQ=Ye(),QQ=J(),pe=_t(),Qi=L(),zQ=vi(),Yw=br().LMDB_ERRORS_ENUM,{getSchemaPath:JQ}=We(),gn=Qi.SEARCH_WILDCARDS;async function jQ(e,t,r){let s;e.schema===Qi.SYSTEM_SCHEMA_NAME?s=zQ[e.table]:s=global.hdb_schema[e.schema][e.table];let n=zw(e,s.hash_attribute,r,t);return Ww(e,n,s.hash_attribute,r)}a(jQ,"prepSearch");async function Ww(e,t,r,s){let n=JQ(e.schema,e.table),i=await WQ.openEnvironment(n,e.table),o=Qw(i,e,t,r),c=o.transaction||i;if([pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,pe.SEARCH_TYPES.SEARCH_ALL,pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(XQ(e,r)===!1){let l=e.search_attribute;if(l===r)return s?Kw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?Kw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?Yt.batchSearchByHashToMap(c,r,e.get_attributes,_):Yt.batchSearchByHash(c,r,e.get_attributes,_)}a(Ww,"executeSearch");function Qw(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 pe.SEARCH_TYPES.EQUALS:n=Yt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.CONTAINS:n=Yt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.ENDS_WITH:case pe.SEARCH_TYPES._ENDS_WITH:n=Yt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.STARTS_WITH:case pe.SEARCH_TYPES._STARTS_WITH:n=Yt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Yt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Yt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case pe.SEARCH_TYPES.SEARCH_ALL:return Yt.searchAll(e,s,t.get_attributes,o,c,u);case pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Yt.searchAllToMap(e,s,t.get_attributes,o,c,u);case pe.SEARCH_TYPES.BETWEEN:n=Yt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case pe.SEARCH_TYPES.GREATER_THAN:case pe.SEARCH_TYPES._GREATER_THAN:n=Yt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.GREATER_THAN_EQUAL:case pe.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Yt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.LESS_THAN:case pe.SEARCH_TYPES._LESS_THAN:n=Yt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.LESS_THAN_EQUAL:case pe.SEARCH_TYPES._LESS_THAN_EQUAL:n=Yt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(Qw,"searchByType");function Kw(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(Kw,"createMapFromIterable");function XQ(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(XQ,"checkToFetchMore");function zw(e,t,r,s){if(QQ.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),gn.indexOf(n)>-1)return r===!0?pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:pe.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(gn[0])<0&&n.indexOf(gn[1])<0)return c===!0?r===!0?pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:pe.SEARCH_TYPES.EQUALS;if(gn.indexOf(i)>=0&&gn.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),pe.SEARCH_TYPES.CONTAINS;if(gn.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),pe.SEARCH_TYPES.ENDS_WITH;if(gn.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),pe.SEARCH_TYPES.STARTS_WITH;if(n.includes(gn[0])||n.includes(gn[1]))return pe.SEARCH_TYPES.EQUALS;throw new Error(Yw.UNKNOWN_SEARCH_TYPE)}else switch(s){case Qi.VALUE_SEARCH_COMPARATORS.BETWEEN:return pe.SEARCH_TYPES.BETWEEN;case Qi.VALUE_SEARCH_COMPARATORS.GREATER:return pe.SEARCH_TYPES.GREATER_THAN;case Qi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return pe.SEARCH_TYPES.GREATER_THAN_EQUAL;case Qi.VALUE_SEARCH_COMPARATORS.LESS:return pe.SEARCH_TYPES.LESS_THAN;case Qi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return pe.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Yw.UNKNOWN_SEARCH_TYPE)}}a(zw,"createSearchTypeFromSearchObject");Jw.exports={executeSearch:Ww,createSearchTypeFromSearchObject:zw,prepSearch:jQ,searchByType:Qw}});var Xw=T((Qle,jw)=>{"use strict";var Wle=zs(),ZQ=Xo(),ez=J(),tz=L(),rz=F_();jw.exports=sz;function sz(e,t){if(!ez.isEmpty(t)&&tz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=ZQ(e,"value");if(s)throw s;return rz.prepSearch(e,t,!0)}a(sz,"lmdbGetDataByValue")});var Vc=T((jle,Zw)=>{"use strict";var Jle=zs(),nz=Xo(),iz=J(),oz=L(),az=F_();Zw.exports=cz;async function cz(e,t){if(!iz.isEmpty(t)&&oz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=nz(e,"value");if(s)throw s;return az.prepSearch(e,t,!1)}a(cz,"lmdbSearchByValue")});var tI=T((e_e,eI)=>{"use strict";var Zle=_t(),pp=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}},Sp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Tp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};eI.exports={SearchByConditionsObject:pp,SearchCondition:Sp,SortAttribute:Tp}});var oI=T((n_e,iI)=>{"use strict";var r_e=tI().SearchByConditionsObject,uz=zs(),lz=Xo(),gp=jo(),G_=_t(),{Resource:s_e}=(Rs(),te(Rp)),nI=F_(),_z=dp(),dz=require("lodash"),{getSchemaPath:fz}=We(),rI=Ye(),{handleHDBError:Ez,hdb_errors:hz}=ee(),{HTTP_STATUS_CODES:mz}=hz,pz=1e8;iI.exports=Sz;async function Sz(e){let t=lz(e,"conditions");if(t)throw Ez(t,t.message,mz.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=fz(e.schema,e.table),s=await rI.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)rI.openDBI(s,_.search_attribute);let i=dz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===G_.SEARCH_TYPES.EQUALS?_.estimated_count=gp.count(s,_.search_attribute,_.search_value):l===G_.SEARCH_TYPES.CONTAINS||l===G_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=pz}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await sI(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(nI.filterByType),d=l.length,f=gp.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=>_z.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await sI(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=gp.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Sz,"lmdbSearchByConditions");async function sI(e,t,r,s){let n=new uz(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===G_.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,nI.searchByType(e,n,i,s).map(o=>o.value)}a(sI,"executeConditionSearch")});var ea=T((o_e,aI)=>{"use strict";var Tz=L().OPERATIONS_ENUM,Ap=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=Tz.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};aI.exports=Ap});var Op=T((c_e,hI)=>{"use strict";var _I=zs(),dI=ea(),fI=Vc(),EI=qc(),rr=L(),cI=J(),uI=Ye(),{getTransactionAuditStorePath:gz,getSchemaPath:Rz}=We(),lI=V();hI.exports=Az;async function Az(e){try{if(cI.isEmpty(global.hdb_schema[e.schema])||cI.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await Oz(e),await bz(e);let t=Rz(e.schema,e.table);try{await uI.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")lI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=gz(e.schema,e.table);await uI.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")lI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Az,"lmdbDropTable");async function Oz(e){let t=new _I(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await fI(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 dI(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await EI(n)}a(Oz,"deleteAttributesFromSystem");async function bz(e){let t=new _I(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await fI(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 dI(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await EI(n)}catch(i){throw i}}a(bz,"dropTableFromSystem")});var pI=T((l_e,mI)=>{"use strict";var Nz=require("fs-extra"),yz=zs(),wz=Zo(),Iz=ea(),Cz=Op(),Dz=qc(),Lz=Ep(),Mz=Vc(),Rn=L(),{getSchemaPath:Uz}=We(),{handleHDBError:Pz,hdb_errors:vz}=ee(),{HDB_ERROR_MSGS:Bz,HTTP_STATUS_CODES:Hz}=vz;mI.exports=xz;async function xz(e){let t;try{t=await qz(e.schema);let r=new yz(Rn.SYSTEM_SCHEMA_NAME,Rn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await Mz(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await Cz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new Iz(Rn.SYSTEM_SCHEMA_NAME,Rn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Dz(n);let i=Uz(t);await Nz.remove(i)}catch(r){throw r}}a(xz,"lmdbDropSchema");async function qz(e){let t=new wz(Rn.SYSTEM_SCHEMA_NAME,Rn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await Lz(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw Pz(new Error,Bz.SCHEMA_NOT_FOUND(e),Hz.NOT_FOUND,void 0,void 0,!0);return s}a(qz,"validateDropSchema")});var k_=T((d_e,SI)=>{"use strict";var bp=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};SI.exports=bp});var gI=T((h_e,TI)=>{"use strict";var Fz=require("fs-extra"),V_=Ye(),{getTransactionAuditStorePath:Gz}=We(),Np=_t(),E_e=k_();TI.exports=kz;async function kz(e){let t;try{let r=Gz(e.schema,e.table);await Fz.mkdirp(r),t=await V_.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{V_.createDBI(t,Np.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),V_.createDBI(t,Np.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),V_.createDBI(t,Np.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(kz,"createTransactionsAuditEnvironment")});var bI=T((p_e,OI)=>{"use strict";var yp=L(),RI=Ye(),Vz=qo(),{getSystemSchemaPath:$z,getSchemaPath:Yz}=We(),Kz=vi(),Wz=__(),wp=l_(),Qz=V(),zz=gI(),Cp=Kz.hdb_table,AI=[];for(let e=0;e<Cp.attributes.length;e++)AI.push(Cp.attributes[e].attribute);OI.exports=Jz;async function Jz(e,t){let r=Yz(t.schema,t.table),s=new wp(t.schema,t.table,yp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new wp(t.schema,t.table,yp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new wp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await RI.createEnvironment(r,t.table),e!==void 0){let o=await RI.openEnvironment($z(),yp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Vz.insertRecords(o,Cp.hash_attribute,AI,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Ip(s),await Ip(n),await Ip(i)}await zz(t)}catch(o){throw o}}a(Jz,"lmdbCreateTable");async function Ip(e){try{await Wz(e)}catch(t){Qz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Ip,"createAttribute")});var yI=T((T_e,NI)=>{"use strict";var jz=Nc(),Xz=Dc(),Zz=P_(),$c=L(),eJ=qo().updateRecords,tJ=Ye(),{getSchemaPath:rJ}=We(),sJ=Hc(),nJ=V();NI.exports=iJ;async function iJ(e){try{let{schema_table:t,attributes:r}=jz(e);Xz(e,r,t.hash_attribute),e.schema!==$c.SYSTEM_SCHEMA_NAME&&(r.includes($c.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push($c.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes($c.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push($c.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await Zz(e.hdb_auth_header,t,r),n=rJ(e.schema,e.table),i=await tJ.openEnvironment(n,e.table),o=await eJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await sJ(e,o)}catch(c){nJ.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(iJ,"lmdbUpdateRecords")});var II=T((R_e,wI)=>{"use strict";var oJ=L().OPERATIONS_ENUM,Dp=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=oJ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};wI.exports=Dp});var DI=T((b_e,CI)=>{"use strict";var O_e=II(),aJ=Nc(),cJ=Dc(),uJ=P_(),Yc=L(),lJ=qo().upsertRecords,_J=Ye(),{getSchemaPath:dJ}=We(),fJ=Hc(),EJ=V(),{handleHDBError:hJ,hdb_errors:mJ}=ee();CI.exports=pJ;async function pJ(e){let t;try{t=aJ(e)}catch(u){throw hJ(u,u.message,mJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;cJ(e,s,r.hash_attribute),e.schema!==Yc.SYSTEM_SCHEMA_NAME&&(s.includes(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await uJ(e.hdb_auth_header,r,s),i=dJ(e.schema,e.table),o=await _J.openEnvironment(i,e.table),c=await lJ(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await fJ(e,c)}catch(u){EJ.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(pJ,"lmdbUpsertRecords")});var MI=T((y_e,LI)=>{"use strict";var Lp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};LI.exports=Lp});var PI=T((I_e,UI)=>{"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}};UI.exports=Mp});var HI=T((L_e,BI)=>{"use strict";var Up=Ye(),{getTransactionAuditStorePath:SJ}=We(),D_e=MI(),Kc=_t(),TJ=J(),vI=PI(),gJ=require("util").promisify,RJ=gJ(setTimeout),AJ=1e4,OJ=100;BI.exports=bJ;async function bJ(e){let t=SJ(e.schema,e.table),r=await Up.openEnvironment(t,e.table,!0),s=Up.listDBIs(r);Up.initializeDBIs(r,Kc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new vI;do n=await NJ(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 RJ(OJ);while(n.transactions_deleted>0);return i}a(bJ,"deleteAuditLogsBefore");async function NJ(e,t){let r=new vI;try{let s=e.dbis[Kc.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[Kc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];TJ.isEmpty(c)||(n=e.dbis[Kc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Kc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>AJ)break}return await n,r}catch(s){throw s}}a(NJ,"deleteTransactions")});var qI=T((U_e,xI)=>{"use strict";var Pp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};xI.exports=Pp});var GI=T((B_e,FI)=>{"use strict";var yJ=zs(),wJ=ea(),v_e=qI(),Js=L(),IJ=J(),vp=Ye(),CJ=vi(),DJ=Vc(),LJ=qc(),{getSchemaPath:MJ}=We();FI.exports=UJ;async function UJ(e,t=!0){let r;e.schema===Js.SYSTEM_SCHEMA_NAME?r=CJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await vJ(e),n=MJ(e.schema,e.table),i=await vp.openEnvironment(n,e.table);return t===!0&&await PJ(e,i,r.hash_attribute),vp.dropDBI(i,e.attribute),s}a(UJ,"lmdbDropAttribute");async function PJ(e,t,r){let s=vp.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(PJ,"removeAttributeFromAllObjects");async function vJ(e){let t=new yJ(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 DJ(t)).filter(o=>o[Js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(IJ.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 wJ(Js.SYSTEM_SCHEMA_NAME,Js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return LJ(i)}a(vJ,"dropAttributeFromSystem")});var WI=T((q_e,KI)=>{"use strict";var Bp=Ye(),ta=_t(),x_e=Nr(),Hp=L(),kI=J(),{getTransactionAuditStorePath:BJ}=We(),HJ=jo(),$_=Qo(),xJ=V();KI.exports=qJ;async function qJ(e){let t=BJ(e.schema,e.table),r=await Bp.openEnvironment(t,e.table,!0),s=Bp.listDBIs(r);Bp.initializeDBIs(r,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Hp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return VI(r,e.search_values);case Hp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,GJ(r,e.search_values,n);case Hp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return FJ(r,e.search_values);default:return VI(r)}}a(qJ,"readAuditLog");function VI(e,t=[0,Date.now()]){kI.isEmpty(t[0])&&(t[0]=0),kI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[ta.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 $_,n))}a(VI,"searchTransactionsByTimestamp");function FJ(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[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,YI(e,i))}return Object.fromEntries(r)}a(FJ,"searchTransactionsByUsername");function GJ(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=HJ.equals(e,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.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=YI(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);$I(u,"records",r,l,o),$I(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(GJ,"searchTransactionsByHashValues");function $I(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 $_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new $_(e.operation,e.user_name,i,void 0);_[t]=[c],n.set(u,[_])}}}a($I,"loopRecords");function YI(e,t){let r=[];try{let s=e.dbis[ta.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 $_,i);r.push(o)}}catch(i){xJ.warn(i)}return r}catch(s){throw s}}a(YI,"batchSearchTransactions")});var zI=T((V_e,QI)=>{"use strict";var{getSchemaPath:G_e}=We(),k_e=Ye(),{database:kJ}=(be(),te(qe));QI.exports={writeTransaction:VJ};async function VJ(e,t,r){return kJ({database:e,table:t}).transaction(r)}a(VJ,"writeTransaction")});var ZI=T((Y_e,XI)=>{"use strict";var{getSchemaPath:JI}=We(),jI=Ye();XI.exports={flush:$J,resetReadTxn:YJ};async function $J(e,t){return(await jI.openEnvironment(JI(e,t),t.toString())).flushed}a($J,"flush");async function YJ(e,t){try{(await jI.openEnvironment(JI(e,t),t.toString())).resetReadTxn()}catch{}}a(YJ,"resetReadTxn")});var sC=T((W_e,rC)=>{"use strict";var{Readable:KJ}=require("stream"),{getDatabases:WJ}=(be(),te(qe)),{readSync:QJ,openSync:zJ,createReadStream:eC}=require("fs"),{open:JJ}=require("lmdb"),tC=e_(),jJ=r_(),{AUDIT_STORE_OPTIONS:XJ}=(Ui(),te(nC)),{INTERNAL_DBIS_NAME:ZJ,AUDIT_STORE_NAME:e2}=_t();rC.exports=r2;var xp=32768,t2=100;async function r2(e){let t=e.database||e.schema||"data",r=WJ()[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=JJ({noSync:!0,maxDbs:jJ.MAX_DBS}),f,E=d.openDB(ZJ,new tC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(g,R){R.encoding="binary",R.encoder=void 0;let B=d.openDB(g,R),H=l.openDB(g,R);for(let{key:v,version:U,value:Y}of H.getRange({transaction:h,versions:H.useVersions}))f=B.put(v,Y,U),p++%t2===0&&(await new Promise(W=>setTimeout(W,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:g,value:R}of l.getRange({transaction:h,start:!1}))if(n.some(B=>g.startsWith?.(B+"/"))){E.put(g,R);let[,B]=g.split("/"),H=!B,v=new tC(!H,H);await S(g,v)}e.include_audit&&await S(e2,Object.assign({},XJ)),await f;let O=eC(d.path);return O.headers=u(),O.on("close",()=>{h.done(),d.close()}),O}let o=r[Object.keys(r)[0]].primaryStore,c=zJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(xp);QJ(c,_,0,xp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=eC(null,{fd:c,start:xp}),f=new KJ.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(r2,"getBackup")});var aC=T((z_e,oC)=>{"use strict";var s2=V(),{handleHDBError:n2}=ee(),i2=Rb(),o2=__(),a2=ap(),c2=pw(),u2=qc(),l2=Ep(),_2=Vw(),d2=Xw(),f2=Vc(),E2=oI(),h2=pI(),m2=bI(),p2=yI(),S2=DI(),T2=HI(),g2=Op(),R2=GI(),A2=WI(),O2=zI(),iC=ZI(),b2=sC(),qp=class extends i2{static{a(this,"LMDBBridge")}async searchByConditions(t){return E2(t)}async getDataByHash(t){return await l2(t)}async searchByHash(t){return await _2(t)}async getDataByValue(t,r){return await d2(t,r)}async searchByValue(t){return await f2(t)}async createSchema(t){return await c2(t)}async dropSchema(t){return await h2(t)}async createTable(t,r){return await m2(t,r)}async dropTable(t){return await g2(t)}async createAttribute(t){return await o2(t)}async createRecords(t){return await a2(t)}async updateRecords(t){return await p2(t)}async upsertRecords(t){try{return await S2(t)}catch(r){throw n2(r,null,null,s2.ERR,r)}}async deleteRecords(t){return await u2(t)}async dropAttribute(t){return await R2(t)}async deleteAuditLogsBefore(t){return await T2(t)}async readAuditLog(t){return await A2(t)}writeTransaction(t,r,s){return O2.writeTransaction(t,r,s)}flush(t,r){return iC.flush(t,r)}resetReadTxn(t,r){return iC.resetReadTxn(t,r)}getBackup(t){return b2(t)}};oC.exports=qp});function I2(){w2=setInterval(function(){for(let e of Fp)if(e.stale){let t=e[Ne]?.url;cC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},y2).unref()}var Gp,cC,N2,Fp,zi,Y_,y2,w2,kp=Oe(()=>{Gp=x(Nr()),cC=x(V());Rs();Ho();N2=100,Fp=new Set,zi=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)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,Xl(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Fp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),Xl(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Fp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(!this.open&&!this.autoCommitMode)throw new Error("Can not use a transaction that is no longer open");this.writes.push(t),this.autoCommitMode&&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,Gp.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 O=S();E?E.push?E.push(O):E=[E,O]:E=O}}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(),t?.prepared?.(),this.open=!1;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<N2>>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=!1,this.writes=[]}},Y_=class extends zi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Gp.getNextMonotonicTime)())}getReadTxn(){}},y2=3e4;a(I2,"startMonitoringTxns");I2()});function ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open&&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 zi;e.timestamp&&(s.timestamp=e.timestamp),s[Ne]=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(r?.resetTransaction?{prepared(){s.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var uC,Ji=Oe(()=>{uC=require("../index");Rs();kp();a(ze,"transaction");(0,uC._assignPackageExport)("transaction",ze);ze.commit=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};ze.abort=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var SC={};Ve(SC,{ResourceBridge:()=>Yp});function Kp({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 _C(e,t){let r=js(e),s=Kp(e,r);if(!r)throw new Is.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;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:n,select:s},i);return l=l&&W_(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 js(e){let t=e.database||e.schema||D2,r=Cs()[t];if(!r)throw(0,Is.handleHDBError)(new Error,C2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function dC(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*fC(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 EC,K_,Is,hC,mC,Ds,Vp,$p,pC,C2,D2,L2,M2,lC,Yp,TC=Oe(()=>{"use strict";EC=x(aC()),K_=x(Xo()),Is=x(ee());be();hC=x(Nc()),mC=x(Dc()),Ds=x(L()),Vp=x(Tn()),$p=x(ws()),pC=x(J());Ji();Q_();({HDB_ERROR_MSGS:C2}=Is.hdb_errors),D2="data",L2=1e4,M2=10,Yp=class extends EC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),lC=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,K_.default)(t,"conditions");if(r)throw(0,Is.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=js(t);if(!s)throw new Is.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:Kp(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 Is.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}]}at({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await js(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=js(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){js(t).dropTable()}createSchema(t){return Wc({database:t.schema,table:null}),Vp.signalSchemaChange(new $p.SchemaEventMsg(process.pid,Ds.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Wp(t.schema),Vp.signalSchemaChange(new $p.SchemaEventMsg(process.pid,Ds.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,lC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,hC.default)(t);(0,mC.default)(t,s,r.primaryKey);let n,i=Cs()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return ze(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=W_(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=Cs()[t.schema][t.table],s={user:t.hdb_user};return ze(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 dC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Cs()[t.schema][t.table];if(!r.createdTimeProperty)throw new Is.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:Ds.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,pC.async_set_timeout)(M2),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%L2===0&&await _();return u.length>0&&await _(),n?dC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,K_.default)(t,"hashes");if(r)throw r;return _C(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of _C(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Ds.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,K_.default)(t,"value");if(s)throw s;let n=js(t);if(!n)throw new Is.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===Ds.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:Kp(t,n)})}async getDataByValue(t,r){let s=new Map,n=js(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){js({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return js(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=js(t),s={};switch(t.search_type){case Ds.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 Ds.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of fC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return fC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Kp,"getSelect");a(_C,"getRecords");a(js,"getTable");a(dC,"createDeleteResponse");a(fC,"groupRecordsInHistory")});var bs=T((lde,gC)=>{"use strict";var{ResourceBridge:U2}=(TC(),te(SC)),P2=X();P2.initSync();var z_;function v2(){return z_||(z_=new U2,z_)}a(v2,"getBridge");gC.exports=v2()});var bC=T((dde,OC)=>{"use strict";var RC=require("lodash"),Qc=require("mathjs"),B2=require("jsonata"),AC=J();OC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?RC.uniqWith(e,RC.isEqual):e,searchJSON:H2,mad:zc.bind(null,Qc.mad),mean:zc.bind(null,Qc.mean),mode:zc.bind(null,Qc.mode),prod:zc.bind(null,Qc.prod),median:zc.bind(null,Qc.median)};function zc(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(zc,"aggregateFunction");function H2(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(AC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),AC.isEmpty(this.__ala__.res[r])){let s=B2(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(H2,"searchJSON")});var yC=T((Ede,NC)=>{"use strict";var ft=require("moment"),Qp="YYYY-MM-DDTHH:mm:ss.SSSZZ";ft.suppressDeprecationWarnings=!0;NC.exports={current_date:()=>ft().utc().format("YYYY-MM-DD"),current_time:()=>ft().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return ft(e).utc().format("YYYY");case"month":return ft(e).utc().format("MM");case"day":return ft(e).utc().format("DD");case"hour":return ft(e).utc().format("HH");case"minute":return ft(e).utc().format("mm");case"second":return ft(e).utc().format("ss");case"millisecond":return ft(e).utc().format("SSS");default:break}},date:e=>ft(e).utc().format(Qp),date_format:(e,t)=>ft(e).utc().format(t),date_add:(e,t,r)=>ft(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>ft(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=ft(e).utc(),n=ft(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>ft().utc().valueOf(),get_server_time:()=>ft().format(Qp),offset_utc:(e,t)=>ft(e).utc().utcOffset(t).format(Qp)}});var DC=T((hde,CC)=>{"use strict";var x2=require("@turf/area"),q2=require("@turf/length"),F2=require("@turf/circle"),G2=require("@turf/difference"),k2=require("@turf/distance"),V2=require("@turf/boolean-contains"),$2=require("@turf/boolean-equal"),Y2=require("@turf/boolean-disjoint"),K2=require("@turf/helpers"),wC=L(),ge=J(),An=V();CC.exports={geoArea:W2,geoLength:Q2,geoCircle:z2,geoDifference:J2,geoDistance:IC,geoNear:j2,geoContains:X2,geoEqual:Z2,geoCrosses:e4,geoConvert:t4};function W2(e){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return x2.default(e)}catch(t){return An.trace(t,e),NaN}}a(W2,"geoArea");function Q2(e,t){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return q2.default(e,{units:t||"kilometers"})}catch(r){return An.trace(r,e),NaN}}a(Q2,"geoLength");function z2(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return F2.default(e,t,{units:r||"kilometers"})}catch(s){return An.trace(s,e,t),NaN}}a(z2,"geoCircle");function J2(e,t){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return G2(e,t)}catch(r){return An.trace(r,e,t),NaN}}a(J2,"geoDifference");function IC(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return k2.default(e,t,{units:r||"kilometers"})}catch(s){return An.trace(s,e,t),NaN}}a(IC,"geoDistance");function j2(e,t,r,s){if(ge.isEmpty(e)||ge.isEmpty(t))return!1;if(ge.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return IC(e,t,s)<=r}catch(n){return An.trace(n,e,t),!1}}a(j2,"geoNear");function X2(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return V2.default(e,t)}catch(r){return An.trace(r,e,t),!1}}a(X2,"geoContains");function Z2(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return $2.default(e,t)}catch(r){return An.trace(r,e,t),!1}}a(Z2,"geoEqual");function e4(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return!Y2.default(e,t)}catch(r){return An.trace(r,e,t),!1}}a(e4,"geoCrosses");function t4(e,t,r){if(ge.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(ge.isEmpty(t))throw new Error("geo_type is required");if(ge.isEmpty(wC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(wC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=ge.autoCastJSON(e)),K2[t](e,r)}a(t4,"geoConvert")});var J_=T((pde,LC)=>{var ji=bC(),Br=yC(),Xs=DC();LC.exports=e=>{e.aggr.mad=e.aggr.MAD=ji.mad,e.aggr.mean=e.aggr.MEAN=ji.mean,e.aggr.mode=e.aggr.MODE=ji.mode,e.aggr.prod=e.aggr.PROD=ji.prod,e.aggr.median=e.aggr.MEDIAN=ji.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ji.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ji.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=Xs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Xs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Xs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Xs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Xs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Xs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Xs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Xs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Xs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Xs.geoNear}});var vC=T((Sde,PC)=>{"use strict";var Jc=require("lodash"),sr=require("alasql");sr.options.cache=!1;var r4=J_(),MC=require("clone"),j_=require("recursive-iterator"),Ee=V(),Ce=J(),ra=bs(),s4=L(),{hdb_errors:n4}=ee(),{getDatabases:UC}=(be(),te(qe)),i4="IS NULL",Ls="There was a problem performing this search. Please check the logs and try again.";r4(sr);var zp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw Ee.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 Ee.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw Ee.error("Error thrown from checkEmptySQL in SQLSearch class method search."),Ee.error(s),new Error(Ls)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw Ee.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),Ee.error(s),new Error(Ls)}if(Object.keys(this.data).length===0)return Ee.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw Ee.error("Error thrown from processJoins in SQLSearch class method search."),Ee.error(s),new Error(Ls)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw Ee.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),Ee.error(s),new Error(Ls)}try{return t=await this._finalSQL(),t}catch(s){throw Ee.error("Error thrown from finalSQL in SQLSearch class method search."),Ee.error(s),new Error(Ls)}}_getColumns(){let t=new j_(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(MC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Jc.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=UC()[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)){Ee.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new j_(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 sr.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 sr.yy.LogicValue({value:i}):s instanceof sr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new sr.yy.NumValue({value:i}))});if(t){Ee.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new j_(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(s4.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&&Jc.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 sr.promise(r)}catch(r){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),Ee.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(MC(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(i4)>-1&&this.tables.forEach(n=>{let i={columnid:UC()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Jc.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 ra.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 Ee.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),Ee.error(l),new Error(Ls)}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 ra.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 Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),Ee.error(l),new Error(Ls)}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 ra.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 Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),Ee.error(l),new Error(Ls)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await ra.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 Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),Ee.error(l),new Error(Ls)}}}_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 sr.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 sr.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new sr.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 sr.yy.FuncValue:new sr.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 sr.promise(h,t),t=null}catch(E){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),Ee.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=Jc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,O=p.length;S<O;S++){let g=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[g]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new j_(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=Jc.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 Ee.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),Ee.error(i),new Error(Ls)}}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 ra.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 Ee.error("Error thrown from getDataByHash function in SQLSearch class method getData."),Ee.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();Ee.trace(`Final SQL: ${n}`),s=await sr.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),Ee.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),Ee.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 Ee.error(n4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),Ee.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 ra.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 Ee.error("There was an error when processing this SQL operation. Check your logs"),Ee.error(o),new Error(Ls)}}return Object.values(Object.values(this.data)[0].__merged_data)}};PC.exports=zp});var Zr=T((gde,BC)=>{"use strict";var o4=Tb();BC.exports={searchByConditions:c4,searchByHash:u4,searchByValue:l4,search:_4};var Jp=bs(),{transformReq:jp}=J(),a4=vC();async function c4(e){return jp(e),Jp.searchByConditions(e)}a(c4,"searchByConditions");async function u4(e){jp(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(u4,"searchByHash");async function l4(e){jp(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(l4,"searchByValue");function _4(e,t){try{let r=new o4(e);r.validate(),new a4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(_4,"search")});var X_=T((Ade,HC)=>{"use strict";var d4=bs();HC.exports={writeTransaction:f4};function f4(e,t,r){return d4.writeTransaction(e,t,r)}a(f4,"writeTransaction")});var GC=T((Nde,FC)=>{"use strict";var E4=Zr(),h4=Sn(),xC=V(),m4=Ir(),bde=X_(),p4=require("clone"),Zp=require("alasql"),S4=J_(),qC=require("util"),T4=qC.promisify(h4.getTableSchema),g4=qC.promisify(E4.search),R4=L(),Xp=J();S4(Zp);FC.exports={update:O4};var A4="There was a problem performing this update. Please check the logs and try again.";async function O4({statement:e,hdb_user:t}){let r=await T4(e.table.databaseid,e.table.tableid),s=b4(e.columns);Xp.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=p4(n),c=Xp.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=Zp.parse(u).statements[0],l=await g4(_),d=N4(s,l);return y4(o,d,t)}a(O4,"update");function b4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=Zp.compile(`SELECT ${r.expression.toString()} AS [${R4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw xC.error(t),new Error(A4)}}a(b4,"createUpdateRecord");function N4(e,t){return Xp.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(N4,"buildUpdateRecords");async function y4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await m4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){xC.error(`Error delete new_attributes from update response: ${i}`)}return n}a(y4,"updateRecords")});var VC=T((Cde,kC)=>{var w4=require("alasql"),I4=Zr(),C4=V(),D4=bs(),tS=require("util"),eS=J(),L4=L(),M4=Sn(),wde=X_(),Ide=Ir(),U4="record",P4="successfully deleted",v4=tS.callbackify(q4),B4=tS.promisify(I4.search),H4=tS.promisify(M4.getTableSchema);kC.exports={convertDelete:v4};function x4(e){return`${e.deleted_hashes.length} ${U4}${e.deleted_hashes.length===1?"":"s"} ${P4}`}a(x4,"generateReturnMessage");async function q4({statement:e,hdb_user:t}){let r=await H4(e.table.databaseid,e.table.tableid);eS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=eS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=w4.parse(o).statements[0],u={operation:L4.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await B4(c);let _=await D4.deleteRecords(u);return eS.isEmptyOrZeroLength(_.message)&&(_.message=x4(_)),delete _.txn_time,_}catch(_){throw C4.error(_),_.hdb_code?_.message:_}}a(q4,"convertDelete")});var QC=T((Lde,WC)=>{"use strict";var F4=jn(),{hdb_errors:$C}=ee(),{getDatabases:YC}=(be(),te(qe));WC.exports={checkSchemaExists:KC,checkSchemaTableExists:G4,schema_describe:F4};async function KC(e){if(!YC()[e])return $C.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(KC,"checkSchemaExists");async function G4(e,t){let r=await KC(e);if(r)return r;if(!YC()[e][t])return $C.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(G4,"checkSchemaTableExists")});var jc=T((Ude,k4)=>{k4.exports={name:"harperdb",version:"4.3.0-beta.3",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.1",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 tu={};Ve(tu,{addAnalyticsListener:()=>eu,recordAction:()=>Hr,recordActionBinary:()=>ts,setAnalyticsEnabled:()=>V4});function V4(e){nD=e}function Hr(e,t,r,s,n){if(!nD)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);let o=td.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},td.set(i,o)}Z_||$4()}function ts(e,t,r,s,n){Hr(!!e,t,r,s,n)}function eu(e){aD.push(e)}function $4(){Z_=performance.now(),setTimeout(async()=>{let e=performance.now()-Z_;Z_=0;let t=[],r={time:Date.now(),period:e,threadId:Xi.threadId,metrics:t};for(let[n,i]of td){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 cD){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 uD()}let s=process.memoryUsage();t.push({metric:"memory",threadId:Xi.threadId,byThread:!0,...s});for(let n of aD)n(t);td=new Map,Xi.parentPort?Xi.parentPort.postMessage({type:oD,report:r}):dD({report:r})},iD).unref()}async function Y4(e,t=6e4){let r=nS(),s=lD(),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:O}=p;for(let g of S||[]){let{path:R,method:B,type:H,metric:v,count:U,total:Y,distribution:W,threads:z,...ne}=g;U||(U=1);let Te=v+(R?"-"+R:"");B!==void 0&&(Te+="-"+B),H!==void 0&&(Te+="-"+H);let oe=o.get(Te);if(oe){if(oe.threads){let de=oe.threads[O];if(de)oe=de;else{oe.threads[O]=Object.assign({},ne);continue}}oe.count||(oe.count=1);let xe=oe.count;for(let de in ne){let It=ne[de];typeof It=="number"&&(oe[de]=(oe[de]*xe+It*U)/(xe+U))}oe.count+=U,Y>=0&&(oe.total+=Y,oe.ratio=oe.total/oe.count)}else oe=Object.assign({period:t},g),delete oe.distribution,o.set(Te,oe),oe.byThread&&(oe.threads=[],oe.threads[O]=Object.assign({},ne),u.push(oe));if(W){W=W.map(de=>typeof de=="number"?{value:de,count:1}:de);let xe=c.get(Te);xe?xe.push(...W):c.set(Te,W)}}await uD()}for(let h of u){let{path:p,method:S,type:O,metric:g,count:R,total:B,distribution:H,threads:v,...U}=h;v=v.filter(Y=>Y);for(let Y in U){if(typeof h[Y]!="number")continue;let W=0;for(let z of v){let ne=z[Y];typeof ne=="number"&&(W+=ne)}h[Y]=W}h.count=v.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((de,It)=>de.value>It.value?1:-1);let O=S.count-1,g=[],R=0,B=0,H;for(let de of cD){let It=O*de;for(;R<It;)H=p[B++],R+=H.count,B===1&&R--;let Dl=p[B>1?B-2:0];H||(H=p[0]),g.push(H.value-(H.value-Dl.value)*(R-It)/H.count)}let[v,U,Y,W,z,ne,Te,oe,xe]=g;Object.assign(S,{p1:v,p10:U,p25:Y,median:W,p75:z,p90:ne,p95:Te,p99:oe,p999:xe})}let l;for(let[h,p]of o)p.id=(0,ed.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,ed.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-zC,active:E-JC,time:d,...process.memoryUsage()};s.primaryStore.put(h,p,{append:!0}).then(S=>{S||s.primaryStore.put(h,p)})}zC=f,JC=E}async function jC(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function nS(){return XC||(XC=at({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function lD(){return ZC||(ZC=at({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function Q4(){_D=!0;let e=(0,Zc.get)(sS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await Y4(iD,e),await jC(nS(),K4),await jC(lD(),W4)},Math.min(e/2,2147483647)).unref()}function dD(e,t){let r=e.report;r.threadId=t?.threadId||Xi.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(eD+=s.mean*s.count);r.totalBytesProcessed=eD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(tD.get(t))}),tD.set(t,t.performance.eventLoopUtilization())),r.id=(0,ed.getNextMonotonicTime)(),nS().primaryStore.put(r.id,r),_D||Q4(),z4&&(fD=j4(r))}async function j4(e){if(await fD,!ii){let r=(0,Xc.dirname)((0,sD.getLogFilePath)());try{ii=await(0,rS.open)((0,Xc.join)(r,"analytics.log"),"r+")}catch{ii=await(0,rS.open)((0,Xc.join)(r,"analytics.log"),"w+")}}let t=(await ii.stat()).size;if(t>J4){let r=Buffer.alloc(t);await ii.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ii.write(r,{position:0}),await ii.truncate(r.length),t=r.length}await ii.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var
|
|
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 to,oD,aD,eu,sS,rd,tu,nS,sd,cD,td,uD,lD,_D,dD,ZC,eD,fD,z4,J4,rD,sD,hD,nD,iD,X4,pD,oi,Z4,bn=Re(()=>{to=require("worker_threads"),oD=x(Ke());Ae();aD=x(V()),eu=require("path"),sS=require("fs/promises"),rd=x(br()),tu=x(Z()),nS=x(L());tr();(0,tu.initSync)();sd=new Map,cD=(0,tu.get)(nS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(K4,"setAnalyticsEnabled");a(Br,"recordAction");tt.recordAnalytics=Br;a(rs,"recordActionBinary");td=0,uD=1e3,lD="analytics-report",_D=[];a(ru,"addAnalyticsListener");dD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(W4,"sendAnalytics");a(Q4,"aggregation");ZC=0,eD=0,fD=a(()=>new Promise(setImmediate),"rest");a(tD,"cleanup");z4=36e5,J4=31536e6;a(iS,"getRawAnalyticsTable");a(ED,"getAnalyticsTable");(0,oD.setChildListenerByType)(lD,mD);a(j4,"startScheduledTasks");nD=0,iD=new Map,X4=!1;a(mD,"recordAnalytics");Z4=1e6;a(e3,"logAnalytics")});var st=T((Xde,HD)=>{"use strict";var qt=Z();qt.initSync();var t3=require("fs-extra"),r3=require("semver"),ou=require("path"),{monotonicFactory:s3}=require("ulidx"),TD=s3(),n3=require("util"),gD=require("child_process"),i3=n3.promisify(gD.exec),o3=gD.spawn,Ne=Ge(),Me=L(),uS=J(),Hr=V(),nd=Sn(),a3=ed(),nu=Lr(),{onMessageByType:c3}=Ke(),{isMainThread:u3}=require("worker_threads"),{Encoder:l3,decode:lS}=require("msgpackr"),RD=new l3,{isEmpty:io}=uS,AD=ts(),_3=48*36e11,d3=5e9;u3&&c3(Me.ITC_EVENT_TYPES.RESTART,()=>{ss=void 0,no=void 0});var{connect:f3,StorageType:OD,RetentionPolicy:bD,AckPolicy:id,DeliverPolicy:od,DiscardPolicy:E3,NatsConnection:Qde,JetStreamManager:zde,JetStreamClient:Jde,StringCodec:jde,JSONCodec:h3,createInbox:_S,headers:m3,ErrorCode:SD}=require("nats"),{PACKAGE_ROOT:p3}=L(),S3=Zc(),{recordAction:T3}=(bn(),se(su)),ND=h3(),g3="clustering",R3=S3.engines[Ne.NATS_SERVER_NAME],A3=ou.join(p3,"dependencies"),cS=ou.join(A3,`${process.platform}-${process.arch}`,Ne.NATS_BINARY_NAME),oS,aS,iu,ro,so;HD.exports={runCommand:yD,checkNATSServerInstalled:O3,createConnection:dS,getConnection:ad,getJetStreamManager:au,getJetStream:ID,getNATSReferences:ar,getServerList:N3,createLocalStream:fS,listStreams:CD,deleteLocalStream:y3,getServerConfig:cu,listRemoteStreams:w3,viewStream:I3,viewStreamIterator:C3,publishToStream:D3,createWorkQueueStream:L3,addSourceToWorkStream:LD,request:M3,removeSourceFromWorkStream:MD,reloadNATS:ES,reloadNATSHub:P3,reloadNATSLeaf:v3,extractServerName:UD,requestErrorHandler:B3,updateWorkStream:H3,createLocalTableStream:vD,createTableStreams:x3,purgeTableStream:BD,purgeSchemaTableStreams:q3,getStreamInfo:F3,updateLocalStreams:k3,closeConnection:b3,getJsmServerName:uu,addNatsMsgHeader:DD,updateIngestStreamConsumer:U3,clearClientCache:wD};async function yD(e,t=void 0){let{stdout:r,stderr:s}=await i3(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(AD,"runCommand");async function g3(){try{await X4.access(aS)}catch{return!1}let e=await AD(`${aS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Z4.eq(t,S3)}a(g3,"checkNATSServerInstalled");async function _S(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await SD.getClusterUser();if(ro(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 l3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ht.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),OD()}),i}a(_S,"createConnection");function OD(){rs=void 0,Zi=void 0,eo=void 0,to=void 0}a(OD,"clearClientCache");async function R3(){rs&&(await rs.drain(),rs=void 0,Zi=void 0,eo=void 0,to=void 0)}a(R3,"closeConnection");var rs,to;async function id(){return to||(to=_S(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),rs=await to),rs||to}a(id,"getConnection");async function iu(){if(Zi)return Zi;ro(rs)&&await id();let{domain:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ro(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Zi=await rs.jetstreamManager({domain:e,timeout:6e4}),Zi}a(iu,"getJetStreamManager");async function bD(){if(eo)return eo;ro(rs)&&await id();let{domain:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ro(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return eo=rs.jetstream({domain:e,timeout:6e4}),eo}a(bD,"getJetStream");async function nr(){let e=rs||await id(),t=Zi||await iu(),r=eo||await bD();return{connection:e,jsm:t,js:r}}a(nr,"getNATSReferences");async function A3(e){let t=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await SD.getClusterUser(),n=await _S(t,r,s),i=lS(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=RD.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 cS.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(A3,"getServerList");async function dS(e,t){let{jsm:r}=await nr(),s=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:TD.File,retention:gD.Limits,subjects:t,discard:_3.Old,max_msgs:n,max_bytes:i,max_age:s})}a(dS,"createLocalStream");async function ND(){let{jsm:e}=await nr(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(ND,"listStreams");async function O3(e){let{jsm:t}=await nr();await t.streams.delete(e)}a(O3,"deleteLocalStream");async function b3(e){let{connection:t}=await nr(),r=[],s=lS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(RD.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(b3,"listRemoteStreams");async function N3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await nr(),i=hD(),o={durable_name:i,ack_policy:sd.Explicit};t&&(o.deliver_policy=nd.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=uS(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(N3,"viewStream");async function*y3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await nr(),i=hD(),o={durable_name:i,ack_policy:sd.Explicit};t&&(o.deliver_policy=nd.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=uS(_.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(y3,"viewStreamIterator");async function w3(e,t,r,s){xr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=yD(s,r);let{js:n}=await nr(),i=await au(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:pD.encode(s);try{xr.trace(`publishToStream publishing to subject: ${o}`),m3(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 DD(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){xr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await dS(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(w3,"publishToStream");function yD(e,t){t===void 0&&(t=f3());let r=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(ye.MSG_HEADERS.ORIGIN)&&r&&t.append(ye.MSG_HEADERS.ORIGIN,r),t}a(yD,"addNatsMsgHeader");function ou(e){e=e.toLowerCase();let t=nu.join(Ht.get(Pe.CONFIG_PARAMS.ROOTPATH),p3);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ro(oS)&&(oS={port:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.HUB,config_file:ye.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:nu.join(t,ye.PID_FILES.HUB),hdb_nats_path:t}),oS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ro(iS)&&(iS={port:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,config_file:ye.NATS_CONFIG_FILES.LEAF_SERVER,domain:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,pid_file_path:nu.join(t,ye.PID_FILES.LEAF),hdb_nats_path:t}),iS;xr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(ou,"getServerConfig");async function I3(e){let{jsm:t}=await nr(),r=await au();try{await t.streams.add({name:e.stream_name,storage:TD.File,retention:gD.Limits,max_age:c3,max_bytes:u3,subjects:[`${ye.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:sd.Explicit,durable_name:e.durable_name,deliver_policy:nd.All,max_ack_pending:1e4});else throw s}}a(I3,"createWorkQueueStream");async function C3(){let{jsm:e}=await nr();(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:sd.Explicit,durable_name:ye.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:nd.All,max_ack_pending:1e4}))}a(C3,"updateIngestStreamConsumer");async function wD(e,t,r){let{jsm:s}=await nr(),n=await s.streams.info(t),i=ID(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=rd.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let p=0,S=n.config.sources.length;p<S;p++)if(d=n.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await s.streams.purge(t,{filter:p}),n.config.sources.splice(f,1),await s.streams.update(t,n.config)}let h={name:_,opt_start_time:o,filter_subject:`${ye.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(wD,"addSourceToWorkStream");function ID(e){return e.split(".")[1]}a(ID,"extractServerName");async function CD(e,t,r){let{jsm:s}=await nr(),{schema:n,table:i}=r,o=`txn.${n}.${i}.${e}`;await s.streams.purge(t,{filter:o});let c=rd.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(CD,"removeSourceFromWorkStream");async function D3(e,t,r=6e4,s=lS()){if(!cS.isObject(t))throw new Error("data param must be an object");let n=pD.encode(t),{connection:i}=await nr(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return uS(c.data)}a(D3,"request");function fS(e){return new Promise(async(t,r)=>{let s=s3(aS,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(fS,"reloadNATS");async function L3(){let{pid_file_path:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await fS(e)}a(L3,"reloadNATSHub");async function M3(){let{pid_file_path:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await fS(e)}a(M3,"reloadNATSLeaf");function U3(e,t,r){let s;switch(e.code){case ED.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case ED.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(U3,"requestErrorHandler");async function P3(e,t){let r=t+ye.SERVER_SUFFIX.LEAF;await DD(async()=>{e.subscribe===!0?await wD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await CD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(P3,"updateWorkStream");function DD(e){return n3.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(DD,"exclusiveLock");async function LD(e,t){let r=rd.createNatsTableStreamName(e,t),s=await au(),n=x3(e,t,s);await dS(r,[n])}a(LD,"createLocalTableStream");async function v3(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await LD(s,n)}}a(v3,"createTableStreams");async function MD(e,t,r=!1){if(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=rd.createNatsTableStreamName(e,t),{jsm:n}=await nr();r?await n.streams.purge(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name):await n.streams.purge(s)}catch(s){if(s.message==="stream not found")xr.warn(s);else throw s}}a(MD,"purgeTableStream");async function B3(e,t){if(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await MD(e,t[r])}a(B3,"purgeSchemaTableStreams");async function H3(e){return(await iu()).streams.info(e)}a(H3,"getStreamInfo");function x3(e,t,r){return`${ye.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(x3,"createSubjectName");async function au(){if(su)return su;if(su=(await iu())?.nc?.info?.server_name,su===void 0)throw new Error("Unable to get jetstream manager server name");return su}a(au,"getJsmServerName");async function q3(){let e=await iu(),t=await au(),r=await ND();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=F3(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");xr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}await e.streams.update(n.name,n)}}}a(q3,"updateLocalStreams");function F3(e){let{config:t}=e,r=!1;if(t.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(F3,"updateStreamLimits")});var cu=T((Jde,HD)=>{"use strict";var sa=u_(),na=QC(),G3=V(),k3=require("uuid").v4,zde=require("clone"),ad=Tn(),ia=L(),V3=require("util"),oi=bs(),{handleHDBError:ir,hdb_errors:$3}=ee(),{HDB_ERROR_MSGS:od,HTTP_STATUS_CODES:or}=$3,{SchemaEventMsg:cd}=ws(),PD=rt(),{getDatabases:Y3}=(be(),te(qe)),{transformReq:oa}=J();HD.exports={createSchema:K3,createSchemaStructure:vD,createTable:W3,createTableStructure:BD,createAttribute:X3,dropSchema:Q3,dropTable:z3,dropAttribute:J3,getBackup:Z3};async function K3(e){let t=await vD(e);return ad.signalSchemaChange(new cd(process.pid,e.operation,e.schema)),t}a(K3,"createSchema");async function vD(e){let t=sa.schema_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);if(oa(e),!await na.checkSchemaExists(e.schema))throw ir(new Error,od.SCHEMA_EXISTS_ERR(e.schema),or.BAD_REQUEST,ia.LOG_LEVELS.ERROR,od.SCHEMA_EXISTS_ERR(e.schema),!0);return await oi.createSchema(e),`database '${e.schema}' successfully created`}a(vD,"createSchemaStructure");async function W3(e){return oa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await BD(e)}a(W3,"createTable");async function BD(e){let t=sa.create_table_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);if(sa.validateTableResidence(e.residence),!await na.checkSchemaTableExists(e.schema,e.table))throw ir(new Error,od.TABLE_EXISTS_ERR(e.schema,e.table),or.BAD_REQUEST,ia.LOG_LEVELS.ERROR,od.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:k3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await oi.createTable(s,e);else throw ir(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",or.BAD_REQUEST);else await oi.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(BD,"createTableStructure");async function Q3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=sa.schema_object(e),s=t??r;if(s)throw ir(s,s.message,or.BAD_REQUEST,void 0,void 0,!0);oa(e);let n=await na.checkSchemaExists(e.schema);if(n)throw ir(new Error,n,or.NOT_FOUND,ia.LOG_LEVELS.ERROR,n,!0);let i=await na.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await oi.dropSchema(e),ad.signalSchemaChange(new cd(process.pid,e.operation,e.schema)),await PD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(Q3,"dropSchema");async function z3(e){let t=sa.table_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);oa(e);let r=await na.checkSchemaTableExists(e.schema,e.table);if(r)throw ir(new Error,r,or.NOT_FOUND,ia.LOG_LEVELS.ERROR,r,!0);return await oi.dropTable(e),await PD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(z3,"dropTable");async function J3(e){let t=sa.attribute_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);oa(e);let r=await na.checkSchemaTableExists(e.schema,e.table);if(r)throw ir(new Error,r,or.NOT_FOUND,ia.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw ir(new Error,"You cannot drop a hash attribute",or.BAD_REQUEST,void 0,void 0,!0);if(ia.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw ir(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,or.BAD_REQUEST,void 0,void 0,!0);try{return await oi.dropAttribute(e),j3(e),ad.signalSchemaChange(new cd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw G3.error(`Got an error deleting attribute ${V3.inspect(e)}.`),s}}a(J3,"dropAttribute");function j3(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(j3,"dropAttributeFromGlobal");async function X3(e){oa(e);let t=Y3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw ir(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,or.BAD_REQUEST,void 0,void 0,!0);return await oi.createAttribute(e),ad.signalSchemaChange(new cd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(X3,"createAttribute");function Z3(e){return oi.getBackup(e)}a(Z3,"getBackup")});var qD=T((Xde,xD)=>{"use strict";var{OPERATIONS_ENUM:ej}=L(),ES=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=ej.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};xD.exports=ES});var hS=T((tfe,$D)=>{"use strict";var tj=bs(),efe=qD(),ud=J(),ld=L(),rj=X(),{handleHDBError:FD,hdb_errors:sj}=ee(),{HDB_ERROR_MSGS:GD,HTTP_STATUS_CODES:kD}=sj,nj=Object.values(ld.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),VD="To use this operation audit log must be enabled in harperdb-config.yaml";$D.exports=ij;async function ij(e){if(ud.isEmpty(e.schema))throw new Error(GD.SCHEMA_REQUIRED_ERR);if(ud.isEmpty(e.table))throw new Error(GD.TABLE_REQUIRED_ERR);if(!rj.get(ld.CONFIG_PARAMS.LOGGING_AUDITLOG))throw FD(new Error,VD,kD.BAD_REQUEST,ld.LOG_LEVELS.ERROR,VD,!0);let t=ud.checkSchemaTableExist(e.schema,e.table);if(t)throw FD(new Error,t,kD.NOT_FOUND,ld.LOG_LEVELS.ERROR,t,!0);if(!ud.isEmpty(e.search_type)&&nj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await tj.readAuditLog(e)}a(ij,"readAuditLog")});var KD=T((sfe,YD)=>{"use strict";var{OPERATIONS_ENUM:oj}=L(),mS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=oj.GET_BACKUP,this.schema=t,this.table=r}};YD.exports=mS});var zD=T((afe,QD)=>{"use strict";var aj=bs(),ife=KD(),pS=J(),cj=L(),ofe=X(),{handleHDBError:uj,hdb_errors:lj}=ee(),{HDB_ERROR_MSGS:WD,HTTP_STATUS_CODES:_j}=lj;QD.exports=dj;async function dj(e){if(pS.isEmpty(e.schema))throw new Error(WD.SCHEMA_REQUIRED_ERR);if(pS.isEmpty(e.table))throw new Error(WD.TABLE_REQUIRED_ERR);let t=pS.checkSchemaTableExist(e.schema,e.table);if(t)throw uj(new Error,t,_j.NOT_FOUND,cj.LOG_LEVELS.ERROR,t,!0);return await aj.getBackup(read_audit_log_object)}a(dj,"getBackup")});var tL=T((ufe,eL)=>{var ai=require("validate.js"),jD=Qe(),aa=L(),{handleHDBError:fj,hdb_errors:Ej}=ee(),{HDB_ERROR_MSGS:ut,HTTP_STATUS_CODES:hj}=Ej,SS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),mj={STRUCTURE_USER:"structure_user"},JD=Object.values(aa.ROLE_TYPES_ENUM),pj="attribute_permissions",Sj="attribute_name",{PERMS_CRUD_ENUM:ca}=aa,Tj=[pj,...Object.values(ca)],XD=[ca.READ,ca.INSERT,ca.UPDATE],gj=[Sj,...XD];function Rj(e){let t=SS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,ZD(e,t)}a(Rj,"addRoleValidation");function Aj(e){let t=SS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,ZD(e,t)}a(Aj,"alterRoleValidation");function Oj(e){let t=SS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,jD.validateObject(e,t)}a(Oj,"dropRoleValidation");var bj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function ZD(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)bj.includes(s[o])||n.push(s[o]);n.length>0&&Et(ut.INVALID_ROLE_JSON_KEYS(n),r);let i=jD.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Et(o,r)}),e.permission){let o=Nj(e);o&&Et(o,r),JD.forEach(c=>{e.permission[c]&&!ai.isBoolean(e.permission[c])&&Et(ut.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(JD.indexOf(o)<0){if(o===mj.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]||Et(ut.SCHEMA_NOT_FOUND(d),r)}continue}Et(ut.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Et(ut.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]){Et(ut.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{Tj.includes(l)||Et(ut.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ca).forEach(l=>{ai.isDefined(_[l])?ai.isBoolean(_[l])||Et(ut.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Et(ut.TABLE_PERM_MISSING(l),r,o,u)}),ai.isDefined(_.attribute_permissions)){if(!ai.isArray(_.attribute_permissions)){Et(ut.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Et(ut.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=>{!gj.includes(p)&&p!==ca.DELETE&&Et(ut.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ai.isDefined(E.attribute_name)){Et(ut.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){Et(ut.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}XD.forEach(p=>{ai.isDefined(E[p])?ai.isBoolean(E[p])||Et(ut.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):Et(ut.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}`;Et(ut.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return yj(r)}a(ZD,"customValidate");eL.exports={addRoleValidation:Rj,alterRoleValidation:Aj,dropRoleValidation:Oj};function Nj(e){let{operation:t,permission:r}=e;if(t===aa.OPERATIONS_ENUM.ADD_ROLE||t===aa.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 ut.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?aa.ROLE_TYPES_ENUM.SUPER_USER:aa.ROLE_TYPES_ENUM.CLUSTER_USER;return ut.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Nj,"validateNoSUPerms");function yj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:ut.ROLE_PERMS_ERROR,...e};return fj(new Error,s,hj.BAD_REQUEST)}else return null}a(yj,"generateRolePermResponse");function Et(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(Et,"addPermError")});var bS=T((_fe,iL)=>{"use strict";var rL=Ir(),sL=Zr(),wj=ei(),gS=tL(),RS=Tn(),Ij=require("uuid").v4,Cj=require("util"),_d=L(),Dj=J(),AS=sL.searchByValue,Lj=sL.searchByHash,Mj=Cj.promisify(wj.delete),Uj=zs(),Pj=Zo(),{hdb_errors:vj,handleHDBError:so}=ee(),{HDB_ERROR_MSGS:nL,HTTP_STATUS_CODES:uu}=vj,{UserEventMsg:OS}=ws();iL.exports={addRole:Bj,alterRole:Hj,dropRole:xj,listRoles:qj};function TS(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(TS,"scrubRoleDetails");async function Bj(e){let t=gS.addRoleValidation(e);if(t)throw t;e=TS(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 AS(r)||[])}catch(i){throw so(i)}if(s&&s.length>0)throw so(new Error,nL.ROLE_ALREADY_EXISTS(e.role),uu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Ij());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await rL.insert(n),RS.signalUserChange(new OS(process.pid)),e=TS(e),e}a(Bj,"addRole");async function Hj(e){let t=gS.alterRoleValidation(e);if(t)throw t;e=TS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await rL.update(r)}catch(n){throw so(n)}if(s&&s?.message==="updated 0 of 1 records")throw so(new Error,"Invalid role id",uu.BAD_REQUEST,void 0,void 0,!0);return await RS.signalUserChange(new OS(process.pid)),e}a(Hj,"alterRole");async function xj(e){let t=gS.dropRoleValidation(e);if(t)throw so(new Error,t,uu.BAD_REQUEST,void 0,void 0,!0);let r=new Pj(_d.SYSTEM_SCHEMA_NAME,_d.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await Lj(r));if(s.length===0)throw so(new Error,nL.ROLE_NOT_FOUND,uu.NOT_FOUND,void 0,void 0,!0);let n=new Uj(_d.SYSTEM_SCHEMA_NAME,_d.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await AS(n)),o=!1;if(Dj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw so(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,uu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Mj(c),RS.signalUserChange(new OS(process.pid)),`${s[0].role} successfully deleted`}a(xj,"dropRole");async function qj(){return AS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(qj,"listRoles")});var uL=T((ffe,cL)=>{"use strict";var Fj=X(),ci=require("joi"),Gj=Qe(),oL=require("moment"),kj=require("fs-extra"),NS=require("path"),Vj=require("lodash"),lu=L(),{LOG_LEVELS:no}=L(),$j="YYYY-MM-DD hh:mm:ss",Yj=NS.resolve(__dirname,"../logs");cL.exports=function(e){return Gj.validateBySchema(e,Kj)};var Kj=ci.object({from:ci.custom(aL),until:ci.custom(aL),level:ci.valid(no.NOTIFY,no.FATAL,no.ERROR,no.WARN,no.INFO,no.DEBUG,no.TRACE),order:ci.valid("asc","desc"),limit:ci.number().min(1),start:ci.number().min(0),log_name:ci.custom(Wj)});function aL(e,t){if(oL(e,oL.ISO_8601).format($j)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(aL,"validateDatetime");function Wj(e,t){if(Vj.invert(lu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Fj.get(lu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?lu.LOG_NAMES.HDB:e,i=n===lu.LOG_NAMES.INSTALL?NS.join(Yj,lu.LOG_NAMES.INSTALL):NS.join(s,n);return kj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Wj,"validateReadLogPath")});var wS=T((hfe,_L)=>{"use strict";var dd=L(),Qj=V(),zj=X(),Jj=uL(),yS=require("path"),lL=require("fs-extra"),{once:jj}=require("events"),{handleHDBError:Xj,hdb_errors:Zj}=ee(),{PACKAGE_ROOT:eX}=L(),tX=yS.join(eX,"logs"),rX=1e3,sX=200;_L.exports=nX;async function nX(e){let t=Jj(e);if(t)throw Xj(t,t.message,Zj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=zj.get(dd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?dd.LOG_NAMES.HDB:e.log_name,n=s===dd.LOG_NAMES.INSTALL?yS.join(tX,dd.LOG_NAMES.INSTALL):yS.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?rX:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(lL.statSync(n).size-(h+5)*sX,0));let S=lL.createReadStream(n,{start:p});S.on("error",v=>{Qj.error(v)});let O=0,g=[],R="",B;S.on("data",v=>{let U=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=R+v;let Y=0,W;for(;(W=U.exec(v))&&!S.destroyed;){B&&(B.message=v.slice(Y,W.index),H(B));let[z,ne,Te]=W,oe=Te.split("] ["),xe=oe[0],de=oe[1];oe.splice(0,2),B={timestamp:ne,thread:xe,level:de,tags:oe,message:""},Y=W.index+z.length}R=v.slice(Y)}),S.on("end",v=>{S.destroyed||B&&(B.message=R.trim(),H(B))}),S.resume();function H(v){let U,Y,W;switch(!0){case(i&&c&&_):U=new Date(v.timestamp),Y=new Date(u),W=new Date(l),v.level===o&&U>=Y&&U<=W&&O<E?O++:v.level===o&&U>=Y&&U<=W&&(ui(v,f,g),O++,O===h&&S.destroy());break;case(i&&c):U=new Date(v.timestamp),Y=new Date(u),v.level===o&&U>=Y&&O<E?O++:v.level===o&&U>=Y&&(ui(v,f,g),O++,O===h&&S.destroy());break;case(i&&_):U=new Date(v.timestamp),W=new Date(l),v.level===o&&U<=W&&O<E?O++:v.level===o&&U<=W&&(ui(v,f,g),O++,O===h&&S.destroy());break;case(c&&_):U=new Date(v.timestamp),Y=new Date(u),W=new Date(l),U>=Y&&U<=W&&O<E?O++:U>=Y&&U<=W&&(ui(v,f,g),O++,O===h&&S.destroy());break;case i:v.level===o&&O<E?O++:v.level===o&&(ui(v,f,g),O++,O===h&&S.destroy());break;case c:U=new Date(v.timestamp),Y=new Date(u),U>=Y&&O<E?O++:U>=Y&&O>=E&&(ui(v,f,g),O++,O===h&&S.destroy());break;case _:U=new Date(v.timestamp),W=new Date(l),U<=W&&O<E?O++:U<=W&&O>=E&&(ui(v,f,g),O++,O===h&&S.destroy());break;default:O<E?O++:(ui(v,f,g),O++,O===h&&S.destroy())}}return a(H,"onLogMessage"),await jj(S,"close"),g}a(nX,"readLog");function ui(e,t,r){t==="desc"?iX(e,r):t==="asc"?oX(e,r):r.push(e)}a(ui,"pushLineToResult");function iX(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(iX,"insertDescending");function oX(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(oX,"insertAscending")});var fd=T((gfe,hL)=>{"use strict";var IS=require("joi"),{string:_u,boolean:dL,date:aX}=IS.types(),cX=Qe(),{validateSchemaExists:pfe,validateTableExists:Sfe,validateSchemaName:Tfe}=$s(),uX=L(),lX=Fe(),fL=X();fL.initSync();var _X=_u.invalid(fL.get(uX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(lX.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(),EL={operation:_u.valid("add_node","update_node","set_node_replication"),node_name:_X,subscriptions:IS.array().items({table:_u.optional(),schema:_u.optional(),database:_u.optional(),subscribe:dL.required(),publish:dL.required().custom(fX),start_time:aX.iso()}).min(1).required()};function dX(e){return cX.validateBySchema(e,IS.object(EL))}a(dX,"addUpdateNodeValidator");function fX(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(fX,"checkForFalsy");hL.exports={addUpdateNodeValidator:dX,validation_schema:EL}});var pL=T((Afe,mL)=>{var EX=Qe(),hX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};mL.exports=function(e){return EX.validateObject(e,hX)}});var Ed=T((Ofe,SL)=>{"use strict";var mX=L().OPERATIONS_ENUM,CS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=mX.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};SL.exports=CS});var gL=T((Nfe,TL)=>{"use strict";var pX={OPERATION:"operation",REFRESH:"refresh"},DS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},LS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};TL.exports={JWTTokens:DS,TOKEN_TYPE_ENUM:pX,JWTRSAKeys:LS}});var Eu=T((wfe,bL)=>{"use strict";var fu=require("jsonwebtoken"),MS=require("fs-extra"),US=J(),ss=L(),{handleHDBError:ar,hdb_errors:SX}=ee(),{HTTP_STATUS_CODES:cr,AUTHENTICATION_ERROR_MSGS:ur}=SX,du=V(),RL=A_(),BS=es(),TX=Ir().update,gX=Ed(),RX=Tn(),{UserEventMsg:AX}=ws(),li=X();li.initSync();var PS=require("path"),{JWTTokens:OX,JWTRSAKeys:bX,TOKEN_TYPE_ENUM:hd}=gL(),NX=li.get(ss.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?li.get(ss.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",yX=li.get(ss.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?li.get(ss.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",md="RS256",vS;bL.exports={createTokens:wX,validateOperationToken:CX,refreshOperationToken:IX,validateRefreshToken:OL};async function wX(e){if(US.isEmpty(e)||typeof e!="object")throw ar(new Error,ur.INVALID_AUTH_OBJECT,cr.BAD_REQUEST,void 0,void 0,!0);if(US.isEmpty(e.username))throw ar(new Error,ur.USERNAME_REQUIRED,cr.BAD_REQUEST,void 0,void 0,!0);if(US.isEmpty(e.password))throw ar(new Error,ur.PASSWORD_REQUIRED,cr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await BS.findAndValidateUser(e.username,e.password),!t)throw ar(new Error,ur.INVALID_CREDENTIALS,cr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw du.error(f),ar(new Error,ur.INVALID_CREDENTIALS,cr.UNAUTHORIZED,void 0,void 0,!0)}let r=await pd(),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 AL(i,r.private_key,r.passphrase),c=await fu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:yX,algorithm:md,subject:hd.REFRESH}),u=RL.hash(c),_=new gX(ss.SYSTEM_SCHEMA_NAME,ss.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await TX(_)}catch(f){du.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw ar(new Error,ur.REFRESH_TOKEN_SAVE_FAILED,cr.INTERNAL_SERVER_ERROR);return RX.signalUserChange(new AX(process.pid)),new OX(o,c)}a(wX,"createTokens");async function AL(e,t,r){return await fu.sign(e,{key:t,passphrase:r},{expiresIn:NX,algorithm:md,subject:hd.OPERATION})}a(AL,"signOperationToken");async function pd(){if(vS===void 0)try{let e=PS.join(li.getHdbBasePath(),ss.LICENSE_KEY_DIR_NAME,ss.JWT_ENUM.JWT_PASSPHRASE_NAME),t=PS.join(li.getHdbBasePath(),ss.LICENSE_KEY_DIR_NAME,ss.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=PS.join(li.getHdbBasePath(),ss.LICENSE_KEY_DIR_NAME,ss.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await MS.readFile(e)).toString(),n=(await MS.readFile(t)).toString(),i=(await MS.readFile(r)).toString();vS=new bX(i,n,s)}catch(e){throw du.error(e),ar(new Error,ur.NO_ENCRYPTION_KEYS,cr.INTERNAL_SERVER_ERROR)}return vS}a(pd,"getJWTRSAKeys");async function IX(e){if(!e)throw ar(new Error,ur.INVALID_BODY,cr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw ar(new Error,ur.REFRESH_TOKEN_REQUIRED,cr.BAD_REQUEST,void 0,void 0,!0);await OL(e.refresh_token);let t=await pd(),r=await fu.decode(e.refresh_token);return{operation_token:await AL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(IX,"refreshOperationToken");async function CX(e){try{let t=await pd(),r=await fu.verify(e,t.public_key,{algorithms:md,subject:hd.OPERATION});return await BS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw du.warn(t),t.name&&t.name==="TokenExpiredError"?ar(new Error,ur.TOKEN_EXPIRED,cr.FORBIDDEN):ar(new Error,ur.INVALID_TOKEN,cr.UNAUTHORIZED)}}a(CX,"validateOperationToken");async function OL(e){let t;try{let r=await pd(),s=await fu.verify(e,r.public_key,{algorithms:md,subject:hd.REFRESH});t=await BS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw du.warn(r),r.name&&r.name==="TokenExpiredError"?ar(new Error,ur.TOKEN_EXPIRED,cr.FORBIDDEN):ar(new Error,ur.INVALID_TOKEN,cr.UNAUTHORIZED)}if(!RL.validate(t.refresh_token,e))throw ar(new Error,ur.INVALID_TOKEN,cr.UNAUTHORIZED);return t}a(OL,"validateRefreshToken")});var HS=T((Dfe,wL)=>{"use strict";var DX=pL(),ua=require("passport"),LX=require("passport-local").Strategy,MX=require("passport-http").BasicStrategy,UX=require("util"),PX=es(),yL=UX.callbackify(PX.findAndValidateUser),Cfe=br(),vX=L(),NL=Eu();ua.use(new LX(function(e,t,r){yL(e,t,r)}));ua.use(new MX(function(e,t,r){yL(e,t,r)}));ua.serializeUser(function(e,t){t(null,e)});ua.deserializeUser(function(e,t){t(null,e)});function BX(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":ua.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?NL.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):NL.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:ua.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(BX,"authorize");function HX(e,t){let r=DX(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(HX,"checkPermissions");wL.exports={authorize:BX,checkPermissions:HX}});var _i=T((Mfe,IL)=>{"use strict";var xS=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},qS=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};IL.exports={Node:xS,NodeSubscription:qS}});var DL=T((Pfe,CL)=>{"use strict";var xX=L().OPERATIONS_ENUM,FS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=xX.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};CL.exports=FS});var hu=T((Bfe,LL)=>{"use strict";var GS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},kS=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)}};LL.exports={RemotePayloadObject:GS,RemotePayloadSubscription:kS}});var UL=T((xfe,ML)=>{"use strict";var VS=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}};ML.exports=VS});var BL=T((Vfe,vL)=>{"use strict";var qX=UL(),Ffe=_t(),PL=Ye(),FX=V(),{getSchemaPath:Gfe,getTransactionAuditStorePath:kfe}=We(),{getDatabases:GX}=(be(),te(qe));vL.exports=kX;async function kX(e){let t=new qX;try{let r=GX()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await PL.environmentDataSize(schema_path,e.name),o=await PL.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){FX.warn(`unable to stat table dbi due to ${r}`)}return t}a(kX,"lmdbGetTableSize")});var xL=T((Yfe,HL)=>{"use strict";var $S=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}};HL.exports=$S});var la=T((zfe,kL)=>{"use strict";var VX=require("fs-extra"),$X=require("path"),Kt=require("systeminformation"),di=V(),YX=rt(),YS=Fe(),Td=L(),KX=BL(),GL=jn(),{getThreadInfo:qL}=$e(),tT=X();tT.initSync();var WX=xL(),{openEnvironment:Wfe}=Ye(),{getSchemaPath:Qfe}=We(),{database:QX}=(be(),te(qe)),Sd;kL.exports={getHDBProcessInfo:zS,getNetworkInfo:jS,getDiskInfo:JS,getMemoryInfo:QS,getCPUInfo:WS,getTimeInfo:KS,getSystemInformation:XS,systemInformation:zX,getTableSize:ZS,getMetrics:eT};function KS(){return Kt.time()}a(KS,"getTimeInfo");async function WS(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Kt.cpu();l.cpu_speed=await Kt.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:O,...g}=await Kt.currentLoad();return g.cpus=[],O.forEach(R=>{let{raw_load:B,raw_load_idle:H,raw_load_irq:v,raw_load_nice:U,raw_load_system:Y,raw_load_user:W,...z}=R;g.cpus.push(z)}),l.current_load=g,l}catch(e){return di.error(`error in getCPUInfo: ${e}`),{}}}a(WS,"getCPUInfo");async function QS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Kt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return di.error(`error in getMemoryInfo: ${e}`),{}}}a(QS,"getMemoryInfo");async function zS(){let e={core:[],clustering:[]};try{let t=await Kt.processes(),r;try{r=Number.parseInt(await VX.readFile($X.join(tT.get(Td.CONFIG_PARAMS.ROOTPATH),Td.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Td.NODE_ERROR_CODES.ENOENT)di.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 di.error(`error in getHDBProcessInfo: ${t}`),e}}a(zS,"getHDBProcessInfo");async function JS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Kt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Kt.fsStats();return e.read_write=_,e.size=await Kt.fsSize(),e}catch(t){return di.error(`error in getDiskInfo: ${t}`),e}}a(JS,"getDiskInfo");async function jS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Kt.networkInterfaceDefault(),e.latency=await Kt.inetChecksite("google.com"),(await Kt.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 Kt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return di.error(`error in getNetworkInfo: ${t}`),e}}a(jS,"getNetworkInfo");async function XS(){if(Sd!==void 0)return Sd;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Kt.osInfo();e=c;let u=await Kt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Sd=e,Sd}catch(t){return di.error(`error in getSystemInformation: ${t}`),e}}a(XS,"getSystemInformation");async function ZS(){let e=[],t=await GL.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await KX(s));return e}a(ZS,"getTableSize");async function eT(){let e=await GL.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=QX({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){di.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(eT,"getMetrics");async function FL(){if(tT.get(Td.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await YX.getNATSReferences(),r=await t.streams.info(YS.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(YS.WORK_QUEUE_CONSUMER_NAMES.stream_name,YS.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(FL,"getNatsStreamInfo");async function zX(e){let t=new WX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await XS(),t.time=KS(),t.cpu=await WS(),t.memory=await QS(),t.disk=await JS(),t.network=await jS(),t.harperdb_processes=await zS(),t.table_size=await ZS(),t.metrics=await eT(),t.threads=await qL(),t.replication=await FL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await XS();break;case"time":t.time=KS();break;case"cpu":t.cpu=await WS();break;case"memory":t.memory=await QS();break;case"disk":t.disk=await JS();break;case"network":t.network=await jS();break;case"harperdb_processes":t.harperdb_processes=await zS();break;case"table_size":t.table_size=await ZS();break;case"database_metrics":case"metrics":t.metrics=await eT();break;case"threads":t.threads=await qL();break;case"replication":t.replication=await FL();break;default:break}return t}a(zX,"systemInformation")});var Rd=T((jfe,VL)=>{"use strict";VL.exports={version:JX,printVersion:jX};var gd=jc();function JX(){if(gd)return gd.version}a(JX,"version");function jX(){gd&&console.log(`HarperDB Version ${gd.version}`)}a(jX,"printVersion")});var ns=T((tEe,WL)=>{"use strict";var XX=Ir(),rT=J(),ZX=require("util"),io=L(),$L=X();$L.initSync();var eZ=HS(),YL=Zr(),{Node:Zfe,NodeSubscription:eEe}=_i(),tZ=Zo(),rZ=DL(),{RemotePayloadObject:sZ,RemotePayloadSubscription:nZ}=hu(),{handleHDBError:iZ,hdb_errors:oZ}=ee(),{HTTP_STATUS_CODES:aZ,HDB_ERROR_MSGS:cZ}=oZ,uZ=zs(),lZ=la(),_Z=Rd(),{getDatabases:dZ}=(be(),te(qe)),fZ=ZX.promisify(eZ.authorize),EZ=YL.searchByHash,hZ=YL.searchByValue;WL.exports={authHeaderToUser:mZ,isEmpty:pZ,getNodeRecord:SZ,upsertNodeRecord:TZ,buildNodePayloads:gZ,checkClusteringEnabled:RZ,getAllNodeRecords:AZ,getSystemInfo:OZ,reverseSubscription:KL};async function mZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await fZ(t,null),e}a(mZ,"authHeaderToUser");function pZ(e){return e==null}a(pZ,"isEmpty");async function SZ(e){let t=new tZ(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return EZ(t)}a(SZ,"getNodeRecord");async function TZ(e){let t=new rZ(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return XX.upsert(t)}a(TZ,"upsertNodeRecord");function KL(e){if(rT.isEmpty(e.subscribe)||rT.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(KL,"reverseSubscription");function gZ(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=rT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=KL(c),E=dZ()[u]?.[_],h=new nZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new sZ(r,t,n,s)}a(gZ,"buildNodePayloads");function RZ(){if(!$L.get(io.CONFIG_PARAMS.CLUSTERING_ENABLED))throw iZ(new Error,cZ.CLUSTERING_NOT_ENABLED,aZ.BAD_REQUEST,void 0,void 0,!0)}a(RZ,"checkClusteringEnabled");async function AZ(){let e=new uZ(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await hZ(e))}a(AZ,"getAllNodeRecords");async function OZ(){let e=await lZ.getSystemInformation();return{hdb_version:_Z.version(),node_version:e.node_version,platform:e.platform}}a(OZ,"getSystemInfo")});var sT=T((sEe,tM)=>{"use strict";var Ad=rt(),QL=J(),zL=Fe(),JL=L(),Od=V(),jL=cu(),bZ=k_(),{RemotePayloadObject:NZ}=hu(),{handleHDBError:XL,hdb_errors:yZ}=ee(),{HTTP_STATUS_CODES:ZL}=yZ,{NodeSubscription:eM}=_i();tM.exports=wZ;async function wZ(e,t){let r;try{r=await Ad.request(`${t}.${zL.REQUEST_SUFFIX}`,new NZ(JL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Od.trace("Response from remote describe all request:",r)}catch(o){Od.error(`addNode received error from describe all request to remote node: ${o}`);let c=Ad.requestErrorHandler(o,"add_node",t);throw XL(new Error,c,ZL.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 XL(new Error,o,ZL.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===JL.SYSTEM_SCHEMA_NAME){await Ad.createLocalTableStream(u,c);let h=new eM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=QL.doesSchemaExist(u),l=s[u]!==void 0,d=c?QL.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(Od.trace(`addNode creating schema: ${u}`),await jL.createSchema({operation:"create_schema",schema:u})),!d&&f){Od.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new bZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await jL.createTable(h)}await Ad.createLocalTableStream(u,c);let E=new eM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(wZ,"reviewSubscriptions")});var yd=T((iEe,nM)=>{"use strict";var{handleHDBError:bd,hdb_errors:IZ}=ee(),{HTTP_STATUS_CODES:Nd}=IZ,{addUpdateNodeValidator:CZ}=fd(),mu=V(),sM=L(),rM=Fe(),DZ=J(),nT=rt(),pu=ns(),LZ=X(),MZ=sT(),{Node:UZ,NodeSubscription:PZ}=_i(),{broadcast:vZ}=$e(),BZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",HZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",xZ=LZ.get(sM.CONFIG_PARAMS.CLUSTERING_NODENAME);nM.exports=qZ;async function qZ(e,t=!1){mu.trace("addNode called with:",e),pu.checkClusteringEnabled();let r=CZ(e);if(r)throw bd(r,r.message,Nd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await pu.getNodeRecord(s);if(!DZ.isEmptyOrZeroLength(d))throw bd(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Nd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await MZ(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=BZ,o;let c=pu.buildNodePayloads(n,xZ,sM.OPERATIONS_ENUM.ADD_NODE,await pu.getSystemInfo());mu.trace("addNode sending remote payload:",c);let u;try{u=await nT.request(`${s}.${rM.REQUEST_SUFFIX}`,c)}catch(d){mu.error(`addNode received error from request: ${d}`);let f=nT.requestErrorHandler(d,"add_node",s);throw bd(new Error,f,Nd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===rM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw bd(new Error,d,Nd.INTERNAL_SERVER_ERROR,"error",d)}mu.trace(u);let _=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];mu.trace("Add node updating work stream for node:",s,"subscriptions:",E),await nT.updateWorkStream(E,s),n[d].start_time===void 0&&delete n[d].start_time,_.push(new PZ(E.schema,E.table,E.publish,E.subscribe))}let l=new UZ(s,_,u.system_info);return await pu.upsertNodeRecord(l),vZ({type:"nats_update"}),i.length>0?o.message=HZ:o.message=`Successfully added '${s}' to manifest`,o}a(qZ,"addNode")});var cT=T((cEe,aM)=>{"use strict";var{handleHDBError:iT,hdb_errors:FZ}=ee(),{HTTP_STATUS_CODES:oT}=FZ,{addUpdateNodeValidator:GZ}=fd(),Su=V(),oM=L(),iM=Fe(),aEe=J(),aT=rt(),Tu=ns(),kZ=X(),{cloneDeep:VZ}=require("lodash"),$Z=sT(),{Node:YZ,NodeSubscription:KZ}=_i(),{broadcast:WZ}=$e(),QZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",zZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",JZ=kZ.get(oM.CONFIG_PARAMS.CLUSTERING_NODENAME);aM.exports=jZ;async function jZ(e){Su.trace("updateNode called with:",e),Tu.checkClusteringEnabled();let t=GZ(e);if(t)throw iT(t,t.message,oT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await Tu.getNodeRecord(r);n.length>0&&(s=VZ(n));let{added:i,skipped:o}=await $Z(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=QZ,c;let u=Tu.buildNodePayloads(i,JZ,oM.OPERATIONS_ENUM.UPDATE_NODE,await Tu.getSystemInfo());Su.trace("updateNode sending remote payload:",u);let _;try{_=await aT.request(`${r}.${iM.REQUEST_SUFFIX}`,u)}catch(l){Su.error(`updateNode received error from request: ${l}`);let d=aT.requestErrorHandler(l,"update_node",r);throw iT(new Error,d,oT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===iM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw iT(new Error,l,oT.INTERNAL_SERVER_ERROR,"error",l)}Su.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Su.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await aT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return s||(s=[new YZ(r,[],_.system_info)]),await XZ(s[0],i,_.system_info),o.length>0?c.message=zZ:c.message=`Successfully updated '${r}'`,c}a(jZ,"updateNode");async function XZ(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 KZ(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Tu.upsertNodeRecord(s),WZ({type:"nats_update"})}a(XZ,"updateNodeTable")});var dM=T((lEe,_M)=>{"use strict";var lM=require("joi"),{string:cM}=lM.types(),ZZ=Qe(),uM=L(),e5=X(),t5=Fe();_M.exports=r5;function r5(e){let t=cM.invalid(e5.get(uM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(t5.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=lM.object({operation:cM.valid(uM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return ZZ.validateBySchema(e,r)}a(r5,"removeNodeValidator")});var Id=T((dEe,SM)=>{"use strict";var{handleHDBError:fM,hdb_errors:s5}=ee(),{HTTP_STATUS_CODES:EM}=s5,n5=dM(),gu=V(),hM=ns(),i5=J(),wd=L(),mM=Fe(),pM=rt(),o5=X(),{RemotePayloadObject:a5}=hu(),{NodeSubscription:c5}=_i(),u5=ea(),l5=ei(),{broadcast:_5}=$e(),d5=o5.get(wd.CONFIG_PARAMS.CLUSTERING_NODENAME);SM.exports=f5;async function f5(e){gu.trace("removeNode called with:",e),hM.checkClusteringEnabled();let t=n5(e);if(t)throw fM(t,t.message,EM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await hM.getNodeRecord(r);if(i5.isEmptyOrZeroLength(s))throw fM(new Error,`Node '${r}' was not found.`,EM.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new a5(wd.OPERATIONS_ENUM.REMOVE_NODE,d5,[]),i,o=!1;try{i=await pM.request(`${r}.${mM.REQUEST_SUFFIX}`,n),gu.trace("Remove node reply from remote node:",r,i)}catch(u){gu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];gu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new c5(l.schema,l.table,!1,!1);await pM.updateWorkStream(d,r)}let c=new u5(wd.SYSTEM_SCHEMA_NAME,wd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await l5.deleteRecord(c),_5({type:"nats_update"}),i?.status===mM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(gu.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(f5,"removeNode")});var RM=T((EEe,gM)=>{"use strict";var TM=require("joi"),{string:E5,array:h5}=TM.types(),m5=Qe(),p5=fd();gM.exports=S5;function S5(e){let t=TM.object({operation:E5.valid("configure_cluster").required(),connections:h5.items(p5.validation_schema).required()});return m5.validateBySchema(e,t)}a(S5,"configureClusterValidator")});var uT=T((mEe,yM)=>{"use strict";var T5=L(),Cd=V(),g5=J(),R5=Id(),A5=yd(),AM=ns(),O5=RM(),{handleHDBError:OM,hdb_errors:b5}=ee(),{HTTP_STATUS_CODES:bM}=b5,N5="Configure cluster complete.",y5="Failed to configure the cluster. Check the logs for more details.",w5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";yM.exports=I5;async function I5(e){Cd.trace("configure cluster called with:",e),AM.checkClusteringEnabled();let t=O5(e);if(t)throw OM(t,t.message,bM.BAD_REQUEST,void 0,void 0,!0);let r=await AM.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(NM(R5,{operation:T5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let n=await Promise.allSettled(s);Cd.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(NM(A5,E,E.node_name))}let c=await Promise.allSettled(i);Cd.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"&&(Cd.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(g5.isEmptyOrZeroLength(u))return{message:N5,connections:_};if(l)return{message:w5,failed_nodes:u,connections:_};throw OM(new Error,y5,bM.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(I5,"configureCluster");async function NM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(NM,"functionWrapper")});var IM=T((SEe,wM)=>{"use strict";var Dd=require("joi"),C5=Qe(),{validateSchemaExists:D5,validateTableExists:L5,validateSchemaName:M5}=$s(),U5=Dd.object({operation:Dd.string().valid("purge_stream"),schema:Dd.string().custom(D5).custom(M5).required(),table:Dd.string().custom(L5).required()});function P5(e){return C5.validateBySchema(e,U5)}a(P5,"purgeStreamValidator");wM.exports=P5});var lT=T((gEe,CM)=>{"use strict";var{handleHDBError:v5,hdb_errors:B5}=ee(),{HTTP_STATUS_CODES:H5}=B5,x5=IM(),q5=rt(),F5=ns();CM.exports=G5;async function G5(e){if(e.purge_ingest!==!0){let n=x5(e);if(n)throw v5(n,n.message,H5.BAD_REQUEST,void 0,void 0,!0)}F5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await q5.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(G5,"purgeStream")});var fT=T((AEe,vM)=>{"use strict";var dT=ns(),k5=rt(),MM=X(),Ld=L(),oo=Fe(),V5=J(),_T=V(),{RemotePayloadObject:$5}=hu(),{ErrorCode:DM}=require("nats"),LM=MM.get(Ld.CONFIG_PARAMS.CLUSTERING_ENABLED),UM=MM.get(Ld.CONFIG_PARAMS.CLUSTERING_NODENAME);vM.exports={clusterStatus:Y5,buildNodeStatus:PM};async function Y5(){let e={node_name:UM,is_enabled:LM,connections:[]};if(!LM)return e;let t=await dT.getAllNodeRecords();if(V5.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(PM(t[s],e.connections));return await Promise.allSettled(r),e}a(Y5,"clusterStatus");async function PM(e,t){let r=e.name,s=new $5(Ld.OPERATIONS_ENUM.CLUSTER_STATUS,UM,void 0,await dT.getSystemInfo()),n,i,o=oo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await k5.request(oo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===oo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=oo.CLUSTER_STATUS_STATUSES.CLOSED,_T.error(`Error getting node status from ${r} `,n))}catch(u){_T.warn(`Error getting node status from ${r}`,u),u.code===DM.NoResponders?o=oo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===DM.Timeout?o=oo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=oo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new K5(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!==Ld.PRE_4_0_0_VERSION&&await dT.upsertNodeRecord(u)}catch(u){_T.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(PM,"buildNodeStatus");function K5(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(K5,"NodeStatusObject")});var hT=T((bEe,BM)=>{"use strict";var{handleHDBError:W5,hdb_errors:Q5}=ee(),{HTTP_STATUS_CODES:z5}=Q5,J5=rt(),j5=ns(),ET=J(),Md=require("joi"),X5=Qe(),Z5=2e3,e8=Md.object({timeout:Md.number().min(1),connected_nodes:Md.boolean(),routes:Md.boolean()});BM.exports=t8;async function t8(e){j5.checkClusteringEnabled();let t=X5.validateBySchema(e,e8);if(t)throw W5(t,t.message,z5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||ET.autoCastBoolean(s),o=n===void 0||ET.autoCastBoolean(n),c={nodes:[]},u=await J5.getServerList(r??Z5),_={};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:ET.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(t8,"clusterNetwork")});var FM=T((yEe,qM)=>{"use strict";var mT=require("joi"),HM=Qe(),{route_constraints:xM}=Hm();qM.exports={setRoutesValidator:r8,deleteRoutesValidator:s8};function r8(e){let t=mT.object({server:mT.valid("hub","leaf").required(),routes:xM.required()});return HM.validateBySchema(e,t)}a(r8,"setRoutesValidator");function s8(e){let t=mT.object({routes:xM.required()});return HM.validateBySchema(e,t)}a(s8,"deleteRoutesValidator")});var ST=T((IEe,$M)=>{"use strict";var ao=Mr(),pT=J(),Ud=L(),GM=FM(),{handleHDBError:kM,hdb_errors:n8}=ee(),{HTTP_STATUS_CODES:VM}=n8,i8="cluster routes successfully set",o8="cluster routes successfully deleted";$M.exports={setRoutes:a8,getRoutes:c8,deleteRoutes:u8};function a8(e){let t=GM.setRoutesValidator(e);if(t)throw kM(t,t.message,VM.BAD_REQUEST,void 0,void 0,!0);let r=ao.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=pT.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"?ao.updateConfigValue(Ud.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):ao.updateConfigValue(Ud.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:i8,set:o,skipped:i}}a(a8,"setRoutes");function c8(){let e=ao.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(c8,"getRoutes");function u8(e){let t=GM.deleteRoutesValidator(e);if(t)throw kM(t,t.message,VM.BAD_REQUEST,void 0,void 0,!0);let r=ao.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=pT.isEmptyOrZeroLength(s)?null:s,ao.updateConfigValue(Ud.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=pT.isEmptyOrZeroLength(n)?null:n,ao.updateConfigValue(Ud.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:o8,deleted:i,skipped:o}}a(u8,"deleteRoutes")});var KM=T((DEe,YM)=>{"use strict";var Ru=require("alasql"),co=require("recursive-iterator"),Ms=V(),l8=J(),Au=L(),TT=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,d8(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=>Au.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=>!Au.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][Au.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=_8(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(_=>!Au.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Ru.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 _8(e){return e.filter(t=>t[Au.PERMS_CRUD_ENUM.READ])}a(_8,"filterReadRestrictedAttrs");function d8(e,t,r,s,n){f8(e,t,r,s,n)}a(d8,"interpretAST");function Ou(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(Ou,"addSchemaTableToMap");function f8(e,t,r,s,n){if(!e){Ms.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Ru.yy.Insert?p8(e,t,r):e instanceof Ru.yy.Select?E8(e,t,r,s,n):e instanceof Ru.yy.Update?h8(e,t,r):e instanceof Ru.yy.Delete?m8(e,t,r):Ms.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(f8,"getRecordAttributesAST");function E8(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(l8.isEmptyOrZeroLength(i)){Ms.error("No schema specified");return}e.from.forEach(c=>{Ou(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Ou(c.table,t,r,s,n)});let o=new co(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 co(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 co(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 co(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(E8,"getSelectAttributes");function h8(e,t,r){if(!e){Ms.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new co(e.columns),n=e.table.databaseid;Ou(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&gT(e.table.tableid,n,i.columnid,t,r)}a(h8,"getUpdateAttributes");function m8(e,t,r){if(!e){Ms.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new co(e.where),n=e.table.databaseid;Ou(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&gT(e.table.tableid,n,i.columnid,t,r)}a(m8,"getDeleteAttributes");function p8(e,t,r){if(!e){Ms.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new co(e.columns),n=e.into.databaseid;Ou(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&gT(e.into.tableid,n,i.columnid,t,r)}a(p8,"getInsertAttributes");function gT(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(gT,"pushAttribute");YM.exports=TT});var OT=T((MEe,JM)=>{var Pd=$i(),WM=require("chalk"),qr=V(),QM=require("prompt"),{promisify:S8}=require("util"),RT=L(),T8=require("fs-extra"),g8=require("path"),R8=J(),A8=Rd(),zM=X();zM.initSync();var O8=require("moment"),b8=S8(QM.get),N8=g8.join(zM.getHdbBasePath(),RT.LICENSE_KEY_DIR_NAME,RT.LICENSE_FILE_NAME,RT.LICENSE_FILE_NAME);JM.exports={getFingerprint:w8,setLicense:y8,parseLicense:AT,register:I8,getRegistrationInfo:D8};async function y8(e){if(e&&e.key&&e.company){try{qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await AT(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(y8,"setLicense");async function w8(){let e={};try{e=await Pd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw qr.error(r),qr.error(t),new Error(r)}return e}a(w8,"getFingerprint");async function AT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");qr.info("Validating license input...");let r=Pd.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 T8.writeFile(N8,JSON.stringify({license_key:e,company:t}))}catch(s){throw qr.error("Failed to write License"),s}return"Registration successful."}a(AT,"parseLicense");async function I8(){let e=await C8();return AT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(I8,"register");async function C8(){let e=await Pd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:WM.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:WM.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{QM.start()}catch(s){qr.error(s)}let r;try{r=await b8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(C8,"promptForRegistration");async function D8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Pd.getLicense()}catch(r){throw qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(R8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=A8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=O8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(D8,"getRegistrationInfo")});var XM=T((PEe,jM)=>{"use strict";var L8=Fe(),bT=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+L8.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"}};jM.exports=bT});var tU=T((BEe,eU)=>{"use strict";var ZM=Fe(),NT=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+ZM.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+ZM.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"}};eU.exports=NT});var sU=T((xEe,rU)=>{"use strict";var yT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};rU.exports=yT});var iU=T((FEe,nU)=>{"use strict";var M8=Fe(),wT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+M8.SERVER_SUFFIX.ADMIN,this.password=r}};nU.exports=wT});var DT=T((kEe,cU)=>{"use strict";var _a=require("path"),Hd=require("fs-extra"),U8=XM(),P8=tU(),v8=sU(),B8=iU(),IT=es(),fa=J(),lr=Mr(),Bd=L(),bu=Fe(),{CONFIG_PARAMS:lt}=Bd,Nu=V(),yu=X(),oU=pn(),CT=rt(),da="clustering",H8=1e4,aU=5;cU.exports={generateNatsConfig:q8,removeNatsConfig:F8,getHubConfigPath:x8};function x8(){let e=yu.get(lt.ROOTPATH);return _a.join(e,da,bu.NATS_CONFIG_FILES.HUB_SERVER)}a(x8,"getHubConfigPath");async function q8(e=!1,t=void 0){yu.initSync();let r=yu.get(lt.ROOTPATH),s=_a.join(r,da,bu.PID_FILES.HUB),n=_a.join(r,da,bu.PID_FILES.LEAF),i=lr.getConfigFromFile(lt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=_a.join(r,da,bu.NATS_CONFIG_FILES.HUB_SERVER),c=_a.join(r,da,bu.NATS_CONFIG_FILES.LEAF_SERVER),u=lr.getConfigFromFile(lt.CLUSTERING_TLS_CERTIFICATE),_=lr.getConfigFromFile(lt.CLUSTERING_TLS_PRIVATEKEY),l=lr.getConfigFromFile(lt.CLUSTERING_TLS_CERT_AUTH),d=lr.getConfigFromFile(lt.CLUSTERING_TLS_INSECURE),f=lr.getConfigFromFile(lt.CLUSTERING_TLS_VERIFY),E=lr.getConfigFromFile(lt.CLUSTERING_NODENAME),h=lr.getConfigFromFile(lt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await CT.checkNATSServerInstalled()||xd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await IT.listUsers(),S=lr.getConfigFromFile(lt.CLUSTERING_USER),O=await IT.getClusterUser();(fa.isEmpty(O)||O.active!==!0)&&xd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await vd(lt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await vd(lt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await vd(lt.CLUSTERING_HUBSERVER_NETWORK_PORT),await vd(lt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let g=[],R=[];for(let[z,ne]of p.entries())ne.role.role===Bd.ROLE_TYPES_ENUM.CLUSTER_USER&&ne.active&&(g.push(new B8(ne.username,oU.decrypt(ne.hash))),R.push(new v8(ne.username,oU.decrypt(ne.hash))));let B=[],{hub_routes:H}=lr.getClusteringRoutes();if(!fa.isEmptyOrZeroLength(H))for(let z of H)B.push(`tls://${O.sys_name_encoded}:${O.uri_encoded_d_hash}@${z.host}:${z.port}`);let v=new U8(lr.getConfigFromFile(lt.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,lr.getConfigFromFile(lt.CLUSTERING_HUBSERVER_CLUSTER_NAME),lr.getConfigFromFile(lt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),B,g,R);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=fa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Bd.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Hd.writeJson(o,v),Nu.trace(`Hub server config written to ${o}`));let U=`tls://${O.sys_name_encoded}:${O.uri_encoded_d_hash}@0.0.0.0:${h}`,Y=`tls://${O.uri_encoded_name}:${O.uri_encoded_d_hash}@0.0.0.0:${h}`,W=new P8(lr.getConfigFromFile(lt.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[U],[Y],g,R,u,_,l,d);l==null&&delete W.tls.ca_file,(t===void 0||t===Bd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Hd.writeJson(c,W),Nu.trace(`Leaf server config written to ${c}`))}a(q8,"generateNatsConfig");async function vd(e){let t=yu.get(e);return fa.isEmpty(t)&&xd(`port undefined for '${e}'`),await fa.isPortTaken(t)&&xd(`'${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(vd,"isPortAvailable");function xd(e){let t=`Error generating clustering config: ${e}`;Nu.error(t),console.error(t),process.exit(1)}a(xd,"generateNatsConfigError");async function F8(e){let{port:t,config_file:r}=CT.getServerConfig(e),{username:s,decrypt_hash:n}=await IT.getClusterUser(),i=0,o=2e3;for(;i<aU;){try{let _=await CT.createConnection(t,s,n,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){Nu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=aU)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 fa.async_set_timeout(o*(i*2))}let c="0".repeat(H8),u=_a.join(yu.get(lt.ROOTPATH),da,r);await Hd.writeFile(u,c),await Hd.remove(u),Nu.notify(e,"started.")}a(F8,"removeNatsConfig")});var EU=T(($Ee,fU)=>{"use strict";var Fr=X(),G8=$i(),Se=L(),wu=Fe(),bn=require("path"),{PACKAGE_ROOT:Fd}=L(),uU=X(),qd=J(),Ea="/dev/null",k8=bn.join(Fd,"launchServiceScripts"),lU=bn.join(Fd,"utility/scripts"),V8=bn.join(lU,Se.HDB_RESTART_SCRIPT),_U=bn.resolve(Fd,"dependencies",`${process.platform}-${process.arch}`,wu.NATS_BINARY_NAME);function dU(){let t=G8.licenseSearch().ram_allocation||Se.RAM_ALLOCATION_ENUM.DEFAULT,r=Se.MEM_SETTING_KEY+t,s={[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return qd.noBootFile()&&(s[Se.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=qd.getEnvCliRootPath()),{name:Se.PROCESS_DESCRIPTORS.HDB,script:Se.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:Fd}}a(dU,"generateMainServerConfig");var $8=9930;function Y8(){Fr.initSync(!0);let e=Fr.get(Se.CONFIG_PARAMS.ROOTPATH),t=bn.join(e,"clustering",wu.NATS_CONFIG_FILES.HUB_SERVER),r=bn.join(Fr.get(Se.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Se.LOG_NAMES.HDB),s=uU.get(Se.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=wu.LOG_LEVEL_FLAGS[Fr.get(Se.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==$8?"-"+s:""),script:_U,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ea,i.error_file=Ea),i}a(Y8,"generateNatsHubServerConfig");var K8=9940;function W8(){Fr.initSync(!0);let e=Fr.get(Se.CONFIG_PARAMS.ROOTPATH),t=bn.join(e,"clustering",wu.NATS_CONFIG_FILES.LEAF_SERVER),r=bn.join(Fr.get(Se.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Se.LOG_NAMES.HDB),s=uU.get(Se.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=wu.LOG_LEVEL_FLAGS[Fr.get(Se.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==K8?"-"+s:""),script:_U,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ea,i.error_file=Ea),i}a(W8,"generateNatsLeafServerConfig");function Q8(){Fr.initSync();let e=bn.join(Fr.get(Se.CONFIG_PARAMS.LOGGING_ROOT),Se.LOG_NAMES.HDB),t={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Se.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:k8,autorestart:!1};return Fr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Ea,t.error_file=Ea),t}a(Q8,"generateClusteringUpgradeV4ServiceConfig");function z8(){let e={[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.RESTART_HDB};return qd.noBootFile()&&(e[Se.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=qd.getEnvCliRootPath()),{...{name:Se.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:lU},script:V8}}a(z8,"generateRestart");function J8(){return{apps:[dU()]}}a(J8,"generateAllServiceConfigs");fU.exports={generateAllServiceConfigs:J8,generateMainServerConfig:dU,generateRestart:z8,generateNatsHubServerConfig:Y8,generateNatsLeafServerConfig:W8,generateClusteringUpgradeV4ServiceConfig:Q8}});var IU=T((WEe,wU)=>{"use strict";var Le=L(),j8=J(),Nn=DT(),Iu=rt(),Zs=Fe(),fi=EU(),Gd=X(),Ei=V(),X8=ns(),{startWorker:hU,onMessageFromWorkers:Z8}=$e(),e6=la(),KEe=require("util"),t6=require("child_process"),r6=require("fs"),{execFile:s6}=t6,we;wU.exports={enterPM2Mode:n6,start:hi,stop:LT,reload:pU,restart:SU,list:MT,describe:gU,connect:yn,kill:u6,startAllServices:l6,startService:UT,getUniqueServicesList:RU,restartAllServices:_6,isServiceRegistered:AU,reloadStopStart:OU,restartHdb:TU,deleteProcess:a6,startClusteringProcesses:NU,startClusteringThreads:yU,isHdbRestartRunning:c6,isClusteringRunning:f6,stopClustering:d6,reloadClustering:E6};var Cu=!1;Z8(e=>{e.type==="restart"&&Gd.initSync(!0)});function n6(){Cu=!0}a(n6,"enterPM2Mode");function yn(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,s)=>{Ei.setupConsoleLogging(),r&&t(r),e(s)})})}a(yn,"connect");var _r,i6=10,mU;function hi(e,t=!1){if(Cu)return o6(e);let r=s6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=_r.indexOf(r);o>-1&&_r.splice(o,1),!mU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<i6&&(r6.existsSync(Nn.getHubConfigPath())?hi(e):(await Nn.generateNatsConfig(!0),hi(e),await new Promise(c=>setTimeout(c,3e3)),await Nn.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Nn.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=Gd.get(Le.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Zs.LOG_LEVEL_HIERARCHY[o]>=Zs.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Zs.LOG_LEVELS.ERR||l===Zs.LOG_LEVELS.WRN?Ei.OUTPUTS.STDERR:Ei.OUTPUTS.STDOUT;Ei.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Zs.LOG_LEVELS[f]}if(Zs.LOG_LEVEL_HIERARCHY[o]>=Zs.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Zs.LOG_LEVELS.ERR||l===Zs.LOG_LEVELS.WRN?Ei.OUTPUTS.STDERR:Ei.OUTPUTS.STDOUT;Ei.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),_r=[],!_r&&!t){let i=a(()=>{mU=!0,_r&&(_r.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)}_r.push(r)}a(hi,"start");function o6(e){return new Promise(async(t,r)=>{try{await yn()}catch(s){r(s)}we.start(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(o6,"startWithPM2");function LT(e){if(!Cu){for(let t of _r||[])t.name===e&&(_r.splice(_r.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await yn()}catch(s){r(s)}we.stop(e,async(s,n)=>{s&&(we.disconnect(),r(s)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(s)),we.disconnect(),t(o)})})})}a(LT,"stop");function pU(e){return new Promise(async(t,r)=>{try{await yn()}catch(s){r(s)}we.reload(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(pU,"reload");function SU(e){if(!Cu)for(let t of _r||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await yn()}catch(s){r(s)}we.restart(e,(s,n)=>{we.disconnect(),t(n)})})}a(SU,"restart");function a6(e){return new Promise(async(t,r)=>{try{await yn()}catch(s){r(s)}we.delete(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(a6,"deleteProcess");async function TU(){await hi(fi.generateRestart())}a(TU,"restartHdb");async function c6(){let e=await MT();for(let t in e)if(e[t].name===Le.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(c6,"isHdbRestartRunning");function MT(){return new Promise(async(e,t)=>{try{await yn()}catch(r){t(r)}we.list((r,s)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(s)})})}a(MT,"list");function gU(e){return new Promise(async(t,r)=>{try{await yn()}catch(s){r(s)}we.describe(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(gU,"describe");function u6(){if(!Cu){for(let e of _r||[])e.kill();_r=[];return}return new Promise(async(e,t)=>{try{await yn()}catch(r){t(r)}we.killDaemon((r,s)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(s)})})}a(u6,"kill");async function l6(){try{await NU(),await yU(),await hi(fi.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(l6,"startAllServices");async function UT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Le.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=fi.generateMainServerConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=fi.generateNatsIngestServiceConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=fi.generateNatsReplyServiceConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=fi.generateNatsHubServerConfig(),await hi(r,t),await Nn.removeNatsConfig(e);return;case Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=fi.generateNatsLeafServerConfig(),await hi(r,t),await Nn.removeNatsConfig(e);return;case Le.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=fi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await hi(r)}catch(r){throw we?.disconnect(),r}}a(UT,"startService");async function RU(){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 we?.disconnect(),e}}a(RU,"getUniqueServicesList");async function _6(e=[]){try{let t=!1,r=await RU();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Le.PROCESS_DESCRIPTORS.HDB?t=!0:await SU(o))}t&&await OU(Le.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(_6,"restartAllServices");async function AU(e){if(_r?.find(r=>r.name===e))return!0;let t=await e6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(AU,"isServiceRegistered");async function OU(e){let t=e===Le.PROCESS_DESCRIPTORS.HDB?Gd.get(Le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):Gd.get(Le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await gU(e),s=j8.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await LT(e),await UT(e)):e===Le.PROCESS_DESCRIPTORS.HDB?await TU():await pU(e)}a(OU,"reloadStopStart");var bU;async function NU(e=!1){for(let t in Le.CLUSTERING_PROCESSES){let r=Le.CLUSTERING_PROCESSES[t];await UT(r,e)}}a(NU,"startClusteringProcesses");async function yU(){bU=hU(Le.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Le.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Iu.createWorkQueueStream(Zs.WORK_QUEUE_CONSUMER_NAMES),await Iu.updateIngestStreamConsumer(),await Iu.updateLocalStreams();let e=await X8.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Le.PRE_4_0_0_VERSION){Ei.info("Starting clustering upgrade 4.0.0 process"),hU(Le.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(yU,"startClusteringThreads");async function d6(){for(let e in Le.CLUSTERING_PROCESSES)if(e!==Le.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Le.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await bU.terminate();else{let t=Le.CLUSTERING_PROCESSES[e];await LT(t)}}a(d6,"stopClustering");async function f6(){for(let e in Le.CLUSTERING_PROCESSES){let t=Le.CLUSTERING_PROCESSES[e];if(await AU(t)===!1)return!1}return!0}a(f6,"isClusteringRunning");async function E6(){await Nn.generateNatsConfig(!0),await Iu.reloadNATSHub(),await Iu.reloadNATSLeaf(),await Nn.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Nn.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(E6,"reloadClustering")});var Yd=T((zEe,vU)=>{"use strict";var h6=require("minimist"),{isMainThread:BT,parentPort:LU}=require("worker_threads"),st=L(),{PROCESS_DESCRIPTORS_VALIDATE:Du}=st,en=V(),HT=J(),kd=DT(),ha=rt(),PT=Fe(),MU=Mr(),tn=IU(),CU=la(),m6=lh(),{restartWorkers:Vd,onMessageByType:p6}=$e(),{handleHDBError:S6,hdb_errors:T6}=ee(),{HTTP_STATUS_CODES:g6}=T6,$d=X();$d.initSync();var Lu=`Restarting HarperDB. This may take up to ${st.RESTART_TIMEOUT_MS/1e3} seconds.`,R6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",DU="Clustering is not enabled so cannot be restarted",A6="Invalid service",ma,is;vU.exports={restart:UU,restartService:xT};BT&&p6(st.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?xT({service:e.workerType}):UU({operation:"restart"})});async function UU(e){is=Object.keys(e).length===0,ma=await tn.isServiceRegistered(st.HDB_PROC_DESCRIPTOR);let t=h6(process.argv);if(t.service){await xT(t);return}if(is&&!ma){console.error(R6);return}if(is&&console.log(Lu),ma){tn.enterPM2Mode(),en.notify(Lu);let r=m6(Object.keys(st.CONFIG_PARAM_MAP),!0);return HT.isEmptyOrZeroLength(Object.keys(r))||MU.updateConfigValue(void 0,void 0,r,!0,!0),b6(),Lu}return BT?(en.notify(Lu),setTimeout(()=>{Vd()},50)):LU.postMessage({type:st.ITC_EVENT_TYPES.RESTART}),Lu}a(UU,"restart");async function xT(e){let{service:t}=e;if(st.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw S6(new Error,A6,g6.BAD_REQUEST,void 0,void 0,!0);if(ma=await tn.isServiceRegistered(st.HDB_PROC_DESCRIPTOR),!BT)return LU.postMessage({type:st.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Du.clustering:if(!$d.get(st.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=DU;break}is&&console.log("Restarting clustering"),en.notify("Restarting clustering"),await PU();break;case Du.clustering_config:case Du["clustering config"]:if(!$d.get(st.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=DU;break}is&&console.log("Restarting clustering_config"),en.notify("Restarting clustering_config"),await tn.reloadClustering();break;case"custom_functions":case"custom functions":case Du.harperdb:case Du.http_workers:if(is&&!ma){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}is&&console.log("Restarting http_workers"),en.notify("Restarting http_workers"),is?await tn.restart(st.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Vd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(en.error(r),is&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(xT,"restartService");async function O6(){await ha.publishToStream(`${PT.SUBJECT_PREFIXES.TXN}.${PT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,PT.WORK_QUEUE_CONSUMER_NAMES.stream_name,ha.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(O6,"postDummyNatsMsg");async function b6(){await PU(),await tn.restart(st.HDB_PROC_DESCRIPTOR),await HT.async_set_timeout(2e3),$d.get(st.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await vT(),is&&(await ha.closeConnection(),process.exit(0))}a(b6,"restartPM2Mode");async function PU(){if(!MU.getConfigFromFile(st.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await CU.getHDBProcessInfo()).clustering.length===0)en.trace("Clustering not running, restart will start clustering services"),await kd.generateNatsConfig(!0),await tn.startClusteringProcesses(),await tn.startClusteringThreads(),await vT(),is&&await ha.closeConnection();else{await O6(),await kd.generateNatsConfig(!0),ma?(en.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await tn.restart(st.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await tn.restart(st.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await CU.getHDBProcessInfo()).clustering.forEach(n=>{en.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await HT.async_set_timeout(3e3),await vT(),await ha.updateLocalStreams(),is&&await ha.closeConnection(),en.trace("Restart clustering restarting ingest and reply service threads");let t=Vd(st.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Vd(st.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(PU,"restartClustering");async function vT(){await kd.removeNatsConfig(st.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await kd.removeNatsConfig(st.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(vT,"removeNatsConfig")});var KU=T((XEe,YU)=>{"use strict";var jEe=require("lodash"),dr=L(),{handleHDBError:BU,hdb_errors:N6}=ee(),{HDB_ERROR_MSGS:y6,HTTP_STATUS_CODES:w6}=N6,qT=V();YU.exports={getRolePermissions:C6};var uo=Object.create(null),I6=a(e=>({key:e,perms:{}}),"perms_template_obj"),FU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),GU=a((e=!1,t=!1,r=!1,s=!1)=>({[dr.PERMS_CRUD_ENUM.READ]:e,[dr.PERMS_CRUD_ENUM.INSERT]:t,[dr.PERMS_CRUD_ENUM.UPDATE]:r,[dr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),FT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...GU(t,r,s,n)}),"table_perms_template"),HU=a((e,t=GU())=>({attribute_name:e,describe:$U(t),[Mu]:t[Mu],[GT]:t[GT],[kT]:t[kT]}),"attr_perms_template"),xU=a((e,t=!1)=>({attribute_name:e,describe:t,[Mu]:t}),"timestamp_attr_perms_template"),{READ:Mu,INSERT:GT,UPDATE:kT}=dr.PERMS_CRUD_ENUM,kU=Object.values(dr.PERMS_CRUD_ENUM),VU=[Mu,GT,kT];function C6(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[dr.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(uo[t]&&uo[t].key===s)return uo[t].perms;let n=D6(e,r);return uo[t]?uo[t].key=s:uo[t]=I6(s),uo[t].perms=n,n}catch(r){if(!e[dr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[dr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<dr.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 qT.error(s),qT.debug(r),BU(new Error,y6.OUTDATED_PERMS_TRANSLATION_ERROR,w6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
-
${r.stack}`;throw qT.error(s),BU(new Error)}}}a(C6,"getRolePermissions");function D6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[dr.SYSTEM_SCHEMA_NAME]=s[dr.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]=L6(t[i]);return}r[i]=FU(),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],_=M6(c,u);r[i].describe||kU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=FT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=FT()})}),r}a(D6,"translateRolePermissions");function L6(e){let t=FU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=FT(!0,!0,!0,!0,!0)}),t}a(L6,"createStructureUserPermissions");function M6(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 dr.TIME_STAMP_NAMES.includes(d)&&(f=xU(d,l[Mu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=HU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=$U(l),n.attribute_permissions.push(l),c||U6(l,u)}else if(_!==o){let l;dr.TIME_STAMP_NAMES.includes(_)?l=xU(_):l=HU(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=qU(n),n}else return e.describe=qU(e),e}a(M6,"getTableAttrPerms");function qU(e){return kU.filter(t=>e[t]).length>0}a(qU,"getSchemaTableDescribePerm");function $U(e){return VU.filter(t=>e[t]).length>0}a($U,"getAttributeDescribePerm");function U6(e,t){VU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(U6,"checkForHashPerms")});var WU={};Ve(WU,{Resources:()=>Kd,keyArrayToString:()=>pa,resetResources:()=>P6,resources:()=>mi});function P6(){return mi=new Kd}function pa(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Kd,mi,Uu=Oe(()=>{Ji();Kd=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 ze(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(P6,"resetResources");a(pa,"keyArrayToString")});var QU={};Ve(QU,{Headers:()=>pi});var pi,Wd=Oe(()=>{pi=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];s?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var Pu={};Ve(Pu,{authentication:()=>rP,bypassAuth:()=>G6,login:()=>V6,logout:()=>$6,start:()=>k6});function G6(){tP=!0}async function rP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?x6?H6:[]:B6?v6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new pi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Qd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Qd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Qd){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 JU.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Jd.AuthAuditLog(E,h,xt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===xt.AUTH_AUDIT_STATUS.SUCCESS?zU.notify(S):zU.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 et.getUser(E,null,null))}let d;if(!e.user)if(s){if(d=lo.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await et.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,zd.validateOperationToken)(h)}catch(O){if(O.message==="invalid token")try{return await(0,zd.validateRefreshToken)(h),c({status:-1})}catch{throw O}}break}}catch(O){return F6&&(lo.get(h)||(lo.set(h,h),l(p,xt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Si({error:O.message},e)})}lo.set(s,d),q6&&l(d.username,xt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await et.getUser(_.user,null,e):(tP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,XU.getSuperUser)());Qd&&(e.session.update=function(E){if(!u){u=(0,ZU.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):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,JU.put(E)},e.login=async function(E,h){e.user=await et.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")&&mi.loginPath?(f.status=302,f.headers.set("Location",mi.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 pi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function k6({server:e,port:t}){e.request(rP,{port:t||"all"}),jU||(jU=!0,setInterval(()=>{lo=new Map},os.get(xt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),eP.user.addListener(()=>{lo=new Map}))}async function V6(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 $6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var XU,zd,ZU,os,xt,Jd,eP,zU,v6,B6,H6,x6,JU,Qd,tP,q6,F6,lo,jU,jd=Oe(()=>{XU=x(es());Xt();Uu();zd=x(Eu());be();ZU=require("uuid"),os=x(X()),xt=x(L()),Jd=x(V()),eP=x(vc());Wd();Sa();zU=(0,Jd.loggerWithTag)("auth-event");os.initSync();v6=os.get(xt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),B6=os.get(xt.CONFIG_PARAMS.HTTP_CORS),H6=os.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),x6=os.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),JU=at({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Qd=os.get(xt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,tP=os.get(xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,q6=os.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,F6=os.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,lo=new Map;et.onInvalidatedUser(()=>{lo=new Map});a(G6,"bypassAuth");a(rP,"authentication");a(k6,"start");a(V6,"login");a($6,"logout")});var uP=T((uhe,cP)=>{"use strict";var Ie=require("joi"),sP=require("fs-extra"),nP=require("path"),In=Qe(),iP=X(),oP=L(),aP=V(),{hdb_errors:Y6}=ee(),{HDB_ERROR_MSGS:Wt}=Y6,wn=/^[a-zA-Z0-9-_]+$/;cP.exports={getDropCustomFunctionValidator:W6,setCustomFunctionValidator:Q6,addComponentValidator:X6,dropCustomFunctionProjectValidator:Z6,packageComponentValidator:e9,deployComponentValidator:t9,setComponentFileValidator:z6,getComponentFileValidator:j6,dropComponentFileValidator:J6};function Xd(e,t,r){try{let s=iP.get(oP.CONFIG_PARAMS.COMPONENTSROOT),n=nP.join(s,t);return sP.existsSync(n)?e?t:r.message(Wt.PROJECT_EXISTS):e?r.message(Wt.NO_PROJECT):t}catch(s){return aP.error(s),r.message(Wt.VALIDATION_ERR)}}a(Xd,"checkProjectExists");function vu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(vu,"checkFilePath");function K6(e,t,r,s){try{let n=iP.get(oP.CONFIG_PARAMS.COMPONENTSROOT),i=nP.join(n,e,t,r+".js");return sP.existsSync(i)?r:s.message(Wt.NO_FILE)}catch(n){return aP.error(n),s.message(Wt.VALIDATION_ERR)}}a(K6,"checkFileExists");function W6(e){let t=Ie.object({project:Ie.string().pattern(wn).custom(Xd.bind(null,!0)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(wn).custom(K6.bind(null,e.project,e.type)).custom(vu).required().messages({"string.pattern.base":Wt.BAD_FILE_NAME})});return In.validateBySchema(e,t)}a(W6,"getDropCustomFunctionValidator");function Q6(e){let t=Ie.object({project:Ie.string().pattern(wn).custom(Xd.bind(null,!0)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(vu).required(),function_content:Ie.string().required()});return In.validateBySchema(e,t)}a(Q6,"setCustomFunctionValidator");function z6(e){let t=Ie.object({project:Ie.string().pattern(wn).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),file:Ie.string().custom(vu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return In.validateBySchema(e,t)}a(z6,"setComponentFileValidator");function J6(e){let t=Ie.object({project:Ie.string().pattern(wn).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),file:Ie.string().custom(vu).optional()});return In.validateBySchema(e,t)}a(J6,"dropComponentFileValidator");function j6(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(vu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return In.validateBySchema(e,t)}a(j6,"getComponentFileValidator");function X6(e){let t=Ie.object({project:Ie.string().pattern(wn).custom(Xd.bind(null,!1)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME})});return In.validateBySchema(e,t)}a(X6,"addComponentValidator");function Z6(e){let t=Ie.object({project:Ie.string().pattern(wn).custom(Xd.bind(null,!0)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME})});return In.validateBySchema(e,t)}a(Z6,"dropCustomFunctionProjectValidator");function e9(e){let t=Ie.object({project:Ie.string().pattern(wn).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return In.validateBySchema(e,t)}a(e9,"packageComponentValidator");function t9(e){let t=Ie.object({project:Ie.string().pattern(wn).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":Wt.BAD_PACKAGE}),package:Ie.string().optional()});return In.validateBySchema(e,t)}a(t9,"deployComponentValidator")});var rf=T((_he,mP)=>{"use strict";var Zd=require("joi"),ef=require("path"),lP=require("fs-extra"),{exec:r9}=require("child_process"),s9=require("util"),_P=s9.promisify(r9),Bu=L(),{handleHDBError:Ta,hdb_errors:n9}=ee(),{HTTP_STATUS_CODES:ga}=n9,Hu=X(),i9=Qe(),Ra=V();Hu.initSync();var VT=Hu.get(Bu.CONFIG_PARAMS.COMPONENTSROOT),dP="npm install --omit=dev --json",o9=`${dP} --dry-run`;mP.exports={installModules:l9,auditModules:_9,installAllRootModules:a9,uninstallRootModule:c9,linkHarperdb:u9};async function a9(e=!1){await tf(),await xu(e?"npm install --ignore-scripts":"npm install",Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(a9,"installAllRootModules");async function c9(e){await xu(`npm uninstall ${e}`,Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(c9,"uninstallRootModule");async function u9(){await tf(),await xu(`npm link ${Bu.PACKAGE_ROOT}`,Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(u9,"linkHarperdb");async function xu(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await _P(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
|
|
12
|
-
`,""))}return s&&!s.includes("Debugger listening")&&
|
|
13
|
-
`,"")}a(
|
|
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 s&&!s.includes("Debugger listening")&&Oa.error("Error running NPM command:",e,s),Oa.trace(r,s),r?.replace(`
|
|
13
|
+
`,"")}a(Gu,"runCommand");async function f9(e){Oa.info(`starting installModules for request: ${e}`);let t=TP(e);if(t)throw Ra(t,t.message,Aa.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?u9:mP;await rf(),await SP(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 _=tf.join(YT,u),l,d=null;try{let{stdout:f,stderr:E}=await hP(n,{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(fP,"parseNPMStdErr");async function _9(e){Ra.info(`starting auditModules for request: ${e}`);let t=hP(e);if(t)throw Ta(t,t.message,ga.BAD_REQUEST);let{projects:r}=e;await tf(),await EP(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=ef.join(VT,o);s[o]={npm_output:null,npm_error:null};try{let u=await xu("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=fP(u.stderr)}}return Ra.info(`finished auditModules with response ${s}`),s}a(_9,"auditModules");async function tf(){try{return await xu("npm -v"),!0}catch{throw Ta(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",ga.BAD_REQUEST,void 0,void 0,!0)}}a(tf,"checkNPMInstalled");async function EP(e){if(!Array.isArray(e)||e.length===0)throw Ta(new Error,"projects argument must be an array with at least 1 element",ga.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=ef.join(VT,i.toString());if(!await lP.pathExists(o)){t.push(i);continue}let u=ef.join(o,"package.json");await lP.pathExists(u)||r.push(i)}if(t.length>0)throw Ta(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,ga.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ta(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,ga.BAD_REQUEST,void 0,void 0,!0)}a(EP,"checkProjectPaths");function hP(e){let t=Zd.object({projects:Zd.array().min(1).items(Zd.string()).required(),dry_run:Zd.boolean().default(!1)});return i9.validateBySchema(e,t)}a(hP,"modulesValidator")});var YT=T((fhe,RP)=>{"use strict";var Aa=require("fs-extra"),$T=require("path"),sf=V(),pP=J(),nf=L(),gP=X(),d9=Mr();RP.exports=f9;async function f9(){let e=E9(),t=gP.get(nf.CONFIG_PARAMS.ROOTPATH),r=$T.join(t,"package.json"),s={dependencies:{harperdb:"file:"+nf.PACKAGE_ROOT}},n=$T.join(t,"node_modules");await Aa.ensureDir(n);let i,o=!0,c=!1;try{i=await Aa.readJson(r)}catch(u){if(pP.isEmptyOrZeroLength(e))return;if(u.code!==nf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!pP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await SP(_);s.dependencies[u]=l+_}if(!o){sf.notify("Installing components"),await TP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await SP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(sf.notify("Removing component",u),c=!0);c&&(sf.notify("Updating components."),await TP(r,s,i))}a(f9,"installComponents");function E9(){let e=d9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(E9,"getComponentsConfig");async function SP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":$T.extname(e)||await Aa.pathExists(e)?"file:":"github:"}a(SP,"getPkgPrefix");async function TP(e,t,r){sf.trace("npm installing components package.json",t),await Aa.writeFile(e,JSON.stringify(t,null," "));try{await rf().installAllRootModules(gP.get(nf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await Aa.writeFile(e,JSON.stringify(r,null," ")):await Aa.unlink(e),s}}a(TP,"installPackages")});var QT=T((mhe,NP)=>{"use strict";var Ge=require("fs-extra"),KT=require("fast-glob"),Re=require("path"),OP=require("tar-fs"),hhe=require("uuid").v4,WT=require("normalize-path"),rn=uP(),Ot=V(),Ke=L(),ht=X(),qu=Mr(),h9=J(),{PACKAGE_ROOT:m9}=L(),{handleHDBError:Mt,hdb_errors:p9}=ee(),{basename:S9}=require("path"),T9=YT(),bP=X(),g9=L(),{Readable:R9}=require("stream"),{isMainThread:A9}=require("worker_threads"),{HDB_ERROR_MSGS:_o,HTTP_STATUS_CODES:Ut}=p9,O9=Re.join(m9,"application-template"),AP=Re.join(ht.get(Ke.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function b9(){Ot.trace("getting custom api status");let e={};try{e={port:ht.get(Ke.CONFIG_PARAMS.HTTP_PORT),directory:ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Mt(new Error,_o.FUNCTION_STATUS,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,t)}return e}a(b9,"customFunctionsStatus");function N9(){Ot.trace("getting custom api endpoints");let e={},t=ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT);try{KT.sync(WT(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:KT.sync(WT(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:KT.sync(WT(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Mt(new Error,_o.GET_FUNCTIONS,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,r)}return e}a(N9,"getCustomFunctions");function y9(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=rn.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("getting custom api endpoint file content");let r=ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=Re.join(r,s,n,i+".js");try{return Ge.readFileSync(o,{encoding:"utf8"})}catch(c){throw Mt(new Error,_o.GET_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,c)}}a(y9,"getCustomFunction");function w9(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=rn.setCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("setting custom function file content");let r=ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return Ge.outputFileSync(Re.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Mt(new Error,_o.SET_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,c)}}a(w9,"setCustomFunction");function I9(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=rn.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("dropping custom function file");let r=ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return Ge.unlinkSync(Re.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Mt(new Error,_o.DROP_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,o)}}a(I9,"dropCustomFunction");function C9(e){e.project&&(e.project=Re.parse(e.project).name);let t=rn.addComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("adding component");let r=ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=Re.join(r,s);return Ge.mkdirSync(n,{recursive:!0}),Ge.copySync(O9,n),`Successfully added project: ${s}`}catch(n){throw Mt(new Error,_o.ADD_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,n)}}a(C9,"addComponent");function D9(e){e.project&&(e.project=Re.parse(e.project).name);let t=rn.dropCustomFunctionProjectValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("dropping custom function project");let r=ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=ht.get(Ke.CONFIG_PARAMS.APPS);if(!h9.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 qu.updateConfigValue(Ke.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=Re.join(r,s);return Ge.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw Mt(new Error,_o.DROP_FUNCTION_PROJECT,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,i)}}a(D9,"dropCustomFunctionProject");async function L9(e){e.project&&(e.project=Re.parse(e.project).name);let t=rn.packageComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;Ot.trace("packaging component",s);let n;try{n=await Ge.realpath(Re.join(r,s))}catch(u){if(u.code!==Ke.NODE_ERROR_CODES.ENOENT)throw u;try{n=await Ge.realpath(Re.join(ht.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===Ke.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await Ge.ensureDir(AP);let i=Re.join(AP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Re.join(n,"node_modules"))}),OP.pack(n,o).pipe(Ge.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Ge.readFileSync(i,{encoding:"base64"});return await Ge.remove(i),{project:s,payload:c}}a(L9,"packageComponent");async function M9(e){e.project&&(e.project=Re.parse(e.project).name);let t=rn.deployComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=ht.get(Ke.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=Re.join(r,s),i="file:"+o,await Ge.ensureDir(o);let f=R9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(OP.extract(o,{finish:h})).on("error",p)});let E=await Ge.readdir(o);E.length===1&&E[0]==="package"&&(await Ge.copy(Re.join(o,"package"),o),await Ge.remove(Re.join(o,"package")))}if(await qu.addConfig(s,{package:i}),!n){await T9();let f=bP.get(g9.CONFIG_PARAMS.ROOTPATH);o=Re.join(f,"node_modules",s)}if(A9)return;let c=new Map;c.isWorker=!0;let u=(af(),te(of)),_;u.setErrorReporter(f=>_=f);let l=S9(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(M9,"deployComponent");async function U9(){let e=qu.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 Ge.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Re.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await Ge.stat(d),E={name:Re.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(ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{name:ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT).split(Re.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(Re.join(ht.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(af(),te(of)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return s}a(U9,"getComponents");async function P9(e){let t=rn.getComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let s=qu.getConfigObj()[e.project]||e.project==="harperdb"?Re.join(bP.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules"):ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ge.stat(Re.join(s,e.project,e.file));return{message:await Ge.readFile(Re.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Ke.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Re.join(e.project,e.file)}'`):i}}a(P9,"getComponentFile");async function v9(e){let t=rn.setComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=Re.join(ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Ge.ensureFile(s),await Ge.outputFile(s,e.payload,r)):await Ge.ensureDir(s),"Successfully set component: "+e.file}a(v9,"setComponentFile");async function B9(e){let t=rn.dropComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=e.file?Re.join(e.project,e.file):e.project,s=Re.join(ht.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ge.pathExists(s)&&await Ge.remove(s),qu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(B9,"dropComponent");NP.exports={customFunctionsStatus:b9,getCustomFunctions:N9,getCustomFunction:y9,setCustomFunction:w9,dropCustomFunction:I9,addComponent:C9,dropCustomFunctionProject:D9,packageComponent:L9,deployComponent:M9,getComponents:U9,getComponentFile:P9,setComponentFile:v9,dropComponent:B9}});var zT=T((She,wP)=>{"use strict";var sn=require("joi"),yP=Qe();wP.exports={readTransactionLogValidator:H9,deleteTransactionLogsBeforeValidator:x9};function H9(e){let t=sn.object({schema:sn.string().required(),table:sn.string().required(),from:sn.date().timestamp(),to:sn.date().timestamp(),limit:sn.number().min(1)});return yP.validateBySchema(e,t)}a(H9,"readTransactionLogValidator");function x9(e){let t=sn.object({schema:sn.string().required(),table:sn.string().required(),timestamp:sn.date().timestamp().required()});return yP.validateBySchema(e,t)}a(x9,"deleteTransactionLogsBeforeValidator")});var uf=T((ghe,MP)=>{"use strict";var JT=L(),cf=rt(),IP=J(),CP=X(),DP=pn(),{handleHDBError:Oa,hdb_errors:q9}=ee(),{HTTP_STATUS_CODES:ba}=q9,{readTransactionLogValidator:F9,deleteTransactionLogsBeforeValidator:G9}=zT(),LP="This operation relies on clustering and cannot run with it disable.",k9="Logs successfully deleted from transaction log.",V9="All logs successfully deleted from transaction log.";MP.exports={readTransactionLog:$9,deleteTransactionLogsBefore:Y9};async function*$9(e){let t=F9(e);if(t)throw Oa(t,t.message,ba.BAD_REQUEST,void 0,void 0,!0);if(!CP.get(JT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Oa(new Error,LP,ba.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=IP.checkSchemaTableExist(r,s);if(n)throw Oa(new Error,n,ba.NOT_FOUND,void 0,void 0,!0);let i=DP.createNatsTableStreamName(r,s),o=await cf.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===JT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a($9,"readTransactionLog");async function Y9(e){let t=G9(e);if(t)throw Oa(t,t.message,ba.BAD_REQUEST,void 0,void 0,!0);if(!CP.get(JT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Oa(new Error,LP,ba.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=IP.checkSchemaTableExist(r,s);if(i)throw Oa(new Error,i,ba.NOT_FOUND,void 0,void 0,!0);let o=DP.createNatsTableStreamName(r,s),{jsm:c}=await cf.getNATSReferences(),u=await cf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=k9,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=V9):d=(await cf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(Y9,"deleteTransactionLogsBefore")});var PP=T((Ahe,UP)=>{"use strict";var jT=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}};UP.exports=jT});var BP=T((bhe,vP)=>{"use strict";var XT=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};vP.exports=XT});var eg=T((yhe,xP)=>{"use strict";var HP=PP(),K9=BP(),{HDB_ERROR_MSGS:W9}=br(),ZT=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=W9.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 HP(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new K9(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 HP(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}};xP.exports=ZT});var ff=T((Ihe,ev)=>{"use strict";var tg=Ir(),lf=Zr(),cs=cu(),ku=jn(),rg=ei(),Q9=hS(),z9=zD(),Vu=es(),_f=bS(),bt=V(),J9=wS(),j9=yd(),X9=cT(),Z9=Id(),e7=uT(),t7=lT(),r7=fT(),s7=hT(),sg=ST(),Cn=J(),n7=KM(),ng=OT(),GP=Yd(),as=L(),kP=KU(),i7=la(),VP=Eu(),$P=(jd(),te(Pu)),YP=Mr(),Gr=QT(),o7=require("alasql"),KP=uf(),WP=rf(),QP=eg(),{handleHDBError:fr,hdb_errors:zP}=ee(),{HDB_ERROR_MSGS:qt,HTTP_STATUS_CODES:Fu}=zP,k=new Map,JP="delete",Ti="insert",Dn="read",fo="update",Gu="describe",qP=ku.describeSchema.name,FP=ku.describeTable.name,jP={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},a7="catchup",c7="handleGetJob",u7="handleGetJobsByStartDate",df={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},l7=[cs.createTable.name,cs.createAttribute.name,cs.dropTable.name,cs.dropAttribute.name],XP={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(tg.insert.name,new Q(!1,[Ti]));k.set(tg.update.name,new Q(!1,[fo]));k.set(tg.upsert.name,new Q(!1,[Ti,fo]));k.set(lf.searchByConditions.name,new Q(!1,[Dn]));k.set(lf.searchByHash.name,new Q(!1,[Dn]));k.set(lf.searchByValue.name,new Q(!1,[Dn]));k.set(lf.search.name,new Q(!1,[Dn]));k.set(cs.createSchema.name,new Q(!0,[]));k.set(cs.createTable.name,new Q(!0,[]));k.set(cs.createAttribute.name,new Q(!1,[Ti]));k.set(cs.dropSchema.name,new Q(!0,[]));k.set(cs.dropTable.name,new Q(!0,[]));k.set(cs.dropAttribute.name,new Q(!0,[]));k.set(ku.describeSchema.name,new Q(!1,[Dn]));k.set(ku.describeTable.name,new Q(!1,[Dn]));k.set(rg.deleteRecord.name,new Q(!1,[JP]));k.set(Vu.addUser.name,new Q(!0,[]));k.set(Vu.alterUser.name,new Q(!0,[]));k.set(Vu.dropUser.name,new Q(!0,[]));k.set(Vu.listUsersExternal.name,new Q(!0,[]));k.set(_f.listRoles.name,new Q(!0,[]));k.set(_f.addRole.name,new Q(!0,[]));k.set(_f.alterRole.name,new Q(!0,[]));k.set(_f.dropRole.name,new Q(!0,[]));k.set(J9.name,new Q(!0,[]));k.set(j9.name,new Q(!0,[]));k.set(X9.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(sg.setRoutes.name,new Q(!0,[]));k.set(sg.getRoutes.name,new Q(!0,[]));k.set(sg.deleteRoutes.name,new Q(!0,[]));k.set(YP.setConfiguration.name,new Q(!0,[]));k.set(r7.clusterStatus.name,new Q(!0,[]));k.set(s7.name,new Q(!0,[]));k.set(ng.getFingerprint.name,new Q(!0,[]));k.set(ng.setLicense.name,new Q(!0,[]));k.set(rg.deleteFilesBefore.name,new Q(!0,[]));k.set(rg.deleteAuditLogsBefore.name,new Q(!0,[]));k.set(GP.restart.name,new Q(!0,[]));k.set(GP.restartService.name,new Q(!0,[]));k.set(Q9.name,new Q(!0,[]));k.set(z9.name,new Q(!0,[Dn]));k.set(i7.systemInformation.name,new Q(!0,[]));k.set(YP.getConfiguration.name,new Q(!0,[]));k.set(KP.readTransactionLog.name,new Q(!0,[]));k.set(KP.deleteTransactionLogsBefore.name,new Q(!0,[]));k.set(WP.installModules.name,new Q(!0,[]));k.set(WP.auditModules.name,new Q(!0,[]));k.set(VP.createTokens.name,new Q(!1,[]));k.set(VP.refreshOperationToken.name,new Q(!1,[]));k.set($P.login.name,new Q(!1,[]));k.set($P.logout.name,new Q(!1,[]));k.set(Gr.customFunctionsStatus.name,new Q(!0,[]));k.set(Gr.getCustomFunctions.name,new Q(!0,[]));k.set(Gr.getComponents.name,new Q(!0,[]));k.set(Gr.getComponentFile.name,new Q(!0,[]));k.set(Gr.setComponentFile.name,new Q(!0,[]));k.set(Gr.dropComponent.name,new Q(!0,[]));k.set(Gr.getCustomFunction.name,new Q(!0,[]));k.set(Gr.setCustomFunction.name,new Q(!0,[]));k.set(Gr.dropCustomFunction.name,new Q(!0,[]));k.set(Gr.addComponent.name,new Q(!0,[]));k.set(Gr.dropCustomFunctionProject.name,new Q(!0,[]));k.set(Gr.packageComponent.name,new Q(!0,[]));k.set(Gr.deployComponent.name,new Q(!0,[]));k.set(ng.getRegistrationInfo.name,new Q(!1,[]));k.set(Vu.userInfo.name,new Q(!1,[]));k.set(ku.describeAll.name,new Q(!1,[]));k.set(c7,new Q(!1,[]));k.set(u7,new Q(!0,[]));k.set(a7,new Q(!0,[]));k.set(df.CSV_DATA_LOAD,new Q(!1,[Ti,fo]));k.set(df.CSV_URL_LOAD,new Q(!1,[Ti,fo]));k.set(df.CSV_FILE_LOAD,new Q(!1,[Ti,fo]));k.set(df.IMPORT_FROM_S3,new Q(!1,[Ti,fo]));k.set(XP.EXPORT_TO_S3,new Q(!0,[]));k.set(XP.EXPORT_LOCAL,new Q(!0,[]));k.set(as.VALID_SQL_OPS_ENUM.DELETE,new Q(!1,[JP]));k.set(as.VALID_SQL_OPS_ENUM.SELECT,new Q(!1,[Dn]));k.set(as.VALID_SQL_OPS_ENUM.INSERT,new Q(!1,[Ti]));k.set(as.VALID_SQL_OPS_ENUM.UPDATE,new Q(!1,[fo]));ev.exports={verifyPerms:d7,verifyPermsAst:_7,verifyBulkLoadAttributePerms:E7};function _7(e,t,r){if(Cn.isEmptyOrZeroLength(e))throw bt.info("verify_perms_ast has an empty user parameter"),fr(new Error);if(Cn.isEmptyOrZeroLength(t))throw bt.info("verify_perms_ast has an empty user parameter"),fr(new Error);if(Cn.isEmptyOrZeroLength(r))throw bt.info("verify_perms_ast has a null operation parameter"),fr(new Error);try{let s=new QP,n=new n7(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."),fr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&jP[r])throw fr(new Error,qt.DROP_SYSTEM,Fu.FORBIDDEN);if(c&&!u)return null;let _=kP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof o7.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=ZP(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=og(t.role.permission,f,d[E]);ig(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw fr(s)}}a(_7,"verifyPermsAst");function d7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw bt.info("null required parameter in verifyPerms"),fr(new Error,qt.DEFAULT_INVALID_REQUEST,Fu.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 QP;if(Cn.isEmptyOrZeroLength(e.hdb_user.role)||Cn.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(qt.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(as.SYSTEM_SCHEMA_NAME)||n===as.SYSTEM_SCHEMA_NAME;if(l&&jP[r])throw fr(new Error,qt.DROP_SYSTEM,Fu.FORBIDDEN);if(u&&!l||_===!0&&(r===cs.createSchema.name||r===cs.dropSchema.name))return null;if(l7.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===qP||r===FP){if(n===as.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(qt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===qP&&(!d[n]||!d[n][Gu]))return c.handleInvalidItem(qt.SCHEMA_NOT_FOUND(n));if(r===FP&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][Gu]))return c.handleInvalidItem(qt.TABLE_NOT_FOUND(n,i))}}let f=ZP(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&&as.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[as.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(g=>g[as.PERMS_CRUD_ENUM.READ]).forEach(g=>{p.push(g.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(O=>O.attribute),e.get_attributes=p)}let E=f7(e),h=og(e.hdb_user.role.permission,n,i);return ig(E,h,r,i,n,c,s),c.getPermsResponse()}a(d7,"verifyPerms");function ZP(e,t,r,s,n){if(Cn.arrayHasEmptyValues([e,t,r]))throw bt.info("hasPermissions has an invalid parameter"),fr(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.`),fr(new Error,qt.OP_NOT_FOUND(t),Fu.BAD_REQUEST);if(k.get(t)&&k.get(t).requires_su)return bt.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(qt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Gu]===!1){s.addInvalidItem(qt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(qt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[Gu]===!1)s.addInvalidItem(qt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=k.get(t).perms;!Cn.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=qt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw bt.error(E),bt.error(f),fr(zP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(ZP,"hasPermissions");function ig(e,t,r,s,n,i,o){if(!e||!t)throw bt.info("no attributes specified in checkAttributePerms."),fr(new Error);let c=k.get(r).perms;if(!c||c==="")throw bt.info(`no permissions found for ${r} in checkAttributePerms().`),fr(new Error);if(Cn.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[Gu]===!1){i.addInvalidItem(qt.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(as.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Dn)throw fr(new Error,qt.SYSTEM_TIMESTAMP_PERMS_ERR,Fu.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(qt.ATTR_NOT_FOUND(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(ig,"checkAttributePerms");function f7(e){let t=new Set;try{if(e.action)return t;if(e.operation===as.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(f7,"getRecordAttributes");function og(e,t,r){let s=new Map;if(Cn.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(og,"getAttributePermissions");function E7(e,t,r,s,n,i,o){let c=new Set(i),u=og(e,s,n);ig(c,u,t,n,s,o,r)}a(E7,"verifyBulkLoadAttributePerms")});var hf=T((Dhe,iv)=>{"use strict";iv.exports={evaluateSQL:w7,processAST:nv,convertSQLToAST:sv,checkASTPermissions:rv};var h7=Ir(),tv=require("util"),m7=tv.callbackify(h7.insert),p7=Zr().search,S7=GC().update,T7=tv.callbackify(S7),g7=VC().convertDelete,gi=require("alasql"),R7=ff(),Ef=V(),A7=J_(),O7=J(),$u=L(),{hdb_errors:b7,handleHDBError:ag}=ee(),{HTTP_STATUS_CODES:cg}=b7;A7(gi);var N7=403,y7="There was a problem performing this insert. Please check the logs and try again.",ug=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function w7(e,t){let r=e.parsed_sql_object;if(!r){r=sv(e.sql);let s,n=r.ast.statements[0];if(n instanceof gi.yy.Insert?s=n.into.databaseid:n instanceof gi.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof gi.yy.Update||n instanceof gi.yy.Delete?s=n.table.databaseid:Ef.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof gi.yy.Select)&&O7.isEmptyOrZeroLength(s))return t("No schema specified",null)}nv(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(w7,"evaluateSQL");function rv(e,t){let r;try{r=R7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(rv,"checkASTPermissions");function sv(e){let t=new ug;if(!e)throw ag(new Error,"The 'sql' parameter is missing from the request body",cg.BAD_REQUEST);try{let r=e.trim(),s=gi.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
17
|
-
`);throw s[1]?ag(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,cg.BAD_REQUEST):ag(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",cg.BAD_REQUEST)}return t}a(sv,"convertSQLToAST");function nv(e,t,r){try{let s=I7;if(!e.bypass_auth&&!t.permissions_checked){let i=rv(e,t);if(i&&i.length>0)return r(N7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case $u.VALID_SQL_OPS_ENUM.SELECT:s=p7,n=t.ast.statements[0];break;case $u.VALID_SQL_OPS_ENUM.INSERT:s=C7;break;case $u.VALID_SQL_OPS_ENUM.UPDATE:s=T7;break;case $u.VALID_SQL_OPS_ENUM.DELETE:s=g7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(nv,"processAST");function I7(e,t){Ef.info(e),t("unknown sql statement")}a(I7,"nullFunction");function C7({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=D7(i,e.values)}catch(o){return r(o)}m7(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Ef.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(C7,"convertInsert");function D7(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]]=gi.compile(`SELECT ${n.toString()} AS [${$u.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw Ef.error(r),new Error(y7)}}a(D7,"createDataObjects")});var lg=T((Mhe,av)=>{"use strict";var{S3:L7,GetObjectCommand:M7}=require("@aws-sdk/client-s3");av.exports={getFileStreamFromS3:U7,getS3AuthObj:ov};async function U7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await ov(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new M7(r))).Body}a(U7,"getFileStreamFromS3");function ov(e,t,r){return new L7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(ov,"getS3AuthObj")});var mf=T((Phe,mv)=>{"use strict";var dg=Zr(),P7=hf(),v7=lg(),{AsyncParser:B7,Transform:H7}=require("json2csv"),Ku=require("stream"),kr=J(),_g=require("fs-extra"),x7=require("path"),us=V(),{promisify:lv}=require("util"),Yu=J(),{handleHDBError:mt,hdb_errors:q7}=ee(),{HDB_ERROR_MSGS:Er,HTTP_STATUS_CODES:pt}=q7,{streamAsJSON:F7}=(Lh(),te(ob)),{Upload:G7}=require("@aws-sdk/lib-storage"),cv=["search_by_value","search_by_hash","sql","search_by_conditions"],uv=["json","csv"],_v="json",dv="csv",k7="Successfully exported JSON locally.",V7="Successfully exported CSV locally.",$7=1e3,Y7=dg.searchByHash,K7=dg.searchByValue,W7=lv(P7.evaluateSQL),Q7=lv(Ku.finished);mv.exports={export_to_s3:X7,export_local:z7,toCsvStream:fv};async function z7(e){us.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=Ev(e);if(!kr.isEmpty(t))throw us.error(t),mt(new Error,t,pt.BAD_REQUEST,void 0,void 0,!0);if(kr.isEmpty(e.path))throw us.error(Er.MISSING_VALUE("path")),mt(new Error,Er.MISSING_VALUE("path"),pt.BAD_REQUEST,void 0,void 0,!0);let r=(kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(x7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=kr.buildFolderPath(e.path,r);await J7(e.path);let n=await hv(e);return await j7(s,e.format,n)}a(z7,"export_local");async function J7(e){if(us.trace("in confirmPath"),kr.isEmptyOrZeroLength(e))throw mt(new Error,`Invalid path: ${e}`,pt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await _g.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,us.error(s),mt(new Error,s,pt.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 us.error(r),mt(new Error,r,pt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(J7,"confirmPath");async function j7(e,t,r){if(us.trace("in saveToLocal"),Yu.isEmptyOrZeroLength(e))throw mt(new Error,Er.INVALID_VALUE("file_path"),pt.BAD_REQUEST,void 0,void 0,!0);if(Yu.isEmptyOrZeroLength(t))throw mt(new Error,Er.INVALID_VALUE("Source format"),pt.BAD_REQUEST,void 0,void 0,!0);if(Yu.isEmpty(r))throw mt(new Error,Er.NOT_FOUND("Data"),pt.BAD_REQUEST,void 0,void 0,!0);if(t===_v){let s=_g.createWriteStream(e);return F7(r).pipe(s),await Q7(s),{message:k7,path:e}}else if(t===dv){let s=_g.createWriteStream(e),n=Ku.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new B7(i,c).fromInput(n).toOutput(s).promise(!1),{message:V7,path:e}}throw mt(new Error,Er.INVALID_VALUE("format"),pt.BAD_REQUEST)}a(j7,"saveToLocal");async function X7(e){if(!e.s3||Object.keys(e.s3).length===0)throw mt(new Error,Er.MISSING_VALUE("S3 object"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw mt(new Error,Er.MISSING_VALUE("aws_access_key_id"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw mt(new Error,Er.MISSING_VALUE("aws_secret_access_key"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.bucket))throw mt(new Error,Er.MISSING_VALUE("bucket"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.key))throw mt(new Error,Er.MISSING_VALUE("key"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.region))throw mt(new Error,Er.MISSING_VALUE("region"),pt.BAD_REQUEST);let t=Ev(e);if(!kr.isEmpty(t))throw mt(new Error,t,pt.BAD_REQUEST);us.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await hv(e)}catch(u){throw us.error(u),u}let s,n=await v7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Ku.PassThrough;if(e.format===dv){i=e.s3.key+".csv";let u=fv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===_v){i=e.s3.key+".json";let u=new Ku.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%$7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw mt(new Error,Er.INVALID_VALUE("format"),pt.BAD_REQUEST);return new G7({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(X7,"export_to_s3");function fv(e,t){let r=Ku.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 H7(s,n);return r.pipe(i)}a(fv,"toCsvStream");function Ev(e){if(us.trace("in exportCoreValidation"),kr.isEmpty(e.format))return"format missing";if(uv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${uv.join(", ")}`;let t=e.search_operation.operation;if(kr.isEmpty(t))return"search_operation.operation missing";if(cv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${cv.join(", ")}`}a(Ev,"exportCoreValidation");async function hv(e){us.trace("in getRecords");let t,r;if(Yu.isEmpty(e.search_operation)||Yu.isEmptyOrZeroLength(e.search_operation.operation))throw mt(new Error,Er.INVALID_VALUE("Search operation"),pt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=K7;break;case"search_by_hash":t=Y7;break;case"search_by_conditions":t=dg.searchByConditions;break;case"sql":t=W7;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,us.error(r),mt(new Error,r,pt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(hv,"getRecords")});var bv={};Ve(bv,{contentTypes:()=>pg,findBestSerializer:()=>Sf,getDeserializer:()=>ho,registerContentHandlers:()=>Sg,serialize:()=>Tf,serializeMessage:()=>Si});function Z7(e){try{return e?.[0]===123?mg(e):e}catch{return e}}function Sg(e){e.register(tee,{serializers:[{regex:/^application\/json$/,serializer:Ec},{regex:/^application\/cbor$/,serializer:function(t){return new Eo.EncoderStream(Qu).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?pf.Readable.from((0,nn.encodeIter)(t,Qu)):(0,nn.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,fg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,nn.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,Eo.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function Sf(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 Tf(e,t,r){let s=Sv&&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=Sf(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,Ln.createBrotliCompress)({params:{[Ln.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Ln.constants.BROTLI_MODE_TEXT:Ln.constants.BROTLI_MODE_GENERIC,[Ln.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e,r)}return s&&n?.length>Sv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Ln.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Si(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Wu(e);let r=t.serialize;if(r)return r(e);let s=Sf(t);return r=t.serialize=s.serializer.serialize,r(e)}function ree(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 ho(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||Tv(e,s);return o=>ree(o).then(i)}return e&&Pt.get(e)?.deserialize||Tv(e,s)}function Tv(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 mg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function see(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 fg,nn,Eo,Ln,pf,gv,Eg,hg,Rv,Av,Wu,mg,Qu,Pt,pg,pv,Ov,eee,tee,Sv,Sa=Oe(()=>{Lh();fg=x(mf()),nn=require("msgpackr"),Eo=require("cbor-x"),Ln=require("zlib"),pf=require("stream");Xt();gv=require("../index"),Eg=x(X()),hg=x(L()),Rv=x(require("yaml")),Av=Eg.default.get(hg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Wu=Av?Li:JSON.stringify,mg=Av?Dh:JSON.parse,Qu={useRecords:!1,useToJSON:!0},Pt=new Map,pg=Pt;et.contentTypes=pg;(0,gv._assignPackageExport)("contentTypes",pg);Pt.set("application/json",{serializeStream:Ec,serialize:Wu,deserialize:mg,q:.8});pv=new Eo.Encoder(Qu);Pt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Eo.EncoderStream(Qu).end(e)},serialize:pv.encode,deserialize:pv.decode,q:1});Pt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?pf.Readable.from((0,nn.encodeIter)(e,Qu)):(0,nn.pack)(e)},serialize:nn.pack,deserialize:nn.unpack,q:.9});Pt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,fg.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 Rv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Pt.set("text/event-stream",{serializeStream:function(e){return pf.Readable.from(see(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=pP(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 Oa.info(`finished installModules with response ${i}`),i}a(f9,"installModules");function pP(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
|
|
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=Ju(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: ${Ju(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()}});Ov={type:"application/json",serializeStream:Ec,serialize:Wu,deserialize:Z7,q:.8};Pt.set("*/*",Ov);Pt.set("",Ov);a(Z7,"tryJSONParse");a(Sg,"registerContentHandlers");eee=require("fastify-plugin"),tee=eee(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Sf(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(Sf,"findBestSerializer");Sv=Eg.default.get(hg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Tf,"serialize");a(Si,"serializeMessage");a(ree,"streamToBuffer");a(ho,"getDeserializer");a(Tv,"deserializerUnknownType");a(see,"transformIterable")});function Rg(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?Rg(d.conditions,d.operator,r,s,n,i,o,c):wa(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 g=h.operator==="or",R=l(h.conditions,!g,E);return g?(B,H)=>R.some(v=>v(B,H)):(B,H)=>R.every(v=>v(B,H))}let S=(h.attribute||h[0])===r.primaryKey,O=Og(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=dee(r.primaryStore,h.estimated_count,E)),O}).filter(Boolean)}a(l,"mapConditionsToFilters")}function wa(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 g=o[0],R=Pn(s.attributes,g);if(R.relationship){if(o.length<2)throw new Un.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let B=R.definition?.tableClass||R.elements?.definition?.tableClass,H=new Map,v=wa({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,B,n,H);if(R.relationship.to){i[o[0]]=H;let U=!!Pn(B.attributes,R.relationship.to)?.elements;v=cee(v,R,B.primaryStore,U,H)}if(R.relationship.from){let U=a(Y=>wa({attribute:R.relationship.from,value:Y},t,r,s,n,H),"searchEntry");R.elements?(i[o[0]]=H,v=uee(v,R,B.primaryStore,H,U)):v=v.flatMap(U)}return v}else if(o.length===1)o=o[0];else throw new Un.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Ag[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]=on.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 Un.ClientError(`Unknown query comparator "${u}"`)}if(r){let g=_;_=l,l=g,g=!f,f=!d,d=g}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)throw new Un.ClientError(E?`Can not use ${u} operator without combining with a condition that uses an index`:`"${o}" is not indexed${c===null&&!p.indexNulls?" for nulls, index needs to be rebuilt to search for nulls":p?.isIndexing?" yet":""}, can not search for this attribute`,404);if(S=Og(e),!S)throw new Un.ClientError(`Unknown search operator ${e.comparator}`)}let O={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let g=p.getRange(O).map(S?({key:R,value:B})=>new Promise((H,v)=>setImmediate(()=>{try{H(B&&S(B)?R:zu.SKIP)}catch(U){v(U)}})):R=>R.value==null?zu.SKIP:R);return g.hasEntries=!0,g}else return p?p.getRange(O).map(S?({key:g,value:R})=>new Promise((B,H)=>setImmediate(()=>{try{B(S({[o]:g})?R:zu.SKIP)}catch(v){H(v)}})):({value:g})=>g):s.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(({key:g,value:R})=>new Promise((B,H)=>setImmediate(()=>{try{B(R&&S(R)?g:zu.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 cee(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;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=Us(d),o=!0);let h=n.get(E);h?h.push(f):n.set(E,h=[f]),d!==E&&(h.key=d)},"add_entry"),l=0;for await(let d of e){let f=d.value??r.get(d.key??d),E=f?.[u];if(E!=null&&!n.filters?.some(h=>!h(f))){if(s)for(let h=0;h<E.length;h++)_(E[h],d);else _(E,d);l++>100&&(await new Promise(setImmediate),l=0)}}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 uee(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 _=Us(u.value);if(!c.has(_))return c.add(_),u}if(!i)return(async()=>{let _=new Map;s.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>_.has(Us(f)));let l=0;for await(let d of e){if(s.filters){let f=r.get(d);if(s.filters.some(E=>!E(f)))continue}_.set(Us(d),d),l++>100&&(await new Promise(setImmediate),l=0)}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 Og(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=Og({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,O=a((g,R)=>{let B,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)}else S=_(p.from,h.idFilter,!1);let v=S(g);return S.idFilter&&(O.idFilter=S.idFilter),v}H=p(g,r,R),B=H?.value}else B=g[l];return B?Array.isArray(B)?B.some(h):h(B,H):!1},"recordFilter");return O}}switch(u instanceof Date&&(u=u.getTime()),Ag[o]||o){case Tg.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,on.compareKeys)(l,u[0])>=0&&(0,on.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,on.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,on.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,on.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,on.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,on.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Un.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f){let E;f=f&&!n&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&Rf(t)(e),E=e.estimated_count>>4,(isNaN(E)||E>=i)&&(f=!1));let h=0,p=3;function S(O){let g=O[l],R;if(typeof g!="object"||!g?R=d(g):Array.isArray(g)?R=g.some(d):g instanceof Date&&(R=d(g.getTime())),f&&(p++,!R&&!S.idFilter&&++h/p*(i-p)>E)){let B=wa(e,r.transaction.getReadTxn(),!1,t).map(Us),H=new Set(B);S.idFilter=v=>H.has(Us(v)),S.idFilter.idSet=H}return R}return a(S,"recordFilter"),n&&(S.idFilter=d),S}a(_,"attributeComparator")}function Rf(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=Ag[s]||s,s===Tg.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=Rf(o)({value:r.value,attribute:n.length>2?n.slice(1):n[1],comparator:"equals"});r.estimated_count=c*Mn(e.indices[i.relationship.from]||e.primaryStore)/(Mn(o.primaryStore)||1)}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=oee*Mn(e.primaryStore)+1:s==="between"?r.estimated_count=iee*Mn(e.primaryStore)+1:s==="sort"?r.estimated_count=Mn(e.primaryStore)+1:r.estimated_count=nee*Mn(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Af(e){if(e)if(Ri=e,Na.lastIndex=0,lee.test(e))try{let t=Ju(new ya,"");if(hr!==Ri.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 ${hr} in '${Ri}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Ju(e,t){let r=Na,s,n,i,o,c,u=decodeURIComponent,_;for(;s=r.exec(Ri);){hr=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=Nv}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");n=ju(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=aee[d],u=gg[i]?Nv:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);n=ju(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"&&yv(h,l),gf(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(ju(l)),n=void 0;break;case"(":Na.lastIndex=hr;let E=Ju(l?[]:new ya,")");switch(l){case"":gf(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=wv(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Ri[hr]===","?r.lastIndex=++hr: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");Na.lastIndex=hr,f=Ju([],"}"),f.name=l,e.push(f),Ri[hr]===","?r.lastIndex=++hr:o=!0;break;case"[":Na.lastIndex=hr,l?(f=Ju(new ya,"]"),f.name=l):f=Ju(e.conditions?new ya:[],"]"),e.conditions?(gf(e,_),e.conditions.push(f),n=null):e.push(f),Ri[hr]===","?r.lastIndex=++hr: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"&&yv(h,l),gf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(ju(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?_ee:Na,r.lastIndex=hr),hr===Ri.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function gf(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 ju(e){return e.indexOf(".")>-1?e.split(".").map(ju):decodeURIComponent(e)}function Nv(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 Un.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function yv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Un.ClientError("wildcard can only be used at the end of a string")}function wv(e){let t=Iv(e[0]);return e.length>1&&(t.next=wv(e.slice(1))),t}function Iv(e){if(Array.isArray(e)){let t=Iv(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 Us(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 dee(e,t,r){return t*r/Mn(e)}var Un,Tg,on,zu,nee,iee,oee,aee,gg,Ag,lee,Na,_ee,hr,Ri,ya,Of=Oe(()=>{Un=x(ee()),Tg=x(_t()),on=require("ordered-binary"),zu=require("lmdb"),nee=.3,iee=.1,oee=.05,aee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},gg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Rg,"executeConditions");a(wa,"searchByIndex");a(Pn,"findAttribute");a(cee,"joinTo");a(uee,"joinFrom");Ag={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(Og,"filterByType");a(Rf,"estimateCondition");lee=/[()[\]|!<>.]|(=\w*=)/,Na=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,_ee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Af,"parseQuery");a(Ju,"parseBlock");a(gf,"assignOperator");a(ju,"decodeProperty");a(Nv,"typedDecoding");a(yv,"wildcardDecoding");a(wv,"toSortObject");a(Iv,"toSortEntry");ya=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(Us,"flattenKey");a(Mn,"estimatedEntryCount");a(dee,"intersectionEstimate")});function Uv(e){let t={openapi:fee,info:{title:"HarperDB HTTP REST interface",version:(0,Mv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,s]of e){if(!s.path)continue;let{path:n}=s,i=n.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=s.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:B,elements:H,relationship:v,definition:U}of o){if(v)R==="array"?_[B]={type:"array",items:{$ref:Ai+H.type}}:_[B]={$ref:Ai+R};else{let Y=U??H?.definition;if(Y){if(!t.components.schemas[Y.type]){let W={};Y.properties.forEach(z=>{W[z.name]=new wg(bg[z.type],z.type)}),t.components.schemas[Y.type]=new Lv(W)}R==="array"?_[B]={type:"array",items:{$ref:Ai+Y.type}}:_[B]={$ref:Ai+Y.type}}else R==="array"?H.type==="Any"||H.type=="ID"?_[B]={type:"array",items:{format:H.type}}:_[B]={type:"array",items:new wg(bg[H.type],H.type)}:R==="Any"||R=="ID"?_[B]={format:R}:_[B]=new wg(bg[R],R)}l.push(new Ig(B,"query",_[B]))}let d=Object.keys(_),f=new Ig(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Ig("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new Lv(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",O=typeof u.delete=="function",g="/"+n+"/";h&&(t.paths[g]={},t.paths[g].post=new Eee(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[g]||(t.paths[g]={}),t.paths[g].get=new Ng(l,r,{200:new yg({$ref:Ai+i})},"search for records by the specified property name and value pairs")),O&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new Dv(l,r,"delete all the records that match the provided query",{204:new Cv})),g="/"+n+"/{"+c+"}",S&&(t.paths[g]={},t.paths[g].get=new Ng([f],r,{200:new yg({$ref:Ai+i})},"retrieve a record by its primary key")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].put=new hee([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),O&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new Dv([f],r,"delete a record with the given primary key",{204:new Cv})),S&&E.schema.enum.length>0&&(g="/"+n+"/{"+c+"}.{property}",t.paths[g]={},t.paths[g].get=new Ng([f,E],r,{200:new yg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function Eee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ai+e}}}},this.security=t,this.responses={200:{description:Cg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Ng(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.responses=r}function yg(e){this.description=Cg,this.content={"application/json":{schema:e}}}function Cv(){this.description="successfully processed request, no content returned to client"}function hee(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ai+r}}}},this.responses={200:{description:Cg}}}function Dv(e,t,r,s){this.description=r,this.parameters=e,this.security=t,this.responses=s}function Lv(e){this.type="object",this.properties=e}function wg(e,t){this.type=e,this.format=t}function Ig(e,t,r){this.name=e,this.in=t,this.schema=r}var Mv,fee,bg,Ai,Cg,Pv=Oe(()=>{Mv=x(Rd()),fee="3.0.3",bg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ai="#/components/schemas/",Cg="successful operation";a(Uv,"generateJsonApi");a(Eee,"Post");a(Ng,"Get");a(yg,"Response200");a(Cv,"Response204");a(hee,"Put");a(Dv,"Delete");a(Lv,"ResourceSchema");a(wg,"Type");a(Ig,"Parameter")});var Nf={};Ve(Nf,{start:()=>See});async function pee(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Af(e);let n=new pi;try{e.responseHeaders=n;let i=e.url.slice(1),o,c;if(i!==vv){let h=bf.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(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=ho(r["content-type"],!0)(e.body)}catch(h){throw new Ia.ClientError(h,400)}if(e.authorize=!0,i===vv&&s==="GET"){if(e?.user?.role?.permission?.super_user)return Uv(bf);throw new Ia.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 Ia.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ia.ServerError(`Method ${s} is not recognized`,501)}}),l=200,d;if(_==null)l=s==="GET"||s==="HEAD"?404:204,Dg.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){mee[0]=d;let h=String.fromCharCode(34,(Ft[0]&63)+62,(Ft[0]>>6)+(Ft[1]<<2&63)+62,(Ft[1]>>4)+(Ft[2]<<4&63)+62,(Ft[2]>>2)+62,(Ft[3]&63)+62,(Ft[3]>>6)+(Ft[4]<<2&63)+62,(Ft[4]>>4)+(Ft[5]<<4&63)+62,(Ft[5]>>2)+62,(Ft[6]&63)+62,(Ft[6]>>6)+(Ft[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):n.setIfNone("ETag",h),Dg.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=Tf(_,e,f),s==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?mo.warn(i):mo.info(i):mo.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=Tf(i.contentType?i:i.toString(),e,o),o}}function See(e){Dg=e,!Bv&&(Bv=!0,bf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return pee(t,r)}),e.server.ws(async(t,r,s)=>{Xu++;let n=new gs;Hv||(Hv=!0,eu(l=>{Xu>0&&l.push({metric:"ws-connections",connections:Xu,byThread:!0})}));let i;t.on("error",l=>{i=!0,mo.warn(l)});let o;t.on("message",a(function(d){o||(o=ho(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{Xu--,ts(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=bf.getMatch(u);if(ts(!!_,"connection","ws","connect"),!_)t.send(Si(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Hr(h=>({count:h.count,total:Xu}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await ze(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Si(E.value,r);t.send(h),Hr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var mo,Ia,Ft,mee,Dg,vv,Bv,bf,Hv,Xu,xv=Oe(()=>{Sa();On();mo=x(V()),Ia=x(ee());Of();dc();Ji();Wd();Pv();Ft=new Uint8Array(8),mee=new Float64Array(Ft.buffer,0,1),Dg={},vv="openapi";a(pee,"http");Xu=0;a(See,"start")});var Lg=T((Xhe,qv)=>{var{recordAction:yf,recordActionBinary:Tee}=(On(),te(tu)),gee=require("fastify-plugin"),Ree=200;qv.exports=gee(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),yf(o,"duration",_,d,l),Tee(n.raw.statusCode<400,"success",_,d,l);let f=Ree;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{yf(performance.now()-c,"transfer",_,d,l),yf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,yf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Hg=T((tme,Vv)=>{var Df=require("clone"),Lf=Qe(),Aee=J(),If=L(),Zhe=V(),Mg=require("fs"),Pg=require("joi"),{string:Cf}=Pg.types(),{hdb_errors:Oee,handleHDBError:wf}=ee(),{HDB_ERROR_MSGS:eme,HTTP_STATUS_CODES:Ug}=Oee,{common_validators:Ca}=$s(),Fv=" is required",bee=["insert","update","upsert"],vg={database:{presence:!1,format:Ca.schema_format,length:Ca.schema_length},schema:{presence:!1,format:Ca.schema_format,length:Ca.schema_length},table:{presence:!0,format:Ca.schema_format,length:Ca.schema_length},action:{inclusion:{within:bee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Nee={schema:Cf.required(),table:Cf.required(),action:Cf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:yee,AWS_SECRET:wee,AWS_BUCKET:Iee,AWS_FILE_KEY:Cee,REGION:Dee}=If.S3_BUCKET_AUTH_KEYS,Lee={s3:{presence:!0},[`s3.${yee}`]:{presence:!0,type:"String"},[`s3.${wee}`]:{presence:!0,type:"String"},[`s3.${Iee}`]:{presence:!0,type:"String"},[`s3.${Cee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Dee}`]:{presence:!0,type:"String"}},Gv=Df(vg);Gv.data.presence={message:Fv};var kv=Df(vg);kv.file_path.presence={message:Fv};var Mee=Object.assign(Df(vg),Lee),Bg=Df(Nee);Bg.csv_url=Cf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Bg.passthrough_headers=Pg.object();function Uee(e){let t=Lf.validateObject(e,Gv);return Mf(e,t)}a(Uee,"dataObject");function Pee(e){let t=Lf.validateBySchema(e,Pg.object(Bg));return Mf(e,t)}a(Pee,"urlObject");function vee(e){let t=Lf.validateObject(e,kv);return Mf(e,t)}a(vee,"fileObject");function Bee(e){let t=Lf.validateObject(e,Mee);return Mf(e,t)}a(Bee,"s3FileObject");function Mf(e,t){if(!t){let r=Aee.checkGlobalSchemaTable(e.schema,e.table);if(r)return wf(new Error,r,Ug.BAD_REQUEST);if(e.operation===If.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Mg.accessSync(e.file_path,Mg.constants.R_OK|Mg.constants.F_OK)}catch(s){return s.code===If.NODE_ERROR_CODES.ENOENT?wf(s,`No such file or directory ${s.path}`,Ug.BAD_REQUEST):s.code===If.NODE_ERROR_CODES.EACCES?wf(s,`Permission denied ${s.path}`,Ug.BAD_REQUEST):wf(s)}}return t}a(Mf,"postValidateChecks");Vv.exports={dataObject:Uee,urlObject:Pee,fileObject:vee,s3FileObject:Bee}});var xg=T((sme,$v)=>{"use strict";var Zu=V(),Uf=L();async function Hee(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===Uf.OPERATIONS_ENUM.INSERT||t.operation===Uf.OPERATIONS_ENUM.UPDATE||t.operation===Uf.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===Uf.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(Zu.info(i.message),i):i.http_resp_msg?(Zu.error(`Error calling operation: ${e.name}`),Zu.error(i.http_resp_msg),i):(Zu.error(`Error calling operation: ${e.name}`),Zu.error(i),i)}}a(Hee,"callOperationFunctionAsAwait");$v.exports={callOperationFunctionAsAwait:Hee}});var Kv=T((ime,Yv)=>{"use strict";var qg=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}},Fg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};Yv.exports={BulkLoadFileObject:qg,BulkLoadDataObject:Fg}});var Qv=T((ame,Wv)=>{"use strict";var Gg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};Wv.exports=Gg});var Wg=T((fme,_0)=>{"use strict";var Pf=Ir(),Bf=Hg(),xee=require("needle"),Ps=L(),ume=Fe(),Da=J(),{handleHDBError:nt,hdb_errors:s0}=ee(),{HTTP_STATUS_CODES:Gt,HDB_ERROR_MSGS:Nt,CHECK_LOGS_WRAPPER:So}=s0,La=V(),kg=require("papaparse");Da.promisifyPapaParse();var vs=require("fs-extra"),qee=require("path"),{chain:zv}=require("stream-chain"),Jv=require("stream-json/streamers/StreamArray"),jv=require("stream-json/utils/Batch"),Xv=require("stream-chain/utils/comp"),{finished:Zv}=require("stream"),Fee=X(),n0=xg(),Gee=lg(),{BulkLoadFileObject:$g,BulkLoadDataObject:kee}=Kv(),Yg=eg(),{verifyBulkLoadAttributePerms:i0}=ff(),lme=Qv(),_me=rt(),dme=pn(),{databases:Vee}=(be(),te(qe)),{coerceType:$ee}=(Hf(),te(Qg)),e0="No records parsed from csv file.",po=`${Fee.get("HDB_ROOT")}/tmp`,{schema_regex:Yee}=$s(),t0=1024*1024*2,r0=5e3,Kee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};_0.exports={csvDataLoad:Wee,csvURLLoad:Qee,csvFileLoad:zee,importFromS3:Jee};async function Wee(e,t){let r=Bf.dataObject(e);if(r)throw nt(r,r.message,Gt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=c0(e.schema,e.table),i=kg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Vg.bind(null,n),dynamicTyping:!1}),o=new Yg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&i0(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 nt(new Error,c,Gt.BAD_REQUEST,void 0,void 0,!0);let u=new kee(e.action,e.schema,e.table,i.data);return s=await n0.callOperationFunctionAsAwait(u0,u,null),s.message===e0?e0:l0(s.records,s.number_written)}catch(n){throw To(n)}}a(Wee,"csvDataLoad");async function Qee(e){let t=Bf.urlObject(e);if(t)throw nt(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${po}/${r}`;try{await jee(e,r)}catch(n){throw La.error(Nt.DOWNLOAD_FILE_ERR(r)+" - "+n),nt(n,So(Nt.DOWNLOAD_FILE_ERR(r)))}try{let n=new $g(this.job_operation_function.name,e.action,e.schema,e.table,s,Ps.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Kg(n);return await vf(s),i}catch(n){throw await vf(s),To(n)}}a(Qee,"csvURLLoad");async function zee(e){let t=Bf.fileObject(e);if(t)throw nt(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r=new $g(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Ps.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Kg(r)}catch(s){throw To(s)}}a(zee,"csvFileLoad");async function Jee(e){let t=Bf.s3FileObject(e);if(t)throw nt(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=qee.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${po}/${n}`;let i=new $g(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await Xee(n,e);let o=await Kg(i);return await vf(r),o}catch(s){throw await vf(r),To(s)}}a(Jee,"importFromS3");async function jee(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await xee("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 nt(s,n,s.statusCode,Ps.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}ete(r,e.csv_url),await Zee(t,r.raw)}a(jee,"downloadCSVFile");async function Xee(e,t){try{let r=`${po}/${e}`;await vs.mkdirp(po),await vs.writeFile(`${po}/${e}`,"",{flag:"a+"});let s=await vs.createWriteStream(r),n=await Gee.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(){La.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw La.error(Nt.S3_DOWNLOAD_ERR+" - "+r),nt(r,So(Nt.S3_DOWNLOAD_ERR))}}a(Xee,"downloadFileFromS3");async function Zee(e,t){try{await vs.mkdirp(po),await vs.writeFile(`${po}/${e}`,t)}catch(r){throw La.error(Nt.WRITE_TEMP_FILE_ERR),nt(r,So(Nt.DEFAULT_BULK_LOAD_ERR))}}a(Zee,"writeFileToTempFolder");async function vf(e){if(e)try{await vs.access(e),await vs.unlink(e)}catch{La.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(vf,"deleteTempFile");function ete(e,t){if(e.statusCode!==s0.HTTP_STATUS_CODES.OK)throw nt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Gt.BAD_REQUEST);if(!Kee[e.headers["content-type"]])throw nt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Gt.BAD_REQUEST);if(!e.raw)throw nt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Gt.BAD_REQUEST)}a(ete,"validateURLResponse");async function Kg(e){try{let t;switch(e.file_type){case Ps.VALID_S3_FILE_TYPES.CSV:t=await tte(e);break;case Ps.VALID_S3_FILE_TYPES.JSON:t=await rte(e);break;default:throw nt(new Error,Nt.DEFAULT_BULK_LOAD_ERR,Gt.BAD_REQUEST,Ps.LOG_LEVELS.ERROR,Nt.INVALID_FILE_EXT_ERR(e))}return l0(t.records,t.number_written)}catch(t){throw To(t)}}a(Kg,"fileLoad");async function o0(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 Pf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&i0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=nt(c);r(u)}}a(o0,"validateChunk");async function a0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Da.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!Da.isEmpty(c)&&!Da.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await n0.callOperationFunctionAsAwait(u0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=nt(c,So(Nt.INSERT_CSV_ERR),Gt.INTERNAL_SERVER_ERROR,Ps.LOG_LEVELS.ERROR,Nt.INSERT_CSV_ERR+" - "+c);r(u)}}a(a0,"insertChunk");async function tte(e){let t={records:0,number_written:0},r=c0(e.schema,e.table);try{let s=new Yg,n=vs.createReadStream(e.file_path,{highWaterMark:t0});n.setEncoding("utf8"),await kg.parsePromise(n,o0.bind(null,e,s),Vg.bind(null,r));let i=s.getPermsResponse();if(i)throw nt(new Error,i,Gt.BAD_REQUEST);return n=vs.createReadStream(e.file_path,{highWaterMark:t0}),n.setEncoding("utf8"),await kg.parsePromise(n,a0.bind(null,e,t),Vg.bind(null,r)),n.destroy(),t}catch(s){throw nt(s,So(Nt.PAPA_PARSE_ERR),Gt.INTERNAL_SERVER_ERROR,Ps.LOG_LEVELS.ERROR,Nt.PAPA_PARSE_ERR+s)}}a(tte,"callPapaParse");function c0(e,t){let r=Vee[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>$ee(i,n));return s}a(c0,"createTransformMap");function Vg(e,t,r){let s=e.get(r);return s?s(t):Da.autoCast(t)}a(Vg,"typeFunction");async function rte(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Yg,n=zv([vs.createReadStream(e.file_path,{encoding:"utf-8"}),Jv.withParser(),c=>c.value,new jv({batchSize:r0}),Xv(async c=>{await o0(e,s,r,c)})]);await new Promise((c,u)=>{Zv(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw nt(new Error,i,Gt.BAD_REQUEST);let o=zv([vs.createReadStream(e.file_path,{encoding:"utf-8"}),Jv.withParser(),c=>c.value,new jv({batchSize:r0}),Xv(async c=>{await a0(e,t,r,c)})]);return await new Promise((c,u)=>{Zv(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw nt(s,So(Nt.INSERT_JSON_ERR),Gt.INTERNAL_SERVER_ERROR,Ps.LOG_LEVELS.ERROR,Nt.INSERT_JSON_ERR+s)}}a(rte,"insertJson");async function u0(e){let t={};try{e.data&&e.data.length>0&&ste(e.data[0])?t=await nte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",La.info(t.message))}catch(r){throw To(r)}return t}a(u0,"callBulkFileLoad");function ste(e){let t=Object.keys(e);for(let r of t)if(!Yee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(ste,"validateColumnNames");async function nte(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=Pf.insert;break;case"update":i=Pf.update;break;case"upsert":i=Pf.upsert;break;default:throw nt(new Error,Nt.INVALID_ACTION_PARAM_ERR(s),Gt.BAD_REQUEST,Ps.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=Da.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw To(o)}}a(nte,"bulkFileLoad");function l0(e,t){return`successfully loaded ${t} of ${e} records`}a(l0,"buildResponseMsg");function To(e){return nt(e,So(Nt.DEFAULT_BULK_LOAD_ERR),Gt.INTERNAL_SERVER_ERROR,Ps.LOG_LEVELS.ERROR,Nt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(To,"buildTopLevelErrMsg")});var f0=T((hme,d0)=>{"use strict";var zg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};d0.exports=zg});var m0=T((pme,h0)=>{"use strict";var ite=L(),E0=require("moment"),ote=require("uuid").v4,Jg=class{static{a(this,"JobObject")}constructor(){this.id=ote(),this.type=void 0,this.start_datetime=E0().valueOf(),this.created_datetime=E0().valueOf(),this.end_datetime=void 0,this.status=ite.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};h0.exports=Jg});var jg=T((Tme,A0)=>{"use strict";var ate=require("uuid").v4,T0=Ir(),g0=Zr(),cte=zs(),ute=Zo(),lte=f0(),it=L(),_te=m0(),dte=Ed(),ls=V(),fte=yc(),Ma=J(),{promisify:Ete}=require("util"),go=require("moment"),hte=hf(),xf=Hg(),p0=ym(),{deleteTransactionLogsBeforeValidator:mte}=zT(),{handleHDBError:pte,hdb_errors:Ste}=ee(),{HTTP_STATUS_CODES:Tte}=Ste,S0=g0.searchByValue,gte=g0.searchByHash,Rte=T0.insert,Ate=Ete(hte.evaluateSQL),Ote=T0.update;A0.exports={addJob:yte,updateJob:Ite,handleGetJob:bte,handleGetJobsByStartDate:Nte,getJobById:R0};async function bte(e){try{let t=await R0(e.id);return Ma.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 ls.error("There was an error getting job",t),new Error(r)}}a(bte,"handleGetJob");async function Nte(e){try{let t=await wte(e);if(ls.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=go(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=go(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 ls.error(r),new Error(r)}}a(Nte,"handleGetJobsByStartDate");async function yte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ma.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return ls.info(l),t.error=l,t}if(!it.JOB_TYPE_ENUM[e.operation])return ls.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case it.OPERATIONS_ENUM.CSV_FILE_LOAD:s=xf.fileObject(e);break;case it.OPERATIONS_ENUM.CSV_URL_LOAD:s=xf.urlObject(e);break;case it.OPERATIONS_ENUM.CSV_DATA_LOAD:s=xf.dataObject(e);break;case it.OPERATIONS_ENUM.IMPORT_FROM_S3:s=xf.s3FileObject(e);break;case it.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case it.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=p0(e,"date");break;case it.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=p0(e,"timestamp");break;case it.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=mte(e);break;default:break}if(s)throw pte(s,s.message,Tte.BAD_REQUEST,void 0,void 0,!0);let n=new _te;n.type=e.operation===it.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?it.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new cte(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await S0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return ls.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=ate();try{o=await S0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return ls.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return ls.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new fte(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await Rte(u)}catch(l){return ls.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,ls.trace(l)}return t}a(yte,"addJob");async function wte(e){let t=go(e.from_date,go.ISO_8601),r=go(e.to_date,go.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 lte(s,e.hdb_user);try{return await Ate(n)}catch(i){throw ls.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(wte,"getJobsInDateRange");async function R0(e){if(Ma.isEmptyOrZeroLength(e))return Ma.errorizeMessage("Invalid job ID specified.");let t=new ute(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await gte(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return ls.error(s),Ma.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(R0,"getJobById");async function Ite(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ma.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===it.JOB_STATUS_ENUM.COMPLETE||e.status===it.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=go().valueOf());let t=new dte(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Ote(t),r}a(Ite,"updateJob")});var I0=T((Rme,w0)=>{"use strict";var O0=J(),mr=L(),Cte=require("moment"),qf=Wg(),Ff=V(),b0=jg(),N0=mf(),y0=ei(),Dte=$e(),Lte=uf(),Xg=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Mte(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(O0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(O0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case mr.JOB_TYPE_ENUM.csv_file_load:await vn(e,qf.csvFileLoad);break;case mr.JOB_TYPE_ENUM.csv_url_load:await vn(e,qf.csvURLLoad);break;case mr.JOB_TYPE_ENUM.csv_data_load:await vn(e,qf.csvDataLoad);break;case mr.JOB_TYPE_ENUM.import_from_s3:await vn(e,qf.importFromS3);break;case mr.JOB_TYPE_ENUM.empty_trash:break;case mr.JOB_TYPE_ENUM.export_local:await vn(e,N0.export_local);break;case mr.JOB_TYPE_ENUM.export_to_s3:await vn(e,N0.export_to_s3);break;case mr.JOB_TYPE_ENUM.delete_files_before:case mr.JOB_TYPE_ENUM.delete_records_before:await vn(e,y0.deleteFilesBefore);break;case mr.JOB_TYPE_ENUM.delete_audit_logs_before:await vn(e,y0.deleteAuditLogsBefore);break;case mr.JOB_TYPE_ENUM.delete_transaction_logs_before:await vn(e,Lte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Mte,"parseMessage");async function vn(e,t){try{e.job.status=mr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Cte().valueOf(),await b0.updateJob(e.job),await Ute(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):Ff.error(`There was an error running ${t.name} job with id ${e.job.id}`),Ff.error(s),e.job.message=s,e.job.status=mr.JOB_STATUS_ENUM.ERROR;try{await b0.updateJob(e.job)}catch(n){throw Ff.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(vn,"runJob");async function Ute(e){Ff.trace("launching job thread:",e),Dte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[mr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Ute,"launchJobThread");w0.exports={parseMessage:Mte,RunnerMessage:Xg}});var D0=T((Ome,C0)=>{"use strict";var Zg=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};C0.exports=Zg});var W0=T((Nme,iR)=>{"use strict";var $f=Zr(),rR=hf(),Gf=Wg(),Bn=cu(),kf=jn(),tl=ei(),Pte=hS(),el=es(),Vf=bS(),kt=QT(),yt=V(),vte=wS(),Bte=yd(),L0=cT(),Hte=Id(),xte=uT(),qte=lT(),Fte=fT(),Gte=hT(),eR=ST(),M0=mf(),kte=ff(),sR=jg(),F=L(),{hdb_errors:sl,handleHDBError:rl}=ee(),{HTTP_STATUS_CODES:U0}=sl,tR=OT(),P0=Yd(),V0=require("util"),Ua=Ir(),Vte=Sn(),$te=la(),v0=I0(),B0=Eu(),H0=(jd(),te(Pu)),x0=Mr(),q0=uf(),F0=rf(),{setServerUtilities:Yte}=(Hf(),te(Qg)),{CONTEXT:Kte}=(Rs(),te(Rp)),{_assignPackageExport:Wte}=require("../index"),{transformReq:Qte}=J(),{server:zte}=(Xt(),te(Di)),Jte=xg(),G0=$f.searchByHash,jte=$f.searchByValue,Xte=V0.promisify($f.search),Zte=V0.promisify(rR.evaluateSQL),ere={[F.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.CREATE_TABLE]:!0,[F.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[F.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.DROP_TABLE]:!0,[F.OPERATIONS_ENUM.DROP_SCHEMA]:!0},$=D0();async function $0(e,t){try{if(e.body.operation!=="read_log"&&(yt.log_level===F.LOG_LEVELS.INFO||yt.log_level===F.LOG_LEVELS.DEBUG||yt.log_level===F.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 Jte.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return ere[e.body.operation]&&Vte.setSchemaDataToGlobal(s=>{s&&yt.error(s)}),r}a($0,"processLocalTransaction");var k0=rre();iR.exports={chooseOperation:Y0,getOperationFunction:K0,operation:nR,processLocalTransaction:$0};Yte(iR.exports);zte.operation=nR;function Y0(e){let t;try{t=K0(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=rR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=rR.checkASTPermissions(e,i);if(o)throw yt.error(`${U0.FORBIDDEN} from operation ${e.operation}`),yt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),rl(new Error,o,sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==F.OPERATIONS_ENUM.LOGIN&&e.operation!==F.OPERATIONS_ENUM.LOGOUT){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=kte.verifyPerms(i,n);if(o)throw yt.error(`${U0.FORBIDDEN} from operation ${e.operation}`),yt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),rl(new Error,o,sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw rl(n,"There was an error when trying to choose an operation path")}return r}a(Y0,"chooseOperation");function K0(e){if(yt.trace(`getOperationFunction with operation: ${e.operation}`),k0.has(e.operation))return k0.get(e.operation);throw rl(new Error,sl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),sl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(K0,"getOperationFunction");Wte("operation",nR);function nR(e,t){e.hdb_user=this[Kte]?.user,e.bypass_auth=!t;let r=Y0(e);return $0({body:e},r)}a(nR,"operation");async function tre(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[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await Ua.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await Ua.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await Ua.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await tl.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(tre,"catchup");async function an(e){Qte(e);let t,r;try{r=await sR.addJob(e),t=r.createdJob,yt.info("addJob result",r);let s=new v0.RunnerMessage(t,e);return await v0.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),rl(s,n)}}a(an,"executeJob");function rre(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new $(Ua.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new $(Ua.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new $(Ua.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new $($f.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new $(G0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new $(G0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(jte)),e.set(F.OPERATIONS_ENUM.SEARCH,new $(Xte)),e.set(F.OPERATIONS_ENUM.SQL,new $(Zte)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new $(an,Gf.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new $(an,Gf.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new $(an,Gf.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new $(an,Gf.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new $(Bn.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new $(Bn.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new $(Bn.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new $(Bn.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new $(Bn.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new $(Bn.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new $(Bn.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new $(Bn.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new $(kf.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new $(kf.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new $(kf.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new $(kf.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new $(tl.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new $(el.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new $(el.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new $(el.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new $(el.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new $(Vf.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new $(Vf.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new $(Vf.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new $(Vf.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new $(el.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new $(vte)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new $(Bte)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new $(L0)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(L0)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new $(Hte)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(xte)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new $(qte)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new $(x0.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new $(Fte.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new $(Gte)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(eR.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(eR.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(eR.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new $(an,M0.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new $(an,tl.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new $(an,tl.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new $(an,M0.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(sR.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new $(sR.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new $(tR.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new $(tR.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new $(tR.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new $(P0.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new $(P0.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new $(tre)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $($te.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(an,tl.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(Pte)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(B0.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(B0.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new $(H0.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new $(H0.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new $(x0.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $(kt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $(kt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $(kt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new $(kt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $(kt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new $(kt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $(kt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $(kt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $(kt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $(kt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new $(kt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $(kt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $(kt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $(kt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $(kt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $(kt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(q0.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(an,q0.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $(F0.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $(F0.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new $(Bn.getBackup)),e}a(rre,"initializeOperationFunctionMap")});var Kf=T((wme,J0)=>{"use strict";var oR=L(),sre=J(),nl=V(),{handleHDBError:aR,hdb_errors:Yf}=ee(),{isMainThread:nre}=require("worker_threads"),{Readable:ire}=require("stream"),Q0=require("os"),ore=require("util"),are=HS(),cre=ore.promisify(are.authorize),z0=W0(),{createGzip:ure,constants:lre}=require("zlib");function _re(e){let t=`Found an uncaught exception with message: ${e.message}. ${Q0.EOL}Stack: ${e.stack} ${Q0.EOL}Terminating ${nre?"HDB":"thread"}.`;console.error(t),nl.fatal(t),process.exit(1)}a(_re,"handleServerUncaughtException");function dre(e,t,r){if(nl[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:Yf.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(dre,"serverErrorHandler");function fre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=aR(new Error,"Invalid JSON.",Yf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(sre.isEmpty(e.body.operation)){let s=aR(new Error,"Request body must include an 'operation' property.",Yf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(fre,"reqBodyValidationHandler");function Ere(e,t,r){let s;e.body.operation!==oR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==oR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==oR.OPERATIONS_ENUM.LOGOUT?cre(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{nl.warn(n),nl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(aR(n,i,Yf.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(Ere,"authHandler");async function hre(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 ire&&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(ure({level:lre.Z_BEST_SPEED})))}return n}catch(n){throw nl.error(n),n}}a(hre,"handlePostRequest");J0.exports={authHandler:Ere,handlePostRequest:hre,handleServerUncaughtException:_re,serverErrorHandler:dre,reqBodyValidationHandler:fre}});var eB=T((Cme,Z0)=>{"use strict";var mre=require("fastify-plugin"),{handlePostRequest:j0,authHandler:pre,reqBodyValidationHandler:Sre}=Kf();async function Tre(e){e.decorate("hdbCore",{preValidation:[Sre,pre],request:t=>X0(j0(t,response)),requestWithoutAuthentication:(t,r)=>X0(j0(t,r,!0))})}a(Tre,"hdbCore");async function X0(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(X0,"convertAsyncIterators");Z0.exports=mre(Tre)});var sB=T((Mme,rB)=>{"use strict";var Lme=require("fs"),cR=X();cR.initSync();var{CONFIG_PARAMS:tB}=L(),gre=1024*1024*1024;function Rre(e){let t=cR.get(tB.HTTP_TIMEOUT),r=cR.get(tB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:gre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Rre,"getServerOptions");rB.exports=Rre});var oB=T((Pme,iB)=>{"use strict";var uR=X();uR.initSync();var{CONFIG_PARAMS:nB}=L();function Are(){let e=uR.get(nB.HTTP_CORSACCESSLIST),t=uR.get(nB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(Are,"getCORSOptions");iB.exports=Are});var uB=T((Bme,cB)=>{"use strict";var aB=X();aB.initSync();var Ore=L();function bre(){return aB.get(Ore.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(bre,"getHeaderTimeoutConfig");cB.exports=bre});var _R={};Ve(_R,{customFunctionsServer:()=>wre,ready:()=>bB,start:()=>yre});function yre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){Hn||(Hn=OB(t),et.http((await Hn).server));let o=await Hn,c=(0,lR.dirname)(n),u=(0,lR.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!lB.has(c)){lB.add(c);try{o.register(Cre(c,u))}catch(_){if(_.message==="Root plugin has already booted")ke.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}},ready:bB}}async function wre(){try{ke.info("In Custom Functions Fastify server"+process.cwd()),ke.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),ke.debug(`Custom Functions server process ${process.pid} starting up.`),await Ire();let e=mB.get(pB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Hn=await OB(e)}catch(r){throw ke.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw ke.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){ke.error(`Custom Functions ${process.pid} Error: ${e}`),ke.error(e),process.exit(1)}}async function Ire(){try{ke.info("Custom Functions starting configuration."),await SB.setUsersToGlobal(),ke.info("Custom Functions completed configuration.")}catch(e){ke.error(e)}}function Cre(e,t){return async function(r){try{ke.info("Custom Functions starting buildRoutes"),ke.trace("Loading fastify routes folder "+e),(0,_B.existsSync)(e)&&r.register(hB.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:ke.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?ke.error(n.message):n&&ke.error(n),o()})}catch(s){ke.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function OB(e){ke.info("Custom Functions starting buildServer.");let t=(0,TB.default)(e),r=(0,dB.default)(t);r.server.headersTimeout=(0,RB.default)(),r.setErrorHandler(AB.serverErrorHandler);let s=(0,gB.default)();return s&&r.register(fB.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(EB.default),await r.register(Nre),await r.after(),Sg(r),ke.info("Custom Functions completed buildServer."),r}function bB(){if(Hn)return Hn.then?Hn.then(e=>e.ready()):Hn.ready()}var lR,_B,dB,fB,EB,hB,mB,pB,ke,Nre,SB,TB,gB,RB,AB,Hn,lB,NB=Oe(()=>{lR=require("path"),_B=require("fs"),dB=x(require("fastify")),fB=x(require("@fastify/cors")),EB=x(Lg()),hB=x(require("@fastify/autoload")),mB=x(X()),pB=x(L()),ke=x(V()),Nre=x(eB()),SB=x(es()),TB=x(sB()),gB=x(oB()),RB=x(uB()),AB=x(Kf());Sa();Xt();lB=new Set;a(yre,"start");a(wre,"customFunctionsServer");a(Ire,"setUp");a(Cre,"buildRouteFolder");a(OB,"buildServer");a(bB,"ready")});var dR={};Ve(dR,{start:()=>Dre});function Dre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,DB.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){wB||(wB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=yB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,IB.default)(n,(0,CB.realpathSync)(o))}}return i(n)},{runFirst:!0})),yB.set(r,s)}}}var IB,CB,DB,yB,wB,LB=Oe(()=>{IB=x(require("send")),CB=require("fs"),DB=x(require("serve-static")),yB=new Map;a(Dre,"start")});function Ure(e,t=1,r){if(fR++,(0,Ro.startWorker)("server/threads/threadServer.js",{name:zf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===zf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});Mre.push(n),await n,Pa.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=Qf.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Pa.indexOf(s);o>-1&&Pa.splice(o,1)}if(a(i,"removeWorker"),va){let o=va;va=[];for(let c of o)vB[c.localPort](null,c)}}}),r){let s=setInterval(()=>{ER?ER=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Ro.shutdownWorkers)(),fR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function BB(e=0,t){if(typeof e=="string")try{(0,Jf.existsSync)(e)&&(0,Jf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Pre:r=vre(t):r=mR;let s=(0,Ba.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=vB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),ER=!0,r(o,(c,u)=>{if(!c){if(MB){let l=o._socket||new Ba.Socket({handle:o,writable:!0,readable:!0});MB.deliverSocket(l,e,u),l.resume()}else fR>0?(va.length===0&&setTimeout(()=>{va.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,va.push(o)):(console.log("start up a dynamic thread to handle request"),Ure(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 Ba.Socket({handle:o,writable:!0,readable:!0});qre(l,c,e)}Hr(!0,"socket-routed")})};let n=jc();hR.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 mR(e,t){let r,s=0;for(let n of Pa){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=Wf)return Wf=i,t(r);s=i}Wf=0,t(r)}function Pre(e,t){let r={};e.getpeername(r);let s=r.address,n=Ha.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);mR(e,o=>{Ha.set(s,{worker:o,lastUsed:i}),t(o)})}function vre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new Ba.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ha.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);mR(s,d=>{Ha.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function Hre(){Wf=0;for(let e of Pa)e.expectedIdle=e.recentELU.idle+Bre,e.requests=1;Pa.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function qre(e,t,r){let s=xre++;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(),Qf.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")),Qf.delete(s)),n.event=="destroy"&&(e.destroy(),Qf.delete(s))})}var Ro,Ba,zf,hR,Jf,PB,Lre,Pa,va,vB,MB,fR,Mre,ER,Wf,UB,Ha,Bre,Qf,xre,HB=Oe(()=>{Ro=x($e()),Ba=require("net"),zf=x(L()),hR=x(V()),Jf=require("fs");On();PB=require("worker_threads"),Lre=x($i()),Pa=[],va=[],vB=[],fR=0,Mre=[];PB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Ure,"startHTTPWorker");a(BB,"startSocketServer");Wf=0;a(mR,"findMostIdleWorker");UB=36e5,Ha=new Map;a(Pre,"findByRemoteAddressAffinity");a(vre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ha)r.lastUsed+UB<e&&Ha.delete(t)},UB).unref();Bre=1e3;a(Hre,"updateWorkerIdleness");(0,Ro.setMonitorListener)(Hre);Qf=new Map,xre=1;a(qre,"proxySocket")});var gR={};Ve(gR,{Request:()=>pR,createReuseportFd:()=>jf});var xB,pR,SR,TR,jf,Xf=Oe(()=>{xB=require("os"),pR=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 TR(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 SR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},SR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},TR=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,xB.platform)()!="win32"&&(jf=require("node-unix-socket").createReuseportFd)});var kB=T((jme,GB)=>{"use strict";var Fre=require("cluster"),Ao=X();Ao.initSync();var FB=L(),Kme=require("util"),xn=V(),Wme=require("fs"),Gre=require("fastify"),Qme=jc(),kre=require("@fastify/cors"),Vre=require("@fastify/compress"),$re=require("@fastify/static"),Yre=Lg(),Kre=require("path"),{PACKAGE_ROOT:Wre}=L(),Qre=Sn(),zre=J(),Jre=es(),jre=$i(),{server:Xre}=(Xt(),te(Di)),{node_request_key:zme}=(Xf(),te(gR)),{authHandler:Zre,handlePostRequest:ese,serverErrorHandler:tse,reqBodyValidationHandler:rse}=Kf(),Jme=require("net"),{registerContentHandlers:sse}=(Sa(),te(bv)),nse=6e4,ise=1024*1024*1024,ose="TRUE",{CONFIG_PARAMS:il}=FB,xa;GB.exports={hdbServer:qB,start:qB};async function qB(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=Fre.isMaster,await ase();let t=e.securePort>0;xa=cse(t),await xa.ready(),e||(e={}),e.isOperationsServer=!0;try{Xre.http(xa.server,e),xa.server.closeIdleConnections||await xa.listen({port:0,host:"::"})}catch(r){throw xa.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(qB,"operationsServer");async function ase(){xn.trace("Configuring HarperDB process."),Qre.setSchemaDataToGlobal(),await Jre.setUsersToGlobal(),await jre.getLicense()}a(ase,"setUp");function cse(e){xn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=use(e),r=Gre(t);r.server.headersTimeout=_se(),r.setErrorHandler(tse);let s=lse();s&&r.register(kre,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Yre),r.register(Vre),r.register($re,{root:Kre.join(Wre,"studio/build-local")}),sse(r);let n=Ao.get(FB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!zre.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[rse,Zre],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),ese(i,o)}),r.get("/health",()=>"HarperDB is running."),xn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(cse,"buildServer");function use(e){let t=Ao.get(il.OPERATIONSAPI_NETWORK_TIMEOUT),r=Ao.get(il.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:ise,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(use,"getServerOptions");function lse(){let e=Ao.get(il.OPERATIONSAPI_NETWORK_CORS),t=Ao.get(il.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===ose)&&(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(lse,"getCORSOpts");function _se(){return Ao.get(il.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??nse}a(_se,"getHeaderTimeoutConfig")});var XB=T((rpe,jB)=>{"use strict";var{decode:dse}=require("msgpackr"),{isMainThread:Zme,parentPort:fse,threadId:epe}=require("worker_threads"),AR=rt(),qn=Fe(),Ese=L(),Oi=V(),VB=X(),YB=L();$e();var hse=pn(),{recordAction:mse,recordActionBinary:pse}=(On(),te(tu)),{publishToStream:Sse}=AR,{ConsumerEvents:Tse}=require("nats"),tpe={durable:qn.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qn.WORK_QUEUE_CONSUMER_NAMES.deliver_group},gse,Rse,Ase,KB,WB;jB.exports={initialize:OR,workQueueListener:JB,setSubscription:Ose,setIgnoreOrigin:Nse,getDatabaseSubscriptions:bse};async function OR(){WB=!0,Oi.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await AR.getNATSReferences();gse=e,Rse=e.info.server_name,Ase=t,KB=r}a(OR,"initialize");var eE=new Map;function Ose(e,t,r){let s=eE.get(e);s||eE.set(e,s=new Map),s.set(t,r),WB||OR().then(JB)}a(Ose,"setSubscription");function bse(){return eE}a(bse,"getDatabaseSubscriptions");var QB;function Nse(e){QB=e}a(Nse,"setIgnoreOrigin");var zB=100,$B=new Array(zB),Zf=0;async function JB(){let e=await KB.consumers.get(qn.WORK_QUEUE_CONSUMER_NAMES.stream_name,qn.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(fse?.on("message",async s=>{let{type:n}=s;n===YB.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===Tse.HeartbeatsMissed){let n=s.data;Oi.trace(`${n} clustering ingest consumer heartbeats missed`),n===2&&(Oi.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let s of r)await $B[Zf],$B[Zf]=yse(s).catch(n=>{Oi.error(n)}),++Zf>=zB&&(Zf=0)}catch(s){Oi.error("Error consuming clustering ingest, restarting consumer",s)}AR.clearClientCache(),await OR()}}a(JB,"workQueueListener");async function yse(e){let t=dse(e.data);mse(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,s=!1,n=VB.get(Ese.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&&!QB),pse(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;Oi.trace("processing message:",o,c,_,(l?"records: "+l.map(R=>R?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Oi.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:O}=f||{},g=eE.get(c)?.get(_);if(!g)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,g.send(t);else if(l.length===1&&!u)g.send({type:RR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:O});else{let R=l.map((B,H)=>({type:RR(o),value:B,expiresAt:E,id:d?.[H],table:_}));for(;u;)R.push({type:RR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;g.send({type:"transaction",writes:R,table:_,timestamp:p,onCommit:h,user:S,nodeName:O})}VB.get(YB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Sse(e.subject.split(".").slice(0,-1).join("."),hse.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Oi.error(o)}e.ack()}a(yse,"messageProcessor");function RR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(RR,"convertOperation")});var CR={};Ve(CR,{disableNATS:()=>Ise,publishToStream:()=>iE,setNATSReplicator:()=>bR,setPublishToStream:()=>Cse,setSubscription:()=>IR,start:()=>wse});function wse(){rE.default.get(sE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Lse()}function Ise(e=!0){sH=e}function Cse(e,t){iE=e,IR=t}function Lse(){if(sH||process.env._DISABLE_NATS)return;let e=Cs(),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];bR(n,r,i)}}DR((r,s)=>{bR(r.tableName,r.databaseName,r),s&&iH(r)}),!ZB&&(ZB=!0)}function bR(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 vt{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Me],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Me]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Me],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Me],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Me]})}static defineSchema(i){iH(i)}static subscribe(){let i=new gs;return IR(t,e,i),i}static subscribeOnThisThread(i){return i<Dse}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 tE(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=nH;return i}a(s,"getNATSTransaction")}function iH(e){let t=rE.default.get(sE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);iE(`${yR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,wR.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 eH,yR,wR,tH,rH,rE,sE,nE,sH,iE,IR,Dse,nH,ZB,tE,NR,oH=Oe(()=>{be();Rs();eH=x(rt()),yR=x(Fe()),wR=x(pn());dc();tH=x(XB()),rH=x(Nr()),rE=x(X()),sE=x(L()),nE=x(V());a(wse,"start");a(Ise,"disableNATS");iE=eH.publishToStream,IR=tH.setSubscription;a(Cse,"setPublishToStream");Dse=2;a(Lse,"assignReplicationSource");a(bR,"setNATSReplicator");a(iH,"publishSchema");tE=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=rE.default.get(sE.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||(nE.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(iE(`${yR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,wR.createNatsTableStreamName)(n,u.table),void 0,u)?.catch(l=>{throw nE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(s)}},NR=class extends tE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,rH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};nH=new NR});var gH=T(Oo=>{"use strict";var{isMainThread:Mse,parentPort:al,threadId:oE}=require("worker_threads"),{Socket:Use,createServer:Pse}=require("net"),{createServer:vse,IncomingMessage:Bse}=require("http"),{createServer:Hse}=require("https"),{readFileSync:qa,unlinkSync:aH,existsSync:xse}=require("fs"),_s=V(),He=X(),pr=L(),{server:uE}=(Xt(),te(Di)),{WebSocketServer:qse}=require("ws"),{createServer:Fse}=require("tls"),{getTicketKeys:Gse,restartNumber:kse,getWorkerIndex:cH}=$e(),{Headers:fH}=(Wd(),te(QU)),{recordAction:ol,recordActionBinary:Vse}=(On(),te(tu)),{Request:EH,createReuseportFd:uH}=(Xf(),te(gR)),{checkMemoryLimit:$se}=$i(),hH=require("tls"),lH=hH.createSecureContext;hH.createSecureContext=function(e){if(!e.cert||!e.key)return lH(e);let t={...e};delete t.key,delete t.cert;let r=lH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){kse<=1&&_s.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:upe,CONFIG_PARAMS:Yse}=pr;He.initSync();var Kse=He.get(Yse.HTTP_SESSIONAFFINITY),cn={};Oo.registerServer=vR;Oo.httpServer=BR;Oo.deliverSocket=PR;Oo.startServers=mH;Oo.when_components_loaded=null;uE.http=BR;uE.request=Jse;uE.socket=jse;uE.ws=Xse;var LR={},aE={},Wse,bi={},cE={},Qse=[],MR=[];function mH(){return Oo.when_components_loaded=HR().loadRootComponents(!0).then(()=>{al?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)PR(s,r,n);else if(t.requestId)zse(t);else if(t.type===pr.ITC_EVENT_TYPES.SHUTDOWN){_s.trace("received shutdown request",oE);for(let i in cn){let o=cn[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?_s.info(`Closing ${E.length} idle connections`):f&&_s.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});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
|
|
27
27
|
Connection: close\r
|
|
28
28
|
\r
|
|
29
|
-
`))}},25).unref()}o.close?.(()=>{if(He.get(
|
|
30
|
-
`)}a(dH,"defaultNotFound")});async function bH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await xR.getResource(e,{});n=new GR(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await xR.get(e);i&&i.delete()}n=new _E(e,t)}return s&&(s.id=e,s.user={username:t?.username},cl.put(s)),n}function qR(){return lE++,lE>65500&&(lE=1),lE}function FR(e,t,r=e){let{topic:s,retain:n}=e;e.data=t,e.async=!0,e.authorize=!0;let i=mi.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 ze(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var RH,bo,AH,OH,xR,cl,lE,_E,GR,NH=Oe(()=>{be();Uu();RH=x(Nr()),bo=x(V());Ji();AH=x($e()),OH=x(gH());Xt();xR=at({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"}]}}]}),cl=at({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,AH.getWorkerIndex)()===0&&(async()=>{await OH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of cl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await et.getUser(r.user.username)),ze(r,()=>{try{FR(r,t)}finally{cl.delete(e.id,r)}})}})();a(bH,"getSession");lE=1;a(qR,"getNextMessageId");_E=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(O=>O.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,bo.trace)("Resuming subscription from",n,"from",o);let E=mi.getMatch(_);if(!E){let O=new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);throw O.statusCode=404,O}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let O=f.url.slice(1);if(O.indexOf("#")>-1&&O.indexOf("#")!==O.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,O.indexOf("+")===O.length-1)f.onlyChildren=!0,f.url="/"+O.slice(0,O.length-1);else{let g=O.split("/"),R;for(let v=0;v<g.length;v++)if(g[v].indexOf("+")>-1)if(g[v]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(s&&R)throw new Error("Filters can not be combined");let B=!0;g[g.length-1]==="#"&&(g.length--,B=!1),R&&(s=a(v=>{let U=v.id;if(!Array.isArray(U)||B&&U.length!==g.length)return!1;for(let Y=0;Y<g.length;Y++)if(g[Y]!=="+"&&g[Y]!==U[Y])return!1;return!0},"filter"));let H=g.indexOf("+");f.url="/"+(H>-1?g.slice(0,H):g).concat("").join("/")}}let h=E.path,p=E.Resource,S=await ze(f,async()=>{let O=await p.subscribe(f);if(!O)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!O[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let g of O)try{let R;if(g.type&&g.type!=="put"&&g.type!=="delete"&&g.type!=="message"&&g.type!=="patch"||s&&!s(g))continue;r?(g.topic=n,R=this.needsAcknowledge(g)):(g.acknowledge?.(),R=qR());let B=g.id;Array.isArray(B)&&(B=pa(B)),B==null&&(B=""),this.listener(h+"/"+B,g.value,R,t)}catch(R){(0,bo.warn)(R)}})(),O});return S.topic=n,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=qR();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,FR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};ze(r,async()=>{if(!t){let s=await cl.get(this.sessionId,r);s?.doesExist()&&await FR(s,s.data,r)}await cl.delete(this.sessionId,r)}).catch(s=>{(0,bo.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(FR,"publish");GR=class extends _E{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=qR(),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,bo.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,RH.getNextMonotonicTime)()),(0,bo.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),xR.put(this.sessionRecord)),t.qos}}});var kR={};Ve(kR,{bypassAuth:()=>Zse,start:()=>ene});function Zse(){DH=!0}function ene({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}=IH(_,(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,Sr.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,Sr.error)(E)}else if(u.required)return(0,Sr.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&DH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,CH.getSuperUser)());let{onMessage:d,onClose:f}=IH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Sr.info)("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function IH(e,t,r,s,n){wH||(wH=!0,eu(d=>{dE>0&&d.push({metric:"mqtt-connections",connections:dE,byThread:!0})}));let i;dE++;let o,c={protocolVersion:4},u=(0,EE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){dE--,i||(i=!0,o?.disconnect(),n.sessions.delete(o),ts(!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 et.getUser(d.username,d.password.toString(),r),(0,fE.get)(un.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&yH.notify({username:s.username,status:un.AUTH_AUDIT_STATUS.SUCCESS,type:un.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,fE.get)(un.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&yH.error({username:s.username,status:un.AUTH_AUDIT_STATUS.FAILURE,type:un.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return ts(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let R=e.deserialize||(e.deserialize=ho(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=bH({user:s,...d}),o=await o,n.sessions.add(o)}catch(R){return(0,Sr.error)(R),ts(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}ts(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,B,H,v)=>{try{let U=R.indexOf("/",1),Y=U>0?R.slice(0,U):R;f({cmd:"publish",topic:R,payload:E(B),messageId:H||Math.floor(Math.random()*1e8),qos:v.qos},Y)}catch(U){(0,Sr.error)(U),o?.disconnect(),n.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let B;try{B=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(H){(0,Sr.error)(H),B=c.protocolVersion<5?128:H.statusCode===403?135:H.statusCode===404?143:128}h.push(B)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let B of d.unsubscriptions)R.push(o.removeSubscription(B)?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=ho(r?.headers.get?.("content-type"))),O=d.payload?.length>0?S(d.payload):void 0,g;try{g=await o.publish(d,O)}catch(R){(0,Sr.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:g===!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),ts(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Sr.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,EE.generate)(h,c);t(S),Hr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Si(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var EE,CH,fE,un,Sr,yH,DH,wH,dE,LH=Oe(()=>{EE=require("mqtt-packet");NH();CH=x(es());Sa();On();Xt();fE=x(X()),un=x(L()),Sr=x(V()),yH=(0,Sr.loggerWithTag)("auth-event"),DH=(0,fE.get)(un.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Zse,"bypassAuth");a(ene,"start");dE=0;a(IH,"onSocket")});var of={};Ve(of,{component_errors:()=>Ga,loadComponent:()=>hE,loadComponentDirectories:()=>FH,setErrorReporter:()=>nne});function FH(e,t){t&&($R=t),e&&(YR=e);let r=[];if((0,Bs.existsSync)(VR)){let n=(0,Bs.readdirSync)(VR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,St.join)(VR,o);r.push(hE(c,$R,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(hE(s,$R,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{qH=!0})}function nne(e){ll=e}async function hE(e,t,r,s,n,i){if(!UH.has(e)){UH.set(e,!0),n&&(YR=n);try{let o;s&&(Ga=new Map);let c=(0,St.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Bs.existsSync)(c)?o=s?(0,xH.getConfigObj)():(0,PH.parseDocument)((0,Bs.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=KR;let u=[],_=s;for(let l in o){let d=o[l];if(Ga.set(s?l:(0,St.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let g=e,R;for(;!(0,Bs.existsSync)(R=(0,St.join)(g,"node_modules",l));)if(g=(0,St.dirname)(g),g.length<(0,HH.getHdbBasePath)().length){R=null;break}if(R)f=await hE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=sne[l];if(!f)continue;u.push(f);let h=a(g=>(g.origin=r,at(g)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,O=!p?.https&&p?.port;if(Fa.isMainThread&&(f=await f.startOnMainThread?.({server:et,ensureTable:h,port:O,securePort:S,resources:t,...d})||f,s&&p))for(let g of[O,S])try{if(+g&&!MH.includes(g)){let R=WR.get(QR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&ul.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!jf)&&(MH.push(g),BB(g,R))}}catch(R){console.error("Error listening on socket",g,R,l)}if(t.isWorker&&(f=await f.start?.({server:et,ensureTable:h,port:O,securePort:S,resources:t,...d})||f),YR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,BH.handleHDBError)("Can not reference parent directories");let g=(0,St.join)(e,d.files).replace(/\\/g,"/"),R=g.indexOf("/*");if(R>-1&&d.files!==KR[l]?.files&&!(0,Bs.existsSync)(g.slice(0,R)))throw new Error(`The path '${g.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let B=(0,St.basename)(e),H=d.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+B+H.slice(2):H==="."?"/"+B:"/"+B+"/"+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,St.join)(e,z)}else(Y=g.indexOf("/*"))>-1&&(U=g.slice(0,Y+1),v=(0,St.relative)(e,U));let W=!1;if(Fa.isMainThread&&f.setupDirectory&&(W=await f.setupDirectory?.(H,U,t)),t.isWorker&&f.handleDirectory&&(W=await f.handleDirectory?.(H,U,t)),W)continue;for(let z of await(0,vH.default)(g,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:Te}=z;_=!0;let oe=(0,St.relative)(e,ne).replace(/\\/g,"/");if(v)if(oe.startsWith(v))oe=oe.slice(v.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${oe}'.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("/")?"":"/")+oe;try{if(Te.isFile()){let de=await rne(ne);Fa.isMainThread&&await f.setupFile?.(de,xe,ne,t),t.isWorker&&await f.handleFile?.(de,xe,ne,t)}else Fa.isMainThread&&await f.setupDirectory?.(xe,ne,t),t.isWorker&&await f.handleDirectory?.(xe,ne,t)}catch(de){de.message=`Could not load ${Te.isFile()?"file":"directory"} '${ne}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${de.message}`,ll?.(de),((0,ka.getWorkerIndex)()===0?console:ul.default).error(de),t.set(d.path||"/",new _l(de)),Ga.set(s?l:(0,St.basename)(e),de.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,St.basename)(e)}' due to: ${h.message}`,ll?.(h),((0,ka.getWorkerIndex)()===0?console:ul.default).error(h),t.set(d.path||"/",new _l(h),null,!0),Ga.set(s?l:(0,St.basename)(e),h.message)}}if(Fa.isMainThread&&!qH&&i&&(0,ka.watchDir)(e,async()=>FH()),o.extensionModule)return await Kl((0,St.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;ll?.(new Error(l)),((0,ka.getWorkerIndex)()===0?console:ul.default).error(l),Ga.set((0,St.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,ll?.(o),t.set("",new _l(o))}}}var Bs,St,Fa,PH,WR,QR,vH,ka,ul,BH,HH,tne,xH,rne,VR,YR,qH,$R,Ga,sne,KR,MH,UH,ll,_l,af=Oe(()=>{Bs=require("fs"),St=require("path"),Fa=require("worker_threads"),PH=require("yaml"),WR=x(X()),QR=x(L());QO();XO();ZO();xv();NB();LB();vH=x(require("fast-glob")),ka=x($e()),ul=x(V());bh();Xt();BH=x(ee());Rs();be();HB();HH=x(X()),tne=x(kB());jd();oH();LH();xH=x(Mr());Xf();({readFile:rne}=Bs.promises),VR=WR.get(QR.CONFIG_PARAMS.COMPONENTSROOT),YR=new Map,Ga=new Map;a(FH,"loadComponentDirectories");sne={REST:Nf,rest:Nf,graphqlSchema:Oh,jsResource:yh,fastifyRoutes:_R,login:Ih,static:dR,operationsApi:tne,customFunctions:{},http:{},clustering:CR,authentication:Pu,mqtt:kR},KR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(KR,"static",{value:{files:"web/**"}});MH=[],UH=new Map;a(nne,"setErrorReporter");a(hE,"loadComponent");_l=class extends vt{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 HR=T((vpe,kH)=>{var{isMainThread:GH}=require("worker_threads"),{getTables:ine}=(be(),te(qe)),{loadComponentDirectories:one,loadComponent:ane}=(af(),te(of)),{resetResources:cne}=(Uu(),te(WU)),une=YT(),lne=Mr(),{dirname:_ne}=require("path"),{getConnection:dne}=rt(),fne=X(),Ene=L(),zR=new Map;async function hne(e=!1){!GH&&fne.get(Ene.CONFIG_PARAMS.CLUSTERING_ENABLED)&&dne();try{GH&&await une()}catch(s){console.error(s)}let t=cne();ine(),t.isWorker=e,await ane(_ne(lne.getConfigFilePath()),t,"hdb",!0,zR),await one(zR,t);let r=[];for(let[s]of zR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(hne,"loadRootComponents");kH.exports.loadRootComponents=hne});var $e=T((Hpe,yi)=>{"use strict";var{Worker:mne,MessageChannel:pne,parentPort:ln,isMainThread:eA,threadId:Sne,workerData:Fn}=require("worker_threads"),{PACKAGE_ROOT:Tne}=L(),{join:KH,isAbsolute:gne,extname:Rne}=require("path"),{server:WH}=(Xt(),te(Di)),{watch:Ane,readdir:One}=require("fs/promises"),{totalmem:VH}=require("os"),dl=L(),QH=X(),Gn=V(),{randomBytes:bne}=require("crypto"),{_assignPackageExport:Nne}=require("../index"),yne=L(),$H=1024*1024,Ni=[],ds=[],wne=50,tA=1e4,Ine="restart",zH="request_thread_info",JH="resource_report",jH="thread_info",XH="added-port",Cne="ack",JR;Nne("threads",ds);yi.exports={startWorker:jR,restartWorkers:sA,shutdownWorkers:Pne,workers:Ni,setMonitorListener:kne,onMessageFromWorkers:vne,onMessageByType:ix,broadcast:Hne,broadcastWithAcknowledgement:qne,setChildListenerByType:Une,getWorkerIndex:ZH,getWorkerCount:ex,getTicketKeys:rx,setMainIsWorker:Lne,setTerminateTimeout:Dne,restartNumber:Fn?.restartNumber||1};ds.onMessageByType=ix;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 rA;function Dne(e){tA=e}a(Dne,"setTerminateTimeout");function ZH(){return Fn?Fn.workerIndex:rA?0:void 0}a(ZH,"getWorkerIndex");function ex(){return Fn?Fn.workerCount:rA?1:void 0}a(ex,"getWorkerCount");function Lne(e){rA=e}a(Lne,"setMainIsWorker");var tx=1,mE;function rx(){return mE||(mE=eA?bne(48):Fn.ticketKeys,mE)}a(rx,"getTicketKeys");Object.defineProperty(WH,"workerIndex",{get(){return ZH()}});Object.defineProperty(WH,"workerCount",{get(){return ex()}});var sx={[zH](e,t){Fne(t)},[JH](e,t){Gne(t,e)}};function jR(e,t={}){let r=process.constrainedMemory?.()||VH();r=Math.min(r,VH(),2e4*$H);let s=QH.get(dl.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/$H/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of ds){let _=new pne;_.existingPort=u,i.push(_),o.push(_.port2)}Rne(e)||(e+=".js");let c=new mne(gne(e)?e:KH(Tne,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:tx=t.threadCount,name:t.name,restartNumber:yi.exports.restartNumber,ticketKeys:rx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:XH,port:u,threadId:c.threadId},[u]);return SE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>jR(e,t),c.on("error",u=>{console.error("Worker error:",u),Gn.error("Worker error:",u)}),c.on("exit",u=>{Ni.splice(Ni.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<wne?(t.unexpectedRestarts=c.unexpectedRestarts+1,jR(e,t)):Gn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{sx[u.type]?.(u,c)}),Ni.push(c),$ne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(jR,"startWorker");var Mne=[dl.THREAD_TYPES.HTTP];async function sA(e=null,t=Math.max(tx>3,1),r=!0){if(eA){if(r){let{loadRootComponents:o}=HR();await o()}yi.exports.restartNumber++,t<1&&(t=t*Ni.length);let s=[],n=[];for(let o of Ni.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Gn.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:yi.exports.restartNumber,type:dl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Mne.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),tA*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===yne.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}=Yd();r&&(e==="http"||!e)&&QH.get(dl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ln.postMessage({type:Ine,workerType:e})}a(sA,"restartWorkers");function Une(e,t){sx[e]=t}a(Une,"setChildListenerByType");function Pne(e){return sA(e,1/0,!1)}a(Pne,"shutdownWorkers");var nx=[];function vne(e){nx.push(e)}a(vne,"onMessageFromWorkers");var XR=new Map;function ix(e,t){let r=XR.get(e);r||XR.set(e,r=[]),r.push(t)}a(ix,"onMessageByType");var Bne=10;async function Hne(e){let t=0;for(let r of ds)try{r.postMessage(e),t++>Bne&&(t=0,await new Promise(setImmediate))}catch(s){Gn.error("Unable to send message to worker",s)}}a(Hne,"broadcast");var pE=new Map,xne=1;function qne(e){return new Promise(t=>{let r=0;for(let s of ds)try{let n=xne++,i=a(()=>{pE.delete(n),--r===0&&t(),s!==ln&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,pE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of pE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){Gn.error("Unable to send message to worker",n)}r===0&&t()})}a(qne,"broadcastWithAcknowledgement");function Fne(e){e.postMessage({type:jH,workers:ox()})}a(Fne,"sendThreadInfo");function ox(){let e=Date.now();return Ni.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(ox,"getChildWorkerInfo");function Gne(e,t){e.resources=t,e.resources.updated=Date.now()}a(Gne,"recordResourceReport");var ZR;function kne(e){ZR=e}a(kne,"setMonitorListener");var Vne=1e3,YH=!1;function $ne(){YH||(YH=!0,setInterval(()=>{for(let e of Ni){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}ZR&&ZR()},Vne).unref())}a($ne,"startMonitoring");var Yne=1e3;if(ln){SE(ln);for(let e=0,t=Fn.addPorts.length;e<t;e++){let r=Fn.addPorts[e];r.threadId=Fn.addThreadIds[e],SE(r)}setInterval(()=>{let e=process.memoryUsage();ln.postMessage({type:JH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Yne).unref(),JR=a(()=>new Promise((e,t)=>{ln.on("message",r),ln.postMessage({type:zH});function r(s){s.type===jH&&(ln.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else JR=ox;yi.exports.getThreadInfo=JR;function SE(e,t){ds.push(e),e.on("message",r=>{if(r.type===XH)r.port.threadId=r.threadId,SE(r.port);else if(r.type===Cne){let s=pE.get(r.id);s&&s()}else{for(let n of nx)n(r,e);let s=XR.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(SE,"addPort");if(eA){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await One(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(KH(s,i.name));try{for await(let{filename:i}of Ane(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await sA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");yi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else ln.on("message",async e=>{let{type:t}=e;t===dl.ITC_EVENT_TYPES.SHUTDOWN&&(yi.exports.restartNumber=e.restartNumber,ln.unref(),setTimeout(()=>{Gn.warn("Thread did not voluntarily terminate",Sne),process.exit(0)},tA).unref())})});var nC={};Ve(nC,{AUDIT_STORE_OPTIONS:()=>mx,createAuditEntry:()=>jl,openAuditStore:()=>AE,readAuditEntry:()=>Ct,setAuditRetention:()=>Wne,transactionKeyEncoder:()=>hx});function AE(e){let t=e.auditStore=e.openDB(dx.AUDIT_STORE_NAME,mx);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=TE){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()-nA})){if((_[0]&15)===aA){let l=Ct(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Kne){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,nA/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,RE.getWorkerIndex)()===(0,RE.getWorkerCount)()-1&&n(TE),t}function Wne(e,t=TE){nA=e,TE=t}function jl(e,t,r,s,n,i,o){let c=px[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?Va.setFloat64(0,s):Es.set(Yh),u=9),f(0),f(t),d(r),Va.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,$a.writeKey)(E,Es,u);let p=u-h-1;p>127?p>16383?(uA.error("Key or username was too large for audit entry",E),u=h+1,Es[h]=0):(Es.copyWithin(h+2,h+1,u),Va.setUint16(h,p|32768),u++):Es[h]=p}function f(E){E<128?Es[u++]=E:E<16384?(Va.setUint16(u,E|32768),u+=2):E<1056964608?(Va.setUint32(u,E|3221225472),u+=4):(Es[u]=255,Va.setUint32(u+1,E),u+=5)}}function Ct(e){try{let t=e.dataView||(e.dataView=new cA(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:px[s&7],tableId:i,get recordId(){return _x(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?_x(e,l,d):void 0},getValue(f,E,h){if(s&iA||s&oA&&!E)return f.decoder.decode(e.subarray(t.position));if(s&oA&&h)return lA(f.getEntry(this.recordId),h,f)}}}catch{return uA.error("Reading audit entry error",e),{}}}function _x(e,t,r){let s=e.subarray(t,r);return(0,$a.readKey)(s,0,r-t)}var $a,gE,dx,fx,RE,Ex,uA,Es,Va,hx,mx,nA,Kne,TE,iA,oA,ax,aA,cx,ux,lx,px,cA,Ui=Oe(()=>{$a=require("ordered-binary"),gE=x(X()),dx=x(_t()),fx=x(L()),RE=x($e()),Ex=x(J());Ho();uA=x(V());OE();(0,gE.initSync)();Es=Buffer.alloc(1024),Va=new DataView(Es.buffer,Es.byteOffset,1024),hx={writeKey(e,t,r){return e===Sc?(t.set(Sc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,$a.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,$a.readKey)(e,t,r)}},mx={encoding:"binary",keyEncoder:hx},nA=(0,Ex.convertToMS)((0,gE.get)(fx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Kne=1e3,TE=1e4;a(AE,"openAuditStore");a(Wne,"setAuditRetention");iA=16,oA=32,ax=1,aA=2,cx=3,ux=4,lx=5,px={put:ax|iA,[ax]:"put",delete:aA,[aA]:"delete",message:cx|iA,[cx]:"message",invalidate:ux,[ux]:"invalidate",patch:lx|oA,[lx]:"patch"};a(jl,"createAuditEntry");a(Ct,"readAuditEntry");cA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(_x,"readKeySafely")});var _A={};Ve(_A,{add:()=>bE,applyReverse:()=>Sx,getRecordAtTime:()=>lA,rebuildUpdateBefore:()=>NE});function bE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function NE(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,bE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function Sx(e,t){for(let r in t){let s=t[r];if(s?.__op__){let n=Qne[s.__op__]?.reverse;if(n)n(e,r,{value:s.value});else throw new Error(`Unsupported operation ${s.__op__}`)}else e[r]=Tx}}function lA(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":Sx(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===Tx&&(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 Qne,Tx,OE=Oe(()=>{Ui();a(bE,"add");bE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Qne={add:bE};a(NE,"rebuildUpdateBefore");a(Sx,"applyReverse");Tx={};a(lA,"getRecordAtTime")});function Vr(e){return e[wt]||(e[wt]=Object.create(null))}function DE(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[Ne])},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}`);Vr(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}`);Vr(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}`);Vr(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}`);Vr(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}`);Vr(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}`);Vr(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}`);Vr(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}`);Vr(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}`);Vr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Vr(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}`);Vr(this)[c]=l},"set")}_={get(){let l=this[wt];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[he]?.[c];return f.update(E)}return f}let d=this[he]?.[c];if(d&&typeof d=="object"){let f=Rx(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[he]?.[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");Vr(this)[o]=c}),i("deleteProperty",function(o){Vr(this)[o]=void 0}),i("toJSON",function(){let o=this[wt],c;for(let _ in o){c||(c=Object.assign({},this[he]));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[he])),Object.assign(c,this)),c||this[he]}),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 Rx(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?.[he])throw new Error("Can not track an already tracked object, check for circular references");this[he]=n}},DE(r,t)),new r(e)):new yE(e);case Array:let s=new IE(e.length);s[he]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=Rx(o,t?.elements)),s[n]=o}return s;default:return e}}function W_(e){let t=e[wt],r;for(let n in t){r||(r=Object.assign({},e[he]));let i=t[n];if(i&&typeof i=="object")if(i.__op__){let o=r[n];i=i.update(o)}else i=W_(i);r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[he])),Object.assign(r,e)),r||e[he]}function yo(e,t=e[wt]){let r;if(gx.call(e,he)&&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=yo(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[he]));let n=t[s];if(n&&typeof n=="object")if(n.__op__){let i=_A[n?.__op__];if(i)i(r,s,n);else throw new Error("Invalid CRDT operation "+n.__op__);continue}else n=yo(n);r[s]=n}return r?Object.freeze(r):gx.call(e,he)?e[he]:e}function wE(e){let t=e[he];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[No]||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?.[he]===n){if(wE(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[he]===i){if(wE(n))return!0}else return!0}else return!0}}return!1}var hs,wt,yE,gx,No,IE,CE,Q_=Oe(()=>{Rs();hs=x(ee());OE();wt=Symbol("own-data");a(Vr,"getChanges");a(DE,"assignTrackedAccessors");a(Rx,"trackObject");yE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[he])throw new Error("Can not track an already tracked object, check for circular references");this[he]=t}};DE(yE,{});a(W_,"collapseData");gx=Object.prototype.hasOwnProperty;a(yo,"deepFreeze");a(wE,"hasChanges");No=Symbol.for("has-array-changes"),IE=class extends Array{static{a(this,"TrackedArray")}[No];constructor(t){super(t)}splice(...t){return this[No]=!0,super.splice(...t)}push(...t){return this[No]=!0,super.push(...t)}pop(){return this[No]=!0,super.pop()}unshift(...t){return this[No]=!0,super.unshift(...t)}shift(){return this[No]=!0,super.shift()}};IE.prototype.constructor=Array;CE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Rp={};Ve(Rp,{CONTEXT:()=>Ne,ID_PROPERTY:()=>Me,IS_COLLECTION:()=>ms,RECORD_PROPERTY:()=>he,Resource:()=>vt,snake_case:()=>Jne,transformForSelect:()=>ME});function Jne(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Ax(e,t){if(fl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(fl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),s=new fA;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){fl=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function $r(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[Ne]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Ne]||i):l=i:(l=n,c=l[Me]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ne]||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 d.resetTransaction=!0,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 LE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new LE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Yr(e,t){let r=new Nx.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 dA(e,t,r){let s=e[he];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[Ne],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):dA(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(dA(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(dA(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 Ox,bx,Nx,Ne,Me,ms,he,zne,vt,LE,fl,fA,Rs=Oe(()=>{Ox=require("crypto");dc();bx=require("../index"),Nx=x(ee());Q_();Ji();Of();Ne=Symbol.for("context"),Me=Symbol.for("primary-key"),ms=Symbol("is-collection"),he=Symbol("stored-record"),zne={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},vt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Me]=t;let s=r?.[Ne];this[Ne]=s!==void 0?s:r||null}static get=$r(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",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=$r(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):Yr(t,"put")},{hasContent:!0,type:"update"});static patch=$r(function(t,r,s,n){return t.patch?t.patch(n,r):Yr(t,"patch")},{hasContent:!0,type:"update"});static delete=$r(function(t,r,s,n){return t.delete?t.delete(r):Yr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,Ox.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),ze(s,()=>{let i=new this(n,s),o=i.update?i.update(r):Yr(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=$r(function(t,r,s,n){return t.invalidate?t.invalidate(r):Yr(t,"delete")},{hasContent:!1,type:"update"});static post=$r(function(t,r,s,n){return t[Me]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=$r(function(t,r,s,n){return t.connect?t.connect(n,r):Yr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=$r(function(t,r,s,n){return t.subscribe?t.subscribe(r):Yr(t,"subscribe")},{type:"read"});static publish=$r(function(t,r,s,n){return t[Me]!=null&&t.update?.(),t.publish?t.publish(n,r):Yr(t,"publish")},{hasContent:!0,type:"create"});static search=$r(function(t,r,s,n){let i=t.search?t.search(r):Yr(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=$r(function(t,r,s,n){return t.search?t.search(n,r):Yr(t,"search")},{hasContent:!0,type:"read"});static copy=$r(function(t,r,s,n){return t.copy?t.copy(n,r):Yr(t,"copy")},{type:"create"});static move=$r(function(t,r,s,n){return t.move?t.move(n,r):Yr(t,"move")},{type:"delete"});post(t){if(this[ms])return this.constructor.create(this[Me],t,this[Ne]);Yr(this,"post")}static isCollection(t){return t?.[ms]}static coerceId(t){return t}static parseQuery(t){return Af(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:Ax(t,this),isCollection:fl}}let i=Ax(t,this);return fl?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[Ne],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[Me]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Me],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[ms]=!0),n}subscribe(t){return new gs}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new gs}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Me]}getContext(){return this[Ne]}};vt.prototype[Ne]=null;(0,bx._assignPackageExport)("Resource",vt);a(Jne,"snake_case");LE=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(Ax,"pathToId");fA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a($r,"transactional");a(Yr,"missingMethod");a(dA,"selectFromObject");a(ME,"transformForSelect")});function wx(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;Ya||((0,UE.onMessageByType)(yx,l=>{Ix(l.path)}),Ya=Object.create(null));let o=Ya[n]||(Ya[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=pa(t);let u=new hA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function Ix(e,t){if(!Ya)return;let r=Ya[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=pa(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,EA.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,EA.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 Cx(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,UE.broadcast)({type:yx,path:n}),Ix(n,!0)})}}var EA,UE,yx,Ya,iSe,hA,Dx=Oe(()=>{EA=x(V()),UE=x($e());dc();Uu();Ui();yx="transaction",iSe=Buffer.alloc(4096);a(wx,"addSubscription");hA=class extends gs{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(Ix,"notifyFromTransactionData");a(Cx,"listenToCommits")});var Qg={};Ve(Qg,{coerceType:()=>PE,makeTable:()=>HE,setServerUtilities:()=>iie,updateResource:()=>vE});function HE(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=[]),Cx(i,u);let S=Qh(i,s,u),O=0,g,R,B={},H=Promise.resolve(),v,U,Y;for(let K of p)(K.assignCreatedTime||K.name==="__createdtime__")&&(v=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(U=K),K.expiresAt&&(Y=K),K.isPrimaryKey&&(B=K);let W,z=[],ne=[],Te=1,oe=2,xe={},de={},It=864e5,Dl,Ll,$n,BA=!1,eh,Pq=i.getRange({start:!1,end:!1}).constructor,vq=10,Bq=6;E&&qA();class Je extends vt{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,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),R=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(w=>{let y=this.sources.slice(0,-1);if(y=y.filter(P=>P[w]&&(!P[w].reliesOnPrototype||P.prototype[w])),y.length>0)if(y.length===1){let P=y[0];return(M,D,q)=>{if(M?.source!==P)return P[w](D,q,M)}}else return(P,M,D)=>{let q=[];for(let G of y){if(P?.source===G)break;q.push(G[w](M,D,P))}return Promise.all(q)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1],N=a(w=>{if(b[w]&&(!b[w].reliesOnPrototype||b.prototype[w]))return(y,P,M)=>{if(!y?.source)return b[w](P,M,y)}},"getApplyToCanonicalSource");return xe={put:N("put"),patch:N("patch"),delete:N("delete"),publish:N("publish")},de={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let w=!1,y=a(async(P,M)=>{let D=P.value,q=P.table?tt[c][P.table]:Je;if(c===Hs.SYSTEM_SCHEMA_NAME&&(P.table===Hs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||P.table===Hs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(w=!0),P.id===void 0&&(P.id=D[q.primaryKey],P.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(P));P.source=m;let G=await q.getResource(P.id,M,Ka);switch(P.type){case"put":return G._writeUpdate(D,!0,Ka);case"patch":return G._writeUpdate(D,!1,Ka);case"delete":return G._writeDelete(Ka);case"publish":return G._writePublish(D,Ka);case"invalidate":return G.invalidate(Ka);default:Xe.error("Unknown operation",P.type,P.id)}},"writeUpdate");try{let P=m.subscribe;P&&h==null&&(h=!0);let M=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Io.getWorkerIndex)()):(0,Io.getWorkerIndex)()===0,D=P&&M&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let q;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){Xe.error("Bad subscription event",G);continue}if(G.source=m,q)if(G.beginTxn)q.resolve();else{y(G,q);continue}if(G.type==="end_txn")continue;let ae=ze(G,()=>{if(G.type==="transaction"){let re=[];for(let ce of G.writes)try{re.push(y(ce,G))}catch(ve){throw ve.message+=" writing "+JSON.stringify(ce)+" of event "+JSON.stringify(G),ve}return Promise.all(re)}else if(G.type==="define_schema"){let re=this.attributes.slice(0),ce;for(let ve of G.attributes)re.find(se=>se.name===ve.name)||(re.push(ve),ce=!0);ce&&(at({table:n,database:c,attributes:re,origin:"cluster"}),gl.signalSchemaChange(new Rl.SchemaEventMsg(process.pid,Hs.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return G.beginTxn?(q=G,y(G,G),new Promise(re=>{q.resolve=re})):y(G,G)});w&&(await ae,gl.signalUserChange(new Rl.UserEventMsg(process.pid))),G.onCommit&&(ae?.then?ae.then(G.onCommit):G.onCommit())}catch(ie){Xe.error("error in subscription handler",ie)}}}catch(P){Xe.error(P)}})(),this}static getResource(m,A,I){let b=super.getResource(m,A,I);if(m!=null){ja(m);try{if(b.hasOwnProperty(he))return b;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let N=!I?.async||i.cache?.get(m),w=gr(A),y=w.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return th(m,A,{transaction:y},N,P=>{if(P?vE(b,P):b[he]=null,A.onlyIfCached&&A.noCacheStore){if(!b.doesExist())throw new ps.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let M=rh(m,P,A,b);if(M)return w?.disregardReadTxn(),b[mA]=!0,SA(M,D=>(vE(b,D),b))}return b})}catch(N){throw N.message.includes("Unable to serialize object")&&(N.message+=": "+JSON.stringify(m)),N}}return b}ensureLoaded(){let m=rh(this[Me],this[Kr],this[Ne]);if(m)return this[mA]=!0,SA(m,A=>{this[Kr]=A,this[he]=A.value,this[Sl]=A.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,nh()}static enableAuditing(m=!0){E=m,m&&qA(),Je.audit=m}static coerceId(m){return m===""?null:PE(m,B)}static async dropTable(){if(delete tt[c][n],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));gl.signalSchemaChange(new Rl.SchemaEventMsg(process.pid,Hs.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[Me]===null){if(m?.conditions)return this.search(m);let A=Je.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:n,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ne]?.returnNonexistent)return this}allowRead(m,A){let I=Ul(m);if(I?.read){if(I.isSuperUser)return!0;let b=I.attribute_permissions,N=A?.select;if(b?.length>0||BA&&N){if(A||(A={}),N){let w=b?.length>0&&pA(b,"read");A.select=N.map(y=>{let P=y.name||y;if(!w||w[P]){let M=$n[P]?.definition?.tableClass;if(M){if(y.name||(y={name:y}),!M.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else A.select=b.filter(w=>w.read&&!$n[w.attribute_name]).map(w=>w.attribute_name);return A}else return!0}}allowUpdate(m,A){let I=Ul(m);if(I?.update){let b=I.attribute_permissions;if(b?.length>0){let N=pA(b,"update");for(let w in A)if(!N[w])return!1;for(let w of b){let y=w.attribute_name;!w.update&&!(y in A)&&(A[y]=this.getProperty(y))}}return!0}}allowCreate(m,A){if(this[ms]){let I=Ul(m);if(I?.insert){let b=I.attribute_permissions;if(b?.length>0){let N=pA(b,"insert");for(let w in A)if(!N[w])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Ul(m)?.delete}update(m,A){if(!gr(this[Ne]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let b;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[he]={},this[wt]=m):(b=this[wt],b&&(m=Object.assign(b,m)),this[wt]=b=m)),this._writeUpdate(this[wt],A),this}addTo(m,A){if(typeof A=="number")this[El]===Mx?this.set(m,(+this.getProperty(m)||0)+A):(this[El]||this.update(),this.set(m,new CE(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let A=this[Ne],I=this[Me];ja(I),gr(this[Ne]).addWrite({key:I,store:i,invalidated:!0,entry:this[Kr],nodeName:this[Ne]?.nodeName,before:xe.invalidate?.bind(this,A,I),beforeIntermediate:de.invalidate?.bind(this,A,I),commit:(N,w)=>{if(w?.version>N)return;let y=null;for(let P in r)y||(y={}),y[P]=this.getProperty(P);S(I,y,this[Kr],N,hl,E,this[Ne],0,"invalidate")}})}static evict(m,A,I){let b=this.Source,N;if(!((R||E)&&(!A||(N=i.getEntry(m),!N||!A)||N.version!==I))){if(R){if(i.hasLock(m,N.version))return;let w;for(let y in r)w||(w={}),w[y]=A[y];if(w)return S(m,w,N,I,ml,null,null,0,null,!0)}return i.ifVersion(I,()=>{Ml(m,A,null)}),E?S(m,null,N,I,ml,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=n,m.schema||=c,xx.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,I){let b=this[Ne],N=gr(b),w=this[Me];ja(w);let y=this[Kr];this[El]=A?Mx:rie;let P={key:w,store:i,entry:y,nodeName:b?.nodeName,validate:M=>{m||(m=this[wt]),A||m&&wE(m)?(this.validate(m,!A),b?.source||(U&&(m[U.name]=U.type==="Date"?new Date(M):U.type==="String"?new Date(M).toISOString():M),A&&(t&&m[t]!==w&&(m[t]=w),v&&(y?.value?m[v.name]=y?.value[v.name]:m[v.name]=v.type==="Date"?new Date(M):v.type==="String"?new Date(M).toISOString():M),m=yo(m)))):N.removeWrite(P)},before:A?xe.put?()=>xe.put(b,w,m):null:xe.patch?()=>xe.patch(b,w,m):xe.put?()=>xe.put(b,w,yo(this)):null,beforeIntermediate:A?de.put?()=>de.put(b,w,m):null:de.patch?()=>de.patch(b,w,m):de.put?()=>de.put(b,w,yo(this)):null,commit:(M,D,q)=>{if(q){if(b&&D?.version>(b.lastModified||0)&&(b.lastModified=D.version),this[Kr]=D,D?.value?.[he])throw new Error("Can not assign a record to a record, check for circular references");A||(this[he]=D?.value??null)}this[wt]=m,this[Sl]=M;let G=D?.value,ie=m;if(this[El]=0,D?.version>=M)if(E){let ve=D.localTime,se=D.version;for(;ie&&(ve>M||se>=M&&ve>0);){let fe=u.get(ve),Z=Ct(fe);if(se=Z.version,se>M){if(Z.type==="patch"){let le=Z.getValue(i);ie=NE(ie,le)}else if(Z.type==="put"||Z.type==="delete")return}else if(se===M)return;ve=Z.previousLocalTime}}else{if(A)return;ie=NE(ie,G)}let ae;if(A?ae=ie:(this[he]=G,ae=A?ie:yo(this,ie)),this[he]=ae,ae?.[he])throw new Error("Can not assign a record to a record, check for circular references");let re;A||(re=m),Ml(w,G,ae);let ce=A?"put":"patch";S(w,ae,D,M,0,E,b,b.expiresAt||(d?d+Date.now():0),ce,!1,re)}};N.addWrite(P)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[ms]){for await(let A of this.search(m))(await Je.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[he]?this._writeDelete(m):!1}_writeDelete(m){let A=gr(this[Ne]),I=this[Me];ja(I);let b=this[Ne];return A.addWrite({key:I,store:i,resource:this,nodeName:b?.nodeName,before:xe.delete?.bind(this,b,I),beforeIntermediate:de.delete?.bind(this,b,I),commit:(N,w,y)=>{let P=w?.value;y&&(b&&w?.version>(b.lastModified||0)&&(b.lastModified=w.version),vE(this,w)),!(w?.version>N)&&(Ml(this[Me],P),Xe.trace("Write delete entry",I,N),E||h?(S(I,null,this[Kr],N,0,E,this[Ne],0,"delete"),E||nh()):i.remove(this[Me]))}}),!0}search(m){let A=this[Ne],I=gr(A);if(!m)throw new Error("No query provided");let b=m.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Me]&&(b=[{attribute:null,comparator:"prefix",value:this[Me]}].concat(b));let N,w={};function y(Z,le){let Tt;switch(le){case"and":case void 0:if(Z.length<1)throw new Error('An "and" operator requires at least one condition');Tt=!0;break;case"or":if(Z.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+le)}let xs=Tt&&{},qs;for(let je of Z){if(je.conditions){je.conditions=y(je.conditions,je.operator);continue}let Rr=je[0]??je.attribute,Jr=Rr==null?B:Pn(p,Rr);if(Jr){if(Tt){let Ar=Us(Rr),Fs=xs[Ar];Fs?(Fs.push(je),qs=!0):xs[Ar]=[je]}(Jr.type||gg[je.comparator])&&(je[1]===void 0?je.value=M(je.value,Jr):je[1]=M(je[1],Jr))}else if(Rr!=null)throw(0,ps.handleHDBError)(new Error,`${Rr} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return Z;if(qs)for(let je in xs){let Rr=xs[je],Jr=Rr.length;if(Jr>1)for(let Ar=0;Ar<Jr;Ar++){let Fs=Rr[Ar];if(Fs.comparator==="ge"||Fs.comparator==="greater_than_equal")for(let Yn=0;Yn<Jr;Yn++){let Mo=Rr[Yn];(Mo.comparator==="le"||Mo.comparator==="less_than_equal")&&(Fs.comparator="between",Fs.value=[Fs.value,Mo.value],Z.splice(Z.indexOf(Mo),1))}if(Fs.comparator==="equals"||!Fs.comparator){for(let Yn=0;Yn<Jr;Yn++)if(Yn!==Ar){let Mo=Rr[Yn];Z.splice(Z.indexOf(Mo),1)}break}}}return Z}a(y,"prepareConditions");function P(Z,le){if(m.enforceExecutionOrder)return Z;for(let Tt of Z)Tt.conditions&&(Tt.conditions=P(Tt.conditions,Tt.operator));return Z.length>1&&le!=="or"?(0,Hx.sortBy)(Z,Rf(Je)):Z}a(P,"orderConditions");function M(Z,le){return Array.isArray(Z)?Z.map(Tt=>PE(Tt,le)):PE(Z,le)}a(M,"coerceTypedValues");let D=m.operator;(b.length>0||D)&&(b=y(b,D));let q=typeof m.sort=="object"&&m.sort,G;if(q&&D!=="or"){let Z=q.attribute;if(N=b.find(le=>Us(le.attribute)===Us(Z)),!N){if(!Pn(p,Z))throw(0,ps.handleHDBError)(new Error,`${Array.isArray(Z)?Z.join("."):Z} is not a defined attribute`,404);N={attribute:Z,comparator:"sort"},b.push(N)}N.descending=!!q.descending}b=P(b,D),q&&(b[0]===N?q.next&&(G={dbOrderedAttribute:q.attribute,attribute:q.next.attribute,descending:q.next.descending,next:q.next.next}):(N&&b.splice(b.indexOf(N),1),G=q));let ie=m.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:b,operator:D,postOrdering:G,selectApplied:!!ie};let ae=I.useReadTxn(),re=Rg(b,D,Je,ae,m,A,(Z,le)=>HA(Z,ie,A,le),w),ce=m.ensureLoaded!==!1;G||(re=fe(re));let ve=Je.transformEntryForSelect(ie,A,w,ce,!0),se=Je.transformToOrderedSelect(re,ie,G,A,ve);function fe(Z){return m.offset||m.limit!==void 0?Z.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):Z}return a(fe,"applyOffset"),G&&(se=fe(se)),se.onDone=()=>{se.onDone=null,I.doneReadTxn()},se.selectApplied=!0,se.getColumns=()=>{if(ie){let Z=[];for(let le of ie)le==="*"?Z.push(...p.map(Tt=>Tt.name)):Z.push(le.name||le);return Z}return p.map(Z=>Z.name)},se}static transformToOrderedSelect(m,A,I,b,N){let w=new Pq;if(I){m=HA(m,A,b,null);let y;w.iterate=function(){let M,D=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),q,G=I.dbOrderedAttribute,ie,ae,re=!0;function ce(se){let fe=se.next&&ce(se.next),Z=se.descending;return(le,Tt)=>{let xs=sh(le,se.attribute,b),qs=sh(Tt,se.attribute,b),je=Z?(0,Co.compareKeys)(qs,xs):(0,Co.compareKeys)(xs,qs);return je===0?fe?.(le,Tt)||0:je}}a(ce,"createComparator");let ve=ce(I);return{async next(){let se;if(M)if(se=M.next(),se.done){if(q)return w.onDone&&w.onDone(),se}else return{value:await N(se.value)};y=[],ie&&y.push(ie);do if(se=await D.next(),se.done){if(q=!0,y.length)break;return w.onDone&&w.onDone(),se}else{let fe=se.value;if(fe?.then&&(fe=await fe),G){let Z=sh(fe,G,b);if(re)re=!1,ae=Z;else if(Z!==ae){ae=Z,ie=fe;break}}y.push(fe)}while(!0);return I.isGrouped,y.sort(ve),M=y[Symbol.iterator](),se=M.next(),se.done?(w.onDone&&w.onDone(),se):{value:await N(se.value)}},return(){w.onDone&&w.onDone(),D.return()},throw(){w.onDone&&w.onDone(),D.throw()}}};let P=a(M=>{if(typeof A=="object"&&Array.isArray(M.attribute))for(let D=0;D<A.length;D++){let q=A[D],G;if(q.name===M.attribute[0]){for(G=q.sort||(q.sort={});G.next;)G=G.next;G.attribute=M.attribute.slice(1),G.descending=M.descending}else q===M.attribute[0]&&(A[D]=G={name:q,sort:{attribute:M.attribute.slice(1),descending:M.descending}})}M.next&&P(M.next)},"applySortingOnSelect");P(I)}else w.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),w=w.map(N);return w}static transformEntryForSelect(m,A,I,b,N){if(m&&(m===t||m?.length===1&&m[0]===t)){let M=a(D=>D?.key??D,"transform");return m===t?M:m.asArray?D=>[M(D)]:D=>({[t]:M(D)})}let w;b&&R&&!m?.every(M=>{let D;return typeof M=="object"?D=M.name:D=M,r[D]||D===t})&&(w=!0);let y,P=a(M=>{let D;if(M!=null){if(eh=M,D=M.value||M.deref?.(),!D&&(M.key===void 0||M.deref)){if(M=th(M.key??M,A,{transaction:gr(A).getReadTxn(),lazy:m?.length<4},!1,q=>q),M?.then)return M.then(P);D=M?.value}if(w&&(M.metadataFlags&(hl|ml)||M.expiresAt&&M.expiresAt<Date.now())){let q=rh(M.key??M,M,A);if(q?.then)return q.then(P)}}if(D==null)return N?wo.SKIP:D;if(m&&!(m[0]==="*"&&m.length===1)){let q,G=a((ae,re)=>{let ce;typeof ae=="object"?ce=ae.name:ce=ae;let ve=$n?.[ce],se;if(ve){let fe=I?.[ce];if(fe)if(fe.hasMappings){let le=ve.from?D[ve.from]:Us(M.key);se=fe.get(le),se||(se=[])}else se=fe.fromRecord?.(D);else se=ve(D,A,M);let Z=a(le=>{if(le&&typeof le=="object"){let Tt=ve.definition?.tableClass||Je;y||(y={});let xs=y[ce]||(y[ce]=Tt.transformEntryForSelect(ce===ae?null:ae.select||(Array.isArray(ae)?ae:null),A,fe,b));if(Array.isArray(le)){let qs=[],je=Tt.transformToOrderedSelect(le,ae.select,typeof ae.sort=="object"&&ae.sort,A,xs)[Symbol.asyncIterator](),Rr=a(Ar=>{for(;!Ar.done;){if(Ar?.then)return Ar.then(Rr);qs.push(Ar.value),Ar=je.next()}re(qs,ce)},"nextValue"),Jr=Rr(je.next());Jr&&(q||(q=[]),q.push(Jr));return}else if(le=xs(le),le?.then){q||(q=[]),q.push(le.then(qs=>re(qs,ce)));return}}re(le,ce)},"handleResolvedValue");se?.then?(q||(q=[]),q.push(se.then(Z))):Z(se);return}else se=D[ce],se&&typeof se=="object"&&ce!==ae&&(se=this.transformEntryForSelect(ae.select||ae,A,null)({value:se}));re(se,ce)},"selectAttribute"),ie;if(typeof m=="string")G(m,ae=>{ie=ae});else if(Array.isArray(m))if(m.asArray)ie=[],m.forEach((ae,re)=>{ae==="*"?m[re]=D:G(ae,ce=>ie[re]=ce)});else{ie={};let ae=m.forceNulls;for(let re of m)if(re==="*")for(let ce in D)ie[ce]=D[ce];else G(re,(ce,ve)=>{ce===void 0&&ae&&(ce=null),ie[ve]=ce})}else throw new ps.ClientError("Invalid select"+m);return q?Promise.all(q).then(()=>ie):ie}return D},"transform");return P}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||at({table:n,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let A=!m.rawEvents,I=wx(Je,this[Me]??null,function(y,P,M,D){try{let q=P.getValue?.(i,A);if(!q&&P.type==="patch"&&A){let G=i.getEntry(y);G?.version===P.version?q=G.value:q=P.getValue?.(i,!0,M),P.type="put"}this.send({id:y,timestamp:M,value:q,version:P.version,type:P.type,beginTxn:D})}catch(q){Xe.error(q)}},m.startTime||0,this[ms]);this[ms]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let b=this[Me],N=m.previousCount;N>1e3&&(N=1e3);let w=m.startTime;if(this[ms]){if(w){if(N)throw new ps.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:P}of u.getRange({start:w,exclusiveStart:!0})){let M=Ct(P);if(M.tableId!==s)continue;let D=M.recordId;(b==null||vx(b,D))&&I.send({id:D,timestamp:y,...M}),I.startTime=y}}else if(N){let y=[];for(let{key:P,value:M}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ct(M);if(D.tableId!==s)continue;let q=D.recordId;if(b==null||vx(b,q)){let G=D.getValue(i,A,P);if(y.push({id:q,timestamp:P,value:G,version:D.version,type:D.type}),--N<=0)break}}catch(D){Xe.error("Error getting history entry",P,D)}for(let P=y.length;P>0;)I.send(y[--P]);y[0]&&(I.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:P,version:M,localTime:D}of i.getRange({start:b??!1,end:b==null?void 0:[b,Co.MAXIMUM_KEY],versions:!0}))P&&I.send({id:y,version:M,timestamp:D,value:P})}else{N&&!w&&(w=0);let y=this[Kr]?.localTime;if(y===Wh&&(i.cache?.delete(b),this[Kr]=i.getEntry(b),Xe.trace("re-retrieved record",y,this[Kr]?.localTime),y=this[Kr]?.localTime),Xe.trace("Subscription from",w,"from",b,y),w<y){let P=[],M=y;do{let D=u.get(M);if(D){m.omitCurrent=!0;let q=Ct(D),G=q.getValue(i,A,M);A&&(q.type="put"),P.push({id:b,value:G,timestamp:M,...q}),M=q.previousLocalTime}else break;N&&N--}while(M>w&&N!==0);for(let D=P.length;D>0;)I.send(P[--D]);I.startTime=y}!m.omitCurrent&&this.doesExist()&&I.send({id:b,version:this[Sl],timestamp:y,value:this})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[he]||this[El])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let I=gr(this[Ne]),b=this[Me]||null;ja(b);let N=this[Ne];I.addWrite({key:b,store:i,entry:this[Kr],nodeName:N?.nodeName,validate:()=>{this.validate(m)},before:xe.publish?.bind(this,N,b,m),beforeIntermediate:de.publish?.bind(this,N,b,m),commit:(w,y,P)=>{y===void 0&&h&&!E&&nh(),S(b,y?.value??null,y,y?.version||w,0,!0,N,y?.expiresAt,"message",!1,m)}})}validate(m,A){let I,b=a((N,w,y)=>{if(w.type&&N!=null)if(A&&N.__op__&&(N=N.value),w.properties){typeof N!="object"&&(I||(I=[])).push(`Property ${y} must be an object${w.type?" ("+w.type+")":""}`);let P=w.properties;for(let M=0,D=P.length;M<D;M++){let q=P[M],G=b(N[q.name],q,y+"."+q.name);G&&(N[q.name]=G)}}else switch(w.type){case"Int":(typeof N!="number"||N>>0!==N)&&(I||(I=[])).push(`Property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof N!="number"||!(Math.floor(N)===N&&Math.abs(N)<=9007199254740992))&&(I||(I=[])).push(`Property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof N!="number"&&(I||(I=[])).push(`Property ${y} must be a number`);break;case"ID":typeof N=="string"||N?.length>0&&N.every?.(P=>typeof P=="string")||(I||(I=[])).push(`Property ${y} must be a string, or an array of strings`);break;case"String":typeof N!="string"&&(I||(I=[])).push(`Property ${y} must be a string`);break;case"Boolean":typeof N!="boolean"&&(I||(I=[])).push(`Property ${y} must be a boolean`);break;case"Date":if(!(N instanceof Date)){if(typeof N=="string"||typeof N=="number")return new Date(N);(I||(I=[])).push(`Property ${y} must be a Date`)}break;case"BigInt":if(typeof N!="bigint"){if(typeof N=="string"||typeof N=="number")return BigInt(N);(I||(I=[])).push(`Property ${y} must be a bigint`)}break;case"Bytes":N instanceof Uint8Array||(I||(I=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(N)){if(w.elements)for(let P=0,M=N.length;P<M;P++){let D=N[P],q=b(D,w.elements,y+"[*]");q&&(N[P]=q)}}else(I||(I=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break}w.nullable===!1&&N==null&&(I||(I=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let N=0,w=p.length;N<w;N++){let y=p[N];if(!y.relationship&&(!A||y.name in m)){let P=b(m[y.name],y,y.name);P&&(m[y.name]=P)}}if(I)throw new ps.ClientError(I.join(". "))}getUpdatedTime(){return this[Sl]}wasLoadedFromSource(){return R?!!this[mA]:void 0}static async addAttributes(m){let A=p.slice(0);for(let I of m){if(!I.name)throw new ps.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new ps.ClientError("Attribute names cannot include backticks or forward slashes");A.push(I)}return at({table:n,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static async removeAttributes(m){let A=p.filter(I=>!m.includes(I.name));return at({table:n,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,I=5e3,b=1e3,N;A>I&&!m?.exactCount&&(N=b);let w=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:N}))y!=null&&w++;if(N){let y=w;w=0;for(let{value:ce}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:N}))ce!=null&&w++;let P=N*2,M=(w+y)/P,D=Math.pow((w-y+1)/N/2,2)+M*(1-M)/P,q=Math.max(Math.sqrt(D)*A,1),G=Math.round(M*A),ie=Math.max(G-1.96*q,0),ae=Math.min(G+1.96*q,A),re=Math.pow(10,Math.round(Math.log10(q)));return re>G&&(re=re/10),w=Math.round(G/re)*re,{recordCount:w,estimatedRange:[Math.round(ie),Math.round(ae)]}}return{recordCount:w}}static updatedAttributes(){$n=this.propertyResolvers={$id:(m,A,I)=>({value:I.key}),$updatedtime:(m,A,I)=>I.version,$record:(m,A,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),BA=!0,A.to)m.elements?.definition?($n[m.name]=m.resolve=(I,b,N)=>{let w=I[A.from?A.from:t],y=m.elements.definition.tableClass;return N?wa({attribute:A.to,value:w},gr(b).getReadTxn(),!1,y).asArray:y.search([{attribute:A.to,value:w}],b).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${n}" must have an array type referencing a table as the elements`);else if(A.from){let I=m.definition||m.elements?.definition;I?($n[m.name]=m.resolve=(b,N,w)=>{let y=b[A.from];if(y!==void 0){if(m.elements){let P,M=y.map(D=>{let q=w?I.tableClass.primaryStore.getEntry(D,{transaction:gr(N).getReadTxn()}):I.tableClass.get(D,N);return q?.then&&(P=!0),q});return A.filterMissing?P?Promise.all(M).then(D=>D.filter(Bx)):M.filter(Bx):P?Promise.all(M):M}return w?I.tableClass.primaryStore.getEntry(y,{transaction:gr(N).getReadTxn()}):I.tableClass.get(y,N)}},m.set=(b,N)=>{if(Array.isArray(N)){let w=N.map(y=>y[Me]||y[I.tableClass.primaryKey]);b[A.from]=w}else{let w=N[Me]||N[I.tableClass.primaryKey];b[A.from]=w}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.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`)}DE(this,this)}static async deleteHistory(m=0){let A;for(let{key:I,value:b}of u.getRange({start:0,end:m}))await pl(),Ct(b).tableId===s&&(A=u.remove(I));await A}static async*getHistory(m=0,A=1/0){for(let{key:I,value:b}of u.getRange({start:m,end:A})){await pl();let N=Ct(b);N.tableId===s&&(yield{id:N.recordId,localTime:I,version:N.version,type:N.type,value:N.getValue(i,!0,I),user:N.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return A;let b=I.localTime;if(!b)throw new Error("The entry does not have a local audit time");let N=0;do{await pl();let w=u.get(b);if(w){let y=Ct(w);A.push({id:y.recordId,localTime:b,version:y.version,type:y.type,value:y.getValue(i,!0,b),user:y.user}),b=y.previousLocalTime}else break}while(N<1e3&&b);return A.reverse()}static cleanup(){W?.remove()}}Je.updatedAttributes();let Hq=Je.prototype;return Hq[tie]=!0,d&&Je.setTTLExpiration(d/1e3),Y&&xq(),Je;function Ml(K,m,A){let I;for(let b in r){let N=r[b],w=N.isIndexing,y=A?.[b],P=m?.[b];if(y===P&&!w)continue;I=!0;let M=N.indexNulls,D=(0,Tl.getIndexedValues)(P,M);if(D){Lx&&N.prefetch(D.map(q=>({key:q,value:K})),Px);for(let q=0,G=D.length;q<G;q++)N.remove(D[q],K)}if(D=(0,Tl.getIndexedValues)(y,M),D){Lx&&N.prefetch(D.map(q=>({key:q,value:K})),Px);for(let q=0,G=D.length;q<G;q++)N.put(D[q],K)}}return I}a(Ml,"updateIndices");function ja(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>Ux)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Co.writeKey)(K,sie,0)>Ux)throw new Error("Primary key size is too large: "+K.length);return!0}a(ja,"checkValidId");function th(K,m,A,I,b){let N=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return b(null,K);let w=i.getEntry(K,A);return w&&m&&(w?.version>(m.lastModified||0)&&(m.lastModified=w.version),w?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=w.localTime)),b(w,K)},"whenPrefetched");return I?N():Te>0?(Te--,N()):new Promise((w,y)=>{Te===0?(Te--,i.prefetch([K],()=>{P(),M()})):(z.push(K),ne.push(M),z.length>Bq&&(Te--,P()));function P(){if(z.length>0){let D=ne;i.prefetch(z,()=>{Te===-1?P():Te++;for(let q of D)q()}),z=[],ne=[],oe>2&&oe--}else Te=oe,oe<vq&&oe++}a(P,"prefetch");function M(){try{w(N())}catch(D){y(D)}}a(M,"load")})}a(th,"loadLocalRecord");function Ul(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return nie;let A=m[c],I,b=A?.tables;if(b)return b[n];if(c==="data"&&(I=m[n])&&!I.tables)return I}a(Ul,"getTablePermissions");function rh(K,m,A,I){if(R){let b;if(A.noCache?b=!0:(m?(!m.value||m.metadataFlags&(hl|ml)||m.expiresAt&&m.expiresAt<Date.now())&&(b=!0):b=!0,ts(!b,"cache-hit",n)),b){let N=xA(K,m,A).then(w=>(w?.value?.[he]&&Xe.error("Can not assign a record with a record property"),A&&(w?.version>(A.lastModified||0)&&(A.lastModified=w.version),A.lastRefreshed=Date.now()),w));if(A?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(N.catch(w=>Xe.warn(w)),A?.onlyIfCached&&!I.doesExist())throw new ps.ServerError("Entry is not cached",504);return}else return N}}}a(rh,"ensureLoadedFromSource");function gr(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new zi,m.lmdbDb=i,m;m=A}while(!0)}else return new Y_}a(gr,"txnForContext");function sh(K,m,A){if(!K)return;eh=K;let I=K.value||K.deref?.()||(eh=i.getEntry(K.key))?.value;if(typeof m=="object"){let N=$n,w=I;for(let y=0,P=m.length;y<P;y++){let M=m[y],D=N?.[M];w=D&&w?D(w,A,!0)?.value:w?.[M],N=D?.definition?.tableClass?.propertyResolvers}return w}let b=$n[m];return b?b(I,A):I[m]}a(sh,"getAttributeValue");function HA(K,m,A,I){let b=gr(A).getReadTxn(),N=I?.length,w={transaction:b,lazy:N>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function P(M,D){let q=M?.value;if(!q)return wo.SKIP;for(let G=0;G<N;G++)if(!y?.includes(G)&&!I[G](q,M))return wo.SKIP;return D!==void 0&&(M.key=D),M}if(a(P,"processEntry"),N>0||!K.hasEntries){let M=K.map(D=>{if(y=null,typeof D=="object"&&D.key!==void 0)return N>0?P(D):D;if(D==null)return wo.SKIP;for(let q=0;q<N;q++){let ie=I[q].idFilter;if(ie){if(!ie(D))return wo.SKIP;y||(y=[]),y.push(q)}}return th(D,A,w,!1,P)});return Array.isArray(K)&&(M=M.filter(D=>D!==wo.SKIP)),M.hasEntries=!0,M}return K}a(HA,"transformToEntries");async function xA(K,m,A){let I=m?.metadataFlags,b=m?.version,N,w;if(!i.attemptLock(K,b,()=>{clearTimeout(w);let D=i.getEntry(K);!D||!D.value||D.metadataFlags&(hl|ml)?N(xA(K,i.getEntry(K),A)):N(D)}))return new Promise(D=>{N=D,w=setTimeout(()=>{i.unlock(K,b)},eie)});let y=m?.value,P={requestContext:A,replacingRecord:y,replacingVersion:b,source:null,resourceCache:A?.resourceCache},M=A?.responseHeaders;return new Promise((D,q)=>{let G;SA(ze(P,async ie=>{let ae=performance.now(),re,ce,ve;try{for(let le of Je.sources)if(le.get&&(!le.get.reliesOnPrototype||le.prototype.get)&&(P.source=le,re=await le.get(K,P),re))break;ve=I&hl;let fe=P.lastModified||ve&&b;ce=ve||fe>b||!y,fe||(fe=(0,Tl.getNextMonotonicTime)());let Z=performance.now()-ae;if(Hr(Z,"cache-resolution",n),M&&M.append("Server-Timing",`cache-resolve;dur=${Z.toFixed(2)}`),ie.timestamp=fe,d&&!P.expiresAt&&(P.expiresAt=Date.now()+d),re){if(typeof re!="object")throw new Error("Only objects can be cached and stored in tables");typeof re.toJSON=="function"&&(re=re.toJSON()),t&&re[t]!==K&&(re[t]=K)}G=!0,D({version:fe,value:re})}catch(fe){fe.message+=` while resolving record ${K} for ${n}`,y&&((fe.code==="ECONNRESET"||fe.code==="ECONNREFUSED"||fe.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(fe.statusCode===500||fe.statusCode===502||fe.statusCode===503||fe.statusCode===504))?(D({version:b,value:y}),Xe.trace(fe.message,"(returned stale record)")):q(fe),P.transaction.abort();return}if(A?.noCacheStore){P.transaction.abort();return}gr(P).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(fe,Z)=>{if(Z?.version!==b)return;let le=Ml(K,y,re);re?(de.put?.(P,K,re),S(K,re,Z,fe,0,E&&ce||null,P,P.expiresAt,"put",!!ve)):(de.delete?.(P,K),E||h?S(K,null,Z,fe,0,E&&ce||null,P,0,"delete",!!ve):i.remove(K,b))}})}),()=>{i.unlock(K,b)},ie=>{i.unlock(K,b),G&&Xe.error("Error committing cache update",ie)})})}a(xA,"getFromSource");function nh(){if(It!==Dl&&(Dl=It,(0,Io.getWorkerIndex)()===(0,Io.getWorkerCount)()-1)){if(Ll&&clearTimeout(Ll),!It)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/It)*It+K.getTime(),A=a(I=>{Xe.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Ll=setTimeout(()=>H=H.then(async()=>{if(A(Math.max(I+It,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ll);return}let b=50,N=new Array(b),w=0;Xe.trace(`Starting cleanup scan for ${n}`);try{let y=0;for(let{key:P,value:M,version:D,expiresAt:q}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;M===null&&!E&&D+Zne<Date.now()?G=i.remove(P,D):q&&q+f<Date.now()&&(G=Je.evict(P,M,D),y++),G&&(await N[w],N[w]=G.catch(ie=>{Xe.error("Cleanup error",ie)}),++w>=b&&(w=0)),await pl()}Xe.trace(`Finished cleanup scan for ${n}, evicted ${y} entries`)}catch(y){Xe.trace(`Error in cleanup scan for ${n}:`,y)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(nh,"scheduleCleanup");function qA(){W=u?.addDeleteRemovalCallback(s,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(qA,"addDeleteRemoval");function xq(){(0,Io.getWorkerIndex)()===0&&setInterval(async()=>{try{let K=Y.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${Y} must be indexed`);for(let{value:A}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let I=i.getEntry(A);I?.value?.[K]<Date.now()&&Je.evict(A,I.value,I.version),await pl()}}catch(K){Xe.error("Error in evicting old records",K)}},Xne).unref()}a(xq,"runRecordExpirationEviction")}function pA(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 Px(){}function iie(e){xx=e}function PE(e,t){let r=t?.type;return e===null?e: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"&&!oie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,BE.autoCast)(e):e}function vx(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 SA(e,t,r){return e?.then?e.then(t,r):t(e)}function vE(e,t){e[Kr]=t,e[he]=t?.value??null,e[Sl]=t?.version}function Bx(e){return e!=null}var Hs,wo,Tl,Hx,Al,ps,gl,Rl,Xe,Co,Io,BE,jne,xx,Xne,Zne,Lx,eie,Sl,tie,Kr,El,Mx,rie,mA,Ka,hl,ml,sie,Ux,nie,ASe,oie,pl,Hf=Oe(()=>{Hs=x(L()),wo=require("lmdb"),Tl=x(Nr()),Hx=require("lodash");Rs();kp();Al=x(X());Dx();ps=x(ee()),gl=x(Tn()),Rl=x(ws());be();Of();Xe=x(V());Q_();Ji();Co=require("ordered-binary"),Io=x($e());Ui();BE=x(J());Ho();On();OE();jne=new Uint8Array(9);jne[8]=192;Xne=6e4,Zne=864e5;Al.initSync();Lx=Al.get(Hs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),eie=1e4,Sl=Symbol.for("version"),tie=Symbol.for("incremental-update"),Kr=Symbol("entry"),El=Symbol("is-saving"),Mx=1,rie=2,mA=Symbol("loaded-from-source"),Ka={isNotification:!0,ensureLoaded:!1},hl=1,ml=8,sie=Buffer.allocUnsafeSlow(8192),Ux=1978,nie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},ASe=(0,BE.convertToMS)(Al.get(Hs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(HE,"makeTable");a(pA,"attributesAsObject");a(Px,"noop");a(iie,"setServerUtilities");oie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(PE,"coerceType");a(vx,"isDescendantId");pl=a(()=>new Promise(setImmediate),"rest");a(SA,"when");a(vE,"updateResource");a(Bx,"exists")});var qe={};Ve(qe,{database:()=>Wc,databases:()=>tt,dropDatabase:()=>Wp,dropTableMeta:()=>die,getDatabases:()=>Cs,getTables:()=>aie,onUpdatedTable:()=>DR,readMetaDb:()=>Ol,resetDatabases:()=>cie,table:()=>at,tables:()=>yr});function aie(){return kE||Cs(),yr||{}}function Cs(){if(kE)return tt;kE=!0,za=new Map;let e=(0,Qt.getHdbBasePath)()&&(0,Ze.join)((0,Qt.getHdbBasePath)(),Qr.DATABASES_DIR_NAME),t=(0,Qt.get)(Qr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Qt.get)(Qr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Wr.existsSync)(e)?e:(0,Ze.join)((0,Qt.getHdbBasePath)(),Qr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Wr.existsSync)(e))for(let r of(0,Wr.readdirSync)(e,{withFileTypes:!0})){let s=(0,Ze.basename)(r.name,".mdb");r.isFile()&&(0,Ze.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Ol((0,Ze.join)(e,r.name),null,s)}if((0,Wr.existsSync)((0,Qa.getBaseSchemaPath)())){for(let r of(0,Wr.readdirSync)((0,Qa.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,Ze.join)((0,Qa.getBaseSchemaPath)(),r.name),n=(0,Ze.join)((0,Qa.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Wr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,Ze.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Ze.join)(n,i.name);Ol((0,Ze.join)(s,i.name),(0,Ze.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,Wr.existsSync)(n))for(let o of(0,Wr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,Ze.extname)(o.name).toLowerCase()===".mdb"&&Ol((0,Ze.join)(n,o.name),(0,Ze.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,Ze.join)(c.path,(0,Ze.basename)(o+".mdb"));(0,Wr.existsSync)(u)&&Ol(u,o,r,null,!0)}}for(let r in tt){let s=za.get(r);if(s){let n=tt[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 tt[r],r==="data"){for(let n in yr)delete yr[n];delete yr[VE]}}return za=null,tt}}function cie(){kE=!1;for(let[,e]of wi)e.needsDeletion=!0;Cs();for(let[e,t]of wi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),wi.delete(e));return tt}function Ol(e,t,r=RA,s,n){let i=new TA.default(e,!1);try{let o=wi.get(e);o?o.needsDeletion=!1:(o=(0,qE.open)(i),wi.set(e,o));let c=new Do.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(xE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,Wr.existsSync)(s)&&(i.path=s,_=(0,qE.open)(i),_.isLegacy=!0):_=AE(o));let l=kx(r),d=l[VE],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 O=f.get(p);O||f.set(p,O={attributes:[]}),(S==null||h.is_hash_attribute)&&(O.primary=h),S!=null&&O.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 O=l[E],g={},R=[],B,H,v=typeof S.audit=="boolean"?S.audit:(0,Qt.get)(Qr.CONFIG_PARAMS.LOGGING_AUDITLOG),U=S.trackDeletes,Y=S.expiration,W=S.eviction;if(O)g=O.indices,R=O.attributes,O.schemaVersion++;else{B=S.tableId,B?B>=(u.get(Wa)||0)&&u.putSync(Wa,B+1):(S.tableId=B=u.get(Wa),B||(B=1),u.putSync(Wa,B+1),u.putSync(S.key,S));let z=new Do.default(!S.is_hash_attribute,S.is_hash_attribute);H=Zl(o.openDB(S.key,z)),H.rootStore=o,H.tableId=B}for(let z of p){z.attribute=z.name;try{if(!z.is_hash_attribute&&(z.indexed||z.attribute&&!z.name)){if(!g[z.name]){let Te=new Do.default(!z.is_hash_attribute,z.is_hash_attribute);g[z.name]=o.openDB(z.key,Te),g[z.name].indexNulls=z.indexNulls}let ne=R.find(Te=>Te.name===z.name);ne?R.splice(R.indexOf(ne),1,z):R.push(z)}}catch(ne){Ss.error("Error trying to update attribute",z,R,g,ne)}}if(!O){O=Vx(l,E,HE({primaryStore:H,auditStore:_,audit:v,expirationMS:Y&&Y*1e3,evictionMS:W&&W*1e3,trackDeletes:U,tableName:E,tableId:B,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:g,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),O.schemaVersion=1;for(let z of AA)z(O)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function kx(e){let t=tt[e];if(t||(e==="data"?t=tt[e]=yr:e==="system"?Object.defineProperty(tt,"system",{value:t=Object.create(null),configurable:!0}):t=tt[e]=Object.create(null)),za&&!za.has(e)){let r=new Set;t[VE]=r,za.set(e,r)}return t}function Vx(e,t,r){return e[t]=r,r}function Wc({database:e,table:t}){e||(e=RA),Cs();let r=kx(e),s=(0,Ze.join)((0,Qt.getHdbBasePath)(),Qr.DATABASES_DIR_NAME),n=(0,Qt.get)(Qr.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,Qt.get)(Qr.CONFIG_PARAMS.STORAGE_PATH)||((0,Wr.existsSync)(s)?s:(0,Ze.join)((0,Qt.getHdbBasePath)(),Qr.LEGACY_DATABASES_DIR_NAME));let o=(0,Ze.join)(s,(i?t:e)+".mdb"),c=wi.get(o);if(!c){let u=new TA.default(o,!1);c=(0,qE.open)(u),wi.set(o,c)}return c}async function Wp(e){if(!tt[e])throw new Error("Schema does not exist");let t=tt[e];for(let r in t){let n=t[r].primaryStore.rootStore;wi.delete(n.path),n.status==="open"&&(await n.close(),await qx.remove(n.path))}if(e==="data"){for(let r in yr)delete yr[r];delete yr[VE]}delete tt[e]}function at({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=RA);let l=Wc({database:t,table:e}),d=tt[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 O=new Do.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 g,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 U=l.auditStore;U||(U=AE(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,Qt.get)(Qr.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 Do.default(!1,!0),W=e+"/",z=Zl(l.openDB(W,Y));z.rootStore=l,S=l.dbisDb=l.openDB(xE.INTERNAL_DBIS_NAME,O),z.tableId=S.get(Wa),z.tableId||(z.tableId=1),S.putSync(Wa,z.tableId+1),h.tableId=z.tableId,f=Vx(d,e,HE({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,g=!0,v(),S.put(W,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(xE.INTERNAL_DBIS_NAME,O)),f.dbisDB=S;let B=[];for(let{key:U,value:Y}of S.getRange({start:!0})){let[W,z]=U.toString().split("/");if(z===""&&(z=Y.name),z){if(W!==e)continue}else z=W;if(!i.find(Te=>Te.name===z)?.indexed&&Y.indexed&&!Y.isPrimaryKey){v(),g=!0,S.remove(U);let Te=f.indices[W];Te&&B.push(Te)}}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 W=S.get(Y);if(U.isPrimaryKey){if(W=W||S.get(Y=e+"/")||{},o!==f.audit||(+r||void 0)!==(+W.expiration||void 0)||(+s||void 0)!==(+W.eviction||void 0)){let ne=Object.assign({},W);typeof o=="boolean"&&(o&&f.enableAuditing(o),ne.audit=o),r&&(ne.expiration=+r),s&&(ne.eviction=+s),g=!0,v(),S.put(Y,ne)}continue}W?.attribute&&!W.name&&(W.indexed=!0);let z=!W||W.type!==U.type||W.indexed!==U.indexed||JSON.stringify(W.attributes)!==JSON.stringify(U.attributes)||JSON.stringify(W.elements)!==JSON.stringify(U.elements);if(U.indexed){let ne=new Do.default(!0,!1),Te=l.openDB(Y,ne);(z||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<bl.workerData?.restartNumber)&&(g=!0,v(),W=S.get(Y),(z||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<bl.workerData?.restartNumber)&&(g=!0,U.lastIndexedKey=W?.lastIndexedKey||!1,U.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(U,"dbi",{value:Te}),U.indexNulls===void 0&&(U.indexNulls=!0),H.push(U)),S.put(Y,U)),W?.indexNulls&&U.indexNulls===void 0&&(U.indexNulls=!0),Te.indexNulls=U.indexNulls,p[U.name]=Te}else z&&(g=!0,v(),S.put(Y,U))}}finally{R&&R()}if(g&&(f.schemaVersion++,f.updatedAttributes()),Ss.trace(`${e} table loading, running index`),H.length>0||B.length>0?f.indexingOperation=_ie(f,H,B):g&&FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,g)for(let U of AA)U(f,_!=="cluster");return(r||s||n)&&f.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),Ss.trace(`${e} table loaded`),f;function v(){R||l.transactionSync(()=>({then(U){R=U}}))}a(v,"startTxn")}async function _ie(e,t,r){try{let s=e.schemaVersion;await FE.signalSchemaChange(new GE.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,Fx.getIndexedValues)(l[h]);if(p)for(let S=0,O=p.length;S<O;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,Ss.error(f)}),bl.workerData&&bl.workerData.restartNumber!==Gx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>uie?await n:u>lie&&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 FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Ss.error("Error in indexing",s)}}function die({table:e,database:t}){let r=Wc({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 DR(e){AA.push(e)}var Qt,xE,qE,Ze,Wr,Qa,Do,TA,Qr,qx,gA,Fx,FE,GE,bl,Ss,Gx,RA,VE,yr,tt,Wa,AA,kE,wi,za,uie,lie,be=Oe(()=>{Qt=x(X()),xE=x(_t()),qE=require("lmdb"),Ze=require("path"),Wr=require("fs"),Qa=x(We());Hf();Do=x(e_()),TA=x(r_()),Qr=x(L()),qx=x(require("fs-extra")),gA=require("../index"),Fx=x(Nr()),FE=x(Tn()),GE=x(ws()),bl=require("worker_threads"),Ss=x(V()),Gx=x($e());Ui();Ho();RA="data",VE=Symbol("defined-tables");(0,Qt.initSync)();yr=Object.create(null),tt=Object.create(null);(0,gA._assignPackageExport)("databases",tt);(0,gA._assignPackageExport)("tables",yr);Wa=Symbol.for("next-table-id"),AA=[],wi=new Map;a(aie,"getTables");a(Cs,"getDatabases");a(cie,"resetDatabases");a(Ol,"readMetaDb");a(kx,"ensureDB");a(Vx,"setTable");a(Wc,"database");a(Wp,"dropDatabase");a(at,"table");uie=1e3,lie=10;a(_ie,"runIndexing");a(die,"dropTableMeta");a(DR,"onUpdatedTable")});var J=T((LSe,sq)=>{"use strict";var Ii=require("path"),Qx=require("fs-extra"),Tr=V(),$x=require("fs-extra"),$E=require("os"),fie=require("net"),Eie=require("recursive-iterator"),ot=L(),hie=SO(),Yx=require("papaparse"),YE=require("moment"),{inspect:mie}=require("util"),Kx=require("is-number"),DSe=require("lodash"),pie=require("minimist"),Sie=require("https"),Tie=require("http"),{hdb_errors:KE}=ee(),gie=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,zx=require("util").promisify(setTimeout),Rie=100,Aie=5,Oie="",bie=4,Wx={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};sq.exports={isEmpty:zr,isEmptyOrZeroLength:_n,arrayHasEmptyValues:wie,arrayHasEmptyOrZeroLengthValues:Iie,buildFolderPath:Cie,isBoolean:Jx,errorizeMessage:Nie,stripFileExtension:Lie,autoCast:Mie,autoCastJSON:jx,autoCastJSONDeep:bA,removeDir:Uie,compareVersions:Pie,isCompatibleDataVersion:vie,escapeRawValue:Bie,unescapeValue:Hie,stringifyProps:xie,timeoutPromise:Fie,isClusterOperation:kie,getClusterUser:$ie,checkGlobalSchemaTable:Vie,getHomeDir:Zx,getPropsFilePath:qie,promisifyPapaParse:Yie,removeBOM:eq,createEventPromise:Kie,checkProcessRunning:Wie,checkSchemaTableExist:Qie,checkSchemaExists:tq,checkTableExists:rq,getStartOfTomorrowInSeconds:zie,getLimitKey:Jie,isObject:Die,isNotEmptyAndHasValue:yie,autoCasterIsNumberCheck:Xx,backtickASTSchemaItems:jie,isPortTaken:Gie,createForkArgs:Xie,autoCastBoolean:Zie,async_set_timeout:zx,getTableHashAttribute:eoe,doesSchemaExist:toe,doesTableExist:roe,stringifyObj:soe,ms_to_time:noe,changeExtension:ioe,getEnvCliRootPath:NA,noBootFile:ooe,httpRequest:aoe,transformReq:coe,convertToMS:uoe,PACKAGE_ROOT:ot.PACKAGE_ROOT};function Nie(e){return e instanceof Error?e:new Error(e)}a(Nie,"errorizeMessage");function zr(e){return e==null}a(zr,"isEmpty");function yie(e){return!zr(e)&&(e||e===0||e===""||Jx(e))}a(yie,"isNotEmptyAndHasValue");function _n(e){return zr(e)||e.length===0||e.size===0}a(_n,"isEmptyOrZeroLength");function wie(e){if(zr(e))return!0;for(let t=0;t<e.length;t++)if(zr(e[t]))return!0;return!1}a(wie,"arrayHasEmptyValues");function Iie(e){if(_n(e))return!0;for(let t=0;t<e.length;t++)if(_n(e[t]))return!0;return!1}a(Iie,"arrayHasEmptyOrZeroLengthValues");function Cie(...e){try{return e.join(Ii.sep)}catch{console.error(e)}}a(Cie,"buildFolderPath");function Jx(e){return zr(e)?!1:e===!0||e===!1}a(Jx,"isBoolean");function Die(e){return zr(e)?!1:typeof e=="object"}a(Die,"isObject");function Lie(e){return _n(e)?Oie:e.slice(0,-bie)}a(Lie,"stripFileExtension");function Mie(e){return zr(e)||e===""||typeof e!="string"?e:Wx[e]!==void 0?Wx[e]:Xx(e)===!0?Number(e):gie.test(e)?new Date(e):e}a(Mie,"autoCast");function jx(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(jx,"autoCastJSON");function bA(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=bA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=bA(r);s!==r&&(e[t]=s)}return e}else return jx(e)}a(bA,"autoCastJSONDeep");function Xx(e){if(e.startsWith("0.")&&Kx(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Kx(e))}a(Xx,"autoCasterIsNumberCheck");async function Uie(e){if(_n(e))throw new Error(`Directory path: ${e} does not exist`);try{await $x.emptyDir(e),await $x.remove(e)}catch(t){throw Tr.error(`Error removing files in ${e} -- ${t}`),t}}a(Uie,"removeDir");function Pie(e,t){if(_n(e)){Tr.info("Invalid current version sent as parameter.");return}if(_n(t)){Tr.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(Pie,"compareVersions");function vie(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(vie,"isCompatibleDataVersion");function Bie(e){if(zr(e))return e;let t=String(e);return t==="."?ot.UNICODE_PERIOD:t===".."?ot.UNICODE_PERIOD+ot.UNICODE_PERIOD:t.replace(ot.FORWARD_SLASH_REGEX,ot.UNICODE_FORWARD_SLASH)}a(Bie,"escapeRawValue");function Hie(e){if(zr(e))return e;let t=String(e);return t===ot.UNICODE_PERIOD?".":t===ot.UNICODE_PERIOD+ot.UNICODE_PERIOD?"..":String(e).replace(ot.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Hie,"unescapeValue");function xie(e,t){if(zr(e))return Tr.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+$E.EOL}!_n(s)&&s[0]===";"?r+=" "+s+n+$E.EOL:_n(s)||(r+=s+"="+n+$E.EOL)}catch{Tr.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(xie,"stringifyProps");function Zx(){let e;try{e=$E.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Zx,"getHomeDir");function qie(){let e=Ii.join(Zx(),ot.HDB_HOME_DIR_NAME,ot.BOOT_PROPS_FILE_NAME);return Qx.existsSync(e)||(e=Ii.join(__dirname,"../","hdb_boot_properties.file")),e}a(qie,"getPropsFilePath");function Fie(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(Fie,"timeoutPromise");async function Gie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=fie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(Gie,"isPortTaken");function kie(e){try{return ot.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Tr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(kie,"isClusterOperation");function Vie(e,t){let r=(be(),te(qe)).getDatabases();if(!r[e])return KE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return KE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Vie,"checkGlobalSchemaTable");function $ie(e,t){if(zr(t)){Tr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(zr(e)||_n(e)){Tr.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){Tr.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Tr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a($ie,"getClusterUser");function Yie(){Yx.parsePromise=function(e,t,r){return new Promise(function(s,n){Yx.parse(e,{header:!0,transformHeader:eq,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(Yie,"promisifyPapaParse");function eq(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(eq,"removeBOM");function Kie(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Tr.info(`Got cluster status event response: ${mie(n)}`);try{i.cancel()}catch{Tr.error("Error trying to cancel timeout.")}s(n)})})}a(Kie,"createEventPromise");async function Wie(e){let t=!0,r=0;do await zx(Rie*r++),(await hie.findPs(e)).length>0&&(t=!1);while(t&&r<Aie);if(t)throw new Error(`process ${e} was not started`)}a(Wie,"checkProcessRunning");function Qie(e,t){let r=tq(e);if(r)return r;let s=rq(e,t);if(s)return s}a(Qie,"checkSchemaTableExist");function tq(e){let{getDatabases:t}=(be(),te(qe));if(!t()[e])return KE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(tq,"checkSchemaExists");function rq(e,t){let{getDatabases:r}=(be(),te(qe));if(!r()[e][t])return KE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(rq,"checkTableExists");function zie(){let e=YE().utc().add(1,ot.MOMENT_DAYS_TAG).startOf(ot.MOMENT_DAYS_TAG).unix(),t=YE().utc().unix();return e-t}a(zie,"getStartOfTomorrowInSeconds");function Jie(){return YE().utc().format("DD-MM-YYYY")}a(Jie,"getLimitKey");function jie(e){try{let t=new Eie(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){Tr.error("Got an error back ticking items."),Tr.error(t)}}a(jie,"backtickASTSchemaItems");function Xie(e){return[e]}a(Xie,"createForkArgs");function Zie(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Zie,"autoCastBoolean");function eoe(e,t){let{getDatabases:r}=(be(),te(qe)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(eoe,"getTableHashAttribute");function toe(e){let{getDatabases:t}=(be(),te(qe));return t()[e]!==void 0}a(toe,"doesSchemaExist");function roe(e,t){let{getDatabases:r}=(be(),te(qe));return r()[e]?.[t]!==void 0}a(roe,"doesTableExist");function soe(e){try{return JSON.stringify(e)}catch{return e}}a(soe,"stringifyObj");function noe(e){let t=YE.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(noe,"ms_to_time");function ioe(e,t){let r=Ii.basename(e,Ii.extname(e));return Ii.join(Ii.dirname(e),r+t)}a(ioe,"changeExtension");function NA(){if(process.env[ot.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ot.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=pie(process.argv);if(e[ot.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ot.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(NA,"getEnvCliRootPath");var OA;function ooe(){if(OA)return OA;let e=NA();NA()&&Qx.pathExistsSync(Ii.join(e,ot.HDB_CONFIG_FILE))&&(OA=!0)}a(ooe,"noBootFile");function aoe(e,t){let r;return e.protocol==="http:"?r=Tie:r=Sie,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(aoe,"httpRequest");function coe(e){if(!e.schema&&!e.database){e.schema=ot.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(coe,"transformReq");function uoe(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(uoe,"convertToMS")});var X=T((USe,aq)=>{"use strict";var yA=require("fs-extra"),Lo=require("path"),nq=require("os"),loe=require("properties-reader"),yl=V(),Nl=J(),_e=L(),WE=Mr(),_oe="Error initializing environment manager",QE="BOOT_PROPS_FILE_PATH",iq=!1,doe={[_e.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},kn={};aq.exports={BOOT_PROPS_FILE_PATH:QE,getHdbBasePath:foe,setHdbBasePath:Eoe,get:oq,initSync:moe,setProperty:Ue,initTestEnvironment:poe};function foe(){return kn[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(foe,"getHdbBasePath");function Eoe(e){kn[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Eoe,"setHdbBasePath");function oq(e){let t=WE.getConfigValue(e);return t===void 0?kn[e]:t}a(oq,"get");function Ue(e,t){doe[e]&&(kn[e]=t),WE.updateConfigObject(e,t)}a(Ue,"setProperty");function hoe(){let e;try{e=Nl.getPropsFilePath(),yA.accessSync(e,yA.constants.F_OK|yA.constants.R_OK),iq=!0;let t=loe(e);return kn[_e.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(_e.HDB_SETTINGS_NAMES.INSTALL_USER),kn[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),kn[QE]=e,!0}catch{return yl.trace(`Environment manager found no properties file at ${e}`),!1}}a(hoe,"doesPropFileExist");function moe(e=!1){try{(iq||hoe()||Nl.noBootFile())&&(WE.initConfig(e),kn[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=WE.getConfigValue(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){yl.error(_oe),yl.error(t),console.error(t),process.exit(1)}}a(moe,"initSync");function poe(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=Lo.join(__dirname,"../../","unitTests");kn[QE]=Lo.join(u,"hdb_boot_properties.file"),Ue(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Lo.join(u,"settings.test")),Ue(_e.HDB_SETTINGS_NAMES.INSTALL_USER,nq.userInfo()?nq.userInfo().username:void 0),Ue(_e.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ue(_e.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Lo.join(u,"envDir","log")),Ue(_e.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ue(_e.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ue(_e.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ue(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Lo.join(u,"envDir")),Ue(_e.CONFIG_PARAMS.STORAGE_PATH,Lo.join(u,"envDir")),n&&(Ue(_e.CONFIG_PARAMS.HTTP_SECUREPORT,oq(_e.CONFIG_PARAMS.HTTP_PORT)),Ue(_e.CONFIG_PARAMS.HTTP_PORT,null)),Ue(_e.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Ue(_e.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ue(_e.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Nl.isEmpty(i)?!1:i),Ue(_e.CONFIG_PARAMS.HTTP_CORS,Nl.isEmpty(i)?!1:i),Ue(_e.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ue(_e.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ue(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ue(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ue(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Lo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ue(_e.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Nl.isEmpty(c)?!1:c),o&&(Ue("CORS_ACCESSLIST",o),Ue(_e.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Ue(_e.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ue(_e.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Ue(_e.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ue(_e.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ue(_e.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ue(_e.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${QE}. Please check your boot props and settings files`;yl.fatal(r),yl.error(t)}}a(poe,"initTestEnvironment")});var dq=T((vSe,_q)=>{"use strict";var lq=require("joi"),{string:wl,boolean:cq,array:Soe}=lq.types(),uq=L(),Toe=Qe();_q.exports=goe;function goe(e){let t=lq.object({operation:wl.valid(uq.OPERATIONS_ENUM.ADD_NODE,uq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:wl.required(),subscriptions:Soe.items({schema:wl.required(),table:wl.optional(),hash_attribute:wl.optional(),subscribe:cq.required(),publish:cq.required()}).min(1).required()});return Toe.validateBySchema(e,t)}a(goe,"updateRemoteSourceValidator")});var Il=T((HSe,fq)=>{"use strict";var wA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};fq.exports=wA});var Sq=T((qSe,pq)=>{"use strict";var Roe=dq(),Vn=V(),IA=Fe(),Eq=L(),CA=ns(),DA=rt(),hq=cu(),Aoe=k_(),{Node:Ooe,NodeSubscription:mq}=_i(),LA=Il(),MA=J(),boe=X(),{cloneDeep:Noe}=require("lodash"),{broadcast:yoe}=$e();pq.exports=woe;async function woe(e){try{let t=Roe(e);if(t)return Vn.error(`Validation error in updateRemoteSource: ${t.message}`),new LA(IA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=Noe(await CA.getNodeRecord(s)),c=!MA.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(!MA.doesSchemaExist(f)){Vn.trace(`updateRemoteSource creating schema: ${f}`);try{await hq.createSchema({operation:"create_schema",schema:f})}catch(h){Vn.error(h)}}if(E&&!MA.doesTableExist(f,E)){let h=new Aoe(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 hq.createTable(h)}catch(p){Vn.error(p)}Vn.trace(`Creating local stream for ${f}.${E}`),await DA.createLocalTableStream(f,E)}if(f===Eq.SYSTEM_SCHEMA_NAME&&await DA.createLocalTableStream(f,E),await DA.updateWorkStream(d,s),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let O=o.subscriptions[p];if(O.schema===f&&O.table===E){O.publish=d.publish,O.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new mq(f,E,d.publish,d.subscribe))}else i.push(new mq(f,E,d.publish,d.subscribe))}c||(o=new Ooe(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 CA.upsertNodeRecord(u),yoe({type:"nats_update"}),new LA(IA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${boe.get(Eq.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await CA.getSystemInfo())}catch(t){Vn.error(t);let r=t.message?t.message:t;return new LA(IA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(woe,"updateRemoteSource")});var Aq=T((GSe,Rq)=>{"use strict";var gq=require("joi"),{string:Tq}=gq.types(),Ioe=L(),Coe=Qe();Rq.exports=Doe;function Doe(e){let t=gq.object({operation:Tq.valid(Ioe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:Tq.required()});return Coe.validateBySchema(e,t)}a(Doe,"removeRemoteSourceValidator")});var bq=T((VSe,Oq)=>{"use strict";var Loe=Aq(),zE=V(),JE=Fe(),UA=L(),Moe=ns(),Uoe=J(),Poe=rt(),voe=X(),jE=Il(),{NodeSubscription:Boe}=_i(),Hoe=ea(),xoe=ei(),{broadcast:qoe}=$e(),Foe=voe.get(UA.CONFIG_PARAMS.CLUSTERING_NODENAME);Oq.exports=Goe;async function Goe(e){try{let t=Loe(e);if(t)return zE.error(`Validation error in removeRemoteSource: ${t.message}`),new jE(JE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,s=await Moe.getNodeRecord(r);if(Uoe.isEmptyOrZeroLength(s)){let i=`No record found for node '${r}'`;return zE.error(i),new jE(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];zE.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Boe(c.schema,c.table,!1,!1);await Poe.updateWorkStream(u,r)}let n=new Hoe(UA.SYSTEM_SCHEMA_NAME,UA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await xoe.deleteRecord(n),qoe({type:"nats_update"}),new jE(JE.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Foe} successfully removed node '${r}'.`)}catch(t){zE.error(t);let r=t.message?t.message:t;return new jE(JE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Goe,"removeRemoteSource")});var Cq=T((YSe,Iq)=>{"use strict";var XE=V(),ZE=L(),Nq=Fe(),yq=X(),koe=J(),wq=Il(),Voe=ns(),$oe=Ed(),Yoe=Ir();Iq.exports=Koe;async function Koe(e){try{XE.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=koe.ms_to_time(t),s=new Woe(yq.get(ZE.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),yq.get(ZE.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT),r,await Voe.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new $oe(ZE.SYSTEM_SCHEMA_NAME,ZE.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await Yoe.update(i)}catch(n){XE.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return XE.trace("getRemoteSourceConfig response:",s),new wq(Nq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){XE.error(t);let r=t.message?t.message:t;return new wq(Nq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Koe,"getRemoteSourceConfig");function Woe(e,t,r,s){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=s}a(Woe,"ConfigResponseObject")});var Uq=T((WSe,Mq)=>{"use strict";var Dq=X();Dq.initSync();var Lq=rt(),Cl=V(),Ja=L(),PA=Fe(),Qoe=Sq(),zoe=bq(),Joe=Cq(),joe=Il(),{encode:Xoe,decode:Zoe}=require("msgpackr"),eae=Sn(),tae=jn(),rae=require("util"),sae=L(),{isMainThread:nae,parentPort:iae}=require("worker_threads");$e();var oae=rae.promisify(eae.setSchemaDataToGlobal),vA=Dq.get(Ja.CONFIG_PARAMS.CLUSTERING_NODENAME);Mq.exports=aae;async function aae(){try{Cl.notify("Starting reply service."),await oae();let e=await Lq.getConnection(),t=`${vA}.__request__`,r=e.subscribe(t,{queue:vA});await cae(r)}catch(e){Cl.error(e)}}a(aae,"initialize");async function cae(e){for await(let t of e){let r=Zoe(t.data),s;switch(r.operation){case Ja.OPERATIONS_ENUM.ADD_NODE:case Ja.OPERATIONS_ENUM.UPDATE_NODE:s=await Qoe(r);break;case Ja.OPERATIONS_ENUM.REMOVE_NODE:s=await zoe(r);break;case Ja.OPERATIONS_ENUM.CLUSTER_STATUS:s=await Joe(r);break;case Ja.OPERATIONS_ENUM.DESCRIBE_ALL:s=await uae();break;default:let n=`node '${vA}' reply service received unrecognized request operation`;Cl.error(n),s=new joe(PA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}Cl.trace(s),t.respond(Xoe(s))}}a(cae,"handleRequest");async function uae(){try{return{status:PA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await tae.describeAll()}}catch(e){return Cl.error(e),{status:PA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(uae,"getRemoteDescribeAll");nae||iae.on("message",async e=>{let{type:t}=e;t===sae.ITC_EVENT_TYPES.SHUTDOWN&&Lq.closeConnection()})});var lae=Uq();(async()=>{try{await lae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
29
|
+
`))}},25).unref()}o.close?.(()=>{if(He.get(Jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&vR()==0)try{_H(He.get(Jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,aE),o.cantCleanupProperly||Vr.warn("Had to forcefully exit the thread",aE),process.exit(0)},5e3).unref()})}if(process.env.DEV_MODE)try{require("inspector").close()}catch(i){console.error("Could not close debugger",i)}}}).ref();let e=[];if(dH&&!Jse)for(let t in un){let r=un[t];if(isNaN(t)&&vR()==0){Gse(t)&&_H(t),e.push(new Promise((n,i)=>{r.listen({path:t},()=>{n(),Vr.info("Domain socket listening on "+t)}).on("error",i)}));continue}let s;try{s=dH(+t,"::")}catch(n){console.error(`Unable to bind to port ${t}`,n);continue}e.push(new Promise((n,i)=>{r.listen({fd:s},()=>{n(),Vr.trace("Listening on port "+t,aE)}).on("error",i)}))}Promise.all(e).then(()=>{ul?.postMessage({type:Jt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(TH,"startServers");vse||TH();function xR(e,t,r){let s=e?.read?e:new Bse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=un[t];if(n.isSecure&&(s.startTime=performance.now()),n)typeof n=="function"?n(s):n.emit("connection",s),r&&s.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=un[t];c?(typeof c=="function"?c(s):c.emit("connection",s),r&&s.emit("data",r)):o<5?i(o+1):(Vr.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(xR,"deliverSocket");var EH=new Map;function Zse(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=EH.get(n),r){case"connection":i=xR(void 0,t),EH.set(n,i),i.write=(c,u,_)=>(ul.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(ul.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),ul.postMessage({requestId:n,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(s,"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(Zse,"proxyRequest");function qR(e,t,r=!0){!+t&&t!==He.get(Jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(He.get(Jt.CONFIG_PARAMS.HTTP_PORT),10));let s=un[t];if(s){let n=s.lastServer||s;if(n===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!n.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);n.off("unhandled",hH),n.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(s.cantCleanupProperly=!0),e.emit("request",i,o)}),s.lastServer=e}else un[t]=e;e.on("unhandled",hH)}a(qR,"registerServer");function gH(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=[],He.get(Jt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:He.get(Jt.CONFIG_PARAMS.HTTP_PORT),secure:He.get(Jt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),He.get(Jt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:He.get(Jt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&He.get(Jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:He.get(Jt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(gH,"getPorts");function FR(e,t){for(let{port:r,secure:s}of gH(t))RH(r,s,t?.isOperationsServer),typeof e=="function"?BR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=s,qR(e,r,!1)),uE[r]=HR(BR,r),jse=HR(Xse,r)}a(FR,"httpServer");function RH(e,t,r){if(!yi[e]){let s=r?"operationsApi_network":"http",n={keepAliveTimeout:He.get(s+"_keepAliveTimeout"),headersTimeout:He.get(s+"_headersTimeout"),requestTimeout:He.get(s+"_timeout")},i=He.get(s+"_mtls"),o=He.get(s+"_mtls_required");if(t){s=r?"operationsApi_":"";let u=He.get(s+"tls_privateKey"),_=He.get(s+"tls_certificate"),l=He.get(s+"tls_certificateAuthority");Object.assign(n,{allowHTTP1:!0,key:Ga(u),ciphers:He.get("tls_ciphers"),cert:Ga(_),ca:l&&Ga(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:$se()})}let c=Qse();yi[e]=(t?Fse:xse)(n,async(u,_)=>{try{let d=performance.now(),f=new pH(u,_);r&&(f.isOperationsServer=!0);let E=await uE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=AH(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,yi[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,A=E.body,R;if(!E.handlesHeaders){let H=E.headers||new mH;A?A.length>=0&&(typeof A=="string"?H.set("Content-Length",Buffer.byteLength(A)):H.set("Content-Length",A.length),R=!0):(H.set("Content-Length","0"),R=!0);let v=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(v+=", miss"),Kse(H,"Server-Timing",v,!0),_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),R&&_.end(A)}let g=f.handlerPath,P=f.method;if(cl(S,"duration",g,P,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),Wse(h<400,"success",g,P),!R)if(A?.pipe){A.pipe(_),A.destroy&&_.on("close",()=>{A.destroy()});let H=0;A.on("data",v=>{H+=v.length}),A.on("end",()=>{cl(performance.now()-p,"transfer",g,P),cl(H,"bytes-sent",g,P)})}else A?.then?A.then(H=>{_.end(H)},l):_.end(A)}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?Vr.warn(d):Vr.info(d):Vr.error(d)}a(l,"onError")}),i&&(yi[e].mtlsConfig=i),t&&(yi[e].on("secureConnection",u=>{u._parent.startTime&&cl(performance.now()-u._parent.startTime,"tls-handshake",e),cl(u.isSessionReused(),"tls-reused",e)}),yi[e].isSecure=!0),qR(yi[e],e)}return yi[e]}a(RH,"getHTTPServer");function HR(e,t){let r=AH;for(let s=e.length;s>0;){let{listener:n,port:i}=e[--s];if(i===t||i==="all"){let o=r;r=a(c=>n(c,o),"next_callback")}}return r}a(HR,"makeCallbackChain");function AH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new mH}}a(AH,"unhandled");function ene(e,t){FR(e,{requestOnly:!0,...t})}a(ene,"onRequest");function tne(e,t){let r;if(t.securePort){let s=He.get("tls_privateKey"),n=He.get("tls_certificate"),i=t.mtls?.certificateAuthority||He.get("tls_certificateAuthority");r=Vse({ciphers:He.get("tls_ciphers"),key:Ga(s),cert:Ga(n),ca:i&&Ga(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),un[t.securePort]=r}return t.port&&(r=Hse(e),un[t.port]=r),r}a(tne,"onSocket");Object.defineProperty(qse.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 rne(e,t){let r;for(let{port:s,secure:n}of gH(t)){cE[s]||(cE[s]=new kse({server:r=RH(s,n)}),cE[s].on("connection",async(c,u)=>{try{let _=new pH(u);_.isWebSocket=!0;let l=uE[s](_),d=u.headers["sec-websocket-protocol"]||"",f=PR[s];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(_){Vr.warn("Error handling WebSocket connection",_)}}),cE[s].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=PR[s];o||(o=PR[s]=[]),o.push({listener:e,protocol:i}),uE[s]=HR(BR,s)}return r}a(rne,"onWebSocket");function hH(e,t){t.writeHead(404),t.end(`Not found
|
|
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)}})();
|