harperdb 4.3.0-beta.4 → 4.3.0-beta.6
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 +3 -3
- package/launchServiceScripts/launchNatsIngestService.js +19 -19
- package/launchServiceScripts/launchNatsReplyService.js +19 -19
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +19 -19
- package/npm-shrinkwrap.json +66 -66
- package/package.json +2 -2
- package/resources/DatabaseTransaction.d.ts +8 -3
- 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.048c8121.js → main.912a850a.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -19
- /package/studio/build-local/static/js/{main.048c8121.js.LICENSE.txt → main.912a850a.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 Vq=Object.create;var ec=Object.defineProperty;var $q=Object.getOwnPropertyDescriptor;var Yq=Object.getOwnPropertyNames;var Kq=Object.getPrototypeOf,Wq=Object.prototype.hasOwnProperty;var a=(e,t)=>ec(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ye=(e,t)=>{for(var r in t)ec(e,r,{get:t[r],enumerable:!0})},VA=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Yq(t))!Wq.call(e,n)&&n!==r&&ec(e,n,{get:()=>t[n],enumerable:!(s=$q(t,n))||s.enumerable});return e};var x=(e,t,r)=>(r=e!=null?Vq(Kq(e)):{},VA(t||!e||!e.__esModule?ec(r,"default",{value:e,enumerable:!0}):r,e)),se=e=>VA(ec({},"__esModule",{value:!0}),e);var KA=T((pae,YA)=>{var Qq=require("fast-glob"),{statSync:ah,existsSync:ch,readFileSync:zq,writeFileSync:Jq}=require("fs"),{spawnSync:jq,spawn:Xq,execFileSync:mae}=require("child_process"),{isMainThread:Zq}=require("worker_threads"),{join:Wn,relative:$A}=require("path"),{PACKAGE_ROOT:gs}=L(),{tmpdir:eF,platform:tF}=require("os");require("source-map-support").install();var rF=["resources","server","dataLayer","components"],tc="ts-build",uh,sF=__filename.endsWith("tsBuild.js");if(sF){if(Zq){let r;try{ah(Wn(gs,tc)),r=!0}catch{}if(r)for(let s of Qq.sync(rF.map(n=>n+"/**/*.ts"),{cwd:gs})){let n=0,i=0;try{n=ah(Wn(gs,s)).mtimeMs-5e3,i=ah(Wn(gs,tc,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),uh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),uh=!0;if(uh){let s=Wn(gs,"node_modules/.bin/tsc");tF()==="win32"&&(s+=".cmd");let n=jq(s,{cwd:gs});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Wn(eF(),"harperdb-tsc.pid"),o;if(ch(i))try{process.kill(+zq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Xq(s,["--watch"],{cwd:gs,detached:!0,stdio:"ignore"});Jq(i,c.pid.toString()),c.unref()}}}}let e=YA.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(gs)&&!s[0].includes("node_modules")){let i=$A(gs,s[0]),o;i.startsWith(tc)?o=Wn(gs,$A(tc,i)):o=Wn(gs,tc,i);let c=Wn(o,r),u=c+".js";if(ch(u))return u;if(c.includes(".")&&ch(c))return c}return t(r,s,n)}}});var L=T((gae,oO)=>{"use strict";var Xr=require("path"),nF=require("fs"),{relative:Sae,join:Tae}=Xr,{existsSync:iF}=nF;function oF(){let e=__dirname;for(;!iF(Xr.join(e,"package.json"));){let t=Xr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(oF,"getHDBPackageRoot");var Qn=oF(),WA="js",Hl=WA,aF="harperdb-config.yaml",cF="defaultConfig.yaml",uF="hdb",QA=`harperdb.${Hl}`,zA=`customFunctionsServer.${Hl}`,lF=`restartHdb.${Hl}`,_h="HarperDB",Bl="Custom Functions",xl="Clustering Hub",ql="Clustering Leaf",_F="Clustering Ingest Service",dF="Clustering Reply Service",fF="foreground.pid",EF="hdb.pid",hF="data",mF={HDB:_h,CLUSTERING_HUB:xl,CLUSTERING_LEAF:ql,CLUSTERING_INGEST_SERVICE:_F,CLUSTERING_REPLY_SERVICE:dF,CUSTOM_FUNCTIONS:Bl,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},pF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},SF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},TF={harperdb:_h,"clustering hub":xl,"clustering leaf":ql,"custom functions":Bl,custom_functions:Bl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},gF={CLUSTERING_HUB_PROC_DESCRIPTOR:xl,CLUSTERING_LEAF_PROC_DESCRIPTOR:ql},lh={HDB:Xr.join(Qn,"server/harperdb"),CUSTOM_FUNCTIONS:Xr.join(Qn,"server/customFunctions"),CLUSTERING_HUB:Xr.join(Qn,"server/nats"),CLUSTERING_LEAF:Xr.join(Qn,"server/nats")},RF={HDB:Xr.join(lh.HDB,QA),CUSTOM_FUNCTIONS:Xr.join(lh.CUSTOM_FUNCTIONS,zA)},AF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Xr.join(Qn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Xr.join(Qn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Xr.join(Qn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},OF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},JA="support@harperdb.io",bF="customer-success@harperdb.io",jA=1,NF=4141,XA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",yF="https://www.harperdb.io/product",wF=`For support, please submit a request at ${XA} or contact ${JA}`,ZA=`For license support, please contact ${bF}`,IF="None of the specified records were found.",CF="hash attribute not found",DF=`Your current license only supports ${jA} role. ${ZA}`,LF="Your current license only supports 3 connections to a node.",UF="127.0.0.1",MF=1,PF=/^\.$/,vF=/^\.\.$/,BF="U+002E",HF=/\//g,xF="U+002F",qF=/U\+002F/g,FF=/^U\+002E$/,GF=/^U\+002EU\+002E$/,kF="d",VF=999999,$F="*",YF="--max-old-space-size=",KF="system",WF="__hdb_hash",QF=".harperdb",zF=".hdb",JF="keys",jF="hdb_boot_properties.file",XF=".updateConfig.json",ZF="SIGTSTP",eG=24,tG=6e4,rG=448,sG="blob",nG="trash",iG="database",oG="schema",aG="transactions",cG=".count",uG="id",lG="PROCESS_NAME",eO={SETTINGS_PATH_KEY:"settings_path"},tO=require("lodash"),_G={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},dG={HDB_PATH_KEY:"HDB_INTERNAL_PATH",HDB_AUTH_HEADER:"hdb_auth_header",HDB_USER_DATA_KEY:"hdb_user",CHUNK_SIZE:1e3,MAX_CHARACTER_SIZE:250},fG={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},EG={JOB_TABLE_NAME:"hdb_job",NODE_TABLE_NAME:"hdb_nodes",ATTRIBUTE_TABLE_NAME:"hdb_attribute",LICENSE_TABLE_NAME:"hdb_license",ROLE_TABLE_NAME:"hdb_role",SCHEMA_TABLE_NAME:"hdb_schema",TABLE_TABLE_NAME:"hdb_table",USER_TABLE_NAME:"hdb_user",INFO_TABLE_NAME:"hdb_info"},hG={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},br="hdb_internal:",mG={CREATE_SCHEMA:br+"create_schema",CREATE_TABLE:br+"create_table",CREATE_ATTRIBUTE:br+"create_attribute",ADD_USER:br+"add_user",ALTER_USER:br+"alter_user",DROP_USER:br+"drop_user",HDB_NODES:br+"hdb_nodes",HDB_USERS:br+"hdb_users",HDB_WORKERS:br+"hdb_workers",CATCHUP:br+"catchup",SCHEMA_CATCHUP:br+"schema_catchup",WORKER_ROOM:br+"cluster_workers"},pG={ATTR_ATTRIBUTE_KEY:"attribute",ATTR_CREATEDDATE_KEY:"createddate",ATTR_HASH_ATTRIBUTE_KEY:"hash_attribute",ATTR_ID_KEY:"id",ATTR_NAME_KEY:"name",ATTR_PASSWORD_KEY:"password",ATTR_RESIDENCE_KEY:"residence",ATTR_ROLE_KEY:"role",ATTR_SCHEMA_KEY:"schema",ATTR_SCHEMA_TABLE_KEY:"schema_table",ATTR_TABLE_KEY:"table",ATTR_USERNAME_KEY:"username"},SG="060493.ks",TG=".license",gG={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},X={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},RG={CSV:".csv",JSON:".json"},AG={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},OG={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},rc={};rc[X.INSERT]=X.INSERT;rc[X.UPDATE]=X.UPDATE;rc[X.UPSERT]=X.UPSERT;rc[X.DELETE]=X.DELETE;var He=Object.create(null);He[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;He[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;He[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;He[X.READ_LOG]=X.READ_LOG;He[X.ADD_NODE]=X.ADD_NODE;He[X.LIST_USERS]=X.LIST_USERS;He[X.LIST_ROLES]=X.LIST_ROLES;He[X.USER_INFO]=X.USER_INFO;He[X.SQL]=X.SQL;He[X.GET_JOB]=X.GET_JOB;He[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;He[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;He[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;He[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;He[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;He[X.REMOVE_NODE]=X.REMOVE_NODE;He[X.RESTART]=X.RESTART;He[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;He[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;He[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;He[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;He[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;He[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;He[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;He[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var bG={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},NG={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},rO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},yG=tO.invert(rO),wG={CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root"},I={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},sO={settings_path:eO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];sO[t.toLowerCase()]=t}var IG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},CG={csv_file_load:"csv_file_load",csv_data_load:X.CSV_DATA_LOAD,csv_url_load:X.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3"},DG={CLUSTERING_PAYLOAD:"clustering_payload",DELEGATE_THREAD_RESPONSE:"delegate_thread_response",CLUSTERING:"clustering",SCHEMA:"schema",CLUSTER_STATUS:"cluster_status",JOB:"job",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",USER:"user",RESTART:"restart"},LG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},UG={VERSION_DEFAULT:"2.2.0"},MG={DEVELOPMENT:8192,DEFAULT:512},PG={IDENTIFY:"identify",AUTHENTICATE:"authenticate",AUTHENTICATE_OK:"authenticated",AUTHENTICATE_FAIL:"authenticate_fail",CONNECTION:"connection",CONNECT:"connect",CATCHUP_REQUEST:"catchup_request",CATCHUP_RESPONSE:"catchup",CONFIRM_MSG:"confirm_msg",ERROR:"error",DISCONNECT:"disconnect",SCHEMA_UPDATE_REQ:"schema_update_request",SCHEMA_UPDATE_RES:"schema_update_response",RECONNECT_ATTEMPT:"reconnect_attempt",CONNECT_ERROR:"connect_error",MESSAGE:"msg",VERSION_MISMATCH:"version_mismatch",DIRECTION_CHANGE:"direction_change"},vG={1e3:"SUCCESSFUL_SHUTDOWN",1001:"CLOSE_GOING_AWAY",1002:"CLOSE_PROTOCOL_ERROR",1003:"CLOSE_UNSUPPORTED",1005:"CLOSE_NO_STATUS",1006:"CLOSE_ABNORMAL",1007:"UNSUPPORTED_PAYLOAD",1008:"POLICY_VIOLATION",1009:"CLOSE_TOO_LARGE",1010:"MANDATORY_EXTENSION",1011:"SERVER_ERROR",1012:"SERVICE_RESTART",1013:"SERVER_BUSY",1014:"BAD_GATEWAY",1015:"HANDSHAKE_FAIL",4141:"LICENSE_LIMIT_REACHED"},BG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},nO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},HG=Symbol("metadata"),xG="__clustering__",qG=Object.values(nO),FG=15984864e5,iO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},GG=tO.invert(iO),kG={GET_CLUSTER_STATUS:"GET_CLUSTER_STATUS",CLUSTER_STATUS_RESPONSE:"CLUSTER_STATUS_RESPONSE",ERROR_RESPONSE:"ERROR",ADD_USER:"ADD_USER",ALTER_USER:"ALTER_USER",DROP_USER:"DROP_USER",HDB_OPERATION:"HDB_OPERATION",ADD_NODE:"ADD_NODE",UPDATE_NODE:"UPDATE_NODE",REMOVE_NODE:"REMOVE_NODE",HDB_USERS_MSG:"HDB_USERS_MSG",HDB_WORKERS:"HDB_WORKERS",HDB_TRANSACTION:"HDB_TRANSACTION"},VG=111,$G=`\r
|
|
2
|
+
`,YG={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},KG=["*","%"],WG="unauthorized_access",QG="func_val",zG={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},JG={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"},XG={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},ZG={HTTP:"http"},ek={STOPPED:"stopped",ONLINE:"online"},tk="3.x.x",rk={SUCCESS:"success",FAILURE:"failure"},sk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};oO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:JA,HDB_SUPPORT_URL:XA,HDB_PRICING_URL:yF,SUPPORT_HELP_MSG:wF,LICENSE_HELP_MSG:ZA,HDB_PROC_NAME:QA,HDB_PROC_DESCRIPTOR:_h,CLUSTERING_LEAF_PROC_DESCRIPTOR:ql,CLUSTERING_HUB_PROC_DESCRIPTOR:xl,SYSTEM_SCHEMA_NAME:KF,HASH_FOLDER_NAME:WF,HDB_HOME_DIR_NAME:QF,UPDATE_FILE_NAME:XF,LICENSE_KEY_DIR_NAME:JF,BOOT_PROPS_FILE_NAME:jF,JOB_TYPE_ENUM:CG,JOB_STATUS_ENUM:gG,SYSTEM_TABLE_NAMES:EG,SYSTEM_TABLE_HASH_ATTRIBUTES:hG,OPERATIONS_ENUM:X,VALID_S3_FILE_TYPES:RG,S3_BUCKET_AUTH_KEYS:AG,VALID_SQL_OPS_ENUM:OG,GEO_CONVERSION_ENUM:NG,HDB_SETTINGS_NAMES:rO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:yG,SERVICE_ACTIONS_ENUM:bG,CLUSTER_MESSAGE_TYPE_ENUM:DG,CLUSTER_CONNECTION_DIRECTION_ENUM:LG,CLUSTER_EVENTS_DEFS_ENUM:PG,PERIOD_REGEX:PF,DOUBLE_PERIOD_REGEX:vF,UNICODE_PERIOD:BF,FORWARD_SLASH_REGEX:HF,UNICODE_FORWARD_SLASH:xF,ESCAPED_FORWARD_SLASH_REGEX:qF,ESCAPED_PERIOD_REGEX:FF,ESCAPED_DOUBLE_PERIOD_REGEX:GF,REG_KEY_FILE_NAME:SG,RESTART_TIMEOUT_MS:tG,HDB_FILE_PERMISSIONS:rG,DATABASES_DIR_NAME:iG,LEGACY_DATABASES_DIR_NAME:oG,TRANSACTIONS_DIR_NAME:aG,LIMIT_COUNT_NAME:cG,ID_ATTRIBUTE_STRING:uG,INSERT_MODULE_ENUM:dG,UPGRADE_JSON_FIELD_NAMES_ENUM:fG,RESTART_CODE:ZF,RESTART_CODE_NUM:eG,CLUSTER_OPERATIONS:rc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:pG,HDB_INTERNAL_SC_CHANNEL_PREFIX:br,INTERNAL_SC_CHANNELS:mG,CLUSTERING_MESSAGE_TYPES:kG,HDB_FILE_SUFFIX:zF,BLOB_FOLDER_NAME:sG,HDB_TRASH_DIR:nG,ORIGINATOR_SET_VALUE:VG,LICENSE_VALUES:UG,RAM_ALLOCATION_ENUM:MG,TIME_STAMP_NAMES_ENUM:nO,TIME_STAMP_NAMES:qG,PERMS_UPDATE_RELEASE_TIMESTAMP:FG,SEARCH_NOT_FOUND_MESSAGE:IF,SEARCH_ATTRIBUTE_NOT_FOUND:CF,LICENSE_ROLE_DENIED_RESPONSE:DF,LICENSE_MAX_CONNS_REACHED:LF,BASIC_LICENSE_MAX_NON_CU_ROLES:jA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:NF,VALUE_SEARCH_COMPARATORS:iO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:GG,LICENSE_FILE_NAME:TG,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:vG,NEW_LINE:$G,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:MF,MOMENT_DAYS_TAG:kF,API_TURNOVER_SEC:VF,LOOPBACK:UF,CODE_EXTENSION:Hl,WILDCARD_SEARCH_VALUE:$F,NODE_ERROR_CODES:BG,JAVASCRIPT_EXTENSION:WA,PERMS_CRUD_ENUM:YG,UNAUTHORIZED_PERMISSION_NAME:WG,SEARCH_WILDCARDS:KG,FUNC_VAL:QG,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:zG,JWT_ENUM:JG,CLUSTERING_FLAG:xG,ITC_EVENT_TYPES:jG,CUSTOM_FUNCTION_PROC_NAME:zA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Bl,SERVICES:XG,THREAD_TYPES:ZG,MEM_SETTING_KEY:YF,HDB_RESTART_SCRIPT:lF,PROCESS_DESCRIPTORS:mF,SERVICE_SERVERS:RF,SERVICE_SERVERS_CWD:lh,PROCESS_DESCRIPTORS_VALIDATE:TF,LAUNCH_SERVICE_SCRIPTS:AF,LOG_LEVELS:SF,PROCESS_NAME_ENV_PROP:lG,LOG_NAMES:pF,PM2_PROCESS_STATUSES:ek,CONFIG_PARAM_MAP:sO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:aF,HDB_DEFAULT_CONFIG_FILE:cF,ROLE_TYPES_ENUM:OF,BOOT_PROP_PARAMS:eO,INSTALL_PROMPTS:_G,HDB_ROOT_DIR_NAME:uF,CLUSTERING_PROCESSES:gF,FOREGROUND_PID_FILE:fF,PACKAGE_ROOT:Qn,PRE_4_0_0_VERSION:tk,DATABASES_PARAM_CONFIG:IG,METADATA_PROPERTY:HG,AUTH_AUDIT_STATUS:rk,AUTH_AUDIT_TYPES:sk,HDB_PID_FILE:EF,DEFAULT_DATABASE_NAME:hF,LEGACY_CONFIG_PARAMS:wG};KA()});var dh=T((Aae,uO)=>{"use strict";var aO=require("minimist");uO.exports=nk;function nk(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=cO(process.env),s=cO(aO(process.argv))):(r=process.env,s=aO(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(nk,"assignCMDENVVariables");function cO(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(cO,"objKeysToLowerCase")});var V=T((bae,Th)=>{"use strict";var Ui=require("fs-extra"),{workerData:ik,threadId:ok}=require("worker_threads"),En=require("path"),dO=require("yaml"),fO=require("properties-reader"),Rt=L(),lO=dh(),ak=require("os"),{PACKAGE_ROOT:Eh}=L(),{_assignPackageExport:ck}=require("../index"),nc={};for(let e in console)nc[e]||(nc[e]=console[e]);var er={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},EO={STDOUT:"stdOut",STDERR:"stdErr"},uk=En.join(Eh,"logs"),lk=En.join(Eh,"config/yaml/",Rt.HDB_DEFAULT_CONFIG_FILE),_k=1e4,fn,ks,Zt,Fl,Gl,ic,Bo,sc;sc===void 0&&hO();Th.exports={notify:SO,fatal:TO,error:oc,warn:Sh,info:kl,debug:ph,trace:mh,setLogLevel:Sk,log_level:Zt,loggerWithTag:dk,suppressLogging:fk,initLogSettings:hO,setupConsoleLogging:mO,logCustomLevel:mk,closeLogFile:hh,getLogFilePath:()=>ic,OUTPUTS:EO,AuthAuditLog:Rk};ck("logger",Th.exports);function hO(e=!1){try{if(sc===void 0||e){hh();let t=pk(),r=lO(["ROOTPATH"]);try{sc=fO(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!Ui.pathExistsSync(En.join(r.ROOTPATH,Rt.HDB_CONFIG_FILE)))throw s}({level:Zt,config_log_path:Gl,to_file:fn,to_stream:ks}=Tk(r.ROOTPATH?En.join(r.ROOTPATH,Rt.HDB_CONFIG_FILE):sc.get("settings_path"))),Fl=Rt.LOG_NAMES.HDB,ic=En.join(Gl,Fl)}}catch(t){if(sc=void 0,t.code===Rt.NODE_ERROR_CODES.ENOENT){let r=lO(Object.keys(Rt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Rt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Rt.CONFIG_PARAMS.LOGGING_LEVEL){Zt=u;continue}if(c===Rt.CONFIG_PARAMS.LOGGING_STDSTREAMS){ks=u;continue}c===Rt.CONFIG_PARAMS.LOGGING_FILE&&(fn=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=gk();fn=fn===void 0?n:fn,fn=_O(fn),ks=ks===void 0?i:ks,ks=_O(ks),Zt=Zt===void 0?s:Zt,Gl=uk,Fl=Rt.LOG_NAMES.INSTALL,ic=En.join(Gl,Fl);return}throw oc("Error initializing log settings"),oc(t),t}process.env.DEV_MODE&&(ks=!0),mO()}a(hO,"initLogSettings");var fh=!0;function mO(){vo("error",oc),vo("warn",Sh),vo("log",kl),vo("info",kl),vo("debug",ph),vo("trace",mh)}a(mO,"setupConsoleLogging");function vo(e,t){console[e]=function(...r){if(fh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return nc[e](...r)}}a(vo,"logConsole");function dk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(SO),fatal:r(TO),error:r(oc),warn:r(Sh),info:r(kl),debug:r(ph),trace:r(mh)};function r(s){return function(...n){return s(t,...n)}}}a(dk,"loggerWithTag");function fk(e){try{fh=!1,e()}finally{fh=!0}}a(fk,"suppressLogging");var Ek=ik?.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||Ek+"/"+ok);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&&pO(e),ks&&process.stdout.write(e)}a(ac,"logStdOut");function Vl(e){fn&&pO(e),ks&&process.stderr.write(e)}a(Vl,"logStdErr");function pO(e){hk(),Bo?Ui.appendFileSync(Bo,e):nc.log(e)}a(pO,"logToFile");function hh(){try{Ui.closeSync(Bo)}catch{}Bo=null}a(hh,"closeLogFile");function hk(){if(!Bo){try{if(!ic)debugger;Bo=Ui.openSync(ic,"a")}catch(e){nc.error(e)}setTimeout(()=>{hh()},_k).unref()}}a(hk,"openLogFile");function kl(...e){er[Zt]<=er.info&&ac(hn("info",e))}a(kl,"info");function mh(...e){er[Zt]<=er.trace&&ac(hn("trace",e))}a(mh,"trace");function oc(...e){er[Zt]<=er.error&&Vl(hn("error",e))}a(oc,"error");function ph(...e){er[Zt]<=er.debug&&ac(hn("debug",e))}a(ph,"debug");function SO(...e){er[Zt]<=er.notify&&ac(hn("notify",e))}a(SO,"notify");function TO(...e){er[Zt]<=er.fatal&&Vl(hn("fatal",e))}a(TO,"fatal");function Sh(...e){er[Zt]<=er.warn&&Vl(hn("warn",e))}a(Sh,"warn");function mk(e,t,...r){t===EO.STDERR?Vl(hn(e,r)):ac(hn(e,r))}a(mk,"logCustomLevel");function pk(){let e;try{e=ak.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=En.join(e,Rt.HDB_HOME_DIR_NAME,Rt.BOOT_PROPS_FILE_NAME);return Ui.existsSync(t)||(t=En.join(Eh,"utility/hdb_boot_properties.file")),t}a(pk,"getPropsFilePath");function Sk(e){Zt=e}a(Sk,"setLogLevel");function _O(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(_O,"autoCastBoolean");function Tk(e){try{if(e.includes("config/settings.js")){let o=fO(e);return{level:o.get(Rt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:En.dirname(o.get(Rt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Rt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Rt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=dO.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===Rt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Tk,"getLogConfig");function gk(){try{let e=dO.parseDocument(Ui.readFileSync(lk,"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(gk,"getDefaultConfig");function Rk(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(Rk,"AuthAuditLog")});var RO=T((yae,gO)=>{"use strict";var Ak=require("util"),Ok=require("path"),bk=require("child_process"),Nk=Ak.promisify(bk.execFile),yk=1e3*1e3*10;gO.exports={findPs:wk};async function wk(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await Nk("ps",["wwxo",`pid,${r}`],{maxBuffer:yk});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:Ok.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(wk,"findPs")});var dt=T((Iae,OO)=>{"use strict";var Ik="__dbis__",Ck="__txns__",Dk="__environment_name__",Lk="__dbi_defintion__",Uk={EQUALS:"equals",STARTS_WITH:"startsWith",_STARTS_WITH:"starts_with",ENDS_WITH:"endsWith",_ENDS_WITH:"ends_with",CONTAINS:"contains",SEARCH_ALL:"searchAll",SEARCH_ALL_TO_MAP:"searchAllToMap",BATCH_SEARCH_BY_HASH:"batchSearchByHash",BATCH_SEARCH_BY_HASH_TO_MAP:"batchSearchByHashToMap",GREATER_THAN:"greaterThan",_GREATER_THAN:"greater_than",GREATER_THAN_EQUAL:"greaterThanEqual",_GREATER_THAN_EQUAL:"greater_than_equal",LESS_THAN:"lessThan",_LESS_THAN:"less_than",LESS_THAN_EQUAL:"lessThanEqual",_LESS_THAN_EQUAL:"less_than_equal",BETWEEN:"between"},Mk=["__createdtime__","__updatedtime__"],Pk="\uFFFF",AO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},vk=Object.values(AO);OO.exports={AUDIT_STORE_NAME:Ck,INTERNAL_DBIS_NAME:Ik,DBI_DEFINITION_NAME:Lk,SEARCH_TYPES:Uk,TIMESTAMP_NAMES:Mk,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Dk,TRANSACTIONS_DBI_NAMES_ENUM:AO,TRANSACTIONS_DBIS:vk,OVERFLOW_MARKER:Pk}});var Nr=T((Cae,UO)=>{"use strict";var bO=L(),NO=dt(),yO={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},wO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),IO={500:wO("There was an error processing your request."),400:"Invalid request"},Bk=IO[yO.INTERNAL_SERVER_ERROR],Hk={OP_NOT_SUPPORTED_FOR_FS:e=>`${e} is not available for this instance because it uses the File System data store.`,MISSING_VALUE:e=>`${e} is missing.`,INVALID_VALUE:e=>`${e} is invalid.`,NOT_FOUND:e=>`${e} not found.`},xk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},qk={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:e=>`There was an error downloading '${e}'.`,INSERT_JSON_ERR:"There was an error inserting the downloaded JSON data.",INSERT_CSV_ERR:"There was an error inserting the downloaded CSV data.",INVALID_ACTION_PARAM_ERR:e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,INVALID_FILE_EXT_ERR:e=>`Error selecting correct parser - valid file type not found in json - ${e}`,MAX_FILE_SIZE_ERR:(e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:e=>`There was an error downloading '${e}' from AWS.`,WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},Fk={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${NO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${NO.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},Gk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${bO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${bO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},CO={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},kk={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},Vk={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},$k={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},Yk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Kk={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},DO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},LO={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},Wk={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file."},Qk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},zk={...CO,...qk,...Hk,...kk,...Vk,...$k,...Yk,...Kk,...Gk,...DO,...LO,...Wk,...Qk,...xk};UO.exports={CHECK_LOGS_WRAPPER:wO,HDB_ERROR_MSGS:zk,DEFAULT_ERROR_MSGS:IO,DEFAULT_ERROR_RESP:Bk,HTTP_STATUS_CODES:yO,LMDB_ERRORS_ENUM:Fk,AUTHENTICATION_ERROR_MSGS:CO,VALIDATION_ERROR_MSGS:DO,ITC_ERRORS:LO}});var re=T((Lae,vO)=>{"use strict";var Ho=Nr(),Jk=V(),jk=L(),$l=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,MO),this.statusCode=s||Ho.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Ho.DEFAULT_ERROR_MSGS[s]?Ho.DEFAULT_ERROR_MSGS[s]:Ho.DEFAULT_ERROR_MSGS[Ho.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&Jk[n](i)}},gh=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},Rh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function MO(e,t,r,s=jk.LOG_LEVELS.ERROR,n=null,i=!1){if(PO(e))return e;let o=new $l(e,t,r,s,n);return i&&delete o.stack,o}a(MO,"handleHDBError");function PO(e){return e.__proto__.constructor.name===$l.name}a(PO,"isHDBError");vO.exports={isHDBError:PO,handleHDBError:MO,ClientError:gh,ServerError:Rh,hdb_errors:Ho}});var Je=T((Mae,kO)=>{"use strict";var dc=L(),Xk=J(),tr=Z(),fc=require("path"),Zk=require("minimist"),BO=require("fs-extra"),HO=require("lodash");tr.initSync();var{CONFIG_PARAMS:zn,DATABASES_PARAM_CONFIG:cc,SYSTEM_SCHEMA_NAME:Yl}=dc,uc,lc,_c;function xO(){if(uc!==void 0)return uc;if(tr.getHdbBasePath()!==void 0)return uc=tr.get(zn.STORAGE_PATH)||fc.join(tr.getHdbBasePath(),dc.DATABASES_DIR_NAME),uc}a(xO,"getBaseSchemaPath");function qO(){if(lc!==void 0)return lc;if(tr.getHdbBasePath()!==void 0)return lc=GO(Yl),lc}a(qO,"getSystemSchemaPath");function FO(){if(_c!==void 0)return _c;if(tr.getHdbBasePath()!==void 0)return _c=tr.get(dc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||fc.join(tr.getHdbBasePath(),dc.TRANSACTIONS_DIR_NAME),_c}a(FO,"getTransactionAuditStoreBasePath");function eV(e,t){let r=tr.get(zn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||fc.join(FO(),e.toString())}a(eV,"getTransactionAuditStorePath");function GO(e,t){e=e.toString(),t=t&&t.toString();let r=tr.get(dc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||fc.join(xO(),e)}a(GO,"getSchemaPath");function tV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,Zk(process.argv));let s=r[zn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!Xk.isObject(s))throw o;i=s}for(let o of i){let c=o[Yl];if(!c)continue;let u=tr.get(zn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[cc.PATH];if(_)return HO.set(u,[Yl,cc.TABLES,t,cc.PATH],_),tr.setProperty(zn.DATABASES,u),_;let l=c?.[cc.PATH];if(l)return HO.set(u,[Yl,cc.PATH],l),tr.setProperty(zn.DATABASES,u),l}}let n=r[zn.STORAGE_PATH.toUpperCase()];if(n){if(!BO.pathExistsSync(n))throw new Error(n+" does not exist");let i=fc.join(n,e);return BO.mkdirsSync(i),tr.setProperty(zn.STORAGE_PATH,n),i}return qO()}a(tV,"initSystemSchemaPaths");function rV(){uc=void 0,lc=void 0,_c=void 0}a(rV,"resetPaths");kO.exports={getBaseSchemaPath:xO,getSystemSchemaPath:qO,getTransactionAuditStorePath:eV,getTransactionAuditStoreBasePath:FO,getSchemaPath:GO,initSystemSchemaPaths:tV,resetPaths:rV}});var yr=T((Hae,WO)=>{"use strict";var sV=Nr().LMDB_ERRORS_ENUM,vae=require("lmdb"),nV=dt(),Bae=require("buffer").Buffer,{OVERFLOW_MARKER:VO,MAX_SEARCH_KEY_LENGTH:Kl}=nV,$O=["number","string","symbol","boolean","bigint"];function iV(e){if(e=e?.primaryStore||e,!e)throw new Error(sV.ENV_REQUIRED)}a(iV,"validateEnv");function oV(e){if(e==null)return null;let t;try{t=typeof e=="object"?JSON.stringify(e):e.toString()}catch{t=e.toString()}return t}a(oV,"stringifyData");function aV(e){return e instanceof Date?e.valueOf():e}a(aV,"convertKeyValueToWrite");function cV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if($O.includes(typeof e))return e.length>Kl?[e.slice(0,Kl)+VO]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if($O.includes(typeof i))i.length>Kl?r.push(i.slice(0,Kl)+VO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(cV,"getIndexedValues");var Wl=0,YO=0;function KO(){YO=Date.now()-performance.now()}a(KO,"adjustStartTime");KO();var uV=6e4;setInterval(KO,uV).unref();function lV(){let e=performance.now()+YO;return e>Wl?(Wl=e,e):(Wl+=488e-6,Wl)}a(lV,"getNextMonotonicTime");WO.exports={validateEnv:iV,stringifyData:oV,convertKeyValueToWrite:aV,getNextMonotonicTime:lV,getIndexedValues:cV}});var QO,Rs,Ah,Ec=Re(()=>{QO=require("events"),Rs=class extends QO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Ah;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},Ah=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Mi={};Ye(Mi,{server:()=>tt});var zO,tt,rr=Re(()=>{zO=require("../index"),tt={};(0,zO._assignPackageExport)("server",tt)});var Nh={};Ye(Nh,{loadGQLSchema:()=>fV,start:()=>bh,startOnMainThread:()=>dV});function bh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),n)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let K=H(v.type);return K.nullable=!1,K}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let Y={type:v.name?.value};return Object.defineProperty(Y,"location",{value:v.loc.startToken}),Y};a(H,"getProperty");let A=S.name.value,R=[],g={table:null,database:null,properties:R};f.set(A,g);for(let v of S.directives){if(v.name.value==="table"){for(let U of v.arguments)g[U.name.value]=U.value.value;g.schema&&(g.database=g.schema),g.table||(g.table=A),g.audit&&(g.audit=g.audit!=="false"),g.attributes=g.properties,E.push(g)}if(v.name.value==="sealed"&&(g.sealed=!0),v.name.value==="export"){g.export=!0;for(let U of v.arguments)U.name.value==="name"&&(g.export={name:U.value.value})}}let P=!1;for(let v of S.fields){let U=H(v.type);U.name=v.name.value,R.push(U);for(let Y of v.directives)if(Y.name.value==="primaryKey")P?console.warn("Can not define two attributes as a primary key"):(U.isPrimaryKey=!0,P=!0);else if(Y.name.value==="indexed")U.indexed=!0;else if(Y.name.value==="relationship"){let K={};for(let z of Y.arguments)K[z.name.value]=z.value.value;U.relationship=K}else if(Y.name.value==="createdTime")U.assignCreatedTime=!0;else if(Y.name.value==="updatedTime")U.assignUpdatedTime=!0;else if(Y.name.value==="expiresAt")U.expiresAt=!0;else if(Y.name.value==="allow"){let K=U.authorizedRoles=[];for(let z of Y.arguments)z.name.value==="role"&&K.push(z.value.value)}}g.type=A,A==="Query"&&(h=g)}function p(S){let A=f.get(S.type);A?(Object.defineProperty(S,"properties",{value:A.properties}),Object.defineProperty(S,"definition",{value:A})):S.type==="array"?p(S.elements):_V.includes(S.type)||(0,JO.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${n}`)}a(p,"connectPropertyType");for(let S of f.values())for(let A of S.properties)p(A);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Oh.dirname)(s),S.tableClass):i.set((0,Oh.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass))}}var Oh,JO,_V,dV,fV,jO=Re(()=>{Oh=require("path");Ae();JO=x(Ke()),_V=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(bh,"start");dV=bh,fV=bh({ensureTable:ct}).handleFile});async function Ql(e){return EV?(hc||(hc=hV(pV)),(await(await hc).import(e)).namespace):import(e)}async function hV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),hc=new Compartment({console,Math,Date,fetch:mV,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,ZO.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:xt,tables:wr,databases:rt})}};let s=await(0,XO.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),hc}function mV(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function pV(){return{Resource:xt,tables:wr}}var XO,ZO,EV,hc,yh=Re(()=>{As();Ae();XO=require("fs/promises"),ZO=require("path"),EV=!1;a(Ql,"secureImport");a(hV,"getCompartment");a(mV,"secureOnlyFetch");a(pV,"getGlobalVars")});var Ih={};Ye(Ih,{handleFile:()=>SV});async function SV(e,t,r,s){let n=new Map,i=(0,eb.pathToFileURL)(r).toString(),o=await Ql(i);u(o.default)&&s.set((0,wh.dirname)(t),o.default),c(o,(0,wh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?s.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),n}var eb,wh,tb=Re(()=>{eb=require("url");yh();wh=require("path");a(SV,"handleFile")});var Dh={};Ye(Dh,{start:()=>TV});function TV({resources:e}){e.set("login",Ch),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Ch,rb=Re(()=>{As();a(TV,"start");Ch=class extends xt{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var ub={};Ye(ub,{parse:()=>Uh,streamAsJSON:()=>mc,stringify:()=>Pi});function mc(e){return new Lh({value:e})}function sb(e){return console.error(e),JSON.stringify(e.toString())}function nb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Pi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===ab)return cb(e);if(t.resolution)return t.resolution.then(()=>Pi(e));throw t}}function cb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let s=0;s<e.length;s++)s>0&&(r+=","),r+=cb(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+Pi(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Uh(e){return AV.test(e)?gV.parse(e):JSON.parse(e)}var ib,ob,gV,RV,ab,Lh,AV,Mh=Re(()=>{ib=require("stream"),ob=x(require("json-bigint-fixes")),gV=(0,ob.default)({useNativeBigInt:!0}),RV=1e4,ab={};BigInt.prototype.toJSON=function(){throw ab};a(mc,"streamAsJSON");Lh=class extends ib.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),sb)}catch(n){yield sb(n)}else yield Pi(t)}else yield Pi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);nb(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>RV?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return nb(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let s of this.activeIterators)t?s.throw(t):s.return();r()}};a(sb,"handleError");a(nb,"when");a(Pi,"stringify");a(cb,"jsStringify");AV=/-?\d{16,}/;a(Uh,"parse")});var Ab=T((Zae,Rb)=>{"use strict";var Ph=require("recursive-iterator"),OV=require("alasql"),vh=require("clone"),lb=J(),{handleHDBError:_b,hdb_errors:bV}=re(),{HDB_ERROR_MSGS:db,HTTP_STATUS_CODES:fb}=bV,{getDatabases:NV}=(Ae(),se(Fe)),yV=["DISTINCT_ARRAY"],Eb=Symbol("validateTables"),Bh=Symbol("validateTable"),Xae=Symbol("getAllColumns"),hb=Symbol("validateAllColumns"),zl=Symbol("findColumn"),mb=Symbol("validateOrderBy"),pc=Symbol("validateSegment"),Hh=Symbol("validateColumn"),pb=Symbol("setColumnsForTable"),Sb=Symbol("checkColumnsForAsterisk"),Tb=Symbol("validateGroupBy"),gb=Symbol("hasColumns"),xh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Eb](),this[Sb](),this[hb]()}[Eb](){if(this[gb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Bh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Bh](t.table)})}}[gb](){let t=!1,r=new Ph(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Bh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=NV();if(!r[t.databaseid])throw _b(new Error,db.SCHEMA_NOT_FOUND(t.databaseid),fb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw _b(new Error,db.TABLE_NOT_FOUND(t.databaseid,t.tableid),fb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=vh(n);i.table=vh(t),this.attributes.push(i)})}[zl](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[Sb](){let t=new Ph(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[pb](r.tableid)}[pb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new OV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[hb](){this[pc](this.statement.columns,!1),this[pc](this.statement.joins,!1),this[pc](this.statement.where,!1),this[Tb](this.statement.group,!1),this[pc](this.statement.order,!0)}[pc](t,r){if(!t)return;let s=new Ph(t),n=[];for(let{node:i,path:o}of s)!lb.isEmpty(i)&&!lb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[mb](i):n.push(this[Hh](i)));return n}[Tb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&yV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=vh(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[zl](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[zl](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[mb](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[Hh](t)}[Hh](t){let r=this[zl](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};Rb.exports=xh});var bb=T((tce,Ob)=>{"use strict";var qh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Ob.exports=qh});var yb=T((sce,Nb)=>{"use strict";var Fh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Nb.exports=Fh});var Db={};Ye(Db,{HAS_EXPIRATION:()=>Qh,LAST_TIMESTAMP_PLACEHOLDER:()=>gc,LOCAL_TIMESTAMP:()=>wV,METADATA:()=>Sc,NO_TIMESTAMP:()=>kh,PENDING_LOCAL_TIME:()=>zh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Wh,RecordEncoder:()=>Yh,TIMESTAMP_ASSIGN_LAST:()=>CV,TIMESTAMP_ASSIGN_NEW:()=>Ib,TIMESTAMP_ASSIGN_PREVIOUS:()=>Cb,TIMESTAMP_PLACEHOLDER:()=>Jl,TIMESTAMP_RECORD_PREVIOUS:()=>Vh,fromResource:()=>e_,getUpdateRecord:()=>Jh,handleLocalTimeForGets:()=>t_});function LV(){return Tc[0]=Tc[0]^64,IV.getFloat64(0)}function e_(e){Kh=!0;try{return e()}finally{Kh=!1}}function t_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[Sc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[Sc]>=0?c.value:c};let s=e.getRange;e.getRange=function(i){let o=s.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[Sc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let n=e.useReadTransaction();if(n.done(),!n.done.isTracked){let i=n.constructor,o=n.use,c=n.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,vi.push(new WeakRef(this))),!Kh)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<vi.length;u++){let _=vi[u].deref();(!_||_.isDone||_.isCommitted)&&vi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Jh(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?xo=i?.localTime?Vh|Cb:kh:xo=u?i?.localTime?Vh|16384:Ib|16384:kh,l>0&&(c|=Qh),Xl=c,$h=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:xo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(u){let A=_?.user?.username;if(E&&(jl=e.encoder.encode(E)),f&&i?.localTime){let R=i?.localTime,g=r.get(R);if(g){let P=Lt(g).previousLocalTime;return r.put(R,Zl(o,t,s,P,A,d,jl),{ifVersion:p}),S}}r.put(gc,Zl(o,t,s,i?.localTime?1:0,A,d,jl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var wb,Gh,Jl,gc,Wh,wV,Sc,Tc,IV,kh,Ib,CV,Cb,Vh,Qh,zh,DV,jl,xo,Xl,$h,Yh,oce,Kh,vi,qo=Re(()=>{wb=require("msgpackr");Bi();Gh=x(V()),Jl=new Uint8Array([1,1,1,1,4,64,0,0]),gc=new Uint8Array([1,1,1,1,1,0,0,0]),Wh=new Uint8Array([1,1,1,1,3,64,0,0]),wV=Symbol("local-timestamp"),Sc=Symbol("metadata"),Tc=new Uint8Array(8),IV=new DataView(Tc.buffer,0,8),kh=0,Ib=0,CV=1,Cb=3,Vh=4,Qh=16,zh=1,xo=0,Xl=-1,$h=0,Yh=class extends wb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){if(xo||Xl>=0){let i=0,o=xo;o&&(i+=8,xo=0);let c=Xl,u=$h;c>=0&&(i+=2,Xl=-1,u&&(i+=8,$h=0));let _=DV=r.call(this,s,n|2048|i);jl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Jl[4]=o,Jl[5]=o>>8,_.set(Jl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,s,n)}}decode(t,r){let s=r?.start||0,n=r>-1?r:r?.end||t.length,i=t[s],o=0;try{if(i<32&&n>2){let c=s,u;if(i===2){if(t.copy)t.copy(Tc,0,c),c+=8;else for(let d=0;d<8;d++)Tc[d]=t[c++];u=LV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Qh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,n),n-c);return{localTime:u,value:l,[Sc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(LV,"getTimestamp");oce=Map.prototype.get;a(e_,"fromResource");a(t_,"handleLocalTimeForGets");vi=[];setInterval(()=>{for(let e=0;e<vi.length;e++){let t=vi[e].deref();!t||t.isDone||t.isCommitted?vi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(Gh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Gh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Jh,"getUpdateRecord")});var r_=T((cce,Lb)=>{"use strict";var Xh=Z(),Zh=L(),{RecordEncoder:UV}=(qo(),se(Db));Xh.initSync();var MV=Xh.get(Zh.CONFIG_PARAMS.STORAGE_COMPRESSION),PV=Xh.get(Zh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,vV=Zh.UPDATES_PROPERTY,jh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=MV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=PV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:UV},this.alwaysLazyProperty=s=>s===vV)}};Lb.exports=jh});var n_=T((lce,Mb)=>{"use strict";var Fo=Z(),Rc=L();Fo.initSync();var BV=Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Fo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Ub=Fo.get(Rc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),HV=Fo.get(Rc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),s_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=BV,this.noFSAccess=!0,Ub!==void 0&&(this.overlappingSync=Ub),this.noReadAhead=HV}};Mb.exports=s_;s_.MAX_DBS=1e4});var We=T((dce,Vb)=>{"use strict";var tm=require("lmdb"),Os=require("fs-extra"),Ir=require("path"),i_=yr(),Bb=V(),sr=Nr().LMDB_ERRORS_ENUM,o_=yb(),rm=r_(),Hb=n_(),Jn=dt(),Pb=L(),{table:xV,resetDatabases:qV}=(Ae(),se(Fe)),vb=Z(),bs=Jn.INTERNAL_DBIS_NAME,xb=Jn.DBI_DEFINITION_NAME,FV="data.mdb",GV="lock.mdb",Ac=".mdb",kV="-lock",em=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=Zr(t,r),this.key_type=this.dbi[Jn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Jn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new tm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function a_(e,t){if(e===void 0)throw new Error(sr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(sr.ENV_NAME_REQUIRED)}a(a_,"pathEnvNameValidation");async function sm(e,t,r=!0){try{await Os.access(e)}catch(s){throw s.code==="ENOENT"?new Error(sr.INVALID_BASE_PATH):s}try{let s=Ir.join(e,t+Ac);return await Os.access(s,Os.constants.R_OK|Os.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Os.access(Ir.join(e,t,FV),Os.constants.R_OK|Os.constants.F_OK),Ir.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(sr.INVALID_ENVIRONMENT)}else throw new Error(sr.INVALID_ENVIRONMENT);throw s}}a(sm,"validateEnvironmentPath");function c_(e,t){if(i_.validateEnv(e),t===void 0)throw new Error(sr.DBI_NAME_REQUIRED)}a(c_,"validateEnvDBIName");async function VV(e,t,r=!1,s=!1){a_(e,t);let n=Ir.basename(e);t=t.toString();let i=vb.get(Pb.CONFIG_PARAMS.DATABASES);i||vb.setProperty(Pb.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await sm(e,t,s),qb(e,t,r)}catch(o){if(o.message===sr.INVALID_ENVIRONMENT){let c=Ir.join(e,t);await Os.mkdirp(s?c:e);let u=new Hb(s?c:c+Ac,!1),_=tm.open(u);_.dbis=Object.create(null);let l=new rm(!1);_.openDB(bs,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=nm(e,t,r);return _[Jn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(VV,"createEnvironment");async function $V(e,t,r,s=!0){a_(e,t),t=t.toString();let n=Ir.join(e,t);return xV({table:t,database:Ir.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a($V,"copyEnvironment");async function qb(e,t,r=!1){a_(e,t),t=t.toString();let s=nm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await sm(e,t),i=Ir.join(e,t+Ac),o=n!=i,c=new Hb(n,o),u=tm.open(c);u.dbis=Object.create(null);let _=Gb(u);for(let l=0;l<_.length;l++)Zr(u,_[l]);return u[Jn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(qb,"openEnvironment");async function YV(e,t,r=!1){a_(e,t),t=t.toString();let s=Ir.join(e,t+Ac),n=await sm(e,t);if(global.lmdb_map!==void 0){let i=nm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Fb(o),delete global.lmdb_map[i]}}await Os.remove(n),await Os.remove(n===s?n+kV:Ir.join(Ir.dirname(n),GV))}a(YV,"deleteEnvironment");async function Fb(e){i_.validateEnv(e);let t=e[Jn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Fb,"closeEnvironment");function nm(e,t,r=!1){let n=`${Ir.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(nm,"getCachedEnvironmentName");function KV(e){i_.validateEnv(e);let t=Object.create(null),r=Zr(e,bs);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==bs)try{t[s]=Object.assign(new o_,n)}catch{Bb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(KV,"listDBIDefinitions");function Gb(e){i_.validateEnv(e);let t=[],r=Zr(e,bs);for(let{key:s}of r.getRange({start:!1}))s!==bs&&t.push(s);return t}a(Gb,"listDBIs");function WV(e,t){let s=Zr(e,bs).getEntry(t),n=new o_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Bb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(WV,"getDBIDefinition");function kb(e,t,r,s=!r){if(c_(e,t),t=t.toString(),t===bs)throw new Error(sr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Zr(e,t)}catch(n){if(n.message===sr.DBI_DOES_NOT_EXIST){let i=new rm(r,s===!0),o=e.openDB(t,i),c=new o_(r===!0,s);return o[xb]=c,Zr(e,bs).putSync(t,c),e.dbis[t]=o,o}throw n}}a(kb,"createDBI");function Zr(e,t){if(c_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==bs?r=WV(e,t):r=new o_,r===void 0)throw new Error(sr.DBI_DOES_NOT_EXIST);let s;try{let n=new rm(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(sr.DBI_DOES_NOT_EXIST):n}return s[xb]=r,e.dbis[t]=s,s}a(Zr,"openDBI");function QV(e,t){c_(e,t),t=t.toString();let r=Zr(e,t),s=r.getStats();return r[Jn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(QV,"statDBI");async function zV(e,t){try{let r=Ir.join(e,t+Ac);return(await Os.stat(r)).size}catch{throw new Error(sr.INVALID_ENVIRONMENT)}}a(zV,"environmentDataSize");function JV(e,t){if(c_(e,t),t=t.toString(),t===bs)throw new Error(sr.CANNOT_DROP_INTERNAL_DBIS_NAME);Zr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Zr(e,bs).removeSync(t)}a(JV,"dropDBI");function jV(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{Zr(e,i)}catch(o){if(o.message===sr.DBI_DOES_NOT_EXIST)kb(e,i,i!==t,i===t),s=!0;else throw o}}s&&qV()}a(jV,"initializeDBIs");Vb.exports={openDBI:Zr,openEnvironment:qb,createEnvironment:VV,listDBIs:Gb,listDBIDefinitions:KV,createDBI:kb,dropDBI:JV,statDBI:QV,deleteEnvironment:YV,initializeDBIs:jV,TransactionCursor:em,environmentDataSize:zV,copyEnvironment:$V,closeEnvironment:Fb}});var Yb=T((Ece,$b)=>{"use strict";var im=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};$b.exports=im});var Wb=T((mce,Kb)=>{"use strict";var om=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};Kb.exports=om});var zb=T((Sce,Qb)=>{"use strict";var am=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};Qb.exports=am});var Go=T((Oce,Xb)=>{"use strict";var XV=We(),ZV=Yb(),e$=Wb(),t$=zb(),Vs=yr(),Oc=Nr().LMDB_ERRORS_ENUM,r$=dt(),mn=L(),s$=J(),n$=require("uuid"),gce=require("lmdb"),{handleHDBError:i$,hdb_errors:o$}=re(),{OVERFLOW_MARKER:Rce,MAX_SEARCH_KEY_LENGTH:Ace}=r$,Jb=Z();Jb.initSync();var u_=Jb.get(mn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),cm=mn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Hi=mn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function a$(e,t,r,s,n=Vs.getNextMonotonicTime()){dm(e,t,r,s),um(e,t,r);let i=new ZV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];jb(_,!0,n);let l=c$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return lm(o,c,s,i,n)}a(a$,"insertRecords");function c$(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][mn.FUNC_VAL],s[o]=c)}let u=Vs.getIndexedValues(c),_=e.dbis[o];if(u){u_&&_.prefetch(u.map(l=>({key:l,value:n})),l_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}u_&&e.dbis[t].prefetch([n],l_),e.dbis[t].put(n,s,s[Hi])})}a(c$,"insertRecord");function u$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(u$,"removeSkippedRecords");function jb(e,t,r){let s=r>0;(s||!Number.isInteger(e[Hi]))&&(e[Hi]=r||(r=Vs.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[cm]))&&(e[cm]=r||Vs.getNextMonotonicTime()):delete e[cm]}a(jb,"setTimestamps");function um(e,t,r){r.indexOf(mn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(mn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(mn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(mn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),XV.initializeDBIs(e,t,r)}a(um,"initializeTransaction");async function l$(e,t,r,s,n=Vs.getNextMonotonicTime()){dm(e,t,r,s),um(e,t,r);let i=new e$,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=_m(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return lm(c,u,s,i,n,o)}a(l$,"updateRecords");async function _$(e,t,r,s,n=Vs.getNextMonotonicTime()){try{dm(e,t,r,s)}catch(u){throw i$(u,u.message,o$.HTTP_STATUS_CODES.BAD_REQUEST)}um(e,t,r);let i=new t$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;s$.isEmpty(_[t])?(l=n$.v4(),_[t]=l):l=_[t];let d=_m(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return lm(o,c,s,i,n)}a(_$,"upsertRecords");async function lm(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||Vs.getNextMonotonicTime(),u$(r,i),s}a(lm,"finalizeWrite");function _m(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(jb(r,!l,o),Number.isInteger(r[Hi])&&_[Hi]>r[Hi])return!1;l&&n.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let A=_[h];if(typeof p=="function"){let g=p([[_]]);Array.isArray(g)&&(p=g[0][mn.FUNC_VAL],r[h]=p)}if(p===A)continue;let R=Vs.getIndexedValues(A);if(R){u_&&S.prefetch(R.map(g=>({key:g,value:s})),l_);for(let g=0,P=R.length;g<P;g++)S.remove(R[g],s)}if(R=Vs.getIndexedValues(p),R){u_&&S.prefetch(R.map(g=>({key:g,value:s})),l_);for(let g=0,P=R.length;g<P;g++)S.put(R[g],s)}}let E=Object.assign({},_,r);c.put(s,E,E[Hi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:_m(e,t,r,s,n,i,o))}a(_m,"updateUpsertRecord");function d$(e,t,r){if(Vs.validateEnv(e),t===void 0)throw new Error(Oc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Oc.WRITE_ATTRIBUTES_REQUIRED):new Error(Oc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(d$,"validateBasic");function dm(e,t,r,s){if(d$(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Oc.RECORDS_REQUIRED):new Error(Oc.RECORDS_MUST_BE_ARRAY)}a(dm,"validateWrite");function l_(){}a(l_,"noop");Xb.exports={insertRecords:a$,updateRecords:l$,upsertRecords:_$}});var xi=T((Nce,f$)=>{f$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var Ys=T((yce,tN)=>{"use strict";var eN=J(),Zb=L(),ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,$s=require("joi"),jn={schema_format:{pattern:ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},E$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(ko).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number(),$s.array()).required(),h$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(ko).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number()),m$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(ko).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number()).required();function p$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>jn.schema_length.maximum?`'${e}' maximum of 250 characters`:ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(p$,"checkValidTable");function S$(e,t){return eN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(S$,"validateSchemaExists");function T$(e,t){let r=t.state.ancestors[0].schema;return eN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(T$,"validateTableExists");function g$(e,t){return e.toLowerCase()===Zb.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Zb.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(g$,"validateSchemaName");tN.exports={common_validators:jn,schema_regex:ko,hdb_schema_table:E$,validateSchemaExists:S$,validateTableExists:T$,validateSchemaName:g$,checkValidTable:p$,hdb_database:h$,hdb_table:m$}});var je=T((Ice,rN)=>{"use strict";var nr=require("validate.js");nr.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||nr.validators.type.checks[t](e)?null:` must be a '${t}' value`};nr.validators.type.checks={Object:function(e){return nr.isObject(e)&&!nr.isArray(e)},Array:nr.isArray,Integer:nr.isInteger,Number:nr.isNumber,String:nr.isString,Date:nr.isDate,Boolean:function(e){return typeof e=="boolean"}};nr.validators.hasValidFileExt=function(e,t){return nr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};rN.exports={validateObject:R$,validateObjectAsync:A$,validateBySchema:O$};function R$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=nr(e,t,{format:"flat"});return r?new Error(r):null}a(R$,"validateObject");async function A$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await nr.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(A$,"validateObjectAsync");function O$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(O$,"validateBySchema")});var __=T((Dce,sN)=>{var{common_validators:Ks}=Ys(),Nc=je(),bc="is required",ft={database:{presence:!1,format:Ks.schema_format,length:Ks.schema_length},schema:{presence:!1,format:Ks.schema_format,length:Ks.schema_length},table:{presence:!0,format:Ks.schema_format,length:Ks.schema_length},attribute:{presence:!0,format:Ks.schema_format,length:Ks.schema_length},hash_attribute:{presence:!0,format:Ks.schema_format,length:Ks.schema_length}};function yc(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(yc,"makeAttributesStrings");function b$(e){return e=yc(e),ft.table.presence=!1,ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(b$,"schema_object");function N$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(N$,"table_object");function y$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,Nc.validateObject(e,ft)}a(y$,"create_table_object");function w$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence={message:bc},ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(w$,"attribute_object");function I$(e){return e=yc(e),ft.table.presence={message:bc},ft.attribute.presence=!1,ft.hash_attribute.presence=!1,Nc.validateObject(e,ft)}a(I$,"describe_table");function C$(e){if(e){if(!Array.isArray(e))throw new Error("residence must be a string array");if(e.length===0)throw new Error("residence cannot be an empty array");for(let t=0;t<e.length;t++)if(typeof e[t]!="string")throw new Error(`residence must be a string array, item '${e[t]}' is not a string`)}}a(C$,"validateTableResidence");sN.exports={schema_object:b$,create_table_object:y$,table_object:N$,attribute_object:w$,describe_table:I$,validateTableResidence:C$}});var iN=T((Uce,nN)=>{"use strict";var D$=require("uuid"),fm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||D$.v4(),this.schema_table=`${this.schema}.${this.table}`}};nN.exports=fm});var d_=T((Pce,oN)=>{"use strict";var L$=iN(),Em=class extends L${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};oN.exports=Em});var cN=T((Bce,aN)=>{"use strict";aN.exports=M$;var U$="inserted";function M$(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===U$?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(M$,"returnObject")});var f_=T((xce,fN)=>{"use strict";var P$=L(),hm=We(),v$=Go(),{getSystemSchemaPath:B$,getSchemaPath:H$}=Je(),x$=xi(),q$=__(),F$=d_(),G$=cN(),{handleHDBError:uN,hdb_errors:_N}=re(),lN=J(),{HTTP_STATUS_CODES:k$}=_N,mm=x$.hdb_attribute,dN=[];for(let e=0;e<mm.attributes.length;e++)dN.push(mm.attributes[e].attribute);var V$="inserted";fN.exports=$$;async function $$(e){let t=q$.attribute_object(e);if(t)throw uN(new Error,t.message,_N.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&lN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw uN(new Error,r,k$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=lN.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new F$(e.schema,e.table,e.attribute,e.id);try{let i=await hm.openEnvironment(H$(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);hm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await hm.openEnvironment(B$(),P$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await v$.insertRecords(o,mm.hash_attribute,dN,[n]);return G$(V$,c,{records:[n]},u)}catch(i){throw i}}a($$,"lmdbCreateAttribute")});var Sm=T((Fce,hN)=>{var{hdb_table:Y$,hdb_database:EN}=Ys(),K$=je(),pm=require("joi"),W$={undefined:"undefined",null:"null"},Q$=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||W$[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),z$=pm.object({database:EN,schema:EN,table:Y$,records:pm.array().items(pm.object().custom(Q$)).required()});hN.exports=function(e){return K$.validateBySchema(e,z$)}});var wc=T((Vce,pN)=>{"use strict";var pn=J(),mN=V(),kce=Sm(),{getDatabases:J$}=(Ae(),se(Fe)),{ClientError:qi}=re();pN.exports=j$;function j$(e){if(pn.isEmpty(e))throw new qi("invalid update parameters defined.");if(pn.isEmptyOrZeroLength(e.schema))throw new qi("invalid schema specified.");if(pn.isEmptyOrZeroLength(e.table))throw new qi("invalid table specified.");if(!Array.isArray(e.records))throw new qi("records must be an array");let t=J$()[e.schema]?.[e.table];if(pn.isEmpty(t))throw new qi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&pn.isEmptyOrZeroLength(o[r]))throw mN.error("a valid hash attribute must be provided with update record:",o),new qi("a valid hash attribute must be provided with update record, check log for more info");if(!pn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw mN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new qi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!pn.isEmpty(o[r])&&o[r]!==""&&s.has(pn.autoCast(o[r]))&&(o.skip=!0),s.add(pn.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(j$,"insertUpdateValidate")});var Ic=T((Yce,SN)=>{"use strict";var X$=L().OPERATIONS_ENUM,Tm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=X$.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};SN.exports=Tm});var Uc=T((Qce,TN)=>{"use strict";var Wce=Ic(),E_=L(),Rm=J(),gm=V(),Z$=require("uuid"),{handleHDBError:Cc,hdb_errors:e1}=re(),{HDB_ERROR_MSGS:Dc,HTTP_STATUS_CODES:Lc}=e1;TN.exports=t1;function t1(e,t,r){for(let n=0;n<t.length;n++)r1(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];s1(i,r,e.operation)}}a(t1,"processRows");function r1(e){if(Buffer.byteLength(String(e))>E_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Cc(new Error,Dc.ATTR_NAME_LENGTH_ERR(e),Lc.BAD_REQUEST,void 0,void 0,!0);if(Rm.isEmptyOrZeroLength(e)||Rm.isEmpty(e.trim()))throw Cc(new Error,Dc.ATTR_NAME_NULLISH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(r1,"validateAttribute");function s1(e,t,r){if(!e.hasOwnProperty(t)||Rm.isEmptyOrZeroLength(e[t])){if(r===E_.OPERATIONS_ENUM.INSERT||r===E_.OPERATIONS_ENUM.UPSERT){e[t]=Z$.v4();return}throw gm.error("Update transaction aborted due to record with no hash value:",e),Cc(new Error,Dc.RECORD_MISSING_HASH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>E_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw gm.error(e),Cc(new Error,Dc.HASH_VAL_LENGTH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw gm.error(e),Cc(new Error,Dc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(s1,"validateHash")});var RN=T((Jce,gN)=>{"use strict";var Am=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};gN.exports=Am});var bN=T((Xce,ON)=>{"use strict";var Om=We(),n1=V(),AN=Nr().LMDB_ERRORS_ENUM;ON.exports=i1;async function i1(e){try{if(global.lmdb_map!==void 0&&e.operation!==void 0){let t=Object.keys(global.lmdb_map),r;switch(e.operation){case"drop_schema":for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith(`${e.schema}.`)||o.startsWith(`txn.${e.schema}.`))try{await Om.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==AN.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Om.closeEnvironment(global.lmdb_map[s]),await Om.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==AN.ENV_REQUIRED)throw i}break;case"drop_attribute":r=global.lmdb_map[`${e.schema}.${e.table}`],r!==void 0&&typeof r.dbis=="object"&&r.dbis[`${e.attribute}`]!==void 0&&delete r.dbis[`${e.attribute}`];break;default:break}}}catch(t){n1.error(t)}}a(i1,"cleanLMDBMap")});var Sn=T((eue,IN)=>{"use strict";var Mc=require("crypto"),o1=Z(),{CONFIG_PARAMS:a1}=L(),yN="aes-256-cbc",c1=32,u1=16,bm=64,wN=32,l1=bm+wN,NN=new Map;IN.exports={encrypt:_1,decrypt:d1,createNatsTableStreamName:f1};function _1(e){let t=Mc.randomBytes(c1),r=Mc.randomBytes(u1),s=Mc.createCipheriv(yN,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(_1,"encrypt");function d1(e){let t=e.substr(0,bm),r=e.substr(bm,wN),s=e.substr(l1,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Mc.createDecipheriv(yN,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(d1,"decrypt");function f1(e,t){let r=o1.get(a1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=NN.get(r);return s||(s=Mc.createHash("md5").update(r).digest("hex"),NN.set(r,s)),s}a(f1,"createNatsTableStreamName")});var Xn=T((sue,DN)=>{"use strict";var rue=es(),h_=V(),CN=__(),E1=Sn(),m_=J(),{handleHDBError:p_,hdb_errors:h1}=re(),{HDB_ERROR_MSGS:S_,HTTP_STATUS_CODES:Nm}=h1,m1=Z();m1.initSync();var{getDatabases:ym}=(Ae(),se(Fe));DN.exports={describeAll:p1,describeTable:T_,describeSchema:S1};async function p1(e){try{let t=m_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=ym(),i={},o={},c=[],u=e?.exact_count;for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let d=n[l];for(let f in d)try{let E;if(t||s)E=await T_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await T_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){h_.error(E)}}let _={};for(let l in c)t||s?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return h_.error("Got an error in describeAll"),h_.error(t),p_(new Error,S_.DESCRIBE_ALL_ERR)}}a(p1,"describeAll");async function T_(e,t){m_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=CN.describe_table(e);if(i)throw i;let c=ym()[r];if(!c)throw p_(new Error,S_.SCHEMA_NOT_FOUND(e.schema),Nm.NOT_FOUND);let u=c[s];if(!u)throw p_(new Error,S_.TABLE_NOT_FOUND(e.schema,e.table),Nm.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(n){let f={};n.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=E1.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){h_.warn(`unable to stat table dbi due to ${f}`)}return d}a(T_,"descTable");async function S1(e){m_.transformReq(e);let t=CN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=ym()[s];if(!i)throw p_(new Error,S_.SCHEMA_NOT_FOUND(e.schema),Nm.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),m_.isEmpty(u)||u.describe){let _=await T_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(S1,"describeSchema")});var Tn=T((aue,vN)=>{var T1=xi(),{callbackify:UN,promisify:g1}=require("util"),{getDatabases:MN}=(Ae(),se(Fe));vN.exports={setSchemaDataToGlobal:LN,getTableSchema:R1,getSystemSchema:A1,setSchemaDataToGlobalAsync:g1(LN)};var PN=Xn(),iue=UN(PN.describeAll),oue=UN(PN.describeTable);function LN(e){global.hdb_schema=MN(),e&&e()}a(LN,"setSchemaDataToGlobal");function R1(e,t,r){let s=MN()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(R1,"getTableSchema");function A1(){return T1}a(A1,"getSystemSchema")});var Cr=T((uue,qN)=>{"use strict";var R_=Sm(),qt=J(),O1=require("util"),A_=Ns(),b1=Tn(),BN=V(),{handleHDBError:Fi,hdb_errors:N1}=re(),{HTTP_STATUS_CODES:Gi}=N1,y1=O1.promisify(b1.getTableSchema),w1="updated",HN="inserted",xN="upserted";qN.exports={insert:C1,update:D1,upsert:L1,validation:I1,flush:U1};async function I1(e){if(qt.isEmpty(e))throw new Error("invalid update parameters defined.");if(qt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(qt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await y1(e.schema,e.table),r=R_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&qt.isEmptyOrZeroLength(c[s]))throw BN.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!qt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw BN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!qt.isEmpty(c[s])&&c[s]!==""&&n.has(qt.autoCast(c[s]))&&(c.skip=!0),n.add(qt.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(I1,"validation");async function C1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=R_(e);if(t)throw Fi(new Error,t.message,Gi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.createRecords(e);return g_(HN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(C1,"insertData");async function D1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=R_(e);if(t)throw Fi(new Error,t.message,Gi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.updateRecords(e);return qt.isEmpty(s.existing_rows)?g_(w1,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):g_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(D1,"updateData");async function L1(e){if(e.operation!=="upsert")throw Fi(new Error,"invalid operation, must be upsert",Gi.INTERNAL_SERVER_ERROR);let t=R_(e);if(t)throw Fi(new Error,t.message,Gi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw Fi(new Error,r,Gi.BAD_REQUEST);let s=await A_.upsertRecords(e);return g_(xN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(L1,"upsertData");function g_(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===HN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===xN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(g_,"returnObject");function U1(e){return qt.transformReq(e),A_.flush(e.schema,e.table)}a(U1,"flush")});var Im=T((_ue,kN)=>{var M1=je(),wm=require("joi"),{hdb_table:P1,hdb_database:FN}=Ys(),GN={schema:FN,database:FN,table:P1},v1={date:wm.date().iso().required()},B1={timestamp:wm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};kN.exports=function(e,t){let r=t==="timestamp"?{...GN,...B1}:{...GN,...v1},s=wm.object(r);return M1.validateBySchema(e,s)}});var YN=T((due,$N)=>{var H1=je(),Cm=require("joi"),{hdb_table:x1,hdb_database:VN}=Ys(),q1=Cm.object({schema:VN,database:VN,table:x1,hash_values:Cm.array().required(),ids:Cm.array()});$N.exports=function(e){return H1.validateBySchema(e,q1)}});var WN=T((fue,KN)=>{"use strict";var Dm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},Lm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},Um=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};KN.exports={InsertObject:Dm,NoSQLSeachObject:Lm,DeleteResponseObject:Um}});var ti=T((hue,XN)=>{"use strict";var zN=Im(),F1=YN(),ki=J(),QN=require("moment"),JN=V(),{promisify:G1,callbackify:k1}=require("util"),Vi=L(),V1=Tn(),Mm=G1(V1.getTableSchema),Pm=Ns(),{DeleteResponseObject:$1}=WN(),{handleHDBError:Zn,hdb_errors:Y1}=re(),{HDB_ERROR_MSGS:O_,HTTP_STATUS_CODES:ei}=Y1,K1="records successfully deleted",W1=k1(jN);XN.exports={delete:W1,deleteRecord:jN,deleteFilesBefore:Q1,deleteAuditLogsBefore:z1};async function Q1(e){let t=zN(e,"date");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(ki.transformReq(e),!QN(e.date,QN.ISO_8601).isValid())throw Zn(new Error,O_.INVALID_DATE,ei.BAD_REQUEST,Vi.LOG_LEVELS.ERROR,O_.INVALID_DATE,!0);let s=ki.checkSchemaTableExist(e.schema,e.table);if(s)throw Zn(new Error,s,ei.NOT_FOUND,Vi.LOG_LEVELS.ERROR,s,!0);let n=await Pm.deleteRecordsBefore(e);if(await Mm(e.schema,e.table),JN.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(Q1,"deleteFilesBefore");async function z1(e){let t=zN(e,"timestamp");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(ki.transformReq(e),isNaN(e.timestamp))throw Zn(new Error,O_.INVALID_VALUE("Timestamp"),ei.BAD_REQUEST,Vi.LOG_LEVELS.ERROR,O_.INVALID_VALUE("Timestamp"),!0);let r=ki.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Vi.LOG_LEVELS.ERROR,r,!0);let s=await Pm.deleteAuditLogsBefore(e);return await Mm(e.schema,e.table),JN.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(z1,"deleteAuditLogsBefore");async function jN(e){e.ids&&(e.hash_values=e.ids);let t=F1(e);if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);ki.transformReq(e);let r=ki.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Vi.LOG_LEVELS.ERROR,r,!0);try{await Mm(e.schema,e.table);let s=await Pm.deleteRecords(e);return ki.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${K1}`),s}catch(s){if(s.message===Vi.SEARCH_NOT_FOUND_MESSAGE){let n=new $1;return n.message=Vi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(jN,"deleteRecord")});var b_=T((pue,ty)=>{var J1=require("crypto"),ZN=9;function j1(e){let t=Z1(ZN),r=ey(e+t);return t+r}a(j1,"createHash");function X1(e,t){let r=e?.substr(0,ZN),s=r+ey(t+r);return e===s}a(X1,"validateHash");function Z1(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(Z1,"generateSalt");function ey(e){return J1.createHash("md5").update(e).digest("hex")}a(ey,"md5");ty.exports={hash:j1,validate:X1}});var sy=T((Tue,ry)=>{var vm=je(),Kt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function eY(e){return Kt.password.presence=!0,Kt.username.presence=!0,Kt.role.presence=!0,Kt.active.presence=!0,vm.validateObject(e,Kt)}a(eY,"addUserValidation");function tY(e){return Kt.password.presence=!1,Kt.username.presence=!0,Kt.role.presence=!1,Kt.active.presence=!1,vm.validateObject(e,Kt)}a(tY,"alterUserValidation");function rY(e){return Kt.password.presence=!1,Kt.username.presence=!0,Kt.role.presence=!1,Kt.active.presence=!1,vm.validateObject(e,Kt)}a(rY,"dropUserValidation");ry.exports={addUserValidation:eY,alterUserValidation:tY,dropUserValidation:rY}});var Ge=T((Aue,iy)=>{"use strict";var{platform:Rue}=require("os"),sY="nats-server.zip",Bm="nats-server",nY=process.platform==="win32"?`${Bm}.exe`:Bm,Hm="HDB",iY=/^[^\s.,*>]+$/,ny="__request__",oY=a(e=>`${e}.${ny}`,"REQUEST_SUBJECT"),aY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},cY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},uY={HUB:"hub.pid",LEAF:"leaf.pid"},lY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},_Y={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Hm,deliver_subject:"__HDB__.WORKQUEUE"},dY={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Hm,deliver_subject:"HDB.SCHEMAQUEUE"},fY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Hm,deliver_subject:"HDB.USERQUEUE"},EY={SUCCESS:"success",ERROR:"error"},hY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},mY={TXN:"txn",MSGID:"msgid"},Vo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},pY={[Vo.ERR]:1,[Vo.WRN]:2,[Vo.INF]:3,[Vo.DBG]:4,[Vo.TRC]:5},SY={debug:"-D",trace:"-DVV"};iy.exports={NATS_SERVER_ZIP:sY,NATS_SERVER_NAME:Bm,NATS_BINARY_NAME:nY,PID_FILES:uY,NATS_CONFIG_FILES:cY,SERVER_SUFFIX:lY,WORK_QUEUE_CONSUMER_NAMES:_Y,SCHEMA_QUEUE_CONSUMER_NAMES:dY,USER_QUEUE_CONSUMER_NAMES:fY,NATS_TERM_CONSTRAINTS_RX:iY,REQUEST_SUFFIX:ny,UPDATE_REMOTE_RESPONSE_STATUSES:EY,CLUSTER_STATUS_STATUSES:hY,REQUEST_SUBJECT:oY,SUBJECT_PREFIXES:mY,MSG_HEADERS:aY,LOG_LEVELS:Vo,LOG_LEVEL_FLAGS:SY,LOG_LEVEL_HIERARCHY:pY}});var ay=T((bue,oy)=>{"use strict";var TY={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
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.4",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
|
+
`)},gY="certificate.pem",RY="privateKey.pem",AY="ca.pem";oy.exports={CERTIFICATE_VALUES:TY,CERTIFICATE_PEM_NAME:gY,PRIVATEKEY_PEM_NAME:RY,CA_PEM_NAME:AY}});var qm=T((yue,dy)=>{"use strict";var _y=require("fs-extra"),ie=require("joi"),OY=require("os"),{boolean:Ne,string:ir,number:At,array:xm}=ie.types(),{totalmem:cy}=require("os"),$i=require("path"),bY=V(),N_=J(),Nue=ay(),uy=L(),NY=je(),ly="log",yY="components",wY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",IY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",CY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",DY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",LY="rootPath config parameter is undefined",UY="clustering.enabled config parameter is undefined",Yi=At.min(0).required(),y_=xm.items({host:ir.required(),port:Yi}).empty(null),Ws;dy.exports={configValidator:MY,routesValidator:qY,route_constraints:y_};function MY(e){if(Ws=e.rootPath,N_.isEmpty(Ws))throw LY;let t=Ne.required(),r=At.min(0).max(1e3).empty(null).default(xY),s=ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Pc),n=ir.optional().empty(null),i=ir.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ie.string().empty(null).default(Pc),c=ie.custom(vY).empty(null).default(Pc),u=e.clustering?.enabled;if(N_.isEmpty(u))throw UY;let _;return u===!0?_=ie.object({enabled:t,hubServer:ie.object({cluster:ie.object({name:ie.required().empty(null),network:ie.object({port:Yi,routes:y_}).required()}).required(),leafNodes:ie.object({network:ie.object({port:Yi}).required()}).required(),network:ie.object({port:Yi}).required()}).required(),leafServer:ie.object({network:ie.object({port:Yi,routes:y_}).required(),streams:ie.object({maxAge:At.min(120).allow(null).optional(),maxBytes:At.min(1).allow(null).optional(),maxMsgs:At.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ie.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Ne.optional(),databaseLevel:Ne.optional(),tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ne.required(),verify:Ne.optional()}),user:ir.optional().empty(null)}).required():_=ie.object({enabled:t,tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ne.required()})}).required(),ie.object({authentication:ie.object({authorizeLocal:Ne,cacheTTL:At.required(),enableSessions:Ne}),analytics:ie.object({aggregatePeriod:At}),componentsRoot:s.optional(),clustering:_,localStudio:ie.object({enabled:t}).required(),logging:ie.object({auditAuthEvents:ie.object({logFailed:Ne,logSuccessful:Ne}),file:Ne.required(),level:ie.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ie.object({enabled:Ne.optional(),compress:Ne.optional(),interval:ir.custom(HY).optional().empty(null),maxSize:ir.custom(BY).optional().empty(null),path:ir.optional().empty(null).default(Pc)}).required(),root:s,stdStreams:Ne.required(),auditLog:Ne.required()}).required(),operationsApi:ie.object({network:ie.object({cors:Ne.optional(),corsAccessList:xm.optional(),headersTimeout:At.min(1).optional(),keepAliveTimeout:At.min(1).optional(),port:At.optional().empty(null),domainSocket:ie.optional().empty("hdb/operations-server").default(Pc),securePort:At.optional().empty(null),timeout:At.min(1).optional()}).optional(),tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ie.object({network:ie.object({port:Yi,securePort:Yi,mtls:ie.alternatives([Ne.optional(),ie.object({user:ir.optional(),certificateAuthority:n,required:Ne.optional()})])}).required(),webSocket:Ne.optional(),requireAuthentication:Ne.optional()}),http:ie.object({compressionThreshold:At.optional(),cors:Ne.optional(),corsAccessList:xm.optional(),headersTimeout:At.min(1).optional(),port:At.min(0).optional().empty(null),securePort:At.min(0).optional().empty(null),mtls:ie.alternatives([Ne.optional(),ie.object({user:ir.optional(),certificateAuthority:n,required:Ne.optional()})])}).required(),threads:ie.alternatives(r.optional(),ie.object({count:r.optional(),debug:ie.alternatives(Ne.optional(),ie.object({startingPort:At.min(1).optional(),host:ir.optional(),waitForDebugger:Ne.optional()})),maxHeapMemory:At.min(0).optional()})),storage:ie.object({writeAsync:Ne.required(),overlappingSync:Ne.optional(),caching:Ne.optional(),compression:Ne.optional(),noReadAhead:Ne.optional(),path:c,prefetchWrites:Ne.optional()}).required(),ignoreScripts:Ne.optional(),tls:ie.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:ir.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(MY,"configValidator");function PY(e){return _y.existsSync(e)?null:`Specified path ${e} does not exist.`}a(PY,"doesPathExist");function vY(e,t){ie.assert(e,ir.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=PY(e);if(r)return t.message(r)}a(vY,"validatePath");function BY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(wY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(CY):e}a(BY,"validateRotationMaxSize");function HY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(IY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(DY):e}a(HY,"validateRotationInterval");function xY(e,t){let r=t.state.path.join("."),s=OY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||cy();return i=Math.round(Math.min(i,cy())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),bY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(xY,"setDefaultThreads");function Pc(e,t){let r=t.state.path.join(".");if(!N_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(N_.isEmpty(Ws))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return $i.join(Ws,yY);case"logging.root":return $i.join(Ws,ly);case"clustering.leafServer.streams.path":return $i.join(Ws,"clustering","leaf");case"storage.path":let s=$i.join(Ws,uy.LEGACY_DATABASES_DIR_NAME);return _y.existsSync(s)?s:$i.join(Ws,uy.DATABASES_DIR_NAME);case"logging.rotation.path":return $i.join(Ws,ly);case"operationsApi.network.domainSocket":return r==null?null:$i.join(Ws,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Pc,"setDefaultRoot");function qY(e){let t=ie.object({routes:y_});return NY.validateBySchema({routes:e},t)}a(qY,"routesValidator")});var Ur=T((Cue,Ry)=>{"use strict";var Lr=L(),Ut=J(),Ot=V(),{configValidator:FY,routesValidator:fy}=qm(),or=require("fs-extra"),GY=require("yaml"),ys=require("path"),kY=require("is-number"),hy=require("properties-reader"),VY=require("lodash"),{handleHDBError:$Y}=re(),{HTTP_STATUS_CODES:YY,HDB_ERROR_MSGS:w_}=Nr(),Iue=require("minimist"),{server:KY}=(rr(),se(Mi)),{DATABASES_PARAM_CONFIG:vc,CONFIG_PARAMS:Dr,CONFIG_PARAM_MAP:ws}=Lr,WY="Unable to get config value because config is uninitialized",QY="Config successfully initialized",zY="Error backing up config file",JY="Empty parameter sent to getConfigValue",my=ys.join(Lr.PACKAGE_ROOT,"config","yaml",Lr.HDB_DEFAULT_CONFIG_FILE),jY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ey={logging_rotation_retain:"logging.rotation.retain",logging_rotation_rotate:"logging.rotation.rotate",logging_rotation_rotateinterval:"logging.rotation.rotateInterval",logging_rotation_rotatemodule:"logging.rotation.rotateModule",logging_rotation_timezone:"logging.rotation.timezone",logging_rotation_workerinterval:"logging.rotation.workerInterval"},I_,bt,C_;Ry.exports={createConfigFile:XY,getDefaultConfig:ZY,getConfigValue:Sy,initConfig:Gm,flattenConfig:$o,updateConfigValue:Ty,updateConfigObject:tK,getConfiguration:nK,setConfiguration:iK,readConfigFile:Vm,getClusteringRoutes:oK,initOldConfig:gy,getConfigFromFile:aK,getConfigFilePath:Ki,addConfig:cK,deleteConfigFromFile:uK,getConfigObj:lK};function XY(e){let t=ri(my);I_=$o(t.toJSON());let r;for(let o in e){let c=ws[o.toLowerCase()];if(c===Dr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=Fm(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){Ot.error(l)}}}r&&py(t,r),km(t);let s=t.toJSON();bt=$o(s);let n=t.getIn(["rootPath"]),i=ys.join(n,Lr.HDB_CONFIG_FILE);or.createFileSync(i),or.writeFileSync(i,String(t)),Ot.trace(`Config file written to ${i}`)}a(XY,"createConfigFile");function py(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!Ut.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(vc.TABLES))for(let i in s[n][vc.TABLES])for(let o in s[n][vc.TABLES][i]){let c=s[n][vc.TABLES][i][o],u=[Dr.DATABASES,n,vc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Dr.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){Ot.error("Error parsing schemas CLI/env config arguments",s)}}a(py,"setSchemasConfig");function ZY(e){if(I_===void 0){let r=ri(my);I_=$o(r.toJSON())}let t=ws[e.toLowerCase()];if(t!==void 0)return I_[t.toLowerCase()]}a(ZY,"getDefaultConfig");function Sy(e){if(e==null){Ot.error(JY);return}if(bt===void 0){Ot.trace(WY);return}let t=ws[e.toLowerCase()];if(t!==void 0)return bt[t.toLowerCase()]}a(Sy,"getConfigValue");function Ki(e=Ut.getPropsFilePath()){let t=Ut.getEnvCliRootPath();return t?ys.join(t,Lr.HDB_CONFIG_FILE):hy(e).get(Lr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ki,"getConfigFilePath");function Gm(e=!1){if(bt===void 0||e){let t;if(!Ut.noBootFile()){t=Ut.getPropsFilePath();try{or.accessSync(t,or.constants.F_OK|or.constants.R_OK)}catch(i){throw Ot.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ki(t),s;if(r.includes("config/settings.js"))try{gy(r);return}catch(i){if(i.code!==Lr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ri(r)}catch(i){if(i.code===Lr.NODE_ERROR_CODES.ENOENT){Ot.trace(`HarperDB config file not found at ${r}.
|
|
7
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw Ot.error(i),new Error(`Error reading HarperDB config file at ${r}`)}eK(s,r),km(s);let n=s.toJSON();if(KY.config=n,bt=$o(n),bt.logging_rotation_rotate)for(let i in Ey)bt[i]&&Ot.error(`Config ${Ey[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Ot.trace(QY)}}a(Gm,"initConfig");function eK(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],ys.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],ys.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],ys.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(Ot.trace("Updating config file with missing config params"),or.writeFileSync(t,String(e)))}a(eK,"checkForUpdatedConfig");function km(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t?.http?.threads&&(t.threads=t?.http?.threads);let r=FY(t);if(r.error)throw w_.CONFIG_VALIDATION(r.error.message);typeof r.value.threads=="object"?e.setIn(["threads","count"],r.value.threads.count):e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(km,"validateConfig");function tK(e,t){bt===void 0&&(bt={});let r=ws[e.toLowerCase()];if(r===void 0){Ot.trace(`Unable to update config object because config param '${e}' does not exist`);return}bt[r.toLowerCase()]=t}a(tK,"updateConfigObject");function Ty(e,t,r=void 0,s=!1,n=!1,i=!1){bt===void 0&&Gm();let o=Sy(ws.hdb_root),c=ys.join(o,Lr.HDB_CONFIG_FILE),u=ri(c),_;if(r===void 0&&e.toLowerCase()===Dr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=ws[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Fm(f,t);u.setIn([...E],h)}else for(let f in r){let E=ws[f.toLowerCase()];if(E===Dr.HTTP_SECUREPORT&&r[f]===bt[Dr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Dr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===bt[Dr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Dr.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Lr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=Fm(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(A){Ot.error(A)}}}_&&py(u,_),km(u);let l=u.getIn(["rootPath"]),d=ys.join(l,Lr.HDB_CONFIG_FILE);s===!0&&rK(c,l),or.writeFileSync(d,String(u)),n&&(bt=$o(u.toJSON())),Ot.trace(`Config parameter: ${e} updated with value: ${t}`)}a(Ty,"updateConfigValue");function rK(e,t){try{let r=ys.join(t,"backup",`${Lr.HDB_CONFIG_FILE}.bak`);or.copySync(e,r),Ot.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Ot.error(zY),Ot.error(r)}}a(rK,"backupConfigFile");var sK=["databases"];function $o(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),C_=e,r(e);function r(s){let n={};for(let i in s)if(s.hasOwnProperty(i)){if(typeof s[i]=="object"&&s[i]!==null&&!Array.isArray(s[i])&&!sK.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Dr[u.toUpperCase()]&&ws[u]&&(n[ws[u].toLowerCase()]=o[c]),n[u]=o[c]}}s[i]!==void 0&&(n[i.toLowerCase()]=s[i])}return n}a(r,"squashObj")}a($o,"flattenConfig");function Fm(e,t){if(e===Dr.CLUSTERING_NODENAME||e===Dr.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(kY(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Ut.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return Ut.autoCast(t)}a(Fm,"castConfigValue");function nK(){let e=Ut.getPropsFilePath(),t=Ki(e);return ri(t).toJSON()}a(nK,"getConfiguration");async function iK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return Ty(void 0,void 0,n,!0),jY}catch(i){throw typeof i=="string"||i instanceof String?$Y(i,i,YY.BAD_REQUEST,void 0,void 0,!0):i}}a(iK,"setConfiguration");function Vm(){let e=Ut.getPropsFilePath();try{or.accessSync(e,or.constants.F_OK|or.constants.R_OK)}catch(s){if(!Ut.noBootFile())throw Ot.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ki(e);return ri(t).toJSON()}a(Vm,"readConfigFile");function ri(e){return GY.parseDocument(or.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ri,"parseYamlDoc");function oK(){let e=Vm(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Ut.isEmptyOrZeroLength(t)?[]:t;let r=fy(t);if(r)throw w_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Ut.isEmptyOrZeroLength(s)?[]:s;let n=fy(s);if(n)throw w_.CONFIG_VALIDATION(n.message);if(!Ut.isEmptyOrZeroLength(s)&&!Ut.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!Ut.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw w_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(oK,"getClusteringRoutes");function gy(e){let t=hy(e);bt={};for(let r in ws){let s=t.get(r.toUpperCase());if(Ut.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=ws[r].toLowerCase();n===Dr.LOGGING_ROOT?bt[n]=ys.dirname(s):bt[n]=s}return bt}a(gy,"initOldConfig");function aK(e){let t=Vm();return VY.get(t,e.replaceAll("_","."))}a(aK,"getConfigFromFile");async function cK(e,t){let r=ri(Ki());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await or.writeFile(Ki(),String(r))}a(cK,"addConfig");function uK(e){let t=Ki(Ut.getPropsFilePath()),r=ri(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=ys.join(s,Lr.HDB_CONFIG_FILE);or.writeFileSync(n,String(r))}a(uK,"deleteConfigFromFile");function lK(){return C_||(Gm(),C_)}a(lK,"getConfigObj")});var Oy=T((Lue,Ay)=>{"use strict";var D_=L(),L_=class{static{a(this,"BaseLicense")}constructor(t=0,r=D_.RAM_ALLOCATION_ENUM.DEFAULT,s=D_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},$m=class extends L_{static{a(this,"ExtendedLicense")}constructor(t=0,r=D_.RAM_ALLOCATION_ENUM.DEFAULT,s=D_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};Ay.exports={BaseLicense:L_,ExtendedLicense:$m}});var Wi=T((Mue,Cy)=>{"use strict";var Ko=require("fs-extra"),Ny=b_(),yy=require("crypto"),_K=require("moment"),dK=require("uuid").v4,Wt=V(),Km=require("path"),fK=J(),si=L(),{totalmem:by}=require("os"),EK=Oy().ExtendedLicense,Yo="invalid license key format",hK="061183",mK="mofi25",pK="aes-256-cbc",SK=16,TK=32,wy=Z();wy.initSync();var Ym;Cy.exports={validateLicense:Iy,generateFingerPrint:RK,licenseSearch:zm,getLicense:bK,checkMemoryLimit:NK};function Wm(){return Km.join(wy.getHdbBasePath(),si.LICENSE_KEY_DIR_NAME,si.LICENSE_FILE_NAME)}a(Wm,"getLicenseDirPath");function gK(){let e=Wm();return Km.join(e,si.LICENSE_FILE_NAME)}a(gK,"getLicenseFilePath");function Qm(){let e=Wm();return Km.join(e,si.REG_KEY_FILE_NAME)}a(Qm,"getFingerPrintFilePath");async function RK(){let e=Qm();try{return await Ko.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await AK();throw Wt.error(`Error writing fingerprint file to ${e}`),Wt.error(t),new Error("There was an error generating the fingerprint")}}a(RK,"generateFingerPrint");async function AK(){let e=dK(),t=Ny.hash(e),r=Qm();try{await Ko.mkdirp(Wm()),await Ko.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Wt.error(`Error writing fingerprint file to ${r}`),Wt.error(s),new Error("There was an error generating the fingerprint")}return t}a(AK,"writeFingerprint");function Iy(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:si.RAM_ALLOCATION_ENUM.DEFAULT,version:si.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Wt.error("empty license key passed to validate."),r;let s=Qm(),n=!1;try{n=Ko.statSync(s)}catch(i){Wt.error(i)}if(n){let i;try{i=Ko.readFileSync(s,"utf8")}catch{Wt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(mK),c=o[1];c=Buffer.concat([Buffer.from(c)],SK);let u=Buffer.concat([Buffer.from(i)],TK),_=yy.createDecipheriv(pK,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=OK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Yo),Wt.error(Yo),new Error(Yo)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(Yo),Wt.error(Yo),new Error(Yo)}else r.exp_date=l;r.exp_date<_K().valueOf()&&(r.valid_date=!1),Ny.validate(o[1],`${hK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||Wt.error("Invalid licence"),r}a(Iy,"validateLicense");function OK(e,t){try{let r=yy.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Wt.warn("Check old license failed")}}a(OK,"checkOldLicense");function zm(){let e=new EK,t=[];try{t=Ko.readFileSync(gK(),"utf-8").split(si.NEW_LINE)}catch(r){r.code==="ENOENT"?Wt.info("no license file found"):Wt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(fK.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=Iy(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){Wt.error("There was an error parsing the license string."),Wt.error(n),e.ram_allocation=si.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Ym=e,e}a(zm,"licenseSearch");async function bK(){return Ym||await zm(),Ym}a(bK,"getLicense");function NK(){let e=zm().ram_allocation,t=process.constrainedMemory?.()||by();if(t=Math.round(Math.min(t,by())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(NK,"checkMemoryLimit")});var ts=T((xue,Yy)=>{"use strict";var My="username is required",Py="nothing to update, must supply active, role or password to update",vy="password cannot be an empty string",By="If role is specified, it cannot be empty.",Hy="active must be true or false";Yy.exports={addUser:PK,alterUser:vK,dropUser:HK,getSuperUser:GK,userInfo:xK,listUsers:M_,listUsersExternal:qK,setUsersToGlobal:Qo,findAndValidateUser:Vy,getClusterUser:kK,USERNAME_REQUIRED:My,ALTERUSER_NOTHING_TO_UPDATE:Py,EMPTY_PASSWORD:vy,EMPTY_ROLE:By,ACTIVE_BOOLEAN:Hy};var xy=Cr(),yK=ti(),Xm=b_(),qy=sy(),Fy=es(),Zm=gn(),Mr=J(),Gy=require("validate.js"),Te=V(),{promisify:wK}=require("util"),ep=Sn(),Dy=L(),Ly=Ge(),IK=Ur(),vue=Z(),Bue=Wi(),CK=xi(),{table:Hue}=(Ae(),se(Fe)),{handleHDBError:Qs,hdb_errors:DK}=re(),{HTTP_STATUS_CODES:zs,AUTHENTICATION_ERROR_MSGS:Jm,HDB_ERROR_MSGS:Wo}=DK,{UserEventMsg:tp}=Is(),jm=require("lodash"),{server:rp}=(rr(),se(Mi)),LK=V();rp.getUser=(e,t)=>Vy(e,t,t!=null);var ky={username:!0,active:!0,role:!0,password:!0},Uy=new Map,U_=Fy.searchByValue,UK=Fy.searchByHash,MK=wK(yK.delete);async function PK(e){let t=Gy.cleanAttributes(e,ky),r=qy.addUserValidation(t);if(r)throw Qs(new Error,r.message,zs.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await U_(s),n=n&&Array.from(n)}catch(u){throw Te.error("There was an error searching for a role in add user"),Te.error(u),u}if(!n||n.length<1)throw Qs(new Error,Wo.ROLE_NAME_NOT_FOUND(t.role),zs.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw Qs(new Error,Wo.DUP_ROLES_FOUND(t.role),zs.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=ep.encrypt(t.password)),t.password=Xm.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await xy.insert(i)}catch(u){throw Te.error("There was an error searching for a user."),Te.error(u),u}Te.debug(o);try{await Qo()}catch(u){throw Te.error("Got an error setting users to global"),Te.error(u),u}if(o.skipped_hashes.length===1)throw Qs(new Error,Wo.USER_ALREADY_EXISTS(t.username),zs.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],Zm.signalUserChange(new tp(process.pid)),`${c.username} successfully added`}a(PK,"addUser");async function vK(e){let t=Gy.cleanAttributes(e,ky);if(Mr.isEmptyOrZeroLength(t.username))throw new Error(My);if(Mr.isEmptyOrZeroLength(t.password)&&Mr.isEmptyOrZeroLength(t.role)&&Mr.isEmptyOrZeroLength(t.active))throw new Error(Py);if(!Mr.isEmpty(t.password)&&Mr.isEmptyOrZeroLength(t.password.trim()))throw new Error(vy);if(!Mr.isEmpty(t.active)&&!Mr.isBoolean(t.active))throw new Error(Hy);let r=BK(t.username);if(!Mr.isEmpty(t.password)&&!Mr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=ep.encrypt(t.password)),t.password=Xm.hash(t.password)),t.role==="")throw new Error(By);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await U_(i)||[])}catch(c){throw Te.error("Got an error searching for a role."),Te.error(c),c}if(!o||o.length===0){let c=Wo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Te.error(c),Qs(new Error,c,zs.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Wo.ALTER_USER_DUP_ROLES(t.role);throw Te.error(c),Qs(new Error,c,zs.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await xy.update(s)}catch(i){throw Te.error("Error during update."),Te.error(i),i}try{await Qo()}catch(i){throw Te.error("Got an error setting users to global"),Te.error(i),i}return Zm.signalUserChange(new tp(process.pid)),n}a(vK,"alterUser");function BK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(BK,"isClusterUser");async function HK(e){try{let t=qy.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Mr.isEmpty(global.hdb_users.get(e.username)))throw Qs(new Error,Wo.USER_NOT_EXIST(e.username),zs.NOT_FOUND,void 0,void 0,!0);let s;try{s=await MK(r)}catch(n){throw Te.error("Got an error deleting a user."),Te.error(n),n}Te.debug(s);try{await Qo()}catch(n){throw Te.error("Got an error setting users to global."),Te.error(n),n}return Zm.signalUserChange(new tp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(HK,"dropUser");async function xK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=jm.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await UK(r)}catch(n){throw Te.error("Got an error searching for a role."),Te.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Te.error(r),r}return t}a(xK,"userInfo");async function qK(){let e;try{e=await M_()}catch(t){throw Te.error("Got an error listing users."),Te.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(qK,"listUsersExternal");async function M_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await U_(e)}catch(o){throw Te.error("Got an error searching for roles."),Te.error(o),o}let r={};for(let o of t)r[o.id]=jm.cloneDeep(o);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await U_(s)}catch(o){throw Te.error("Got an error searching for users."),Te.error(o),o}let i=new Map;for(let o of n)o=jm.cloneDeep(o),o.role=r[o.role],FK(o.role),i.set(o.username,o);return i}catch(e){throw Te.error("got an error listing users"),Te.error(e),Mr.errorizeMessage(e)}return null}a(M_,"listUsers");function FK(e){try{if(!e){Te.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(CK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Te.error("Got an error trying to set system permissions."),Te.error(t)}}a(FK,"appendSystemTablesToRole");async function Qo(){try{let e=await M_();global.hdb_users=e}catch(e){throw Te.error(e),e}}a(Qo,"setUsersToGlobal");async function Vy(e,t,r=!0){global.hdb_users||await Qo();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw Qs(new Error,Jm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw Qs(new Error,Jm.USER_INACTIVE,zs.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(Uy.get(t)===s.password)return n;if(Xm.validate(s.password,t))Uy.set(t,s.password);else throw Qs(new Error,Jm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}return n}a(Vy,"findAndValidateUser");async function GK(){global.hdb_users||await Qo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(GK,"getSuperUser");async function kK(){let e=await M_(),t=IK.getConfigFromFile(Dy.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Mr.isEmpty(r)&&r?.role?.role===Dy.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=ep.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+Ly.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+Ly.SERVER_SUFFIX.ADMIN,r}a(kK,"getClusterUser");var $y=[];rp.invalidateUser=function(e){for(let t of $y)try{t(e)}catch(r){LK.error("Error invalidating user",r)}};rp.onInvalidatedUser=function(e){$y.push(e)}});var Hc=T((kue,zy)=>{"use strict";var Qi=V(),Pr=L(),VK=bN(),Fue=Tn(),Gue=Xn(),$K=ts(),{validateEvent:Ky}=Is(),Bc=Ns(),YK=require("process"),{resetDatabases:KK}=(Ae(),se(Fe)),WK={[Pr.ITC_EVENT_TYPES.SCHEMA]:QK,[Pr.ITC_EVENT_TYPES.USER]:Qy};async function QK(e){let t=Ky(e);if(t){Qi.error(t);return}Qi.trace("ITC schemaHandler received schema event:",e),await VK(e.message),await zK(e.message)}a(QK,"schemaHandler");async function zK(e){try{Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=KK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Qi.error(t)}}a(zK,"syncSchemaMetadata");var Wy=[];async function Qy(e){try{try{Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Bc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Qi.warn(r)}let t=Ky(e);if(t){Qi.error(t);return}Qi.trace(`ITC userHandler ${Pr.HDB_ITC_CLIENT_PREFIX}${YK.pid} received user event:`,e),await $K.setUsersToGlobal();for(let r of Wy)r()}catch(t){Qi.error(t)}}a(Qy,"userHandler");Qy.addListener=function(e){Wy.push(e)};zy.exports=WK});var Is=T((Que,jy)=>{"use strict";var $ue=V(),sp=J(),JK=L(),{ITC_ERRORS:xc}=Nr(),{parentPort:Yue,threadId:jK,isMainThread:XK,workerData:Kue}=require("worker_threads"),{onMessageFromWorkers:ZK,broadcast:Wue,broadcastWithAcknowledgement:eW}=Ke();jy.exports={sendItcEvent:tW,validateEvent:Jy,SchemaEventMsg:rW,UserEventMsg:sW};var P_;ZK(async(e,t)=>{P_=P_||Hc(),Jy(e),P_[e.type]&&await P_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function tW(e){return!XK&&e.message&&(e.message.originator=jK),eW(e)}a(tW,"sendItcEvent");function Jy(e){if(typeof e!="object")return xc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||sp.isEmpty(e.type))return xc.MISSING_TYPE;if(!e.hasOwnProperty("message")||sp.isEmpty(e.message))return xc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||sp.isEmpty(e.message.originator))return xc.MISSING_ORIGIN;if(JK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return xc.INVALID_EVENT(e.type)}a(Jy,"validateEvent");function rW(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(rW,"SchemaEventMsg");function sW(e){this.originator=e}a(sW,"UserEventMsg")});var gn=T((jue,tw)=>{"use strict";var Xy=L(),Jue=J(),v_=V(),Zy=RN(),zo,{sendItcEvent:ew}=Is();function nW(e){try{v_.trace("signalSchemaChange called with message:",e),zo=zo||Hc();let t=new Zy(Xy.ITC_EVENT_TYPES.SCHEMA,e);return zo.schema(t),ew(t)}catch(t){v_.error(t)}}a(nW,"signalSchemaChange");function iW(e){try{v_.trace("signalUserChange called with message:",e),zo=zo||Hc();let t=new Zy(Xy.ITC_EVENT_TYPES.USER,e);return zo.user(t),ew(t)}catch(t){v_.error(t)}}a(iW,"signalUserChange");tw.exports={signalSchemaChange:nW,signalUserChange:iW}});var B_=T((Zue,sw)=>{"use strict";var rw=J(),oW=L(),aW=V(),cW=f_(),uW=d_(),lW=gn(),{SchemaEventMsg:_W}=Is(),dW="already exists in";sw.exports=fW;async function fW(e,t,r){if(rw.isEmptyOrZeroLength(r))return r;let s=[];rw.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await EW(e,t.schema,t.name,i)})),n}a(fW,"lmdbCheckForNewAttributes");async function EW(e,t,r,s){let n=new uW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await hW(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(dW))aW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(EW,"createNewAttribute");async function hW(e){let t;return t=await cW(e),lW.signalSchemaChange(new _W(process.pid,oW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(hW,"createAttribute")});var Jo=T((tle,nw)=>{"use strict";var np=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};nw.exports=np});var ow=T((sle,iw)=>{"use strict";var mW=Jo(),pW=L().OPERATIONS_ENUM,ip=class extends mW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(pW.INSERT,r,s,n,i),this.records=t}};iw.exports=ip});var cw=T((ile,aw)=>{"use strict";var SW=Jo(),TW=L().OPERATIONS_ENUM,op=class extends SW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(TW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};aw.exports=op});var lw=T((ale,uw)=>{"use strict";var gW=Jo(),RW=L().OPERATIONS_ENUM,ap=class extends gW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(RW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};uw.exports=ap});var dw=T((ule,_w)=>{"use strict";var AW=Jo(),OW=L().OPERATIONS_ENUM,cp=class extends AW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(OW.DELETE,s,n,t,i),this.original_records=r}};_w.exports=cp});var qc=T((dle,mw)=>{"use strict";var _le=require("path"),fw=We(),bW=ow(),NW=cw(),yW=lw(),wW=dw(),jo=dt(),Ew=J(),{CONFIG_PARAMS:IW}=L(),hw=Z();hw.initSync();var H_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:CW}=Je();mw.exports=DW;async function DW(e,t){if(hw.get(IW.LOGGING_AUDITLOG)===!1)return;let r=CW(e.schema,e.table),s=await fw.openEnvironment(r,e.table,!0),n=LW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){fw.initializeDBIs(s,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,jo.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),Ew.isEmpty(n.user_name)||s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(DW,"writeTransaction");function LW(e,t){let r=Ew.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===H_.INSERT)return new bW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.UPDATE)return new NW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.UPSERT)return new yW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===H_.DELETE)return new wW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(LW,"createTransactionObject")});var up=T((hle,pw)=>{"use strict";var UW=wc(),Ele=Ic(),Fc=L(),MW=Uc(),PW=Go().insertRecords,vW=We(),BW=V(),HW=B_(),{getSchemaPath:xW}=Je(),qW=qc();pw.exports=FW;async function FW(e){try{let{schema_table:t,attributes:r}=UW(e);MW(e,r,t.hash_attribute),e.schema!==Fc.SYSTEM_SCHEMA_NAME&&(r.includes(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await HW(e.hdb_auth_header,t,r),n=xW(e.schema,e.table),i=await vW.openEnvironment(n,e.table),o=await PW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await qW(e,o)}catch(c){BW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(FW,"lmdbCreateRecords")});var gw=T((ple,Tw)=>{"use strict";var Sw=L(),GW=up(),kW=Ic(),VW=require("fs-extra"),{getSchemaPath:$W}=Je();Tw.exports=YW;async function YW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new kW(Sw.SYSTEM_SCHEMA_NAME,Sw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await GW(r),await VW.mkdirp($W(e.schema))}a(YW,"lmdbCreateSchema")});var Aw=T((Tle,Rw)=>{"use strict";var lp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};Rw.exports=lp});var yw=T((ble,Nw)=>{"use strict";var Ow=We(),_p=yr(),dp=Nr().LMDB_ERRORS_ENUM,KW=dt(),bw=V(),Rle=J(),WW=require("lmdb"),QW=Aw(),zW=L(),{OVERFLOW_MARKER:Ale,MAX_SEARCH_KEY_LENGTH:Ole}=KW,JW=zW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function jW(e,t,r,s){if(_p.validateEnv(e),t===void 0)throw new Error(dp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(dp.IDS_REQUIRED):new Error(dp.IDS_MUST_BE_ITERABLE);try{let n=Ow.listDBIs(e);Ow.initializeDBIs(e,t,n);let i=new QW,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||s&&h[JW]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,WW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let A=n[S];if(!h.hasOwnProperty(A)||A===t)continue;let R=e.dbis[A],g=h[A];if(g!=null)try{let P=_p.getIndexedValues(g);if(P)for(let H=0,v=P.length;H<v;H++)R.remove(P[H],o)}catch{bw.warn(`cannot delete from attribute: ${A}, ${g}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){bw.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=_p.getNextMonotonicTime(),i}catch(n){throw n}}a(jW,"deleteRecords");Nw.exports={deleteRecords:jW}});var Gc=T((yle,Iw)=>{"use strict";var Xo=J(),XW=yw(),ZW=We(),{getSchemaPath:eQ}=Je(),tQ=qc(),rQ=V();Iw.exports=sQ;async function sQ(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Xo.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Xo.isEmptyOrZeroLength(e.hash_values)&&!Xo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Xo.isEmpty(u)||e.hash_values.push(u)}}if(Xo.isEmptyOrZeroLength(e.hash_values))return ww([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Xo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[s]:e.hash_values[c]}}let n=eQ(e.schema,e.table),i=await ZW.openEnvironment(n,e.table),o=await XW.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await tQ(e,o)}catch(c){rQ.error(`unable to write transaction due to ${c.message}`)}return ww(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(sQ,"lmdbDeleteRecords");function ww(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(ww,"createDeleteResponse")});var Ep=T((Cle,Cw)=>{"use strict";var nQ=L(),Ile=yr();function fp(e,t){let r=Object.create(null);if(t.length===1&&nQ.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(fp,"parseRow");function iQ(e,t,r,s){let n=fp(r,e);s.push(n)}a(iQ,"searchAll");function oQ(e,t,r,s){let n=fp(r,e);s[t]=n}a(oQ,"searchAllToMap");function aQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(aQ,"iterateDBI");function zi(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(zi,"pushResults");function cQ(e,t,r,s,n,i){t.toString().endsWith(e)&&zi(t,r,s,n,i)}a(cQ,"endsWith");function uQ(e,t,r,s,n,i){t.toString().includes(e)&&zi(t,r,s,n,i)}a(uQ,"contains");function lQ(e,t,r,s,n,i){t>e&&zi(t,r,s,n,i)}a(lQ,"greaterThanCompare");function _Q(e,t,r,s,n,i){t>=e&&zi(t,r,s,n,i)}a(_Q,"greaterThanEqualCompare");function dQ(e,t,r,s,n,i){t<e&&zi(t,r,s,n,i)}a(dQ,"lessThanCompare");function fQ(e,t,r,s,n,i){t<=e&&zi(t,r,s,n,i)}a(fQ,"lessThanEqualCompare");Cw.exports={parseRow:fp,searchAll:iQ,searchAllToMap:oQ,iterateDBI:aQ,endsWith:cQ,contains:uQ,greaterThanCompare:lQ,greaterThanEqualCompare:_Q,lessThanCompare:dQ,lessThanEqualCompare:fQ,pushResults:zi}});var Zo=T((Ple,Bw)=>{"use strict";var ni=We(),Lle=V(),vr=yr(),x_=dt(),ut=Nr().LMDB_ERRORS_ENUM,Ule=J(),EQ=L(),q_=Ep(),{parseRow:hQ}=q_,Mle=require("lmdb"),{OVERFLOW_MARKER:Dw,MAX_SEARCH_KEY_LENGTH:mQ}=x_;function Lw(e,t,r,s=!1,n=void 0,i=void 0){return Ji(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(Lw,"iterateFullIndex");function kc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Ji(e,t,r,(l,d,f,E)=>{let R={transaction:l,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(R.values=!1,d.getRange(R).map(g=>({value:g}))):d.getRange(R)})}a(kc,"iterateRangeBetween");function Ji(e,t,r,s){let n=e.database||e,i=ni.openDBI(n,r);i[x_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ni.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Ji,"setupTransaction");function Uw(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(Dw)){if(!n)if(r)n=ni.openDBI(e,r);else{let u=ni.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=ni.openDBI(e,u[_]),!n[x_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(Uw,"getOverflowCheck");function pQ(e,t,r,s=!1,n=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);return Ji(e,t,t,(o,c,u)=>(F_(r),r=Vc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>hQ(_.value,r))))}a(pQ,"searchAll");function SQ(e,t,r,s=!1,n=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);F_(r),r=Vc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of Lw(e,t,t,s,n,i))o.set(c,q_.parseRow(u,r));return o}a(SQ,"searchAllToMap");function TQ(e,t,r=!1,s=void 0,n=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=Lw(e,void 0,t,r,s,n),c=o.transaction,u=Uw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(TQ,"iterateDBI");function gQ(e,t){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);return ni.statDBI(e,t).entryCount}a(gQ,"countAll");function RQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Ji(e,t,r,(c,u,_,l)=>(s=vr.convertKeyValueToWrite(s),l===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(RQ,"equals");function AQ(e,t,r){return ii(e,t,r),ni.openDBI(e,t).getValuesCount(r)}a(AQ,"count");function OQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Ji(e,null,r,(c,u)=>{s=vr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(OQ,"startsWith");function bQ(e,t,r,s,n=!1,i=void 0,o=void 0){return Mw(e,t,r,s,n,i,o,!0)}a(bQ,"endsWith");function Mw(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ii(e,r,s),Ji(e,null,r,(u,_,l,d)=>{let f=Uw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(E=>{let h=E.toString();return h.endsWith(Dw)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(s):S.includes(s))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(s):h.includes(s))?_[x_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(Mw,"contains");function NQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),kc(e,t,r,s,u,n,i,o,!0,!1)}a(NQ,"greaterThan");function yQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),kc(e,t,r,s,u,n,i,o,!1,!1)}a(yQ,"greaterThanEqual");function wQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),kc(e,t,r,u,s,n,i,o,!1,!0)}a(wQ,"lessThan");function IQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),kc(e,t,r,u,s,n,i,o,!1,!1)}a(IQ,"lessThanEqual");function CQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(vr.validateEnv(e),r===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ut.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ut.END_VALUE_REQUIRED);if(s=vr.convertKeyValueToWrite(s),n=vr.convertKeyValueToWrite(n),s>n)throw new Error(ut.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return kc(e,t,r,s,n,i,o,c)}a(CQ,"between");function DQ(e,t,r,s){vr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(F_(r),r=Vc(n,r),s===void 0)throw new Error(ut.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=q_.parseRow(c,r)),o}a(DQ,"searchByHash");function LQ(e,t,r){vr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ut.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(LQ,"checkHashExists");function UQ(e,t,r,s,n=[]){return vw(e,t,r,s,n),Pw(e,t,r,s,n).map(i=>i[1])}a(UQ,"batchSearchByHash");function MQ(e,t,r,s,n=[]){vw(e,t,r,s,n);let i=new Map;for(let[o,c]of Pw(e,t,r,s,n))i.set(o,c);return i}a(MQ,"batchSearchByHashToMap");function Pw(e,t,r,s,n=[]){return Ji(e,t,t,(i,o,c)=>{r=Vc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,q_.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(Pw,"batchHashSearch");function vw(e,t,r,s,n){if(vr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(F_(r),s==null)throw new Error(ut.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ut.IDS_MUST_BE_ITERABLE)}a(vw,"initializeBatchSearchByHash");function F_(e){if(!Array.isArray(e))throw e===void 0?new Error(ut.FETCH_ATTRIBUTES_REQUIRED):new Error(ut.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(F_,"validateFetchAttributes");function ii(e,t,r){if(vr.validateEnv(e),t===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ut.SEARCH_VALUE_REQUIRED);if(r?.length>mQ)throw new Error(ut.SEARCH_VALUE_TOO_LARGE)}a(ii,"validateComparisonFunctions");function Vc(e,t){return t.length===1&&EQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ni.listDBIs(e)),t}a(Vc,"setGetWholeRowAttributes");Bw.exports={searchAll:pQ,searchAllToMap:SQ,count:AQ,countAll:gQ,equals:RQ,startsWith:OQ,endsWith:bQ,contains:Mw,searchByHash:DQ,setGetWholeRowAttributes:Vc,batchSearchByHash:UQ,batchSearchByHashToMap:MQ,checkHashExists:LQ,iterateDBI:TQ,greaterThan:NQ,greaterThanEqual:yQ,lessThan:wQ,lessThanEqual:IQ,between:CQ}});var ea=T((Ble,Gw)=>{var Hw=require("lodash"),xw=je(),fe=require("joi"),PQ=J(),{hdb_schema_table:$c,checkValidTable:qw,hdb_table:Fw,hdb_database:G_}=Ys(),{handleHDBError:vQ,hdb_errors:BQ}=re(),{getDatabases:HQ}=(Ae(),se(Fe)),{HTTP_STATUS_CODES:xQ}=BQ,qQ=fe.object({database:G_,schema:G_,table:Fw,search_attribute:$c,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives($c,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),FQ=fe.object({database:G_,schema:G_,table:Fw,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives($c,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives($c,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives($c,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});Gw.exports=function(e,t){let r=null;switch(t){case"value":r=xw.validateBySchema(e,qQ);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(qw("database",e.schema)),i(qw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),n&&(r=new Error(n.trim()));break;case"conditions":r=xw.validateBySchema(e,FQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=PQ.checkGlobalSchemaTable(e.schema,e.table);if(n)return vQ(new Error,n,xQ.NOT_FOUND);let o=HQ()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=Hw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!Hw.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var hp=T((xle,kw)=>{"use strict";var GQ=We(),kQ=ea(),{getSchemaPath:VQ}=Je();kw.exports=$Q;function $Q(e){let t=kQ(e,"hashes");if(t)throw t;let r=VQ(e.schema,e.table);return GQ.openEnvironment(r,e.table)}a($Q,"initialize")});var mp=T((Fle,Vw)=>{"use strict";var YQ=Zo(),KQ=hp();Vw.exports=WQ;async function WQ(e){let t=await KQ(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return YQ.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(WQ,"lmdbGetDataByHash")});var ta=T((kle,$w)=>{"use strict";var pp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};$w.exports=pp});var Kw=T((Yle,Yw)=>{"use strict";var $le=ta(),QQ=Zo(),zQ=hp();Yw.exports=JQ;async function JQ(e){let t=await zQ(e),r=global.hdb_schema[e.schema][e.table];return QQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(JQ,"lmdbSearchByHash")});var Js=T((Wle,Ww)=>{"use strict";var Sp=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};Ww.exports=Sp});var k_=T((zle,Zw)=>{"use strict";var Qt=Zo(),jQ=We(),XQ=J(),Ee=dt(),ji=L(),ZQ=xi(),Qw=Nr().LMDB_ERRORS_ENUM,{getSchemaPath:ez}=Je(),Rn=ji.SEARCH_WILDCARDS;async function tz(e,t,r){let s;e.schema===ji.SYSTEM_SCHEMA_NAME?s=ZQ[e.table]:s=global.hdb_schema[e.schema][e.table];let n=Xw(e,s.hash_attribute,r,t);return Jw(e,n,s.hash_attribute,r)}a(tz,"prepSearch");async function Jw(e,t,r,s){let n=ez(e.schema,e.table),i=await jQ.openEnvironment(n,e.table),o=jw(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(rz(e,r)===!1){let l=e.search_attribute;if(l===r)return s?zw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?zw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?Qt.batchSearchByHashToMap(c,r,e.get_attributes,_):Qt.batchSearchByHash(c,r,e.get_attributes,_)}a(Jw,"executeSearch");function jw(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:n=Qt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:n=Qt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:n=Qt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:n=Qt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Qt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Qt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Qt.searchAll(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Qt.searchAllToMap(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:n=Qt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:n=Qt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Qt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:n=Qt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:n=Qt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(jw,"searchByType");function zw(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(zw,"createMapFromIterable");function rz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(rz,"checkToFetchMore");function Xw(e,t,r,s){if(XQ.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Rn.indexOf(n)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(Rn[0])<0&&n.indexOf(Rn[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(Rn.indexOf(i)>=0&&Rn.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(Rn.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(Rn.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(n.includes(Rn[0])||n.includes(Rn[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(Qw.UNKNOWN_SEARCH_TYPE)}else switch(s){case ji.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case ji.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case ji.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case ji.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case ji.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Qw.UNKNOWN_SEARCH_TYPE)}}a(Xw,"createSearchTypeFromSearchObject");Zw.exports={executeSearch:Jw,createSearchTypeFromSearchObject:Xw,prepSearch:tz,searchByType:jw}});var tI=T((Xle,eI)=>{"use strict";var jle=Js(),sz=ea(),nz=J(),iz=L(),oz=k_();eI.exports=az;function az(e,t){if(!nz.isEmpty(t)&&iz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=sz(e,"value");if(s)throw s;return oz.prepSearch(e,t,!0)}a(az,"lmdbGetDataByValue")});var Yc=T((t_e,rI)=>{"use strict";var e_e=Js(),cz=ea(),uz=J(),lz=L(),_z=k_();rI.exports=dz;async function dz(e,t){if(!uz.isEmpty(t)&&lz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=cz(e,"value");if(s)throw s;return _z.prepSearch(e,t,!1)}a(dz,"lmdbSearchByValue")});var nI=T((n_e,sI)=>{"use strict";var s_e=dt(),Tp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},gp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Rp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};sI.exports={SearchByConditionsObject:Tp,SearchCondition:gp,SortAttribute:Rp}});var uI=T((c_e,cI)=>{"use strict";var o_e=nI().SearchByConditionsObject,fz=Js(),Ez=ea(),Ap=Zo(),V_=dt(),{Resource:a_e}=(As(),se(Op)),aI=k_(),hz=Ep(),mz=require("lodash"),{getSchemaPath:pz}=Je(),iI=We(),{handleHDBError:Sz,hdb_errors:Tz}=re(),{HTTP_STATUS_CODES:gz}=Tz,Rz=1e8;cI.exports=Az;async function Az(e){let t=Ez(e,"conditions");if(t)throw Sz(t,t.message,gz.BAD_REQUEST,void 0,void 0,!0);e.operator=e.operator?e.operator.toLowerCase():void 0,e.offset=Number.isInteger(e.offset)?e.offset:0;let r=pz(e.schema,e.table),s=await iI.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)iI.openDBI(s,_.search_attribute);let i=mz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===V_.SEARCH_TYPES.EQUALS?_.estimated_count=Ap.count(s,_.search_attribute,_.search_value):l===V_.SEARCH_TYPES.CONTAINS||l===V_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Rz}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await oI(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=s.dbis[n.hash_attribute],l=i.slice(1).map(aI.filterByType),d=l.length,f=Ap.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>hz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await oI(o,e,f,n.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Ap.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Az,"lmdbSearchByConditions");async function oI(e,t,r,s){let n=new fz(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===V_.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,aI.searchByType(e,n,i,s).map(o=>o.value)}a(oI,"executeConditionSearch")});var ra=T((l_e,lI)=>{"use strict";var Oz=L().OPERATIONS_ENUM,bp=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=Oz.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};lI.exports=bp});var Np=T((d_e,SI)=>{"use strict";var EI=Js(),hI=ra(),mI=Yc(),pI=Gc(),ar=L(),_I=J(),dI=We(),{getTransactionAuditStorePath:bz,getSchemaPath:Nz}=Je(),fI=V();SI.exports=yz;async function yz(e){try{if(_I.isEmpty(global.hdb_schema[e.schema])||_I.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await wz(e),await Iz(e);let t=Nz(e.schema,e.table);try{await dI.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")fI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=bz(e.schema,e.table);await dI.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")fI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(yz,"lmdbDropTable");async function wz(e){let t=new EI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await mI(t)),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new hI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await pI(n)}a(wz,"deleteAttributesFromSystem");async function Iz(e){let t=new EI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await mI(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new hI(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await pI(n)}catch(i){throw i}}a(Iz,"dropTableFromSystem")});var gI=T((E_e,TI)=>{"use strict";var Cz=require("fs-extra"),Dz=Js(),Lz=ta(),Uz=ra(),Mz=Np(),Pz=Gc(),vz=mp(),Bz=Yc(),An=L(),{getSchemaPath:Hz}=Je(),{handleHDBError:xz,hdb_errors:qz}=re(),{HDB_ERROR_MSGS:Fz,HTTP_STATUS_CODES:Gz}=qz;TI.exports=kz;async function kz(e){let t;try{t=await Vz(e.schema);let r=new Dz(An.SYSTEM_SCHEMA_NAME,An.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,An.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[An.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await Bz(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await Mz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new Uz(An.SYSTEM_SCHEMA_NAME,An.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Pz(n);let i=Hz(t);await Cz.remove(i)}catch(r){throw r}}a(kz,"lmdbDropSchema");async function Vz(e){let t=new Lz(An.SYSTEM_SCHEMA_NAME,An.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[An.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await vz(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw xz(new Error,Fz.SCHEMA_NOT_FOUND(e),Gz.NOT_FOUND,void 0,void 0,!0);return s}a(Vz,"validateDropSchema")});var $_=T((m_e,RI)=>{"use strict";var yp=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};RI.exports=yp});var OI=T((T_e,AI)=>{"use strict";var $z=require("fs-extra"),Y_=We(),{getTransactionAuditStorePath:Yz}=Je(),wp=dt(),S_e=$_();AI.exports=Kz;async function Kz(e){let t;try{let r=Yz(e.schema,e.table);await $z.mkdirp(r),t=await Y_.createEnvironment(r,e.table,!0)}catch(r){throw r.message=`unable to create transactions audit environment for ${e.schema}.${e.table} due to: ${r.message}`,r}try{Y_.createDBI(t,wp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Y_.createDBI(t,wp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Y_.createDBI(t,wp.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(Kz,"createTransactionsAuditEnvironment")});var wI=T((R_e,yI)=>{"use strict";var Ip=L(),bI=We(),Wz=Go(),{getSystemSchemaPath:Qz,getSchemaPath:zz}=Je(),Jz=xi(),jz=f_(),Cp=d_(),Xz=V(),Zz=OI(),Lp=Jz.hdb_table,NI=[];for(let e=0;e<Lp.attributes.length;e++)NI.push(Lp.attributes[e].attribute);yI.exports=eJ;async function eJ(e,t){let r=zz(t.schema,t.table),s=new Cp(t.schema,t.table,Ip.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Cp(t.schema,t.table,Ip.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Cp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await bI.createEnvironment(r,t.table),e!==void 0){let o=await bI.openEnvironment(Qz(),Ip.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Wz.insertRecords(o,Lp.hash_attribute,NI,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Dp(s),await Dp(n),await Dp(i)}await Zz(t)}catch(o){throw o}}a(eJ,"lmdbCreateTable");async function Dp(e){try{await jz(e)}catch(t){Xz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Dp,"createAttribute")});var CI=T((O_e,II)=>{"use strict";var tJ=wc(),rJ=Uc(),sJ=B_(),Kc=L(),nJ=Go().updateRecords,iJ=We(),{getSchemaPath:oJ}=Je(),aJ=qc(),cJ=V();II.exports=uJ;async function uJ(e){try{let{schema_table:t,attributes:r}=tJ(e);rJ(e,r,t.hash_attribute),e.schema!==Kc.SYSTEM_SCHEMA_NAME&&(r.includes(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await sJ(e.hdb_auth_header,t,r),n=oJ(e.schema,e.table),i=await iJ.openEnvironment(n,e.table),o=await nJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await aJ(e,o)}catch(c){cJ.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(uJ,"lmdbUpdateRecords")});var LI=T((N_e,DI)=>{"use strict";var lJ=L().OPERATIONS_ENUM,Up=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=lJ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};DI.exports=Up});var MI=T((I_e,UI)=>{"use strict";var w_e=LI(),_J=wc(),dJ=Uc(),fJ=B_(),Wc=L(),EJ=Go().upsertRecords,hJ=We(),{getSchemaPath:mJ}=Je(),pJ=qc(),SJ=V(),{handleHDBError:TJ,hdb_errors:gJ}=re();UI.exports=RJ;async function RJ(e){let t;try{t=_J(e)}catch(u){throw TJ(u,u.message,gJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;dJ(e,s,r.hash_attribute),e.schema!==Wc.SYSTEM_SCHEMA_NAME&&(s.includes(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await fJ(e.hdb_auth_header,r,s),i=mJ(e.schema,e.table),o=await hJ.openEnvironment(i,e.table),c=await EJ(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await pJ(e,c)}catch(u){SJ.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(RJ,"lmdbUpsertRecords")});var vI=T((D_e,PI)=>{"use strict";var Mp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};PI.exports=Mp});var HI=T((U_e,BI)=>{"use strict";var Pp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};BI.exports=Pp});var FI=T((v_e,qI)=>{"use strict";var vp=We(),{getTransactionAuditStorePath:AJ}=Je(),P_e=vI(),Qc=dt(),OJ=J(),xI=HI(),bJ=require("util").promisify,NJ=bJ(setTimeout),yJ=1e4,wJ=100;qI.exports=IJ;async function IJ(e){let t=AJ(e.schema,e.table),r=await vp.openEnvironment(t,e.table,!0),s=vp.listDBIs(r);vp.initializeDBIs(r,Qc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new xI;do n=await CJ(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await NJ(wJ);while(n.transactions_deleted>0);return i}a(IJ,"deleteAuditLogsBefore");async function CJ(e,t){let r=new xI;try{let s=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[Qc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];OJ.isEmpty(c)||(n=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>yJ)break}return await n,r}catch(s){throw s}}a(CJ,"deleteTransactions")});var kI=T((H_e,GI)=>{"use strict";var Bp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};GI.exports=Bp});var $I=T((F_e,VI)=>{"use strict";var DJ=Js(),LJ=ra(),q_e=kI(),js=L(),UJ=J(),Hp=We(),MJ=xi(),PJ=Yc(),vJ=Gc(),{getSchemaPath:BJ}=Je();VI.exports=HJ;async function HJ(e,t=!0){let r;e.schema===js.SYSTEM_SCHEMA_NAME?r=MJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await qJ(e),n=BJ(e.schema,e.table),i=await Hp.openEnvironment(n,e.table);return t===!0&&await xJ(e,i,r.hash_attribute),Hp.dropDBI(i,e.attribute),s}a(HJ,"lmdbDropAttribute");async function xJ(e,t,r){let s=Hp.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);n=t.dbis[r].put(o,_,u)}await n}a(xJ,"removeAttributeFromAllObjects");async function qJ(e){let t=new DJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await PJ(t)).filter(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(UJ.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new LJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return vJ(i)}a(qJ,"dropAttributeFromSystem")});var JI=T((V_e,zI)=>{"use strict";var xp=We(),sa=dt(),k_e=yr(),qp=L(),YI=J(),{getTransactionAuditStorePath:FJ}=Je(),GJ=Zo(),K_=Jo(),kJ=V();zI.exports=VJ;async function VJ(e){let t=FJ(e.schema,e.table),r=await xp.openEnvironment(t,e.table,!0),s=xp.listDBIs(r);xp.initializeDBIs(r,sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return KI(r,e.search_values);case qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,YJ(r,e.search_values,n);case qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return $J(r,e.search_values);default:return KI(r)}}a(VJ,"readAuditLog");function KI(e,t=[0,Date.now()]){YI.isEmpty(t[0])&&(t[0]=0),YI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new K_,n))}a(KI,"searchTransactionsByTimestamp");function $J(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[sa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,QI(e,i))}return Object.fromEntries(r)}a($J,"searchTransactionsByUsername");function YJ(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=GJ.equals(e,sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,sa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);s.has(f)?s.get(f).push(_.toString()):s.set(f,[_.toString()])}}let n=Array.from(s.keys()),i=QI(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);WI(u,"records",r,l,o),WI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(YJ,"searchTransactionsByHashValues");function WI(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let _=n.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new K_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new K_(e.operation,e.user_name,i,void 0);_[t]=[c],n.set(u,[_])}}}a(WI,"loopRecords");function QI(e,t){let r=[];try{let s=e.dbis[sa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new K_,i);r.push(o)}}catch(i){kJ.warn(i)}return r}catch(s){throw s}}a(QI,"batchSearchTransactions")});var XI=T((W_e,jI)=>{"use strict";var{getSchemaPath:Y_e}=Je(),K_e=We(),{database:KJ}=(Ae(),se(Fe));jI.exports={writeTransaction:WJ};async function WJ(e,t,r){return KJ({database:e,table:t}).transaction(r)}a(WJ,"writeTransaction")});var rC=T((z_e,tC)=>{"use strict";var{getSchemaPath:ZI}=Je(),eC=We();tC.exports={flush:QJ,resetReadTxn:zJ};async function QJ(e,t){return(await eC.openEnvironment(ZI(e,t),t.toString())).flushed}a(QJ,"flush");async function zJ(e,t){try{(await eC.openEnvironment(ZI(e,t),t.toString())).resetReadTxn()}catch{}}a(zJ,"resetReadTxn")});var oC=T((j_e,iC)=>{"use strict";var{Readable:JJ}=require("stream"),{getDatabases:jJ}=(Ae(),se(Fe)),{readSync:XJ,openSync:ZJ,createReadStream:sC}=require("fs"),{open:e2}=require("lmdb"),nC=r_(),t2=n_(),{AUDIT_STORE_OPTIONS:r2}=(Bi(),se(aC)),{INTERNAL_DBIS_NAME:s2,AUDIT_STORE_NAME:n2}=dt();iC.exports=o2;var Fp=32768,i2=100;async function o2(e){let t=e.database||e.schema||"data",r=jJ()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let _=r[n[0]];if(!_)throw new Error(`Can not find table ${n[0]}`);let l=_.dbisDB,d=e2({noSync:!0,maxDbs:t2.MAX_DBS}),f,E=d.openDB(s2,new nC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(R,g){g.encoding="binary",g.encoder=void 0;let P=d.openDB(R,g),H=l.openDB(R,g);for(let{key:v,version:U,value:Y}of H.getRange({transaction:h,versions:H.useVersions}))f=P.put(v,Y,U),p++%i2===0&&(await new Promise(K=>setTimeout(K,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:g}of l.getRange({transaction:h,start:!1}))if(n.some(P=>R.startsWith?.(P+"/"))){E.put(R,g);let[,P]=R.split("/"),H=!P,v=new nC(!H,H);await S(R,v)}e.include_audit&&await S(n2,Object.assign({},r2)),await f;let A=sC(d.path);return A.headers=u(),A.on("close",()=>{h.done(),d.close()}),A}let o=r[Object.keys(r)[0]].primaryStore,c=ZJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(Fp);XJ(c,_,0,Fp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=sC(null,{fd:c,start:Fp}),f=new JJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",s),_}}a(o2,"getBackup")});var lC=T((Z_e,uC)=>{"use strict";var a2=V(),{handleHDBError:c2}=re(),u2=bb(),l2=f_(),_2=up(),d2=gw(),f2=Gc(),E2=mp(),h2=Kw(),m2=tI(),p2=Yc(),S2=uI(),T2=gI(),g2=wI(),R2=CI(),A2=MI(),O2=FI(),b2=Np(),N2=$I(),y2=JI(),w2=XI(),cC=rC(),I2=oC(),Gp=class extends u2{static{a(this,"LMDBBridge")}async searchByConditions(t){return S2(t)}async getDataByHash(t){return await E2(t)}async searchByHash(t){return await h2(t)}async getDataByValue(t,r){return await m2(t,r)}async searchByValue(t){return await p2(t)}async createSchema(t){return await d2(t)}async dropSchema(t){return await T2(t)}async createTable(t,r){return await g2(t,r)}async dropTable(t){return await b2(t)}async createAttribute(t){return await l2(t)}async createRecords(t){return await _2(t)}async updateRecords(t){return await R2(t)}async upsertRecords(t){try{return await A2(t)}catch(r){throw c2(r,null,null,a2.ERR,r)}}async deleteRecords(t){return await f2(t)}async dropAttribute(t){return await N2(t)}async deleteAuditLogsBefore(t){return await O2(t)}async readAuditLog(t){return await y2(t)}writeTransaction(t,r,s){return w2.writeTransaction(t,r,s)}flush(t,r){return cC.flush(t,r)}resetReadTxn(t,r){return cC.resetReadTxn(t,r)}getBackup(t){return I2(t)}};uC.exports=Gp});function U2(){L2=setInterval(function(){for(let e of kp)if(e.stale){let t=e[Oe]?.url;_C.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},D2).unref()}var Vp,_C,C2,kp,Xi,W_,D2,L2,$p=Re(()=>{Vp=x(yr()),_C=x(V());As();qo();C2=100,kp=new Set,Xi=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===0)return this.readTxnsUsed=1,e_(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),kp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),e_(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(kp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(this.open===2)throw new Error("Can not use a transaction that is no longer open");if(this.open===1){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,Vp.getNextMonotonicTime)());let s=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let A=S();E?E.push?E.push(A):E=[E,A]:E=A}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}s||this.doneReadTxn(),this.open=t?.letItLinger?1:2;let n,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,s)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){s>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);n=n||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<C2>>s?u():n=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),n)return n.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=s+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=2,this.writes=[]}},W_=class extends Xi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Vp.getNextMonotonicTime)())}getReadTxn(){}},D2=3e4;a(U2,"startMonitoringTxns");U2()});function Xe(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===0&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let s=e.transaction=new Xi;e.timestamp&&(s.timestamp=e.timestamp),s[Oe]=e,e.resourceCache||(e.resourceCache=[]);let n;try{if(n=t(s),n?.then)return n.then(i,o)}catch(c){o(c)}return i(n);function i(c){let u=s.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var dC,Zi=Re(()=>{dC=require("../index");As();$p();a(Xe,"transaction");(0,dC._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var RC={};Ye(RC,{ResourceBridge:()=>Wp});function Qp({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function EC(e,t){let r=Xs(e),s=Qp(e,r);if(!r)throw new Cs.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user},o;Xe(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:n,select:s},i);return l=l&&z_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function Xs(e){let t=e.database||e.schema||P2,r=Ds()[t];if(!r)throw(0,Cs.handleHDBError)(new Error,M2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function hC(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*mC(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var pC,Q_,Cs,SC,TC,Ls,Yp,Kp,gC,M2,P2,v2,B2,fC,Wp,AC=Re(()=>{"use strict";pC=x(lC()),Q_=x(ea()),Cs=x(re());Ae();SC=x(wc()),TC=x(Uc()),Ls=x(L()),Yp=x(gn()),Kp=x(Is()),gC=x(J());Zi();J_();({HDB_ERROR_MSGS:M2}=Cs.hdb_errors),P2="data",v2=1e4,B2=10,Wp=class extends pC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),fC=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,Q_.default)(t,"conditions");if(r)throw(0,Cs.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=Xs(t);if(!s)throw new Cs.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Qp(t,s),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Cs.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ct({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await Xs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Xs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(o,c,u),await new Promise(_=>setImmediate(_));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Xs(t).dropTable()}createSchema(t){return zc({database:t.schema,table:null}),Yp.signalSchemaChange(new Kp.SchemaEventMsg(process.pid,Ls.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await zp(t.schema),Yp.signalSchemaChange(new Kp.SchemaEventMsg(process.pid,Ls.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,fC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,SC.default)(t);(0,TC.default)(t,s,r.primaryKey);let n,i=Ds()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Xe(o,async c=>{if(!i.schemaDefined){n=[];for(let l of s)i.attributes.find(f=>f.name==l)||n.push(l);n.length>0&&await i.addAttributes(n.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=z_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:_}})}async deleteRecords(t){let r=Ds()[t.schema][t.table],s={user:t.hdb_user};return Xe(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return hC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Ds()[t.schema][t.table];if(!r.createdTimeProperty)throw new Cs.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Ls.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,gC.async_set_timeout)(B2),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%v2===0&&await _();return u.length>0&&await _(),n?hC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,Q_.default)(t,"hashes");if(r)throw r;return EC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of EC(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Ls.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let s=(0,Q_.default)(t,"value");if(s)throw s;let n=Xs(t);if(!n)throw new Cs.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Ls.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Qp(t,n)})}async getDataByValue(t,r){let s=new Map,n=Xs(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){Xs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Xs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Xs(t),s={};switch(t.search_type){case Ls.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case Ls.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of mC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return mC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Qp,"getSelect");a(EC,"getRecords");a(Xs,"getTable");a(hC,"createDeleteResponse");a(mC,"groupRecordsInHistory")});var Ns=T((hde,OC)=>{"use strict";var{ResourceBridge:H2}=(AC(),se(RC)),x2=Z();x2.initSync();var j_;function q2(){return j_||(j_=new H2,j_)}a(q2,"getBridge");OC.exports=q2()});var wC=T((pde,yC)=>{"use strict";var bC=require("lodash"),Jc=require("mathjs"),F2=require("jsonata"),NC=J();yC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?bC.uniqWith(e,bC.isEqual):e,searchJSON:G2,mad:jc.bind(null,Jc.mad),mean:jc.bind(null,Jc.mean),mode:jc.bind(null,Jc.mode),prod:jc.bind(null,Jc.prod),median:jc.bind(null,Jc.median)};function jc(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(jc,"aggregateFunction");function G2(e,t){if(typeof e!="string"||e.length===0)throw new Error("search json expression must be a non-empty string");let r="__"+e+"__";if(NC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),NC.isEmpty(this.__ala__.res[r])){let s=F2(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(G2,"searchJSON")});var CC=T((Tde,IC)=>{"use strict";var Et=require("moment"),Jp="YYYY-MM-DDTHH:mm:ss.SSSZZ";Et.suppressDeprecationWarnings=!0;IC.exports={current_date:()=>Et().utc().format("YYYY-MM-DD"),current_time:()=>Et().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Et(e).utc().format("YYYY");case"month":return Et(e).utc().format("MM");case"day":return Et(e).utc().format("DD");case"hour":return Et(e).utc().format("HH");case"minute":return Et(e).utc().format("mm");case"second":return Et(e).utc().format("ss");case"millisecond":return Et(e).utc().format("SSS");default:break}},date:e=>Et(e).utc().format(Jp),date_format:(e,t)=>Et(e).utc().format(t),date_add:(e,t,r)=>Et(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Et(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=Et(e).utc(),n=Et(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>Et().utc().valueOf(),get_server_time:()=>Et().format(Jp),offset_utc:(e,t)=>Et(e).utc().utcOffset(t).format(Jp)}});var MC=T((gde,UC)=>{"use strict";var k2=require("@turf/area"),V2=require("@turf/length"),$2=require("@turf/circle"),Y2=require("@turf/difference"),K2=require("@turf/distance"),W2=require("@turf/boolean-contains"),Q2=require("@turf/boolean-equal"),z2=require("@turf/boolean-disjoint"),J2=require("@turf/helpers"),DC=L(),pe=J(),On=V();UC.exports={geoArea:j2,geoLength:X2,geoCircle:Z2,geoDifference:e4,geoDistance:LC,geoNear:t4,geoContains:r4,geoEqual:s4,geoCrosses:n4,geoConvert:i4};function j2(e){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return k2.default(e)}catch(t){return On.trace(t,e),NaN}}a(j2,"geoArea");function X2(e,t){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return V2.default(e,{units:t||"kilometers"})}catch(r){return On.trace(r,e),NaN}}a(X2,"geoLength");function Z2(e,t,r){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return $2.default(e,t,{units:r||"kilometers"})}catch(s){return On.trace(s,e,t),NaN}}a(Z2,"geoCircle");function e4(e,t){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return Y2(e,t)}catch(r){return On.trace(r,e,t),NaN}}a(e4,"geoDifference");function LC(e,t,r){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return K2.default(e,t,{units:r||"kilometers"})}catch(s){return On.trace(s,e,t),NaN}}a(LC,"geoDistance");function t4(e,t,r,s){if(pe.isEmpty(e)||pe.isEmpty(t))return!1;if(pe.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return LC(e,t,s)<=r}catch(n){return On.trace(n,e,t),!1}}a(t4,"geoNear");function r4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return W2.default(e,t)}catch(r){return On.trace(r,e,t),!1}}a(r4,"geoContains");function s4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return Q2.default(e,t)}catch(r){return On.trace(r,e,t),!1}}a(s4,"geoEqual");function n4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return!z2.default(e,t)}catch(r){return On.trace(r,e,t),!1}}a(n4,"geoCrosses");function i4(e,t,r){if(pe.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(pe.isEmpty(t))throw new Error("geo_type is required");if(pe.isEmpty(DC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(DC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=pe.autoCastJSON(e)),J2[t](e,r)}a(i4,"geoConvert")});var X_=T((Ade,PC)=>{var eo=wC(),Br=CC(),Zs=MC();PC.exports=e=>{e.aggr.mad=e.aggr.MAD=eo.mad,e.aggr.mean=e.aggr.MEAN=eo.mean,e.aggr.mode=e.aggr.MODE=eo.mode,e.aggr.prod=e.aggr.PROD=eo.prod,e.aggr.median=e.aggr.MEDIAN=eo.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=eo.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=eo.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Br.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Br.current_time,e.fn.extract=e.fn.EXTRACT=Br.extract,e.fn.date=e.fn.DATE=Br.date,e.fn.date_format=e.fn.DATE_FORMAT=Br.date_format,e.fn.date_add=e.fn.DATE_ADD=Br.date_add,e.fn.date_sub=e.fn.DATE_SUB=Br.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Br.date_diff,e.fn.now=e.fn.NOW=Br.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Br.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Br.get_server_time,e.fn.getdate=e.fn.GETDATE=Br.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Br.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=Zs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Zs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Zs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Zs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Zs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Zs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Zs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Zs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Zs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Zs.geoNear}});var xC=T((Ode,HC)=>{"use strict";var Xc=require("lodash"),cr=require("alasql");cr.options.cache=!1;var o4=X_(),vC=require("clone"),Z_=require("recursive-iterator"),_e=V(),Ce=J(),na=Ns(),a4=L(),{hdb_errors:c4}=re(),{getDatabases:BC}=(Ae(),se(Fe)),u4="IS NULL",Us="There was a problem performing this search. Please check the logs and try again.";o4(cr);var jp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw _e.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),Ce.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(s))return _e.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw _e.error("Error thrown from checkEmptySQL in SQLSearch class method search."),_e.error(s),new Error(Us)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw _e.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),_e.error(s),new Error(Us)}if(Object.keys(this.data).length===0)return _e.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw _e.error("Error thrown from processJoins in SQLSearch class method search."),_e.error(s),new Error(Us)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw _e.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),_e.error(s),new Error(Us)}try{return t=await this._finalSQL(),t}catch(s){throw _e.error("Error thrown from finalSQL in SQLSearch class method search."),_e.error(s),new Error(Us)}}_getColumns(){let t=new Z_(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(vC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Xc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=BC()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){_e.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Z_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let s=Ce.autoCast(r.right.value);[!0,!1].indexOf(s)>=0&&(r.right=new cr.yy.LogicValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=Ce.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new cr.yy.LogicValue({value:i}):s instanceof cr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new cr.yy.NumValue({value:i}))});if(t){_e.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Z_(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(a4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ce.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ce.isEmptyOrZeroLength(r.left.columnid)||Ce.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(Ce.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!Ce.isEmpty(r.right.value)||!Ce.isEmpty(r.left.value)?s.add(Ce.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)s.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Xc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(Ce.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);Ce.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&!Ce.isEmptyOrZeroLength(this.columns.columns))return t;if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await cr.promise(r)}catch(r){throw _e.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),_e.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let s=this._findColumn(r);s&&this.fetch_attributes.push(vC(s))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(Ce.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(u4)>-1&&this.tables.forEach(n=>{let i={columnid:BC()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Xc.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,_=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!Ce.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await na.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(Us)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await na.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(Us)}else if(!Ce.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await na.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...s[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]):(this.data[i].__merged_data[p]=[...s[i]],this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(Us)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await na.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(Us)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof cr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new cr.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new cr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let n=t.is_func?new cr.yy.FuncValue:new cr.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,n);f=await cr.promise(h,t),t=null}catch(E){throw _e.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),_e.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=Xc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,A=p.length;S<A;S++){let R=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[R]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Z_(this.columns);for(let{node:i}of n)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&s.push(o)}}s=Xc.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw _e.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),_e.error(i),new Error(Us)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await na.getDataByHash(c),_=n.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=n.columns[h],S=E[p]===void 0?null:E[p];this.data[s].__merged_data[f].push(S)}}}}catch(r){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getData."),_e.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let s;try{let n=this._buildSQL();_e.trace(`Final SQL: ${n}`),s=await cr.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),_e.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw _e.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),_e.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return _e.error(c4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),_e.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;s=s.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;s=s.replace(u,_)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await na.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw _e.error("There was an error when processing this SQL operation. Check your logs"),_e.error(o),new Error(Us)}}return Object.values(Object.values(this.data)[0].__merged_data)}};HC.exports=jp});var es=T((Nde,qC)=>{"use strict";var l4=Ab();qC.exports={searchByConditions:d4,searchByHash:f4,searchByValue:E4,search:h4};var Xp=Ns(),{transformReq:Zp}=J(),_4=xC();async function d4(e){return Zp(e),Xp.searchByConditions(e)}a(d4,"searchByConditions");async function f4(e){Zp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Xp.searchByHash(e))r&&t.push(r);return t}a(f4,"searchByHash");async function E4(e){Zp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Xp.searchByValue(e))t.push(r);return t}a(E4,"searchByValue");function h4(e,t){try{let r=new l4(e);r.validate(),new _4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(h4,"search")});var ed=T((wde,FC)=>{"use strict";var m4=Ns();FC.exports={writeTransaction:p4};function p4(e,t,r){return m4.writeTransaction(e,t,r)}a(p4,"writeTransaction")});var $C=T((Dde,VC)=>{"use strict";var S4=es(),T4=Tn(),GC=V(),g4=Cr(),Cde=ed(),R4=require("clone"),tS=require("alasql"),A4=X_(),kC=require("util"),O4=kC.promisify(T4.getTableSchema),b4=kC.promisify(S4.search),N4=L(),eS=J();A4(tS);VC.exports={update:w4};var y4="There was a problem performing this update. Please check the logs and try again.";async function w4({statement:e,hdb_user:t}){let r=await O4(e.table.databaseid,e.table.tableid),s=I4(e.columns);eS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=R4(n),c=eS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=tS.parse(u).statements[0],l=await b4(_),d=C4(s,l);return D4(o,d,t)}a(w4,"update");function I4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=tS.compile(`SELECT ${r.expression.toString()} AS [${N4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw GC.error(t),new Error(y4)}}a(I4,"createUpdateRecord");function C4(e,t){return eS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(C4,"buildUpdateRecords");async function D4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await g4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){GC.error(`Error delete new_attributes from update response: ${i}`)}return n}a(D4,"updateRecords")});var KC=T((Pde,YC)=>{var L4=require("alasql"),U4=es(),M4=V(),P4=Ns(),sS=require("util"),rS=J(),v4=L(),B4=Tn(),Ude=ed(),Mde=Cr(),H4="record",x4="successfully deleted",q4=sS.callbackify(V4),F4=sS.promisify(U4.search),G4=sS.promisify(B4.getTableSchema);YC.exports={convertDelete:q4};function k4(e){return`${e.deleted_hashes.length} ${H4}${e.deleted_hashes.length===1?"":"s"} ${x4}`}a(k4,"generateReturnMessage");async function V4({statement:e,hdb_user:t}){let r=await G4(e.table.databaseid,e.table.tableid);rS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=rS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=L4.parse(o).statements[0],u={operation:v4.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await F4(c);let _=await P4.deleteRecords(u);return rS.isEmptyOrZeroLength(_.message)&&(_.message=k4(_)),delete _.txn_time,_}catch(_){throw M4.error(_),_.hdb_code?_.message:_}}a(V4,"convertDelete")});var jC=T((Bde,JC)=>{"use strict";var $4=Xn(),{hdb_errors:WC}=re(),{getDatabases:QC}=(Ae(),se(Fe));JC.exports={checkSchemaExists:zC,checkSchemaTableExists:Y4,schema_describe:$4};async function zC(e){if(!QC()[e])return WC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(zC,"checkSchemaExists");async function Y4(e,t){let r=await zC(e);if(r)return r;if(!QC()[e][t])return WC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Y4,"checkSchemaTableExists")});var Zc=T((xde,K4)=>{K4.exports={name:"harperdb",version:"4.3.0-beta.6",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.10.0-beta.2",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.3.3","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var su={};Ye(su,{addAnalyticsListener:()=>ru,recordAction:()=>Hr,recordActionBinary:()=>rs,setAnalyticsEnabled:()=>W4});function W4(e){aD=e}function Hr(e,t,r,s,n){if(!aD)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);let o=sd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:s,type:n},sd.set(i,o)}td||Q4()}function rs(e,t,r,s,n){Hr(!!e,t,r,s,n)}function ru(e){lD.push(e)}function Q4(){td=performance.now(),setTimeout(async()=>{let e=performance.now()-td;td=0;let t=[],r={time:Date.now(),period:e,threadId:to.threadId,metrics:t};for(let[n,i]of sd){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of _D){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await dD()}let s=process.memoryUsage();t.push({metric:"memory",threadId:to.threadId,byThread:!0,...s});for(let n of lD)n(t);sd=new Map,to.parentPort?to.parentPort.postMessage({type:uD,report:r}):hD({report:r})},cD).unref()}async function z4(e,t=6e4){let r=oS(),s=fD(),n;for(let h of s.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){n=h.value.time;break}if(Date.now()-t<n)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:n||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:A}=p;for(let R of S||[]){let{path:g,method:P,type:H,metric:v,count:U,total:Y,distribution:K,threads:z,...ne}=R;U||(U=1);let me=v+(g?"-"+g:"");P!==void 0&&(me+="-"+P),H!==void 0&&(me+="-"+H);let ce=o.get(me);if(ce){if(ce.threads){let le=ce.threads[A];if(le)ce=le;else{ce.threads[A]=Object.assign({},ne);continue}}ce.count||(ce.count=1);let xe=ce.count;for(let le in ne){let Dt=ne[le];typeof Dt=="number"&&(ce[le]=(ce[le]*xe+Dt*U)/(xe+U))}ce.count+=U,Y>=0&&(ce.total+=Y,ce.ratio=ce.total/ce.count)}else ce=Object.assign({period:t},R),delete ce.distribution,o.set(me,ce),ce.byThread&&(ce.threads=[],ce.threads[A]=Object.assign({},ne),u.push(ce));if(K){K=K.map(le=>typeof le=="number"?{value:le,count:1}:le);let xe=c.get(me);xe?xe.push(...K):c.set(me,K)}}await dD()}for(let h of u){let{path:p,method:S,type:A,metric:R,count:g,total:P,distribution:H,threads:v,...U}=h;v=v.filter(Y=>Y);for(let Y in U){if(typeof h[Y]!="number")continue;let K=0;for(let z of v){let ne=z[Y];typeof ne=="number"&&(K+=ne)}h[Y]=K}h.count=v.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((le,Dt)=>le.value>Dt.value?1:-1);let A=S.count-1,R=[],g=0,P=0,H;for(let le of _D){let Dt=A*le;for(;g<Dt;)H=p[P++],g+=H.count,P===1&&g--;let Ul=p[P>1?P-2:0];H||(H=p[0]),R.push(H.value-(H.value-Ul.value)*(g-Dt)/H.count)}let[v,U,Y,K,z,ne,me,ce,xe]=R;Object.assign(S,{p1:v,p10:U,p25:Y,median:K,p75:z,p90:ne,p95:me,p99:ce,p999:xe})}let l;for(let[h,p]of o)p.id=(0,rd.getNextMonotonicTime)(),p.time=_,s.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||s.primaryStore.put(p.id,p)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,rd.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-XC,active:E-ZC,time:d,...process.memoryUsage()};s.primaryStore.put(h,p,{append:!0}).then(S=>{S||s.primaryStore.put(h,p)})}XC=f,ZC=E}async function eD(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function oS(){return tD||(tD=ct({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function fD(){return rD||(rD=ct({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function X4(){ED=!0;let e=(0,tu.get)(iS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await z4(cD,e),await eD(oS(),J4),await eD(fD(),j4)},Math.min(e/2,2147483647)).unref()}function hD(e,t){let r=e.report;r.threadId=t?.threadId||to.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(sD+=s.mean*s.count);r.totalBytesProcessed=sD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(nD.get(t))}),nD.set(t,t.performance.eventLoopUtilization())),r.id=(0,rd.getNextMonotonicTime)(),oS().primaryStore.put(r.id,r),ED||X4(),Z4&&(mD=t3(r))}async function t3(e){if(await mD,!oi){let r=(0,eu.dirname)((0,oD.getLogFilePath)());try{oi=await(0,nS.open)((0,eu.join)(r,"analytics.log"),"r+")}catch{oi=await(0,nS.open)((0,eu.join)(r,"analytics.log"),"w+")}}let t=(await oi.stat()).size;if(t>e3){let r=Buffer.alloc(t);await oi.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await oi.write(r,{position:0}),await oi.truncate(r.length),t=r.length}await oi.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var to,iD,oD,eu,nS,rd,tu,iS,sd,aD,td,cD,uD,lD,_D,XC,ZC,dD,J4,j4,tD,rD,ED,sD,nD,Z4,mD,oi,e3,bn=Re(()=>{to=require("worker_threads"),iD=x(Ke());Ae();oD=x(V()),eu=require("path"),nS=require("fs/promises"),rd=x(yr()),tu=x(Z()),iS=x(L());rr();(0,tu.initSync)();sd=new Map,aD=(0,tu.get)(iS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(W4,"setAnalyticsEnabled");a(Hr,"recordAction");tt.recordAnalytics=Hr;a(rs,"recordActionBinary");td=0,cD=1e3,uD="analytics-report",lD=[];a(ru,"addAnalyticsListener");_D=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(Q4,"sendAnalytics");a(z4,"aggregation");XC=0,ZC=0,dD=a(()=>new Promise(setImmediate),"rest");a(eD,"cleanup");J4=36e5,j4=31536e6;a(oS,"getRawAnalyticsTable");a(fD,"getAnalyticsTable");(0,iD.setChildListenerByType)(uD,hD);a(X4,"startScheduledTasks");sD=0,nD=new Map,Z4=!1;a(hD,"recordAnalytics");e3=1e6;a(t3,"logAnalytics")});var st=T((Xde,BD)=>{"use strict";var Ft=Z();Ft.initSync();var r3=require("fs-extra"),s3=require("semver"),ou=require("path"),{monotonicFactory:n3}=require("ulidx"),SD=n3(),i3=require("util"),TD=require("child_process"),o3=i3.promisify(TD.exec),a3=TD.spawn,ye=Ge(),Pe=L(),lS=J(),xr=V(),nd=Sn(),c3=ed(),nu=Ur(),{onMessageByType:u3}=Ke(),{isMainThread:l3}=require("worker_threads"),{Encoder:_3,decode:_S}=require("msgpackr"),gD=new _3,{isEmpty:io}=lS,RD=ts(),d3=48*36e11,f3=5e9;l3&&u3(Pe.ITC_EVENT_TYPES.RESTART,()=>{ss=void 0,no=void 0});var{connect:E3,StorageType:AD,RetentionPolicy:OD,AckPolicy:id,DeliverPolicy:od,DiscardPolicy:h3,NatsConnection:Qde,JetStreamManager:zde,JetStreamClient:Jde,StringCodec:jde,JSONCodec:m3,createInbox:dS,headers:p3,ErrorCode:pD}=require("nats"),{PACKAGE_ROOT:S3}=L(),T3=Zc(),{recordAction:g3}=(bn(),se(su)),bD=m3(),R3="clustering",A3=T3.engines[ye.NATS_SERVER_NAME],O3=ou.join(S3,"dependencies"),uS=ou.join(O3,`${process.platform}-${process.arch}`,ye.NATS_BINARY_NAME),aS,cS,iu,ro,so;BD.exports={runCommand:ND,checkNATSServerInstalled:b3,createConnection:fS,getConnection:ad,getJetStreamManager:au,getJetStream:wD,getNATSReferences:ur,getServerList:y3,createLocalStream:ES,listStreams:ID,deleteLocalStream:w3,getServerConfig:cu,listRemoteStreams:I3,viewStream:C3,viewStreamIterator:D3,publishToStream:L3,createWorkQueueStream:U3,addSourceToWorkStream:DD,request:P3,removeSourceFromWorkStream:UD,reloadNATS:hS,reloadNATSHub:v3,reloadNATSLeaf:B3,extractServerName:LD,requestErrorHandler:H3,updateWorkStream:x3,createLocalTableStream:PD,createTableStreams:q3,purgeTableStream:vD,purgeSchemaTableStreams:F3,getStreamInfo:G3,updateLocalStreams:V3,closeConnection:N3,getJsmServerName:uu,addNatsMsgHeader:CD,updateIngestStreamConsumer:M3,clearClientCache:yD};async function ND(e,t=void 0){let{stdout:r,stderr:s}=await o3(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(ND,"runCommand");async function b3(){try{await r3.access(uS)}catch{return!1}let e=await ND(`${uS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return s3.eq(t,A3)}a(b3,"checkNATSServerInstalled");async function fS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await RD.getClusterUser();if(io(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}xr.trace("create nats connection called");let i=await E3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),xr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&xr.error("Error with Nats client connection, connection closed",o),yD()}),i}a(fS,"createConnection");function yD(){ss=void 0,ro=void 0,so=void 0,no=void 0}a(yD,"clearClientCache");async function N3(){ss&&(await ss.drain(),ss=void 0,ro=void 0,so=void 0,no=void 0)}a(N3,"closeConnection");var ss,no;async function ad(){return no||(no=fS(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),ss=await no),ss||no}a(ad,"getConnection");async function au(){if(ro)return ro;io(ss)&&await ad();let{domain:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(io(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ro=await ss.jetstreamManager({domain:e,timeout:6e4}),ro}a(au,"getJetStreamManager");async function wD(){if(so)return so;io(ss)&&await ad();let{domain:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(io(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return so=ss.jetstream({domain:e,timeout:6e4}),so}a(wD,"getJetStream");async function ur(){let e=ss||await ad(),t=ro||await au(),r=so||await wD();return{connection:e,jsm:t,js:r}}a(ur,"getNATSReferences");async function y3(e){let t=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await RD.getClusterUser(),n=await fS(t,r,s),i=dS(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=bD.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await lS.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(y3,"getServerList");async function ES(e,t){let{jsm:r}=await ur(),s=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:AD.File,retention:OD.Limits,subjects:t,discard:h3.Old,max_msgs:n,max_bytes:i,max_age:s})}a(ES,"createLocalStream");async function ID(){let{jsm:e}=await ur(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(ID,"listStreams");async function w3(e){let{jsm:t}=await ur();await t.streams.delete(e)}a(w3,"deleteLocalStream");async function I3(e){let{connection:t}=await ur(),r=[],s=dS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(bD.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(I3,"listRemoteStreams");async function C3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ur(),i=SD(),o={durable_name:i,ack_policy:id.Explicit};t&&(o.deliver_policy=od.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=_S(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(ye.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(C3,"viewStream");async function*D3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ur(),i=SD(),o={durable_name:i,ack_policy:id.Explicit};t&&(o.deliver_policy=od.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=_S(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(ye.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(D3,"viewStreamIterator");async function L3(e,t,r,s){xr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=CD(s,r);let{js:n}=await ur(),i=await uu(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:gD.encode(s);try{xr.trace(`publishToStream publishing to subject: ${o}`),g3(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return MD(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){xr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await ES(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(L3,"publishToStream");function CD(e,t){t===void 0&&(t=p3());let r=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(ye.MSG_HEADERS.ORIGIN)&&r&&t.append(ye.MSG_HEADERS.ORIGIN,r),t}a(CD,"addNatsMsgHeader");function cu(e){e=e.toLowerCase();let t=ou.join(Ft.get(Pe.CONFIG_PARAMS.ROOTPATH),R3);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return io(cS)&&(cS={port:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.HUB,config_file:ye.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:ou.join(t,ye.PID_FILES.HUB),hdb_nats_path:t}),cS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return io(aS)&&(aS={port:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,config_file:ye.NATS_CONFIG_FILES.LEAF_SERVER,domain:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,pid_file_path:ou.join(t,ye.PID_FILES.LEAF),hdb_nats_path:t}),aS;xr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(cu,"getServerConfig");async function U3(e){let{jsm:t}=await ur(),r=await uu();try{await t.streams.add({name:e.stream_name,storage:AD.File,retention:OD.Limits,max_age:d3,max_bytes:f3,subjects:[`${ye.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:id.Explicit,durable_name:e.durable_name,deliver_policy:od.All,max_ack_pending:1e4});else throw s}}a(U3,"createWorkQueueStream");async function M3(){let{jsm:e}=await ur();(await e.consumers.info(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(xr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name),xr.info("Adding pull consumer to ingest stream"),await e.consumers.add(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:id.Explicit,durable_name:ye.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:od.All,max_ack_pending:1e4}))}a(M3,"updateIngestStreamConsumer");async function DD(e,t,r){let{jsm:s}=await ur(),n=await s.streams.info(t),i=LD(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=nd.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let p=0,S=n.config.sources.length;p<S;p++)if(d=n.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await s.streams.purge(t,{filter:p}),n.config.sources.splice(f,1),await s.streams.update(t,n.config)}let h={name:_,opt_start_time:o,filter_subject:`${ye.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(DD,"addSourceToWorkStream");function LD(e){return e.split(".")[1]}a(LD,"extractServerName");async function UD(e,t,r){let{jsm:s}=await ur(),{schema:n,table:i}=r,o=`txn.${n}.${i}.${e}`;await s.streams.purge(t,{filter:o});let c=nd.createNatsTableStreamName(n,i),u=await s.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await s.streams.update(t,u.config)}a(UD,"removeSourceFromWorkStream");async function P3(e,t,r=6e4,s=dS()){if(!lS.isObject(t))throw new Error("data param must be an object");let n=gD.encode(t),{connection:i}=await ur(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return _S(c.data)}a(P3,"request");function hS(e){return new Promise(async(t,r)=>{let s=a3(uS,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(hS,"reloadNATS");async function v3(){let{pid_file_path:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await hS(e)}a(v3,"reloadNATSHub");async function B3(){let{pid_file_path:e}=cu(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await hS(e)}a(B3,"reloadNATSLeaf");function H3(e,t,r){let s;switch(e.code){case pD.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case pD.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(H3,"requestErrorHandler");async function x3(e,t){let r=t+ye.SERVER_SUFFIX.LEAF;await MD(async()=>{e.subscribe===!0?await DD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await UD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(x3,"updateWorkStream");function MD(e){return c3.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(MD,"exclusiveLock");async function PD(e,t){let r=nd.createNatsTableStreamName(e,t),s=await uu(),n=k3(e,t,s);await ES(r,[n])}a(PD,"createLocalTableStream");async function q3(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await PD(s,n)}}a(q3,"createTableStreams");async function vD(e,t,r=!1){if(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=nd.createNatsTableStreamName(e,t),{jsm:n}=await ur();r?await n.streams.purge(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name):await n.streams.purge(s)}catch(s){if(s.message==="stream not found")xr.warn(s);else throw s}}a(vD,"purgeTableStream");async function F3(e,t){if(Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await vD(e,t[r])}a(F3,"purgeSchemaTableStreams");async function G3(e){return(await au()).streams.info(e)}a(G3,"getStreamInfo");function k3(e,t,r){return`${ye.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(k3,"createSubjectName");async function uu(){if(iu)return iu;if(iu=(await au())?.nc?.info?.server_name,iu===void 0)throw new Error("Unable to get jetstream manager server name");return iu}a(uu,"getJsmServerName");async function V3(){let e=await au(),t=await uu(),r=await ID();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=$3(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");xr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}await e.streams.update(n.name,n)}}}a(V3,"updateLocalStreams");function $3(e){let{config:t}=e,r=!1;if(t.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Ft.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a($3,"updateStreamLimits")});var lu=T((tfe,FD)=>{"use strict";var ia=__(),oa=jC(),Y3=V(),K3=require("uuid").v4,efe=require("clone"),ud=gn(),aa=L(),W3=require("util"),ai=Ns(),{handleHDBError:lr,hdb_errors:Q3}=re(),{HDB_ERROR_MSGS:cd,HTTP_STATUS_CODES:_r}=Q3,{SchemaEventMsg:ld}=Is(),HD=st(),{getDatabases:z3}=(Ae(),se(Fe)),{transformReq:ca}=J();FD.exports={createSchema:J3,createSchemaStructure:xD,createTable:j3,createTableStructure:qD,createAttribute:rj,dropSchema:X3,dropTable:Z3,dropAttribute:ej,getBackup:sj};async function J3(e){let t=await xD(e);return ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema)),t}a(J3,"createSchema");async function xD(e){let t=ia.schema_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(ca(e),!await oa.checkSchemaExists(e.schema))throw lr(new Error,cd.SCHEMA_EXISTS_ERR(e.schema),_r.BAD_REQUEST,aa.LOG_LEVELS.ERROR,cd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ai.createSchema(e),`database '${e.schema}' successfully created`}a(xD,"createSchemaStructure");async function j3(e){return ca(e),e.hash_attribute=e.primary_key??e.hash_attribute,await qD(e)}a(j3,"createTable");async function qD(e){let t=ia.create_table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(ia.validateTableResidence(e.residence),!await oa.checkSchemaTableExists(e.schema,e.table))throw lr(new Error,cd.TABLE_EXISTS_ERR(e.schema,e.table),_r.BAD_REQUEST,aa.LOG_LEVELS.ERROR,cd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:K3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await ai.createTable(s,e);else throw lr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",_r.BAD_REQUEST);else await ai.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(qD,"createTableStructure");async function X3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ia.schema_object(e),s=t??r;if(s)throw lr(s,s.message,_r.BAD_REQUEST,void 0,void 0,!0);ca(e);let n=await oa.checkSchemaExists(e.schema);if(n)throw lr(new Error,n,_r.NOT_FOUND,aa.LOG_LEVELS.ERROR,n,!0);let i=await oa.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ai.dropSchema(e),ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema)),await HD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(X3,"dropSchema");async function Z3(e){let t=ia.table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);ca(e);let r=await oa.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,aa.LOG_LEVELS.ERROR,r,!0);return await ai.dropTable(e),await HD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Z3,"dropTable");async function ej(e){let t=ia.attribute_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);ca(e);let r=await oa.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,aa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw lr(new Error,"You cannot drop a hash attribute",_r.BAD_REQUEST,void 0,void 0,!0);if(aa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw lr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,_r.BAD_REQUEST,void 0,void 0,!0);try{return await ai.dropAttribute(e),tj(e),ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw Y3.error(`Got an error deleting attribute ${W3.inspect(e)}.`),s}}a(ej,"dropAttribute");function tj(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(tj,"dropAttributeFromGlobal");async function rj(e){ca(e);let t=z3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw lr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,_r.BAD_REQUEST,void 0,void 0,!0);return await ai.createAttribute(e),ud.signalSchemaChange(new ld(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(rj,"createAttribute");function sj(e){return ai.getBackup(e)}a(sj,"getBackup")});var kD=T((sfe,GD)=>{"use strict";var{OPERATIONS_ENUM:nj}=L(),mS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=nj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};GD.exports=mS});var pS=T((ofe,WD)=>{"use strict";var ij=Ns(),ife=kD(),_d=J(),dd=L(),oj=Z(),{handleHDBError:VD,hdb_errors:aj}=re(),{HDB_ERROR_MSGS:$D,HTTP_STATUS_CODES:YD}=aj,cj=Object.values(dd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),KD="To use this operation audit log must be enabled in harperdb-config.yaml";WD.exports=uj;async function uj(e){if(_d.isEmpty(e.schema))throw new Error($D.SCHEMA_REQUIRED_ERR);if(_d.isEmpty(e.table))throw new Error($D.TABLE_REQUIRED_ERR);if(!oj.get(dd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw VD(new Error,KD,YD.BAD_REQUEST,dd.LOG_LEVELS.ERROR,KD,!0);let t=_d.checkSchemaTableExist(e.schema,e.table);if(t)throw VD(new Error,t,YD.NOT_FOUND,dd.LOG_LEVELS.ERROR,t,!0);if(!_d.isEmpty(e.search_type)&&cj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await ij.readAuditLog(e)}a(uj,"readAuditLog")});var zD=T((cfe,QD)=>{"use strict";var{OPERATIONS_ENUM:lj}=L(),SS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=lj.GET_BACKUP,this.schema=t,this.table=r}};QD.exports=SS});var XD=T((dfe,jD)=>{"use strict";var _j=Ns(),lfe=zD(),TS=J(),dj=L(),_fe=Z(),{handleHDBError:fj,hdb_errors:Ej}=re(),{HDB_ERROR_MSGS:JD,HTTP_STATUS_CODES:hj}=Ej;jD.exports=mj;async function mj(e){if(TS.isEmpty(e.schema))throw new Error(JD.SCHEMA_REQUIRED_ERR);if(TS.isEmpty(e.table))throw new Error(JD.TABLE_REQUIRED_ERR);let t=TS.checkSchemaTableExist(e.schema,e.table);if(t)throw fj(new Error,t,hj.NOT_FOUND,dj.LOG_LEVELS.ERROR,t,!0);return await _j.getBackup(read_audit_log_object)}a(mj,"getBackup")});var nL=T((Efe,sL)=>{var ci=require("validate.js"),eL=je(),ua=L(),{handleHDBError:pj,hdb_errors:Sj}=re(),{HDB_ERROR_MSGS:lt,HTTP_STATUS_CODES:Tj}=Sj,gS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),gj={STRUCTURE_USER:"structure_user"},ZD=Object.values(ua.ROLE_TYPES_ENUM),Rj="attribute_permissions",Aj="attribute_name",{PERMS_CRUD_ENUM:la}=ua,Oj=[Rj,...Object.values(la)],tL=[la.READ,la.INSERT,la.UPDATE],bj=[Aj,...tL];function Nj(e){let t=gS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,rL(e,t)}a(Nj,"addRoleValidation");function yj(e){let t=gS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,rL(e,t)}a(yj,"alterRoleValidation");function wj(e){let t=gS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,eL.validateObject(e,t)}a(wj,"dropRoleValidation");var Ij=["operation","role","id","permission","hdb_user","hdb_auth_header"];function rL(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)Ij.includes(s[o])||n.push(s[o]);n.length>0&&ht(lt.INVALID_ROLE_JSON_KEYS(n),r);let i=eL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{ht(o,r)}),e.permission){let o=Cj(e);o&&ht(o,r),ZD.forEach(c=>{e.permission[c]&&!ci.isBoolean(e.permission[c])&&ht(lt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(ZD.indexOf(o)<0){if(o===gj.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||ht(lt.SCHEMA_NOT_FOUND(d),r)}continue}ht(lt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){ht(lt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){ht(lt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{Oj.includes(l)||ht(lt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(la).forEach(l=>{ci.isDefined(_[l])?ci.isBoolean(_[l])||ht(lt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):ht(lt.TABLE_PERM_MISSING(l),r,o,u)}),ci.isDefined(_.attribute_permissions)){if(!ci.isArray(_.attribute_permissions)){ht(lt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{ht(lt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(p=>{!bj.includes(p)&&p!==la.DELETE&&ht(lt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ci.isDefined(E.attribute_name)){ht(lt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){ht(lt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}tL.forEach(p=>{ci.isDefined(E[p])?ci.isBoolean(E[p])||ht(lt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):ht(lt.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;ht(lt.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return Dj(r)}a(rL,"customValidate");sL.exports={addRoleValidation:Nj,alterRoleValidation:yj,dropRoleValidation:wj};function Cj(e){let{operation:t,permission:r}=e;if(t===ua.OPERATIONS_ENUM.ADD_ROLE||t===ua.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return lt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ua.ROLE_TYPES_ENUM.SUPER_USER:ua.ROLE_TYPES_ENUM.CLUSTER_USER;return lt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Cj,"validateNoSUPerms");function Dj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:lt.ROLE_PERMS_ERROR,...e};return pj(new Error,s,Tj.BAD_REQUEST)}else return null}a(Dj,"generateRolePermResponse");function ht(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(ht,"addPermError")});var yS=T((mfe,cL)=>{"use strict";var iL=Cr(),oL=es(),Lj=ti(),AS=nL(),OS=gn(),Uj=require("uuid").v4,Mj=require("util"),fd=L(),Pj=J(),bS=oL.searchByValue,vj=oL.searchByHash,Bj=Mj.promisify(Lj.delete),Hj=Js(),xj=ta(),{hdb_errors:qj,handleHDBError:oo}=re(),{HDB_ERROR_MSGS:aL,HTTP_STATUS_CODES:_u}=qj,{UserEventMsg:NS}=Is();cL.exports={addRole:Fj,alterRole:Gj,dropRole:kj,listRoles:Vj};function RS(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(RS,"scrubRoleDetails");async function Fj(e){let t=AS.addRoleValidation(e);if(t)throw t;e=RS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await bS(r)||[])}catch(i){throw oo(i)}if(s&&s.length>0)throw oo(new Error,aL.ROLE_ALREADY_EXISTS(e.role),_u.CONFLICT,void 0,void 0,!0);e.id||(e.id=Uj());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await iL.insert(n),OS.signalUserChange(new NS(process.pid)),e=RS(e),e}a(Fj,"addRole");async function Gj(e){let t=AS.alterRoleValidation(e);if(t)throw t;e=RS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await iL.update(r)}catch(n){throw oo(n)}if(s&&s?.message==="updated 0 of 1 records")throw oo(new Error,"Invalid role id",_u.BAD_REQUEST,void 0,void 0,!0);return await OS.signalUserChange(new NS(process.pid)),e}a(Gj,"alterRole");async function kj(e){let t=AS.dropRoleValidation(e);if(t)throw oo(new Error,t,_u.BAD_REQUEST,void 0,void 0,!0);let r=new xj(fd.SYSTEM_SCHEMA_NAME,fd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await vj(r));if(s.length===0)throw oo(new Error,aL.ROLE_NOT_FOUND,_u.NOT_FOUND,void 0,void 0,!0);let n=new Hj(fd.SYSTEM_SCHEMA_NAME,fd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await bS(n)),o=!1;if(Pj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw oo(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,_u.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Bj(c),OS.signalUserChange(new NS(process.pid)),`${s[0].role} successfully deleted`}a(kj,"dropRole");async function Vj(){return bS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Vj,"listRoles")});var dL=T((Sfe,_L)=>{"use strict";var $j=Z(),ui=require("joi"),Yj=je(),uL=require("moment"),Kj=require("fs-extra"),wS=require("path"),Wj=require("lodash"),du=L(),{LOG_LEVELS:ao}=L(),Qj="YYYY-MM-DD hh:mm:ss",zj=wS.resolve(__dirname,"../logs");_L.exports=function(e){return Yj.validateBySchema(e,Jj)};var Jj=ui.object({from:ui.custom(lL),until:ui.custom(lL),level:ui.valid(ao.NOTIFY,ao.FATAL,ao.ERROR,ao.WARN,ao.INFO,ao.DEBUG,ao.TRACE),order:ui.valid("asc","desc"),limit:ui.number().min(1),start:ui.number().min(0),log_name:ui.custom(jj)});function lL(e,t){if(uL(e,uL.ISO_8601).format(Qj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(lL,"validateDatetime");function jj(e,t){if(Wj.invert(du.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=$j.get(du.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?du.LOG_NAMES.HDB:e,i=n===du.LOG_NAMES.INSTALL?wS.join(zj,du.LOG_NAMES.INSTALL):wS.join(s,n);return Kj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(jj,"validateReadLogPath")});var CS=T((gfe,EL)=>{"use strict";var Ed=L(),Xj=V(),Zj=Z(),eX=dL(),IS=require("path"),fL=require("fs-extra"),{once:tX}=require("events"),{handleHDBError:rX,hdb_errors:sX}=re(),{PACKAGE_ROOT:nX}=L(),iX=IS.join(nX,"logs"),oX=1e3,aX=200;EL.exports=cX;async function cX(e){let t=eX(e);if(t)throw rX(t,t.message,sX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Zj.get(Ed.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?Ed.LOG_NAMES.HDB:e.log_name,n=s===Ed.LOG_NAMES.INSTALL?IS.join(iX,Ed.LOG_NAMES.INSTALL):IS.join(r,s),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?oX:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(fL.statSync(n).size-(h+5)*aX,0));let S=fL.createReadStream(n,{start:p});S.on("error",v=>{Xj.error(v)});let A=0,R=[],g="",P;S.on("data",v=>{let U=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=g+v;let Y=0,K;for(;(K=U.exec(v))&&!S.destroyed;){P&&(P.message=v.slice(Y,K.index),H(P));let[z,ne,me]=K,ce=me.split("] ["),xe=ce[0],le=ce[1];ce.splice(0,2),P={timestamp:ne,thread:xe,level:le,tags:ce,message:""},Y=K.index+z.length}g=v.slice(Y)}),S.on("end",v=>{S.destroyed||P&&(P.message=g.trim(),H(P))}),S.resume();function H(v){let U,Y,K;switch(!0){case(i&&c&&_):U=new Date(v.timestamp),Y=new Date(u),K=new Date(l),v.level===o&&U>=Y&&U<=K&&A<E?A++:v.level===o&&U>=Y&&U<=K&&(li(v,f,R),A++,A===h&&S.destroy());break;case(i&&c):U=new Date(v.timestamp),Y=new Date(u),v.level===o&&U>=Y&&A<E?A++:v.level===o&&U>=Y&&(li(v,f,R),A++,A===h&&S.destroy());break;case(i&&_):U=new Date(v.timestamp),K=new Date(l),v.level===o&&U<=K&&A<E?A++:v.level===o&&U<=K&&(li(v,f,R),A++,A===h&&S.destroy());break;case(c&&_):U=new Date(v.timestamp),Y=new Date(u),K=new Date(l),U>=Y&&U<=K&&A<E?A++:U>=Y&&U<=K&&(li(v,f,R),A++,A===h&&S.destroy());break;case i:v.level===o&&A<E?A++:v.level===o&&(li(v,f,R),A++,A===h&&S.destroy());break;case c:U=new Date(v.timestamp),Y=new Date(u),U>=Y&&A<E?A++:U>=Y&&A>=E&&(li(v,f,R),A++,A===h&&S.destroy());break;case _:U=new Date(v.timestamp),K=new Date(l),U<=K&&A<E?A++:U<=K&&A>=E&&(li(v,f,R),A++,A===h&&S.destroy());break;default:A<E?A++:(li(v,f,R),A++,A===h&&S.destroy())}}return a(H,"onLogMessage"),await tX(S,"close"),R}a(cX,"readLog");function li(e,t,r){t==="desc"?uX(e,r):t==="asc"?lX(e,r):r.push(e)}a(li,"pushLineToResult");function uX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(uX,"insertDescending");function lX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(lX,"insertAscending")});var hd=T((Nfe,SL)=>{"use strict";var DS=require("joi"),{string:fu,boolean:hL,date:_X}=DS.types(),dX=je(),{validateSchemaExists:Afe,validateTableExists:Ofe,validateSchemaName:bfe}=Ys(),fX=L(),EX=Ge(),mL=Z();mL.initSync();var hX=fu.invalid(mL.get(fX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(EX.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),pL={operation:fu.valid("add_node","update_node","set_node_replication"),node_name:hX,subscriptions:DS.array().items({table:fu.optional(),schema:fu.optional(),database:fu.optional(),subscribe:hL.required(),publish:hL.required().custom(pX),start_time:_X.iso()}).min(1).required()};function mX(e){return dX.validateBySchema(e,DS.object(pL))}a(mX,"addUpdateNodeValidator");function pX(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}a(pX,"checkForFalsy");SL.exports={addUpdateNodeValidator:mX,validation_schema:pL}});var gL=T((wfe,TL)=>{var SX=je(),TX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};TL.exports=function(e){return SX.validateObject(e,TX)}});var md=T((Ife,RL)=>{"use strict";var gX=L().OPERATIONS_ENUM,LS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=gX.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};RL.exports=LS});var OL=T((Dfe,AL)=>{"use strict";var RX={OPERATION:"operation",REFRESH:"refresh"},US=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},MS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};AL.exports={JWTTokens:US,TOKEN_TYPE_ENUM:RX,JWTRSAKeys:MS}});var mu=T((Ufe,wL)=>{"use strict";var hu=require("jsonwebtoken"),PS=require("fs-extra"),vS=J(),ns=L(),{handleHDBError:dr,hdb_errors:AX}=re(),{HTTP_STATUS_CODES:fr,AUTHENTICATION_ERROR_MSGS:Er}=AX,Eu=V(),bL=b_(),xS=ts(),OX=Cr().update,bX=md(),NX=gn(),{UserEventMsg:yX}=Is(),_i=Z();_i.initSync();var BS=require("path"),{JWTTokens:wX,JWTRSAKeys:IX,TOKEN_TYPE_ENUM:pd}=OL(),CX=_i.get(ns.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?_i.get(ns.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",DX=_i.get(ns.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?_i.get(ns.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Sd="RS256",HS;wL.exports={createTokens:LX,validateOperationToken:MX,refreshOperationToken:UX,validateRefreshToken:yL};async function LX(e){if(vS.isEmpty(e)||typeof e!="object")throw dr(new Error,Er.INVALID_AUTH_OBJECT,fr.BAD_REQUEST,void 0,void 0,!0);if(vS.isEmpty(e.username))throw dr(new Error,Er.USERNAME_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);if(vS.isEmpty(e.password))throw dr(new Error,Er.PASSWORD_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await xS.findAndValidateUser(e.username,e.password),!t)throw dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Eu.error(f),dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Td(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await NL(i,r.private_key,r.passphrase),c=await hu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:DX,algorithm:Sd,subject:pd.REFRESH}),u=bL.hash(c),_=new bX(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await OX(_)}catch(f){Eu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw dr(new Error,Er.REFRESH_TOKEN_SAVE_FAILED,fr.INTERNAL_SERVER_ERROR);return NX.signalUserChange(new yX(process.pid)),new wX(o,c)}a(LX,"createTokens");async function NL(e,t,r){return await hu.sign(e,{key:t,passphrase:r},{expiresIn:CX,algorithm:Sd,subject:pd.OPERATION})}a(NL,"signOperationToken");async function Td(){if(HS===void 0)try{let e=BS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PASSPHRASE_NAME),t=BS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=BS.join(_i.getHdbBasePath(),ns.LICENSE_KEY_DIR_NAME,ns.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await PS.readFile(e)).toString(),n=(await PS.readFile(t)).toString(),i=(await PS.readFile(r)).toString();HS=new IX(i,n,s)}catch(e){throw Eu.error(e),dr(new Error,Er.NO_ENCRYPTION_KEYS,fr.INTERNAL_SERVER_ERROR)}return HS}a(Td,"getJWTRSAKeys");async function UX(e){if(!e)throw dr(new Error,Er.INVALID_BODY,fr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw dr(new Error,Er.REFRESH_TOKEN_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);await yL(e.refresh_token);let t=await Td(),r=await hu.decode(e.refresh_token);return{operation_token:await NL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(UX,"refreshOperationToken");async function MX(e){try{let t=await Td(),r=await hu.verify(e,t.public_key,{algorithms:Sd,subject:pd.OPERATION});return await xS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Eu.warn(t),t.name&&t.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}}a(MX,"validateOperationToken");async function yL(e){let t;try{let r=await Td(),s=await hu.verify(e,r.public_key,{algorithms:Sd,subject:pd.REFRESH});t=await xS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Eu.warn(r),r.name&&r.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}if(!bL.validate(t.refresh_token,e))throw dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED);return t}a(yL,"validateRefreshToken")});var qS=T((vfe,DL)=>{"use strict";var PX=gL(),_a=require("passport"),vX=require("passport-local").Strategy,BX=require("passport-http").BasicStrategy,HX=require("util"),xX=ts(),CL=HX.callbackify(xX.findAndValidateUser),Pfe=Nr(),qX=L(),IL=mu();_a.use(new vX(function(e,t,r){CL(e,t,r)}));_a.use(new BX(function(e,t,r){CL(e,t,r)}));_a.serializeUser(function(e,t){t(null,e)});_a.deserializeUser(function(e,t){t(null,e)});function FX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),s){case"Basic":_a.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===qX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?IL.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):IL.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:_a.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(FX,"authorize");function GX(e,t){let r=PX(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n?.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(GX,"checkPermissions");DL.exports={authorize:FX,checkPermissions:GX}});var di=T((Hfe,LL)=>{"use strict";var FS=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},GS=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};LL.exports={Node:FS,NodeSubscription:GS}});var ML=T((qfe,UL)=>{"use strict";var kX=L().OPERATIONS_ENUM,kS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=kX.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};UL.exports=kS});var pu=T((Gfe,PL)=>{"use strict";var VS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},$S=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,o,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};PL.exports={RemotePayloadObject:VS,RemotePayloadSubscription:$S}});var BL=T((Vfe,vL)=>{"use strict";var YS=class{static{a(this,"TableSizeObject")}constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};vL.exports=YS});var qL=T((Qfe,xL)=>{"use strict";var VX=BL(),Yfe=dt(),HL=We(),$X=V(),{getSchemaPath:Kfe,getTransactionAuditStorePath:Wfe}=Je(),{getDatabases:YX}=(Ae(),se(Fe));xL.exports=KX;async function KX(e){let t=new VX;try{let r=YX()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await HL.environmentDataSize(schema_path,e.name),o=await HL.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=n.entryCount}catch(r){$X.warn(`unable to stat table dbi due to ${r}`)}return t}a(KX,"lmdbGetTableSize")});var GL=T((Jfe,FL)=>{"use strict";var KS=class{static{a(this,"SystemInformationObject")}constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};FL.exports=KS});var da=T((eEe,YL)=>{"use strict";var WX=require("fs-extra"),QX=require("path"),zt=require("systeminformation"),fi=V(),zX=st(),WS=Ge(),Rd=L(),JX=qL(),$L=Xn(),{getThreadInfo:kL}=Ke(),sT=Z();sT.initSync();var jX=GL(),{openEnvironment:Xfe}=We(),{getSchemaPath:Zfe}=Je(),{database:XX}=(Ae(),se(Fe)),gd;YL.exports={getHDBProcessInfo:jS,getNetworkInfo:ZS,getDiskInfo:XS,getMemoryInfo:JS,getCPUInfo:zS,getTimeInfo:QS,getSystemInformation:eT,systemInformation:ZX,getTableSize:tT,getMetrics:rT};function QS(){return zt.time()}a(QS,"getTimeInfo");async function zS(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await zt.cpu();l.cpu_speed=await zt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:A,...R}=await zt.currentLoad();return R.cpus=[],A.forEach(g=>{let{raw_load:P,raw_load_idle:H,raw_load_irq:v,raw_load_nice:U,raw_load_system:Y,raw_load_user:K,...z}=g;R.cpus.push(z)}),l.current_load=R,l}catch(e){return fi.error(`error in getCPUInfo: ${e}`),{}}}a(zS,"getCPUInfo");async function JS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await zt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return fi.error(`error in getMemoryInfo: ${e}`),{}}}a(JS,"getMemoryInfo");async function jS(){let e={core:[],clustering:[]};try{let t=await zt.processes(),r;try{r=Number.parseInt(await WX.readFile(QX.join(sT.get(Rd.CONFIG_PARAMS.ROOTPATH),Rd.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Rd.NODE_ERROR_CODES.ENOENT)fi.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return fi.error(`error in getHDBProcessInfo: ${t}`),e}}a(jS,"getHDBProcessInfo");async function XS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await zt.fsStats();return e.read_write=_,e.size=await zt.fsSize(),e}catch(t){return fi.error(`error in getDiskInfo: ${t}`),e}}a(XS,"getDiskInfo");async function ZS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await zt.networkInterfaceDefault(),e.latency=await zt.inetChecksite("google.com"),(await zt.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=s;e.interfaces.push(f)}),(await zt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return fi.error(`error in getNetworkInfo: ${t}`),e}}a(ZS,"getNetworkInfo");async function eT(){if(gd!==void 0)return gd;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await zt.osInfo();e=c;let u=await zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,gd=e,gd}catch(t){return fi.error(`error in getSystemInformation: ${t}`),e}}a(eT,"getSystemInformation");async function tT(){let e=[],t=await $L.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await JX(s));return e}a(tT,"getTableSize");async function rT(){let e=await $L.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=XX({database:r,table:n}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),s[n]=o}catch(i){fi.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(rT,"getMetrics");async function VL(){if(sT.get(Rd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await zX.getNATSReferences(),r=await t.streams.info(WS.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(WS.WORK_QUEUE_CONSUMER_NAMES.stream_name,WS.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.sources&&(n.ingest.stream.sources=r.sources),n}}a(VL,"getNatsStreamInfo");async function ZX(e){let t=new jX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await eT(),t.time=QS(),t.cpu=await zS(),t.memory=await JS(),t.disk=await XS(),t.network=await ZS(),t.harperdb_processes=await jS(),t.table_size=await tT(),t.metrics=await rT(),t.threads=await kL(),t.replication=await VL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await eT();break;case"time":t.time=QS();break;case"cpu":t.cpu=await zS();break;case"memory":t.memory=await JS();break;case"disk":t.disk=await XS();break;case"network":t.network=await ZS();break;case"harperdb_processes":t.harperdb_processes=await jS();break;case"table_size":t.table_size=await tT();break;case"database_metrics":case"metrics":t.metrics=await rT();break;case"threads":t.threads=await kL();break;case"replication":t.replication=await VL();break;default:break}return t}a(ZX,"systemInformation")});var Od=T((rEe,KL)=>{"use strict";KL.exports={version:eZ,printVersion:tZ};var Ad=Zc();function eZ(){if(Ad)return Ad.version}a(eZ,"version");function tZ(){Ad&&console.log(`HarperDB Version ${Ad.version}`)}a(tZ,"printVersion")});var is=T((oEe,JL)=>{"use strict";var rZ=Cr(),nT=J(),sZ=require("util"),co=L(),WL=Z();WL.initSync();var nZ=qS(),QL=es(),{Node:nEe,NodeSubscription:iEe}=di(),iZ=ta(),oZ=ML(),{RemotePayloadObject:aZ,RemotePayloadSubscription:cZ}=pu(),{handleHDBError:uZ,hdb_errors:lZ}=re(),{HTTP_STATUS_CODES:_Z,HDB_ERROR_MSGS:dZ}=lZ,fZ=Js(),EZ=da(),hZ=Od(),{getDatabases:mZ}=(Ae(),se(Fe)),pZ=sZ.promisify(nZ.authorize),SZ=QL.searchByHash,TZ=QL.searchByValue;JL.exports={authHeaderToUser:gZ,isEmpty:RZ,getNodeRecord:AZ,upsertNodeRecord:OZ,buildNodePayloads:bZ,checkClusteringEnabled:NZ,getAllNodeRecords:yZ,getSystemInfo:wZ,reverseSubscription:zL};async function gZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await pZ(t,null),e}a(gZ,"authHeaderToUser");function RZ(e){return e==null}a(RZ,"isEmpty");async function AZ(e){let t=new iZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return SZ(t)}a(AZ,"getNodeRecord");async function OZ(e){let t=new oZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return rZ.upsert(t)}a(OZ,"upsertNodeRecord");function zL(e){if(nT.isEmpty(e.subscribe)||nT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(zL,"reverseSubscription");function bZ(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=nT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=zL(c),E=mZ()[u]?.[_],h=new cZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new aZ(r,t,n,s)}a(bZ,"buildNodePayloads");function NZ(){if(!WL.get(co.CONFIG_PARAMS.CLUSTERING_ENABLED))throw uZ(new Error,dZ.CLUSTERING_NOT_ENABLED,_Z.BAD_REQUEST,void 0,void 0,!0)}a(NZ,"checkClusteringEnabled");async function yZ(){let e=new fZ(co.SYSTEM_SCHEMA_NAME,co.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await TZ(e))}a(yZ,"getAllNodeRecords");async function wZ(){let e=await EZ.getSystemInformation();return{hdb_version:hZ.version(),node_version:e.node_version,platform:e.platform}}a(wZ,"getSystemInfo")});var iT=T((cEe,nU)=>{"use strict";var bd=st(),jL=J(),XL=Ge(),ZL=L(),Nd=V(),eU=lu(),IZ=$_(),{RemotePayloadObject:CZ}=pu(),{handleHDBError:tU,hdb_errors:DZ}=re(),{HTTP_STATUS_CODES:rU}=DZ,{NodeSubscription:sU}=di();nU.exports=LZ;async function LZ(e,t){let r;try{r=await bd.request(`${t}.${XL.REQUEST_SUFFIX}`,new CZ(ZL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Nd.trace("Response from remote describe all request:",r)}catch(o){Nd.error(`addNode received error from describe all request to remote node: ${o}`);let c=bd.requestErrorHandler(o,"add_node",t);throw tU(new Error,c,rU.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===XL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw tU(new Error,o,rU.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===ZL.SYSTEM_SCHEMA_NAME){await bd.createLocalTableStream(u,c);let h=new sU(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=jL.doesSchemaExist(u),l=s[u]!==void 0,d=c?jL.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(Nd.trace(`addNode creating schema: ${u}`),await eU.createSchema({operation:"create_schema",schema:u})),!d&&f){Nd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new IZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await eU.createTable(h)}await bd.createLocalTableStream(u,c);let E=new sU(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(LZ,"reviewSubscriptions")});var Id=T((lEe,aU)=>{"use strict";var{handleHDBError:yd,hdb_errors:UZ}=re(),{HTTP_STATUS_CODES:wd}=UZ,{addUpdateNodeValidator:MZ}=hd(),Su=V(),oU=L(),iU=Ge(),PZ=J(),oT=st(),Tu=is(),vZ=Z(),BZ=iT(),{Node:HZ,NodeSubscription:xZ}=di(),{broadcast:qZ}=Ke(),FZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",GZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",kZ=vZ.get(oU.CONFIG_PARAMS.CLUSTERING_NODENAME);aU.exports=VZ;async function VZ(e,t=!1){Su.trace("addNode called with:",e),Tu.checkClusteringEnabled();let r=MZ(e);if(r)throw yd(r,r.message,wd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Tu.getNodeRecord(s);if(!PZ.isEmptyOrZeroLength(d))throw yd(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,wd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await BZ(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=FZ,o;let c=Tu.buildNodePayloads(n,kZ,oU.OPERATIONS_ENUM.ADD_NODE,await Tu.getSystemInfo());Su.trace("addNode sending remote payload:",c);let u;try{u=await oT.request(`${s}.${iU.REQUEST_SUFFIX}`,c)}catch(d){Su.error(`addNode received error from request: ${d}`);let f=oT.requestErrorHandler(d,"add_node",s);throw yd(new Error,f,wd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===iU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw yd(new Error,d,wd.INTERNAL_SERVER_ERROR,"error",d)}Su.trace(u);let _=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];Su.trace("Add node updating work stream for node:",s,"subscriptions:",E),await oT.updateWorkStream(E,s),n[d].start_time===void 0&&delete n[d].start_time,_.push(new xZ(E.schema,E.table,E.publish,E.subscribe))}let l=new HZ(s,_,u.system_info);return await Tu.upsertNodeRecord(l),qZ({type:"nats_update"}),i.length>0?o.message=GZ:o.message=`Successfully added '${s}' to manifest`,o}a(VZ,"addNode")});var lT=T((fEe,lU)=>{"use strict";var{handleHDBError:aT,hdb_errors:$Z}=re(),{HTTP_STATUS_CODES:cT}=$Z,{addUpdateNodeValidator:YZ}=hd(),gu=V(),uU=L(),cU=Ge(),dEe=J(),uT=st(),Ru=is(),KZ=Z(),{cloneDeep:WZ}=require("lodash"),QZ=iT(),{Node:zZ,NodeSubscription:JZ}=di(),{broadcast:jZ}=Ke(),XZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",ZZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",e5=KZ.get(uU.CONFIG_PARAMS.CLUSTERING_NODENAME);lU.exports=t5;async function t5(e){gu.trace("updateNode called with:",e),Ru.checkClusteringEnabled();let t=YZ(e);if(t)throw aT(t,t.message,cT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await Ru.getNodeRecord(r);n.length>0&&(s=WZ(n));let{added:i,skipped:o}=await QZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=XZ,c;let u=Ru.buildNodePayloads(i,e5,uU.OPERATIONS_ENUM.UPDATE_NODE,await Ru.getSystemInfo());gu.trace("updateNode sending remote payload:",u);let _;try{_=await uT.request(`${r}.${cU.REQUEST_SUFFIX}`,u)}catch(l){gu.error(`updateNode received error from request: ${l}`);let d=uT.requestErrorHandler(l,"update_node",r);throw aT(new Error,d,cT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===cU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw aT(new Error,l,cT.INTERNAL_SERVER_ERROR,"error",l)}gu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];gu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await uT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return s||(s=[new zZ(r,[],_.system_info)]),await r5(s[0],i,_.system_info),o.length>0?c.message=ZZ:c.message=`Successfully updated '${r}'`,c}a(t5,"updateNode");async function r5(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=s.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new JZ(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Ru.upsertNodeRecord(s),jZ({type:"nats_update"})}a(r5,"updateNodeTable")});var hU=T((hEe,EU)=>{"use strict";var fU=require("joi"),{string:_U}=fU.types(),s5=je(),dU=L(),n5=Z(),i5=Ge();EU.exports=o5;function o5(e){let t=_U.invalid(n5.get(dU.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(i5.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=fU.object({operation:_U.valid(dU.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return s5.validateBySchema(e,r)}a(o5,"removeNodeValidator")});var Dd=T((pEe,RU)=>{"use strict";var{handleHDBError:mU,hdb_errors:a5}=re(),{HTTP_STATUS_CODES:pU}=a5,c5=hU(),Au=V(),SU=is(),u5=J(),Cd=L(),TU=Ge(),gU=st(),l5=Z(),{RemotePayloadObject:_5}=pu(),{NodeSubscription:d5}=di(),f5=ra(),E5=ti(),{broadcast:h5}=Ke(),m5=l5.get(Cd.CONFIG_PARAMS.CLUSTERING_NODENAME);RU.exports=p5;async function p5(e){Au.trace("removeNode called with:",e),SU.checkClusteringEnabled();let t=c5(e);if(t)throw mU(t,t.message,pU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await SU.getNodeRecord(r);if(u5.isEmptyOrZeroLength(s))throw mU(new Error,`Node '${r}' was not found.`,pU.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new _5(Cd.OPERATIONS_ENUM.REMOVE_NODE,m5,[]),i,o=!1;try{i=await gU.request(`${r}.${TU.REQUEST_SUFFIX}`,n),Au.trace("Remove node reply from remote node:",r,i)}catch(u){Au.error("removeNode received error from request:",u),o=!0}for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];Au.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new d5(l.schema,l.table,!1,!1);await gU.updateWorkStream(d,r)}let c=new f5(Cd.SYSTEM_SCHEMA_NAME,Cd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await E5.deleteRecord(c),h5({type:"nats_update"}),i?.status===TU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Au.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(p5,"removeNode")});var bU=T((TEe,OU)=>{"use strict";var AU=require("joi"),{string:S5,array:T5}=AU.types(),g5=je(),R5=hd();OU.exports=A5;function A5(e){let t=AU.object({operation:S5.valid("configure_cluster").required(),connections:T5.items(R5.validation_schema).required()});return g5.validateBySchema(e,t)}a(A5,"configureClusterValidator")});var _T=T((REe,CU)=>{"use strict";var O5=L(),Ld=V(),b5=J(),N5=Dd(),y5=Id(),NU=is(),w5=bU(),{handleHDBError:yU,hdb_errors:I5}=re(),{HTTP_STATUS_CODES:wU}=I5,C5="Configure cluster complete.",D5="Failed to configure the cluster. Check the logs for more details.",L5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";CU.exports=U5;async function U5(e){Ld.trace("configure cluster called with:",e),NU.checkClusteringEnabled();let t=w5(e);if(t)throw yU(t,t.message,wU.BAD_REQUEST,void 0,void 0,!0);let r=await NU.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(IU(N5,{operation:O5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let n=await Promise.allSettled(s);Ld.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(IU(y5,E,E.node_name))}let c=await Promise.allSettled(i);Ld.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=n.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(Ld.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let p=h?.value?.result;typeof p=="string"&&p.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(b5.isEmptyOrZeroLength(u))return{message:C5,connections:_};if(l)return{message:L5,failed_nodes:u,connections:_};throw yU(new Error,D5,wU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(U5,"configureCluster");async function IU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(IU,"functionWrapper")});var LU=T((OEe,DU)=>{"use strict";var Ud=require("joi"),M5=je(),{validateSchemaExists:P5,validateTableExists:v5,validateSchemaName:B5}=Ys(),H5=Ud.object({operation:Ud.string().valid("purge_stream"),schema:Ud.string().custom(P5).custom(B5).required(),table:Ud.string().custom(v5).required()});function x5(e){return M5.validateBySchema(e,H5)}a(x5,"purgeStreamValidator");DU.exports=x5});var dT=T((NEe,UU)=>{"use strict";var{handleHDBError:q5,hdb_errors:F5}=re(),{HTTP_STATUS_CODES:G5}=F5,k5=LU(),V5=st(),$5=is();UU.exports=Y5;async function Y5(e){if(e.purge_ingest!==!0){let n=k5(e);if(n)throw q5(n,n.message,G5.BAD_REQUEST,void 0,void 0,!0)}$5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await V5.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(Y5,"purgeStream")});var hT=T((wEe,xU)=>{"use strict";var ET=is(),K5=st(),vU=Z(),Md=L(),uo=Ge(),W5=J(),fT=V(),{RemotePayloadObject:Q5}=pu(),{ErrorCode:MU}=require("nats"),PU=vU.get(Md.CONFIG_PARAMS.CLUSTERING_ENABLED),BU=vU.get(Md.CONFIG_PARAMS.CLUSTERING_NODENAME);xU.exports={clusterStatus:z5,buildNodeStatus:HU};async function z5(){let e={node_name:BU,is_enabled:PU,connections:[]};if(!PU)return e;let t=await ET.getAllNodeRecords();if(W5.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(HU(t[s],e.connections));return await Promise.allSettled(r),e}a(z5,"clusterStatus");async function HU(e,t){let r=e.name,s=new Q5(Md.OPERATIONS_ENUM.CLUSTER_STATUS,BU,void 0,await ET.getSystemInfo()),n,i,o=uo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await K5.request(uo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===uo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=uo.CLUSTER_STATUS_STATUSES.CLOSED,fT.error(`Error getting node status from ${r} `,n))}catch(u){fT.warn(`Error getting node status from ${r}`,u),u.code===MU.NoResponders?o=uo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===MU.Timeout?o=uo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=uo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new J5(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Md.PRE_4_0_0_VERSION&&await ET.upsertNodeRecord(u)}catch(u){fT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(HU,"buildNodeStatus");function J5(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(J5,"NodeStatusObject")});var pT=T((CEe,qU)=>{"use strict";var{handleHDBError:j5,hdb_errors:X5}=re(),{HTTP_STATUS_CODES:Z5}=X5,e8=st(),t8=is(),mT=J(),Pd=require("joi"),r8=je(),s8=2e3,n8=Pd.object({timeout:Pd.number().min(1),connected_nodes:Pd.boolean(),routes:Pd.boolean()});qU.exports=i8;async function i8(e){t8.checkClusteringEnabled();let t=r8.validateBySchema(e,n8);if(t)throw j5(t,t.message,Z5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||mT.autoCastBoolean(s),o=n===void 0||mT.autoCastBoolean(n),c={nodes:[]},u=await e8.getServerList(r??s8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:mT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(i8,"clusterNetwork")});var VU=T((LEe,kU)=>{"use strict";var ST=require("joi"),FU=je(),{route_constraints:GU}=qm();kU.exports={setRoutesValidator:o8,deleteRoutesValidator:a8};function o8(e){let t=ST.object({server:ST.valid("hub","leaf").required(),routes:GU.required()});return FU.validateBySchema(e,t)}a(o8,"setRoutesValidator");function a8(e){let t=ST.object({routes:GU.required()});return FU.validateBySchema(e,t)}a(a8,"deleteRoutesValidator")});var gT=T((MEe,WU)=>{"use strict";var lo=Ur(),TT=J(),vd=L(),$U=VU(),{handleHDBError:YU,hdb_errors:c8}=re(),{HTTP_STATUS_CODES:KU}=c8,u8="cluster routes successfully set",l8="cluster routes successfully deleted";WU.exports={setRoutes:_8,getRoutes:d8,deleteRoutes:f8};function _8(e){let t=$U.setRoutesValidator(e);if(t)throw YU(t,t.message,KU.BAD_REQUEST,void 0,void 0,!0);let r=lo.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=TT.autoCast(_.port);let l=s.some(f=>f.host===_.host&&f.port===_.port),d=n.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(s.push(_),o.push(_))}return e.server==="hub"?lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:u8,set:o,skipped:i}}a(_8,"setRoutes");function d8(){let e=lo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(d8,"getRoutes");function f8(e){let t=$U.deleteRoutesValidator(e);if(t)throw YU(t,t.message,KU.BAD_REQUEST,void 0,void 0,!0);let r=lo.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=TT.isEmptyOrZeroLength(s)?null:s,lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=TT.isEmptyOrZeroLength(n)?null:n,lo.updateConfigValue(vd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:l8,deleted:i,skipped:o}}a(f8,"deleteRoutes")});var zU=T((vEe,QU)=>{"use strict";var Ou=require("alasql"),_o=require("recursive-iterator"),Ms=V(),E8=J(),bu=L(),RT=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,m8(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>bu.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!bu.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][bu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=h8(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!bu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Ou.yy.Column({columnid:_});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function h8(e){return e.filter(t=>t[bu.PERMS_CRUD_ENUM.READ])}a(h8,"filterReadRestrictedAttrs");function m8(e,t,r,s,n){p8(e,t,r,s,n)}a(m8,"interpretAST");function Nu(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(Nu,"addSchemaTableToMap");function p8(e,t,r,s,n){if(!e){Ms.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Ou.yy.Insert?R8(e,t,r):e instanceof Ou.yy.Select?S8(e,t,r,s,n):e instanceof Ou.yy.Update?T8(e,t,r):e instanceof Ou.yy.Delete?g8(e,t,r):Ms.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(p8,"getRecordAttributesAST");function S8(e,t,r,s,n){if(!e){Ms.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(E8.isEmptyOrZeroLength(i)){Ms.error("No schema specified");return}e.from.forEach(c=>{Nu(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Nu(c.table,t,r,s,n)});let o=new _o(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Ms.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new _o(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Ms.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new _o(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Ms.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new _o(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Ms.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(S8,"getSelectAttributes");function T8(e,t,r){if(!e){Ms.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new _o(e.columns),n=e.table.databaseid;Nu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&AT(e.table.tableid,n,i.columnid,t,r)}a(T8,"getUpdateAttributes");function g8(e,t,r){if(!e){Ms.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new _o(e.where),n=e.table.databaseid;Nu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&AT(e.table.tableid,n,i.columnid,t,r)}a(g8,"getDeleteAttributes");function R8(e,t,r){if(!e){Ms.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new _o(e.columns),n=e.into.databaseid;Nu(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&AT(e.into.tableid,n,i.columnid,t,r)}a(R8,"getInsertAttributes");function AT(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(AT,"pushAttribute");QU.exports=RT});var NT=T((HEe,ZU)=>{var Bd=Wi(),JU=require("chalk"),qr=V(),jU=require("prompt"),{promisify:A8}=require("util"),OT=L(),O8=require("fs-extra"),b8=require("path"),N8=J(),y8=Od(),XU=Z();XU.initSync();var w8=require("moment"),I8=A8(jU.get),C8=b8.join(XU.getHdbBasePath(),OT.LICENSE_KEY_DIR_NAME,OT.LICENSE_FILE_NAME,OT.LICENSE_FILE_NAME);ZU.exports={getFingerprint:L8,setLicense:D8,parseLicense:bT,register:U8,getRegistrationInfo:P8};async function D8(e){if(e&&e.key&&e.company){try{qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await bT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw qr.error(r),qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(D8,"setLicense");async function L8(){let e={};try{e=await Bd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw qr.error(r),qr.error(t),new Error(r)}return e}a(L8,"getFingerprint");async function bT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");qr.info("Validating license input...");let r=Bd.validateLicense(e,t);if(qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{qr.info("writing license to disk"),await O8.writeFile(C8,JSON.stringify({license_key:e,company:t}))}catch(s){throw qr.error("Failed to write License"),s}return"Registration successful."}a(bT,"parseLicense");async function U8(){let e=await M8();return bT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(U8,"register");async function M8(){let e=await Bd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:JU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:JU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{jU.start()}catch(s){qr.error(s)}let r;try{r=await I8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(M8,"promptForRegistration");async function P8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Bd.getLicense()}catch(r){throw qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(N8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=y8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=w8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(P8,"getRegistrationInfo")});var tM=T((qEe,eM)=>{"use strict";var v8=Ge(),yT=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+v8.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};eM.exports=yT});var nM=T((GEe,sM)=>{"use strict";var rM=Ge(),wT=class{static{a(this,"LeafConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+rM.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+rM.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};sM.exports=wT});var oM=T((VEe,iM)=>{"use strict";var IT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};iM.exports=IT});var cM=T((YEe,aM)=>{"use strict";var B8=Ge(),CT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+B8.SERVER_SUFFIX.ADMIN,this.password=r}};aM.exports=CT});var UT=T((WEe,_M)=>{"use strict";var fa=require("path"),qd=require("fs-extra"),H8=tM(),x8=nM(),q8=oM(),F8=cM(),DT=ts(),ha=J(),hr=Ur(),xd=L(),yu=Ge(),{CONFIG_PARAMS:_t}=xd,wu=V(),Iu=Z(),uM=Sn(),LT=st(),Ea="clustering",G8=1e4,lM=5;_M.exports={generateNatsConfig:V8,removeNatsConfig:$8,getHubConfigPath:k8};function k8(){let e=Iu.get(_t.ROOTPATH);return fa.join(e,Ea,yu.NATS_CONFIG_FILES.HUB_SERVER)}a(k8,"getHubConfigPath");async function V8(e=!1,t=void 0){Iu.initSync();let r=Iu.get(_t.ROOTPATH),s=fa.join(r,Ea,yu.PID_FILES.HUB),n=fa.join(r,Ea,yu.PID_FILES.LEAF),i=hr.getConfigFromFile(_t.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=fa.join(r,Ea,yu.NATS_CONFIG_FILES.HUB_SERVER),c=fa.join(r,Ea,yu.NATS_CONFIG_FILES.LEAF_SERVER),u=hr.getConfigFromFile(_t.CLUSTERING_TLS_CERTIFICATE),_=hr.getConfigFromFile(_t.CLUSTERING_TLS_PRIVATEKEY),l=hr.getConfigFromFile(_t.CLUSTERING_TLS_CERT_AUTH),d=hr.getConfigFromFile(_t.CLUSTERING_TLS_INSECURE),f=hr.getConfigFromFile(_t.CLUSTERING_TLS_VERIFY),E=hr.getConfigFromFile(_t.CLUSTERING_NODENAME),h=hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await LT.checkNATSServerInstalled()||Fd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await DT.listUsers(),S=hr.getConfigFromFile(_t.CLUSTERING_USER),A=await DT.getClusterUser();(ha.isEmpty(A)||A.active!==!0)&&Fd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Hd(_t.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Hd(_t.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Hd(_t.CLUSTERING_HUBSERVER_NETWORK_PORT),await Hd(_t.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],g=[];for(let[z,ne]of p.entries())ne.role.role===xd.ROLE_TYPES_ENUM.CLUSTER_USER&&ne.active&&(R.push(new F8(ne.username,uM.decrypt(ne.hash))),g.push(new q8(ne.username,uM.decrypt(ne.hash))));let P=[],{hub_routes:H}=hr.getClusteringRoutes();if(!ha.isEmptyOrZeroLength(H))for(let z of H)P.push(`tls://${A.sys_name_encoded}:${A.uri_encoded_d_hash}@${z.host}:${z.port}`);let v=new H8(hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_CLUSTER_NAME),hr.getConfigFromFile(_t.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),P,R,g);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=ha.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===xd.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await qd.writeJson(o,v),wu.trace(`Hub server config written to ${o}`));let U=`tls://${A.sys_name_encoded}:${A.uri_encoded_d_hash}@0.0.0.0:${h}`,Y=`tls://${A.uri_encoded_name}:${A.uri_encoded_d_hash}@0.0.0.0:${h}`,K=new x8(hr.getConfigFromFile(_t.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[U],[Y],R,g,u,_,l,d);l==null&&delete K.tls.ca_file,(t===void 0||t===xd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await qd.writeJson(c,K),wu.trace(`Leaf server config written to ${c}`))}a(V8,"generateNatsConfig");async function Hd(e){let t=Iu.get(e);return ha.isEmpty(t)&&Fd(`port undefined for '${e}'`),await ha.isPortTaken(t)&&Fd(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(Hd,"isPortAvailable");function Fd(e){let t=`Error generating clustering config: ${e}`;wu.error(t),console.error(t),process.exit(1)}a(Fd,"generateNatsConfigError");async function $8(e){let{port:t,config_file:r}=LT.getServerConfig(e),{username:s,decrypt_hash:n}=await DT.getClusterUser(),i=0,o=2e3;for(;i<lM;){try{let _=await LT.createConnection(t,s,n,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){wu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=lM)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await ha.async_set_timeout(o*(i*2))}let c="0".repeat(G8),u=fa.join(Iu.get(_t.ROOTPATH),Ea,r);await qd.writeFile(u,c),await qd.remove(u),wu.notify(e,"started.")}a($8,"removeNatsConfig")});var pM=T((zEe,mM)=>{"use strict";var Fr=Z(),Y8=Wi(),he=L(),Cu=Ge(),Nn=require("path"),{PACKAGE_ROOT:kd}=L(),dM=Z(),Gd=J(),ma="/dev/null",K8=Nn.join(kd,"launchServiceScripts"),fM=Nn.join(kd,"utility/scripts"),W8=Nn.join(fM,he.HDB_RESTART_SCRIPT),EM=Nn.resolve(kd,"dependencies",`${process.platform}-${process.arch}`,Cu.NATS_BINARY_NAME);function hM(){let t=Y8.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,s={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Gd.noBootFile()&&(s[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Gd.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:kd}}a(hM,"generateMainServerConfig");var Q8=9930;function z8(){Fr.initSync(!0);let e=Fr.get(he.CONFIG_PARAMS.ROOTPATH),t=Nn.join(e,"clustering",Cu.NATS_CONFIG_FILES.HUB_SERVER),r=Nn.join(Fr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=dM.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=Cu.LOG_LEVEL_FLAGS[Fr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==Q8?"-"+s:""),script:EM,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ma,i.error_file=ma),i}a(z8,"generateNatsHubServerConfig");var J8=9940;function j8(){Fr.initSync(!0);let e=Fr.get(he.CONFIG_PARAMS.ROOTPATH),t=Nn.join(e,"clustering",Cu.NATS_CONFIG_FILES.LEAF_SERVER),r=Nn.join(Fr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=dM.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=Cu.LOG_LEVEL_FLAGS[Fr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==J8?"-"+s:""),script:EM,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ma,i.error_file=ma),i}a(j8,"generateNatsLeafServerConfig");function X8(){Fr.initSync();let e=Nn.join(Fr.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:K8,autorestart:!1};return Fr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ma,t.error_file=ma),t}a(X8,"generateClusteringUpgradeV4ServiceConfig");function Z8(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return Gd.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Gd.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:fM},script:W8}}a(Z8,"generateRestart");function e6(){return{apps:[hM()]}}a(e6,"generateAllServiceConfigs");mM.exports={generateAllServiceConfigs:e6,generateMainServerConfig:hM,generateRestart:Z8,generateNatsHubServerConfig:z8,generateNatsLeafServerConfig:j8,generateClusteringUpgradeV4ServiceConfig:X8}});var LM=T((XEe,DM)=>{"use strict";var ve=L(),t6=J(),yn=UT(),Du=st(),en=Ge(),Ei=pM(),Vd=Z(),hi=V(),r6=is(),{startWorker:SM,onMessageFromWorkers:s6}=Ke(),n6=da(),jEe=require("util"),i6=require("child_process"),o6=require("fs"),{execFile:a6}=i6,we;DM.exports={enterPM2Mode:c6,start:mi,stop:MT,reload:gM,restart:RM,list:PT,describe:OM,connect:wn,kill:f6,startAllServices:E6,startService:vT,getUniqueServicesList:bM,restartAllServices:h6,isServiceRegistered:NM,reloadStopStart:yM,restartHdb:AM,deleteProcess:_6,startClusteringProcesses:IM,startClusteringThreads:CM,isHdbRestartRunning:d6,isClusteringRunning:p6,stopClustering:m6,reloadClustering:S6};var Lu=!1;s6(e=>{e.type==="restart"&&Vd.initSync(!0)});function c6(){Lu=!0}a(c6,"enterPM2Mode");function wn(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,s)=>{hi.setupConsoleLogging(),r&&t(r),e(s)})})}a(wn,"connect");var mr,u6=10,TM;function mi(e,t=!1){if(Lu)return l6(e);let r=a6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=mr.indexOf(r);o>-1&&mr.splice(o,1),!TM&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<u6&&(o6.existsSync(yn.getHubConfigPath())?mi(e):(await yn.generateNatsConfig(!0),mi(e),await new Promise(c=>setTimeout(c,3e3)),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=Vd.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&en.LOG_LEVEL_HIERARCHY[o]>=en.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===en.LOG_LEVELS.ERR||l===en.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=en.LOG_LEVELS[f]}if(en.LOG_LEVEL_HIERARCHY[o]>=en.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===en.LOG_LEVELS.ERR||l===en.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),mr=[],!mr&&!t){let i=a(()=>{TM=!0,mr&&(mr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}mr.push(r)}a(mi,"start");function l6(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.start(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(l6,"startWithPM2");function MT(e){if(!Lu){for(let t of mr||[])t.name===e&&(mr.splice(mr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.stop(e,async(s,n)=>{s&&(we.disconnect(),r(s)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(s)),we.disconnect(),t(o)})})})}a(MT,"stop");function gM(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.reload(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(gM,"reload");function RM(e){if(!Lu)for(let t of mr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.restart(e,(s,n)=>{we.disconnect(),t(n)})})}a(RM,"restart");function _6(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.delete(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(_6,"deleteProcess");async function AM(){await mi(Ei.generateRestart())}a(AM,"restartHdb");async function d6(){let e=await PT();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(d6,"isHdbRestartRunning");function PT(){return new Promise(async(e,t)=>{try{await wn()}catch(r){t(r)}we.list((r,s)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(s)})})}a(PT,"list");function OM(e){return new Promise(async(t,r)=>{try{await wn()}catch(s){r(s)}we.describe(e,(s,n)=>{s&&(we.disconnect(),r(s)),we.disconnect(),t(n)})})}a(OM,"describe");function f6(){if(!Lu){for(let e of mr||[])e.kill();mr=[];return}return new Promise(async(e,t)=>{try{await wn()}catch(r){t(r)}we.killDaemon((r,s)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(s)})})}a(f6,"kill");async function E6(){try{await IM(),await CM(),await mi(Ei.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(E6,"startAllServices");async function vT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ei.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ei.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ei.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ei.generateNatsHubServerConfig(),await mi(r,t),await yn.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ei.generateNatsLeafServerConfig(),await mi(r,t),await yn.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ei.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await mi(r)}catch(r){throw we?.disconnect(),r}}a(vT,"startService");async function bM(){try{let e=await PT(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(bM,"getUniqueServicesList");async function h6(e=[]){try{let t=!1,r=await bM();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await RM(o))}t&&await yM(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(h6,"restartAllServices");async function NM(e){if(mr?.find(r=>r.name===e))return!0;let t=await n6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(NM,"isServiceRegistered");async function yM(e){let t=Vd.get(ve.CONFIG_PARAMS.THREADS_COUNT)??Vd.get(ve.CONFIG_PARAMS.THREADS),r=await OM(e),s=t6.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await MT(e),await vT(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await AM():await gM(e)}a(yM,"reloadStopStart");var wM;async function IM(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await vT(r,e)}}a(IM,"startClusteringProcesses");async function CM(){wM=SM(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Du.createWorkQueueStream(en.WORK_QUEUE_CONSUMER_NAMES),await Du.updateIngestStreamConsumer(),await Du.updateLocalStreams();let e=await r6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){hi.info("Starting clustering upgrade 4.0.0 process"),SM(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(CM,"startClusteringThreads");async function m6(){for(let e in ve.CLUSTERING_PROCESSES)if(e!==ve.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ve.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await wM.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await MT(t)}}a(m6,"stopClustering");async function p6(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await NM(t)===!1)return!1}return!0}a(p6,"isClusteringRunning");async function S6(){await yn.generateNatsConfig(!0),await Du.reloadNATSHub(),await Du.reloadNATSLeaf(),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await yn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(S6,"reloadClustering")});var Wd=T((ehe,xM)=>{"use strict";var T6=require("minimist"),{isMainThread:xT,parentPort:PM}=require("worker_threads"),nt=L(),{PROCESS_DESCRIPTORS_VALIDATE:Uu}=nt,tn=V(),qT=J(),$d=UT(),pa=st(),BT=Ge(),vM=Ur(),rn=LM(),UM=da(),g6=dh(),{restartWorkers:Yd,onMessageByType:R6}=Ke(),{handleHDBError:A6,hdb_errors:O6}=re(),{HTTP_STATUS_CODES:b6}=O6,Kd=Z();Kd.initSync();var Mu=`Restarting HarperDB. This may take up to ${nt.RESTART_TIMEOUT_MS/1e3} seconds.`,N6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",MM="Clustering is not enabled so cannot be restarted",y6="Invalid service",Sa,os;xM.exports={restart:BM,restartService:FT};xT&&R6(nt.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?FT({service:e.workerType}):BM({operation:"restart"})});async function BM(e){os=Object.keys(e).length===0,Sa=await rn.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR);let t=T6(process.argv);if(t.service){await FT(t);return}if(os&&!Sa){console.error(N6);return}if(os&&console.log(Mu),Sa){rn.enterPM2Mode(),tn.notify(Mu);let r=g6(Object.keys(nt.CONFIG_PARAM_MAP),!0);return qT.isEmptyOrZeroLength(Object.keys(r))||vM.updateConfigValue(void 0,void 0,r,!0,!0),I6(),Mu}return xT?(tn.notify(Mu),setTimeout(()=>{Yd()},50)):PM.postMessage({type:nt.ITC_EVENT_TYPES.RESTART}),Mu}a(BM,"restart");async function FT(e){let{service:t}=e;if(nt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw A6(new Error,y6,b6.BAD_REQUEST,void 0,void 0,!0);if(Sa=await rn.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR),!xT)return PM.postMessage({type:nt.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Uu.clustering:if(!Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=MM;break}os&&console.log("Restarting clustering"),tn.notify("Restarting clustering"),await HM();break;case Uu.clustering_config:case Uu["clustering config"]:if(!Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=MM;break}os&&console.log("Restarting clustering_config"),tn.notify("Restarting clustering_config"),await rn.reloadClustering();break;case"custom_functions":case"custom functions":case Uu.harperdb:case Uu.http_workers:if(os&&!Sa){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}os&&console.log("Restarting http_workers"),tn.notify("Restarting http_workers"),os?await rn.restart(nt.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Yd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(tn.error(r),os&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(FT,"restartService");async function w6(){await pa.publishToStream(`${BT.SUBJECT_PREFIXES.TXN}.${BT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,BT.WORK_QUEUE_CONSUMER_NAMES.stream_name,pa.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(w6,"postDummyNatsMsg");async function I6(){await HM(),await rn.restart(nt.HDB_PROC_DESCRIPTOR),await qT.async_set_timeout(2e3),Kd.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await HT(),os&&(await pa.closeConnection(),process.exit(0))}a(I6,"restartPM2Mode");async function HM(){if(!vM.getConfigFromFile(nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await UM.getHDBProcessInfo()).clustering.length===0)tn.trace("Clustering not running, restart will start clustering services"),await $d.generateNatsConfig(!0),await rn.startClusteringProcesses(),await rn.startClusteringThreads(),await HT(),os&&await pa.closeConnection();else{await w6(),await $d.generateNatsConfig(!0),Sa?(tn.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await rn.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await rn.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await UM.getHDBProcessInfo()).clustering.forEach(n=>{tn.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await qT.async_set_timeout(3e3),await HT(),await pa.updateLocalStreams(),os&&await pa.closeConnection(),tn.trace("Restart clustering restarting ingest and reply service threads");let t=Yd(nt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Yd(nt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(HM,"restartClustering");async function HT(){await $d.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await $d.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(HT,"removeNatsConfig")});var zM=T((she,QM)=>{"use strict";var rhe=require("lodash"),pr=L(),{handleHDBError:qM,hdb_errors:C6}=re(),{HDB_ERROR_MSGS:D6,HTTP_STATUS_CODES:L6}=C6,GT=V();QM.exports={getRolePermissions:M6};var fo=Object.create(null),U6=a(e=>({key:e,perms:{}}),"perms_template_obj"),VM=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),$M=a((e=!1,t=!1,r=!1,s=!1)=>({[pr.PERMS_CRUD_ENUM.READ]:e,[pr.PERMS_CRUD_ENUM.INSERT]:t,[pr.PERMS_CRUD_ENUM.UPDATE]:r,[pr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),kT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...$M(t,r,s,n)}),"table_perms_template"),FM=a((e,t=$M())=>({attribute_name:e,describe:WM(t),[Pu]:t[Pu],[VT]:t[VT],[$T]:t[$T]}),"attr_perms_template"),GM=a((e,t=!1)=>({attribute_name:e,describe:t,[Pu]:t}),"timestamp_attr_perms_template"),{READ:Pu,INSERT:VT,UPDATE:$T}=pr.PERMS_CRUD_ENUM,YM=Object.values(pr.PERMS_CRUD_ENUM),KM=[Pu,VT,$T];function M6(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[pr.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(fo[t]&&fo[t].key===s)return fo[t].perms;let n=P6(e,r);return fo[t]?fo[t].key=s:fo[t]=U6(s),fo[t].perms=n,n}catch(r){if(!e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<pr.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw GT.error(s),GT.debug(r),qM(new Error,D6.OUTDATED_PERMS_TRANSLATION_ERROR,L6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
+
${r.stack}`;throw GT.error(s),qM(new Error)}}}a(M6,"getRolePermissions");function P6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[pr.SYSTEM_SCHEMA_NAME]=s[pr.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=v6(t[i]);return}r[i]=VM(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],u=t[i][o],_=B6(c,u);r[i].describe||YM.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=kT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=kT()})}),r}a(P6,"translateRolePermissions");function v6(e){let t=VM(!0);return Object.keys(e).forEach(r=>{t.tables[r]=kT(!0,!0,!0,!0,!0)}),t}a(v6,"createStructureUserPermissions");function B6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return pr.TIME_STAMP_NAMES.includes(d)&&(f=GM(d,l[Pu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=FM(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=WM(l),n.attribute_permissions.push(l),c||H6(l,u)}else if(_!==o){let l;pr.TIME_STAMP_NAMES.includes(_)?l=GM(_):l=FM(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=kM(n),n}else return e.describe=kM(e),e}a(B6,"getTableAttrPerms");function kM(e){return YM.filter(t=>e[t]).length>0}a(kM,"getSchemaTableDescribePerm");function WM(e){return KM.filter(t=>e[t]).length>0}a(WM,"getAttributeDescribePerm");function H6(e,t){KM.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(H6,"checkForHashPerms")});var JM={};Ye(JM,{Resources:()=>Qd,keyArrayToString:()=>Ta,resetResources:()=>x6,resources:()=>pi});function x6(){return pi=new Qd}function Ta(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Qd,pi,vu=Re(()=>{Zi();Qd=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!n)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return n=this.get(o),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(t[0]!=="/"&&(t="/"+t),n.relativeURL=t)),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return Xe(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(x6,"resetResources");a(Ta,"keyArrayToString")});var jM={};Ye(jM,{Headers:()=>Si,appendHeader:()=>YT});function YT(e,t,r,s){if(e.append)e.append(t,r,s);else if(e.set){let n=e.get(t);if(n)if(s)r=(typeof n=="string"?n:n.join(", "))+", "+r;else if(typeof n=="string")r=[n,r];else{n.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var Si,Bu=Re(()=>{Si=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase();if(!super.has(s))return super.set(s,[t,r])}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];if(s)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(YT,"appendHeader")});var Hu={};Ye(Hu,{authentication:()=>iP,bypassAuth:()=>Y6,login:()=>W6,logout:()=>Q6,start:()=>K6});function Y6(){nP=!0}async function iP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?k6?G6:[]:F6?q6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Si([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return zd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),zd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(zd){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(E);if(h>=0){let p=n.indexOf(";",h),S=n.indexOf("=",h);u=n.slice(S+1,p===-1?n.length:p),_=await ZM.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new jd.AuthAuditLog(E,h,Gt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Gt.AUTH_AUDIT_STATUS.SUCCESS?XM.notify(S):XM.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let E=e.mtlsConfig.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=e.peerCertificate.subject.CN),e.user=await tt.getUser(E,null,null))}let d;if(!e.user)if(s){if(d=Eo.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await tt.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Jd.validateOperationToken)(h)}catch(A){if(A.message==="invalid token")try{return await(0,Jd.validateRefreshToken)(h),c({status:-1})}catch{throw A}}break}}catch(A){return $6&&(Eo.get(h)||(Eo.set(h,h),l(p,Gt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ti({error:A.message},e)})}Eo.set(s,d),V6&&l(d.username,Gt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await tt.getUser(_.user,null,e):(nP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,tP.getSuperUser)());zd&&(e.session.update=function(E){if(!u){u=(0,rP.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):f?.headers?.set&&f.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,ZM.put(E)},e.login=async function(E,h){e.user=await tt.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&pi.loginPath?(f.status=302,f.headers.set("Location",pi.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new Si);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function K6({server:e,port:t}){e.request(iP,{port:t||"all"}),eP||(eP=!0,setInterval(()=>{Eo=new Map},as.get(Gt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),sP.user.addListener(()=>{Eo=new Map}))}async function W6(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function Q6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var tP,Jd,rP,as,Gt,jd,sP,XM,q6,F6,G6,k6,ZM,zd,nP,V6,$6,Eo,eP,Xd=Re(()=>{tP=x(ts());rr();vu();Jd=x(mu());Ae();rP=require("uuid"),as=x(Z()),Gt=x(L()),jd=x(V()),sP=x(Hc());Bu();ga();XM=(0,jd.loggerWithTag)("auth-event");as.initSync();q6=as.get(Gt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),F6=as.get(Gt.CONFIG_PARAMS.HTTP_CORS),G6=as.get(Gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),k6=as.get(Gt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),ZM=ct({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),zd=as.get(Gt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,nP=as.get(Gt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,V6=as.get(Gt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,$6=as.get(Gt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Eo=new Map;tt.onInvalidatedUser(()=>{Eo=new Map});a(Y6,"bypassAuth");a(iP,"authentication");a(K6,"start");a(W6,"login");a(Q6,"logout")});var dP=T((Ehe,_P)=>{"use strict";var Ie=require("joi"),oP=require("fs-extra"),aP=require("path"),Cn=je(),cP=Z(),uP=L(),lP=V(),{hdb_errors:z6}=re(),{HDB_ERROR_MSGS:Jt}=z6,In=/^[a-zA-Z0-9-_]+$/;_P.exports={getDropCustomFunctionValidator:j6,setCustomFunctionValidator:X6,addComponentValidator:r9,dropCustomFunctionProjectValidator:s9,packageComponentValidator:n9,deployComponentValidator:i9,setComponentFileValidator:Z6,getComponentFileValidator:t9,dropComponentFileValidator:e9};function Zd(e,t,r){try{let s=cP.get(uP.CONFIG_PARAMS.COMPONENTSROOT),n=aP.join(s,t);return oP.existsSync(n)?e?t:r.message(Jt.PROJECT_EXISTS):e?r.message(Jt.NO_PROJECT):t}catch(s){return lP.error(s),r.message(Jt.VALIDATION_ERR)}}a(Zd,"checkProjectExists");function xu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(xu,"checkFilePath");function J6(e,t,r,s){try{let n=cP.get(uP.CONFIG_PARAMS.COMPONENTSROOT),i=aP.join(n,e,t,r+".js");return oP.existsSync(i)?r:s.message(Jt.NO_FILE)}catch(n){return lP.error(n),s.message(Jt.VALIDATION_ERR)}}a(J6,"checkFileExists");function j6(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(In).custom(J6.bind(null,e.project,e.type)).custom(xu).required().messages({"string.pattern.base":Jt.BAD_FILE_NAME})});return Cn.validateBySchema(e,t)}a(j6,"getDropCustomFunctionValidator");function X6(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(xu).required(),function_content:Ie.string().required()});return Cn.validateBySchema(e,t)}a(X6,"setCustomFunctionValidator");function Z6(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),file:Ie.string().custom(xu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(Z6,"setComponentFileValidator");function e9(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),file:Ie.string().custom(xu).optional()});return Cn.validateBySchema(e,t)}a(e9,"dropComponentFileValidator");function t9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(xu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(t9,"getComponentFileValidator");function r9(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!1)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(r9,"addComponentValidator");function s9(e){let t=Ie.object({project:Ie.string().pattern(In).custom(Zd.bind(null,!0)).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(s9,"dropCustomFunctionProjectValidator");function n9(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Cn.validateBySchema(e,t)}a(n9,"packageComponentValidator");function i9(e){let t=Ie.object({project:Ie.string().pattern(In).required().messages({"string.pattern.base":Jt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":Jt.BAD_PACKAGE}),package:Ie.string().optional()});return Cn.validateBySchema(e,t)}a(i9,"deployComponentValidator")});var sf=T((mhe,TP)=>{"use strict";var ef=require("joi"),tf=require("path"),fP=require("fs-extra"),{exec:o9}=require("child_process"),a9=require("util"),EP=a9.promisify(o9),qu=L(),{handleHDBError:Ra,hdb_errors:c9}=re(),{HTTP_STATUS_CODES:Aa}=c9,Fu=Z(),u9=je(),Oa=V();Fu.initSync();var KT=Fu.get(qu.CONFIG_PARAMS.COMPONENTSROOT),hP="npm install --omit=dev --json",l9=`${hP} --dry-run`;TP.exports={installModules:E9,auditModules:h9,installAllRootModules:_9,uninstallRootModule:d9,linkHarperdb:f9};async function _9(e=!1){await rf(),await Gu(e?"npm install --ignore-scripts":"npm install",Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(_9,"installAllRootModules");async function d9(e){await Gu(`npm uninstall ${e}`,Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(d9,"uninstallRootModule");async function f9(){await rf(),await Gu(`npm link ${qu.PACKAGE_ROOT}`,Fu.get(qu.CONFIG_PARAMS.ROOTPATH))}a(f9,"linkHarperdb");async function Gu(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await EP(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
|
|
12
|
+
`,""))}return 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 E9(e){Oa.info(`starting installModules for request: ${e}`);let t=SP(e);if(t)throw Ra(t,t.message,Aa.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?l9:hP;await rf(),await pP(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(KT,u),l,d=null;try{let{stdout:f,stderr:E}=await EP(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=mP(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(E9,"installModules");function mP(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(mP,"parseNPMStdErr");async function h9(e){Oa.info(`starting auditModules for request: ${e}`);let t=SP(e);if(t)throw Ra(t,t.message,Aa.BAD_REQUEST);let{projects:r}=e;await rf(),await pP(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=tf.join(KT,o);s[o]={npm_output:null,npm_error:null};try{let u=await Gu("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=mP(u.stderr)}}return Oa.info(`finished auditModules with response ${s}`),s}a(h9,"auditModules");async function rf(){try{return await Gu("npm -v"),!0}catch{throw Ra(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Aa.BAD_REQUEST,void 0,void 0,!0)}}a(rf,"checkNPMInstalled");async function pP(e){if(!Array.isArray(e)||e.length===0)throw Ra(new Error,"projects argument must be an array with at least 1 element",Aa.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=tf.join(KT,i.toString());if(!await fP.pathExists(o)){t.push(i);continue}let u=tf.join(o,"package.json");await fP.pathExists(u)||r.push(i)}if(t.length>0)throw Ra(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Aa.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ra(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Aa.BAD_REQUEST,void 0,void 0,!0)}a(pP,"checkProjectPaths");function SP(e){let t=ef.object({projects:ef.array().min(1).items(ef.string()).required(),dry_run:ef.boolean().default(!1)});return u9.validateBySchema(e,t)}a(SP,"modulesValidator")});var QT=T((She,bP)=>{"use strict";var ba=require("fs-extra"),WT=require("path"),nf=V(),gP=J(),of=L(),OP=Z(),m9=Ur();bP.exports=p9;async function p9(){let e=S9(),t=OP.get(of.CONFIG_PARAMS.ROOTPATH),r=WT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+of.PACKAGE_ROOT}},n=WT.join(t,"node_modules");await ba.ensureDir(n);let i,o=!0,c=!1;try{i=await ba.readJson(r)}catch(u){if(gP.isEmptyOrZeroLength(e))return;if(u.code!==of.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!gP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await RP(_);s.dependencies[u]=l+_}if(!o){nf.notify("Installing components"),await AP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await RP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(nf.notify("Removing component",u),c=!0);c&&(nf.notify("Updating components."),await AP(r,s,i))}a(p9,"installComponents");function S9(){let e=m9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(S9,"getComponentsConfig");async function RP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":WT.extname(e)||await ba.pathExists(e)?"file:":"github:"}a(RP,"getPkgPrefix");async function AP(e,t,r){nf.trace("npm installing components package.json",t),await ba.writeFile(e,JSON.stringify(t,null," "));try{await sf().installAllRootModules(OP.get(of.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await ba.writeFile(e,JSON.stringify(r,null," ")):await ba.unlink(e),s}}a(AP,"installPackages")});var jT=T((Rhe,IP)=>{"use strict";var ke=require("fs-extra"),zT=require("fast-glob"),Se=require("path"),yP=require("tar-fs"),ghe=require("uuid").v4,JT=require("normalize-path"),sn=dP(),Nt=V(),Qe=L(),mt=Z(),ku=Ur(),T9=J(),{PACKAGE_ROOT:g9}=L(),{handleHDBError:Mt,hdb_errors:R9}=re(),{basename:A9}=require("path"),O9=QT(),wP=Z(),b9=L(),{Readable:N9}=require("stream"),{isMainThread:y9}=require("worker_threads"),{HDB_ERROR_MSGS:ho,HTTP_STATUS_CODES:Pt}=R9,w9=Se.join(g9,"application-template"),NP=Se.join(mt.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function I9(){Nt.trace("getting custom api status");let e={};try{e={port:mt.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Mt(new Error,ho.FUNCTION_STATUS,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(I9,"customFunctionsStatus");function C9(){Nt.trace("getting custom api endpoints");let e={},t=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{zT.sync(JT(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:zT.sync(JT(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:zT.sync(JT(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Mt(new Error,ho.GET_FUNCTIONS,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(C9,"getCustomFunctions");function D9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=sn.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("getting custom api endpoint file content");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=Se.join(r,s,n,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Mt(new Error,ho.GET_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(D9,"getCustomFunction");function L9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=sn.setCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("setting custom function file content");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return ke.outputFileSync(Se.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Mt(new Error,ho.SET_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(L9,"setCustomFunction");function U9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=sn.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("dropping custom function file");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return ke.unlinkSync(Se.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Mt(new Error,ho.DROP_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(U9,"dropCustomFunction");function M9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.addComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("adding component");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=Se.join(r,s);return ke.mkdirSync(n,{recursive:!0}),ke.copySync(w9,n),`Successfully added project: ${s}`}catch(n){throw Mt(new Error,ho.ADD_FUNCTION,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,n)}}a(M9,"addComponent");function P9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.dropCustomFunctionProjectValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);Nt.trace("dropping custom function project");let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=mt.get(Qe.CONFIG_PARAMS.APPS);if(!T9.isEmptyOrZeroLength(n)){let i=!1;for(let[o,c]of n.entries())if(c.name===s){n.splice(o,1),i=!0;break}if(i)return ku.updateConfigValue(Qe.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=Se.join(r,s);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw Mt(new Error,ho.DROP_FUNCTION_PROJECT,Pt.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(P9,"dropCustomFunctionProject");async function v9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.packageComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;Nt.trace("packaging component",s);let n;try{n=await ke.realpath(Se.join(r,s))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{n=await ke.realpath(Se.join(mt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await ke.ensureDir(NP);let i=Se.join(NP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Se.join(n,"node_modules"))}),yP.pack(n,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:s,payload:c}}a(v9,"packageComponent");async function B9(e){e.project&&(e.project=Se.parse(e.project).name);let t=sn.deployComponentValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(Nt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(n){o=Se.join(r,s),i="file:"+o,await ke.ensureDir(o);let f=N9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(yP.extract(o,{finish:h})).on("error",p)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(Se.join(o,"package"),o),await ke.remove(Se.join(o,"package")))}if(await ku.addConfig(s,{package:i}),!n){await O9();let f=wP.get(b9.CONFIG_PARAMS.ROOTPATH);o=Se.join(f,"node_modules",s)}if(y9)return;let c=new Map;c.isWorker=!0;let u=(cf(),se(af)),_;u.setErrorReporter(f=>_=f);let l=A9(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Nt.info("Installed component"),`Successfully deployed: ${s}`}a(B9,"deployComponent");async function H9(){let e=ku.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await ke.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Se.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await ke.stat(d),E={name:Se.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return Nt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),s=await r(mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Se.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(Se.join(mt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(cf(),se(af)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return s}a(H9,"getComponents");async function x9(e){let t=sn.getComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let s=ku.getConfigObj()[e.project]||e.project==="harperdb"?Se.join(wP.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Se.join(s,e.project,e.file));return{message:await ke.readFile(Se.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Se.join(e.project,e.file)}'`):i}}a(x9,"getComponentFile");async function q9(e){let t=sn.setComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=Se.join(mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(s),await ke.outputFile(s,e.payload,r)):await ke.ensureDir(s),"Successfully set component: "+e.file}a(q9,"setComponentFile");async function F9(e){let t=sn.dropComponentFileValidator(e);if(t)throw Mt(t,t.message,Pt.BAD_REQUEST);let r=e.file?Se.join(e.project,e.file):e.project,s=Se.join(mt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(s)&&await ke.remove(s),ku.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(F9,"dropComponent");IP.exports={customFunctionsStatus:I9,getCustomFunctions:C9,getCustomFunction:D9,setCustomFunction:L9,dropCustomFunction:U9,addComponent:M9,dropCustomFunctionProject:P9,packageComponent:v9,deployComponent:B9,getComponents:H9,getComponentFile:x9,setComponentFile:q9,dropComponent:F9}});var XT=T((Ohe,DP)=>{"use strict";var nn=require("joi"),CP=je();DP.exports={readTransactionLogValidator:G9,deleteTransactionLogsBeforeValidator:k9};function G9(e){let t=nn.object({schema:nn.string().required(),table:nn.string().required(),from:nn.date().timestamp(),to:nn.date().timestamp(),limit:nn.number().min(1)});return CP.validateBySchema(e,t)}a(G9,"readTransactionLogValidator");function k9(e){let t=nn.object({schema:nn.string().required(),table:nn.string().required(),timestamp:nn.date().timestamp().required()});return CP.validateBySchema(e,t)}a(k9,"deleteTransactionLogsBeforeValidator")});var lf=T((Nhe,vP)=>{"use strict";var ZT=L(),uf=st(),LP=J(),UP=Z(),MP=Sn(),{handleHDBError:Na,hdb_errors:V9}=re(),{HTTP_STATUS_CODES:ya}=V9,{readTransactionLogValidator:$9,deleteTransactionLogsBeforeValidator:Y9}=XT(),PP="This operation relies on clustering and cannot run with it disable.",K9="Logs successfully deleted from transaction log.",W9="All logs successfully deleted from transaction log.";vP.exports={readTransactionLog:Q9,deleteTransactionLogsBefore:z9};async function*Q9(e){let t=$9(e);if(t)throw Na(t,t.message,ya.BAD_REQUEST,void 0,void 0,!0);if(!UP.get(ZT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Na(new Error,PP,ya.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=LP.checkSchemaTableExist(r,s);if(n)throw Na(new Error,n,ya.NOT_FOUND,void 0,void 0,!0);let i=MP.createNatsTableStreamName(r,s),o=await uf.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===ZT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(Q9,"readTransactionLog");async function z9(e){let t=Y9(e);if(t)throw Na(t,t.message,ya.BAD_REQUEST,void 0,void 0,!0);if(!UP.get(ZT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Na(new Error,PP,ya.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=LP.checkSchemaTableExist(r,s);if(i)throw Na(new Error,i,ya.NOT_FOUND,void 0,void 0,!0);let o=MP.createNatsTableStreamName(r,s),{jsm:c}=await uf.getNATSReferences(),u=await uf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=K9,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=W9):d=(await uf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(z9,"deleteTransactionLogsBefore")});var HP=T((whe,BP)=>{"use strict";var eg=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};BP.exports=eg});var qP=T((Che,xP)=>{"use strict";var tg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};xP.exports=tg});var sg=T((Lhe,GP)=>{"use strict";var FP=HP(),J9=qP(),{HDB_ERROR_MSGS:j9}=Nr(),rg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=j9.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new FP(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new J9(c,n[c]);i.push(u)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new FP(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};GP.exports=rg});var Ef=T((Mhe,sv)=>{"use strict";var ng=Cr(),_f=es(),us=lu(),Yu=Xn(),ig=ti(),X9=pS(),Z9=XD(),Ku=ts(),df=yS(),yt=V(),e7=CS(),t7=Id(),r7=lT(),s7=Dd(),n7=_T(),i7=dT(),o7=hT(),a7=pT(),og=gT(),Dn=J(),c7=zU(),ag=NT(),$P=Wd(),cs=L(),YP=zM(),u7=da(),KP=mu(),WP=(Xd(),se(Hu)),QP=Ur(),Gr=jT(),l7=require("alasql"),zP=lf(),JP=sf(),jP=sg(),{handleHDBError:Sr,hdb_errors:XP}=re(),{HDB_ERROR_MSGS:kt,HTTP_STATUS_CODES:Vu}=XP,k=new Map,ZP="delete",gi="insert",Ln="read",mo="update",$u="describe",kP=Yu.describeSchema.name,VP=Yu.describeTable.name,ev={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},_7="catchup",d7="handleGetJob",f7="handleGetJobsByStartDate",ff={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},E7=[us.createTable.name,us.createAttribute.name,us.dropTable.name,us.dropAttribute.name],tv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},Q=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};k.set(ng.insert.name,new Q(!1,[gi]));k.set(ng.update.name,new Q(!1,[mo]));k.set(ng.upsert.name,new Q(!1,[gi,mo]));k.set(_f.searchByConditions.name,new Q(!1,[Ln]));k.set(_f.searchByHash.name,new Q(!1,[Ln]));k.set(_f.searchByValue.name,new Q(!1,[Ln]));k.set(_f.search.name,new Q(!1,[Ln]));k.set(us.createSchema.name,new Q(!0,[]));k.set(us.createTable.name,new Q(!0,[]));k.set(us.createAttribute.name,new Q(!1,[gi]));k.set(us.dropSchema.name,new Q(!0,[]));k.set(us.dropTable.name,new Q(!0,[]));k.set(us.dropAttribute.name,new Q(!0,[]));k.set(Yu.describeSchema.name,new Q(!1,[Ln]));k.set(Yu.describeTable.name,new Q(!1,[Ln]));k.set(ig.deleteRecord.name,new Q(!1,[ZP]));k.set(Ku.addUser.name,new Q(!0,[]));k.set(Ku.alterUser.name,new Q(!0,[]));k.set(Ku.dropUser.name,new Q(!0,[]));k.set(Ku.listUsersExternal.name,new Q(!0,[]));k.set(df.listRoles.name,new Q(!0,[]));k.set(df.addRole.name,new Q(!0,[]));k.set(df.alterRole.name,new Q(!0,[]));k.set(df.dropRole.name,new Q(!0,[]));k.set(e7.name,new Q(!0,[]));k.set(t7.name,new Q(!0,[]));k.set(r7.name,new Q(!0,[]));k.set(s7.name,new Q(!0,[]));k.set(n7.name,new Q(!0,[]));k.set(i7.name,new Q(!0,[]));k.set(og.setRoutes.name,new Q(!0,[]));k.set(og.getRoutes.name,new Q(!0,[]));k.set(og.deleteRoutes.name,new Q(!0,[]));k.set(QP.setConfiguration.name,new Q(!0,[]));k.set(o7.clusterStatus.name,new Q(!0,[]));k.set(a7.name,new Q(!0,[]));k.set(ag.getFingerprint.name,new Q(!0,[]));k.set(ag.setLicense.name,new Q(!0,[]));k.set(ig.deleteFilesBefore.name,new Q(!0,[]));k.set(ig.deleteAuditLogsBefore.name,new Q(!0,[]));k.set($P.restart.name,new Q(!0,[]));k.set($P.restartService.name,new Q(!0,[]));k.set(X9.name,new Q(!0,[]));k.set(Z9.name,new Q(!0,[Ln]));k.set(u7.systemInformation.name,new Q(!0,[]));k.set(QP.getConfiguration.name,new Q(!0,[]));k.set(zP.readTransactionLog.name,new Q(!0,[]));k.set(zP.deleteTransactionLogsBefore.name,new Q(!0,[]));k.set(JP.installModules.name,new Q(!0,[]));k.set(JP.auditModules.name,new Q(!0,[]));k.set(KP.createTokens.name,new Q(!1,[]));k.set(KP.refreshOperationToken.name,new Q(!1,[]));k.set(WP.login.name,new Q(!1,[]));k.set(WP.logout.name,new Q(!1,[]));k.set(Gr.customFunctionsStatus.name,new Q(!0,[]));k.set(Gr.getCustomFunctions.name,new Q(!0,[]));k.set(Gr.getComponents.name,new Q(!0,[]));k.set(Gr.getComponentFile.name,new Q(!0,[]));k.set(Gr.setComponentFile.name,new Q(!0,[]));k.set(Gr.dropComponent.name,new Q(!0,[]));k.set(Gr.getCustomFunction.name,new Q(!0,[]));k.set(Gr.setCustomFunction.name,new Q(!0,[]));k.set(Gr.dropCustomFunction.name,new Q(!0,[]));k.set(Gr.addComponent.name,new Q(!0,[]));k.set(Gr.dropCustomFunctionProject.name,new Q(!0,[]));k.set(Gr.packageComponent.name,new Q(!0,[]));k.set(Gr.deployComponent.name,new Q(!0,[]));k.set(ag.getRegistrationInfo.name,new Q(!1,[]));k.set(Ku.userInfo.name,new Q(!1,[]));k.set(Yu.describeAll.name,new Q(!1,[]));k.set(d7,new Q(!1,[]));k.set(f7,new Q(!0,[]));k.set(_7,new Q(!0,[]));k.set(ff.CSV_DATA_LOAD,new Q(!1,[gi,mo]));k.set(ff.CSV_URL_LOAD,new Q(!1,[gi,mo]));k.set(ff.CSV_FILE_LOAD,new Q(!1,[gi,mo]));k.set(ff.IMPORT_FROM_S3,new Q(!1,[gi,mo]));k.set(tv.EXPORT_TO_S3,new Q(!0,[]));k.set(tv.EXPORT_LOCAL,new Q(!0,[]));k.set(cs.VALID_SQL_OPS_ENUM.DELETE,new Q(!1,[ZP]));k.set(cs.VALID_SQL_OPS_ENUM.SELECT,new Q(!1,[Ln]));k.set(cs.VALID_SQL_OPS_ENUM.INSERT,new Q(!1,[gi]));k.set(cs.VALID_SQL_OPS_ENUM.UPDATE,new Q(!1,[mo]));sv.exports={verifyPerms:m7,verifyPermsAst:h7,verifyBulkLoadAttributePerms:S7};function h7(e,t,r){if(Dn.isEmptyOrZeroLength(e))throw yt.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Dn.isEmptyOrZeroLength(t))throw yt.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Dn.isEmptyOrZeroLength(r))throw yt.info("verify_perms_ast has a null operation parameter"),Sr(new Error);try{let s=new jP,n=new c7(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw yt.info("No schemas defined in verifyPermsAst(), will not continue."),Sr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&ev[r])throw Sr(new Error,kt.DROP_SYSTEM,Vu.FORBIDDEN);if(c&&!u)return null;let _=YP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof l7.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=n.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=rv(t,r,o,s);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=n.getAttributesBySchemaTableName(f,d[E]),p=ug(t.role.permission,f,d[E]);cg(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw Sr(s)}}a(h7,"verifyPermsAst");function m7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw yt.info("null required parameter in verifyPerms"),Sr(new Error,kt.DEFAULT_INVALID_REQUEST,Vu.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema??e.database,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new jP;if(Dn.isEmptyOrZeroLength(e.hdb_user.role)||Dn.isEmptyOrZeroLength(e.hdb_user.role.permission))return yt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(kt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(cs.SYSTEM_SCHEMA_NAME)||n===cs.SYSTEM_SCHEMA_NAME;if(l&&ev[r])throw Sr(new Error,kt.DROP_SYSTEM,Vu.FORBIDDEN);if(u&&!l||_===!0&&(r===us.createSchema.name||r===us.dropSchema.name))return null;if(E7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=YP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===kP||r===VP){if(n===cs.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(kt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===kP&&(!d[n]||!d[n][$u]))return c.handleInvalidItem(kt.SCHEMA_NOT_FOUND(n));if(r===VP&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][$u]))return c.handleInvalidItem(kt.TABLE_NOT_FOUND(n,i))}}let f=rv(e.hdb_user,r,o,c,s);if(f)return f;if(k.get(r)&&k.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&cs.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[cs.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[cs.PERMS_CRUD_ENUM.READ]).forEach(R=>{p.push(R.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(A=>A.attribute),e.get_attributes=p)}let E=p7(e),h=ug(e.hdb_user.role.permission,n,i);return cg(E,h,r,i,n,c,s),c.getPermsResponse()}a(m7,"verifyPerms");function rv(e,t,r,s,n){if(Dn.arrayHasEmptyValues([e,t,r]))throw yt.info("hasPermissions has an invalid parameter"),Sr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||k.get(t).requires_su))return null;if(!k.get(t))throw yt.info(`operation ${t} not found.`),Sr(new Error,kt.OP_NOT_FOUND(t),Vu.BAD_REQUEST);if(k.get(t)&&k.get(t).requires_su)return yt.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(kt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][$u]===!1){s.addInvalidItem(kt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(kt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[$u]===!1)s.addInvalidItem(kt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=k.get(t).perms;!Dn.isEmpty(n)&&E.includes(n)&&(E=[n]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(yt.info(`Required ${p} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&s.addUnauthorizedTable(u,l,f)}catch(f){let E=kt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw yt.error(E),yt.error(f),Sr(XP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(rv,"hasPermissions");function cg(e,t,r,s,n,i,o){if(!e||!t)throw yt.info("no attributes specified in checkAttributePerms."),Sr(new Error);let c=k.get(r).perms;if(!c||c==="")throw yt.info(`no permissions found for ${r} in checkAttributePerms().`),Sr(new Error);if(Dn.isEmptyOrZeroLength(t))return yt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[$u]===!1){i.addInvalidItem(kt.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(cs.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Ln)throw Sr(new Error,kt.SYSTEM_TIMESTAMP_PERMS_ERR,Vu.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(kt.ATTR_NOT_FOUND(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(cg,"checkAttributePerms");function p7(e){let t=new Set;try{if(e.action)return t;if(e.operation===cs.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){yt.info(r)}return t}a(p7,"getRecordAttributes");function ug(e,t,r){let s=new Map;if(Dn.isEmpty(e))return yt.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{yt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(ug,"getAttributePermissions");function S7(e,t,r,s,n,i,o){let c=new Set(i),u=ug(e,s,n);cg(c,u,t,n,s,o,r)}a(S7,"verifyBulkLoadAttributePerms")});var mf=T((vhe,cv)=>{"use strict";cv.exports={evaluateSQL:L7,processAST:av,convertSQLToAST:ov,checkASTPermissions:iv};var T7=Cr(),nv=require("util"),g7=nv.callbackify(T7.insert),R7=es().search,A7=$C().update,O7=nv.callbackify(A7),b7=KC().convertDelete,Ri=require("alasql"),N7=Ef(),hf=V(),y7=X_(),w7=J(),Wu=L(),{hdb_errors:I7,handleHDBError:lg}=re(),{HTTP_STATUS_CODES:_g}=I7;y7(Ri);var C7=403,D7="There was a problem performing this insert. Please check the logs and try again.",dg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function L7(e,t){let r=e.parsed_sql_object;if(!r){r=ov(e.sql);let s,n=r.ast.statements[0];if(n instanceof Ri.yy.Insert?s=n.into.databaseid:n instanceof Ri.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Ri.yy.Update||n instanceof Ri.yy.Delete?s=n.table.databaseid:hf.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Ri.yy.Select)&&w7.isEmptyOrZeroLength(s))return t("No schema specified",null)}av(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(L7,"evaluateSQL");function iv(e,t){let r;try{r=N7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(iv,"checkASTPermissions");function ov(e){let t=new dg;if(!e)throw lg(new Error,"The 'sql' parameter is missing from the request body",_g.BAD_REQUEST);try{let r=e.trim(),s=Ri.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
17
|
+
`);throw s[1]?lg(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,_g.BAD_REQUEST):lg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",_g.BAD_REQUEST)}return t}a(ov,"convertSQLToAST");function av(e,t,r){try{let s=U7;if(!e.bypass_auth&&!t.permissions_checked){let i=iv(e,t);if(i&&i.length>0)return r(C7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Wu.VALID_SQL_OPS_ENUM.SELECT:s=R7,n=t.ast.statements[0];break;case Wu.VALID_SQL_OPS_ENUM.INSERT:s=M7;break;case Wu.VALID_SQL_OPS_ENUM.UPDATE:s=O7;break;case Wu.VALID_SQL_OPS_ENUM.DELETE:s=b7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(av,"processAST");function U7(e,t){hf.info(e),t("unknown sql statement")}a(U7,"nullFunction");function M7({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=P7(i,e.values)}catch(o){return r(o)}g7(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){hf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(M7,"convertInsert");function P7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=Ri.compile(`SELECT ${n.toString()} AS [${Wu.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw hf.error(r),new Error(D7)}}a(P7,"createDataObjects")});var fg=T((Hhe,lv)=>{"use strict";var{S3:v7,GetObjectCommand:B7}=require("@aws-sdk/client-s3");lv.exports={getFileStreamFromS3:H7,getS3AuthObj:uv};async function H7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await uv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new B7(r))).Body}a(H7,"getFileStreamFromS3");function uv(e,t,r){return new v7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(uv,"getS3AuthObj")});var pf=T((qhe,Tv)=>{"use strict";var hg=es(),x7=mf(),q7=fg(),{AsyncParser:F7,Transform:G7}=require("json2csv"),zu=require("stream"),kr=J(),Eg=require("fs-extra"),k7=require("path"),ls=V(),{promisify:fv}=require("util"),Qu=J(),{handleHDBError:pt,hdb_errors:V7}=re(),{HDB_ERROR_MSGS:Tr,HTTP_STATUS_CODES:St}=V7,{streamAsJSON:$7}=(Mh(),se(ub)),{Upload:Y7}=require("@aws-sdk/lib-storage"),_v=["search_by_value","search_by_hash","sql","search_by_conditions"],dv=["json","csv"],Ev="json",hv="csv",K7="Successfully exported JSON locally.",W7="Successfully exported CSV locally.",Q7=1e3,z7=hg.searchByHash,J7=hg.searchByValue,j7=fv(x7.evaluateSQL),X7=fv(zu.finished);Tv.exports={export_to_s3:ree,export_local:Z7,toCsvStream:mv};async function Z7(e){ls.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=pv(e);if(!kr.isEmpty(t))throw ls.error(t),pt(new Error,t,St.BAD_REQUEST,void 0,void 0,!0);if(kr.isEmpty(e.path))throw ls.error(Tr.MISSING_VALUE("path")),pt(new Error,Tr.MISSING_VALUE("path"),St.BAD_REQUEST,void 0,void 0,!0);let r=(kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(k7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=kr.buildFolderPath(e.path,r);await eee(e.path);let n=await Sv(e);return await tee(s,e.format,n)}a(Z7,"export_local");async function eee(e){if(ls.trace("in confirmPath"),kr.isEmptyOrZeroLength(e))throw pt(new Error,`Invalid path: ${e}`,St.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Eg.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,ls.error(s),pt(new Error,s,St.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw ls.error(r),pt(new Error,r,St.BAD_REQUEST,void 0,void 0,!0)}return!0}a(eee,"confirmPath");async function tee(e,t,r){if(ls.trace("in saveToLocal"),Qu.isEmptyOrZeroLength(e))throw pt(new Error,Tr.INVALID_VALUE("file_path"),St.BAD_REQUEST,void 0,void 0,!0);if(Qu.isEmptyOrZeroLength(t))throw pt(new Error,Tr.INVALID_VALUE("Source format"),St.BAD_REQUEST,void 0,void 0,!0);if(Qu.isEmpty(r))throw pt(new Error,Tr.NOT_FOUND("Data"),St.BAD_REQUEST,void 0,void 0,!0);if(t===Ev){let s=Eg.createWriteStream(e);return $7(r).pipe(s),await X7(s),{message:K7,path:e}}else if(t===hv){let s=Eg.createWriteStream(e),n=zu.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new F7(i,c).fromInput(n).toOutput(s).promise(!1),{message:W7,path:e}}throw pt(new Error,Tr.INVALID_VALUE("format"),St.BAD_REQUEST)}a(tee,"saveToLocal");async function ree(e){if(!e.s3||Object.keys(e.s3).length===0)throw pt(new Error,Tr.MISSING_VALUE("S3 object"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw pt(new Error,Tr.MISSING_VALUE("aws_access_key_id"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw pt(new Error,Tr.MISSING_VALUE("aws_secret_access_key"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.bucket))throw pt(new Error,Tr.MISSING_VALUE("bucket"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.key))throw pt(new Error,Tr.MISSING_VALUE("key"),St.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.region))throw pt(new Error,Tr.MISSING_VALUE("region"),St.BAD_REQUEST);let t=pv(e);if(!kr.isEmpty(t))throw pt(new Error,t,St.BAD_REQUEST);ls.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await Sv(e)}catch(u){throw ls.error(u),u}let s,n=await q7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new zu.PassThrough;if(e.format===hv){i=e.s3.key+".csv";let u=mv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===Ev){i=e.s3.key+".json";let u=new zu.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%Q7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw pt(new Error,Tr.INVALID_VALUE("format"),St.BAD_REQUEST);return new Y7({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(ree,"export_to_s3");function mv(e,t){let r=zu.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),s={};t&&(s.fields=t.map(o=>({label:o,value:o})));let n={objectMode:!0},i=new G7(s,n);return r.pipe(i)}a(mv,"toCsvStream");function pv(e){if(ls.trace("in exportCoreValidation"),kr.isEmpty(e.format))return"format missing";if(dv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${dv.join(", ")}`;let t=e.search_operation.operation;if(kr.isEmpty(t))return"search_operation.operation missing";if(_v.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${_v.join(", ")}`}a(pv,"exportCoreValidation");async function Sv(e){ls.trace("in getRecords");let t,r;if(Qu.isEmpty(e.search_operation)||Qu.isEmptyOrZeroLength(e.search_operation.operation))throw pt(new Error,Tr.INVALID_VALUE("Search operation"),St.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=J7;break;case"search_by_hash":t=z7;break;case"search_by_conditions":t=hg.searchByConditions;break;case"sql":t=j7;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,ls.error(r),pt(new Error,r,St.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(Sv,"getRecords")});var wv={};Ye(wv,{contentTypes:()=>gg,findBestSerializer:()=>Tf,getDeserializer:()=>So,registerContentHandlers:()=>Rg,serialize:()=>gf,serializeMessage:()=>Ti});function see(e){try{return e?.[0]===123?Tg(e):e}catch{return e}}function Rg(e){e.register(iee,{serializers:[{regex:/^application\/json$/,serializer:mc},{regex:/^application\/cbor$/,serializer:function(t){return new po.EncoderStream(ju).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Sf.Readable.from((0,on.encodeIter)(t,ju)):(0,on.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,mg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,on.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,po.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function Tf(e){let r=(e.headers.asObject||e.headers).accept,s,n=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=vt.get(_);if(E){let h=(E.q||1)*d;h>n&&(s=E,i=E.type||_,n=h,o=f)}}if(!s){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(vt.keys()).join(", "))}};s=vt.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function gf(e,t,r){let s=Rv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),n=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=Tf(t);if(i.serializer.compressible===!1&&(s=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Un.createBrotliCompress)({params:{[Un.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Un.constants.BROTLI_MODE_TEXT:Un.constants.BROTLI_MODE_GENERIC,[Un.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e,r)}return s&&n?.length>Rv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Un.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ti(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Ju(e);let r=t.serialize;if(r)return r(e);let s=Tf(t);return r=t.serialize=s.serializer.serialize,r(e)}function oee(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function So(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=vt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=vt.get(e)?.deserialize||Av(e,s);return o=>oee(o).then(i)}return e&&vt.get(e)?.deserialize||Av(e,s)}function Av(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Tg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function aee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var mg,on,po,Un,Sf,Ov,pg,Sg,bv,Nv,Ju,Tg,ju,vt,gg,gv,yv,nee,iee,Rv,ga=Re(()=>{Mh();mg=x(pf()),on=require("msgpackr"),po=require("cbor-x"),Un=require("zlib"),Sf=require("stream");rr();Ov=require("../index"),pg=x(Z()),Sg=x(L()),bv=x(require("yaml")),Nv=pg.default.get(Sg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Ju=Nv?Pi:JSON.stringify,Tg=Nv?Uh:JSON.parse,ju={useRecords:!1,useToJSON:!0},vt=new Map,gg=vt;tt.contentTypes=gg;(0,Ov._assignPackageExport)("contentTypes",gg);vt.set("application/json",{serializeStream:mc,serialize:Ju,deserialize:Tg,q:.8});gv=new po.Encoder(ju);vt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new po.EncoderStream(ju).end(e)},serialize:gv.encode,deserialize:gv.decode,q:1});vt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Sf.Readable.from((0,on.encodeIter)(e,ju)):(0,on.pack)(e)},serialize:on.pack,deserialize:on.unpack,q:.9});vt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,mg.toCsvStream)(e,e?.getColumns?.())},q:.1});vt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});vt.set("text/yaml",{serialize(e){return bv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});vt.set("text/event-stream",{serializeStream:function(e){return Sf.Readable.from(aee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
18
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=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});vt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,s]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let n=t[r];Array.isArray(n)?n.push(s):t.key=[n,s]}else t[r]=s},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});yv={type:"application/json",serializeStream:mc,serialize:Ju,deserialize:see,q:.8};vt.set("*/*",yv);vt.set("",yv);a(see,"tryJSONParse");a(Rg,"registerContentHandlers");nee=require("fastify-plugin"),iee=nee(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Tf(s.raw);n.type(c),n.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{n.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Tf,"findBestSerializer");Rv=pg.default.get(Sg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(gf,"serialize");a(Ti,"serializeMessage");a(oee,"streamToBuffer");a(So,"getDeserializer");a(Av,"deserializerUnknownType");a(aee,"transformIterable")});function bg(e,t,r,s,n,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],p=_(h);d=d.concat(p)}let f=new Set;return d.filter(E=>{let h=E.key??E;return f.has(h)?!1:(f.add(h),!0)})}else{let d=_(u),f=l(e.slice(1),!0,u.estimated_count);return f.length>0?o(d,f):d}function _(d){return d.conditions?bg(d.conditions,d.operator,r,s,n,i,o,c):Ca(d,s,d.descending||n.reverse===!0,r,n.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",g=l(h.conditions,!R,E);return R?(P,H)=>g.some(v=>v(P,H)):(P,H)=>g.every(v=>v(P,H))}let S=(h.attribute||h[0])===r.primaryKey,A=yg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=mee(r.primaryStore,h.estimated_count,E)),A}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ca(e,t,r,s,n,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],g=Pn(s.attributes,R);if(g.relationship){if(o.length<2)throw new Vr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let P=g.definition?.tableClass||g.elements?.definition?.tableClass,H=new Map,v=Ca({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,P,n,H);if(g.relationship.to){i[o[0]]=H;let U=!!Pn(P.attributes,g.relationship.to)?.elements;v=dee(v,g,P.primaryStore,U,H)}if(g.relationship.from){let U=a(Y=>Ca({attribute:g.relationship.from,value:Y},t,r,s,n,H),"searchEntry");g.elements?(i[o[0]]=H,v=fee(v,g,P.primaryStore,H,U)):v=v.flatMap(U)}return v}else if(o.length===1)o=o[0];else throw new Vr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Ng[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=an.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"sort":case"contains":case"ends_with":_=!0,E=!0;break;default:throw new Vr.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!f,f=!d,d=R}let h=o===s.primaryKey||o==null,p=h?s.primaryStore:s.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(n===!1&&!p)throw new Vr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(n===!1&&E)throw new Vr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Vr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Vr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=yg(e),!S)throw new Vr.ClientError(`Unknown search operator ${e.comparator}`)}let A={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(A).map(S?function({key:g,value:P}){return this.isSync?P&&S(P)?g:Ai.SKIP:new Promise((H,v)=>setImmediate(()=>{try{H(P&&S(P)?g:Ai.SKIP)}catch(U){v(U)}}))}:g=>g.value==null?Ai.SKIP:g);return R.hasEntries=!0,R}else return p?p.getRange(A).map(S?function({key:R,value:g}){return this.isSync?S({[o]:R})?g:Ai.SKIP:new Promise((P,H)=>setImmediate(()=>{try{P(S({[o]:R})?g:Ai.SKIP)}catch(v){H(v)}}))}:({value:R})=>R):s.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:g}){return this.isSync?g&&S(g)?R:Ai.SKIP:new Promise((P,H)=>setImmediate(()=>{try{P(g&&S(g)?R:Ai.SKIP)}catch(v){H(v)}}))})}function Pn(e,t){if(Array.isArray(t))if(t.length>1){let r=Pn(e,t[0]),s=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return s?Pn(s,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function dee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i;n.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Ps(l),o=!0);let E=n.get(f);E?E.push(d):n.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!n.filters?.some(E=>!E(d)))if(s)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?n:n.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function fee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Ps(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;s.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Ps(d)));for(let l of e){if(s.filters){let d=r.get(l);if(s.filters.some(f=>!f(d)))continue}_.set(Ps(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=n(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function yg(e,t,r,s,n,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Pn(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=s?.[l],h=yg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let p=t.propertyResolvers?.[l],S,A=a((R,g)=>{let P,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let U of h.idFilter.idSet)e={attribute:p.from,value:U};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(R);return S.idFilter&&(A.idFilter=S.idFilter),v}H=p(R,r,g),P=H?.value}else P=R[l];return P?Array.isArray(P)?P.some(h):h(P,H):!1},"recordFilter");return A}}switch(u instanceof Date&&(u=u.getTime()),Ng[o]||o){case Ag.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,an.compareKeys)(l,u[0])>=0&&(0,an.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,an.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,an.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,an.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,an.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,an.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Vr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!n&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&Af(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let p=0,S=3;function A(R){let g=R[l],P;if(typeof g!="object"||!g||E?P=d(g):Array.isArray(g)?P=g.some(d):g instanceof Date&&(P=d(g.getTime())),f&&(S++,!P&&!A.idFilter&&++p/S*(i-S)>h)){let H=Ca(e,r.transaction.getReadTxn(),!1,t).map(Ps),v=new Set(H);A.idFilter=U=>v.has(Ps(U)),A.idFilter.idSet=v}return P}return a(A,"recordFilter"),n&&(A.idFilter=d),A}a(_,"attributeComparator")}function Af(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let n;if(r.operator==="or"){n=0;for(let i of r.conditions)t(i),n+=i.estimated_count}else{n=1/0;for(let i of r.conditions)t(i),n=isFinite(n)?n*i.estimated_count/Mn(e.primaryStore):i.estimated_count}return r.estimated_count=n,r.estimated_count}let s=r.comparator||r.search_type;if(s=Ng[s]||s,s===Ag.SEARCH_TYPES.EQUALS||!s){let n=r[0]??r.attribute;if(n==null||n===e.primaryKey)r.estimated_count=1;else if(Array.isArray(n)&&n.length>1){let i=Pn(e.attributes,n[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Af(o)({value:r.value,attribute:n.length>2?n.slice(1):n[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Mn(e.indices[i.relationship.from])/(Mn(o.primaryStore)||1):c)}else{let i=e.indices[n];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(s==="contains"||s==="ends_with"||s==="ne"){let n=r[0]??r.attribute,i=e.indices[n];r.value===null&&s==="ne"?r.estimated_count=Mn(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else s==="starts_with"||s==="prefix"?r.estimated_count=lee*Mn(e.primaryStore)+1:s==="between"?r.estimated_count=uee*Mn(e.primaryStore)+1:s==="sort"?r.estimated_count=Mn(e.primaryStore)+1:r.estimated_count=cee*Mn(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Of(e){if(e)if(Oi=e,wa.lastIndex=0,Eee.test(e))try{let t=Xu(new Ia,"");if(gr!==Oi.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${gr} in '${Oi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Xu(e,t){let r=wa,s,n,i,o,c,u=decodeURIComponent,_;for(;s=r.exec(Oi);){gr=r.lastIndex;let[,l,d]=s;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(n){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=Iv}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");n=Zu(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=_ee[d],u=Og[i]?Iv:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);n=Zu(l);break;case"|":case"&":case"":case void 0:if(n==null){if(n===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:n,value:u(l)};i==="eq"&&Cv(h,l),Rf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),n=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Zu(l)),n=void 0;break;case"(":wa.lastIndex=gr;let E=Xu(l?[]:new Ia,")");switch(l){case"":Rf(e,_),e.conditions.push(E);break;case"limit":switch(E.length){case 1:e.limit=+E[0];break;case 2:e.offset=+E[0],e.limit=E[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(E[0])&&E.length===1&&!E[0].name?(e.select=E[0],e.select.asArray=!0):E.length===1?e.select=E[0]:E.length===2&&E[1]===""?e.select=E.slice(0,1):e.select=E;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=Dv(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Oi[gr]===","?r.lastIndex=++gr:o=!0,n=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");wa.lastIndex=gr,f=Xu([],"}"),f.name=l,e.push(f),Oi[gr]===","?r.lastIndex=++gr:o=!0;break;case"[":wa.lastIndex=gr,l?(f=Xu(new Ia,"]"),f.name=l):f=Xu(e.conditions?new Ia:[],"]"),e.conditions?(Rf(e,_),e.conditions.push(f),n=null):e.push(f),Oi[gr]===","?r.lastIndex=++gr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(n){let h={comparator:i||"equals",attribute:n,value:u(l)};i==="eq"&&Cv(h,l),Rf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(Zu(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=n?hee:wa,r.lastIndex=gr),gr===Oi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Rf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function Zu(e){return e.indexOf(".")>-1?e.split(".").map(Zu):decodeURIComponent(e)}function Iv(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new Vr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function Cv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Vr.ClientError("wildcard can only be used at the end of a string")}function Dv(e){let t=Lv(e[0]);return e.length>1&&(t.next=Dv(e.slice(1))),t}function Lv(e){if(Array.isArray(e)){let t=Lv(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function Ps(e){return Array.isArray(e)?e.join("\0"):e}function Mn(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function mee(e,t,r){return t*r/Mn(e)}var Vr,Ag,an,Ai,cee,uee,lee,_ee,Og,Ng,Eee,wa,hee,gr,Oi,Ia,bf=Re(()=>{Vr=x(re()),Ag=x(dt()),an=require("ordered-binary"),Ai=require("lmdb"),cee=.3,uee=.1,lee=.05,_ee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Og={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(bg,"executeConditions");a(Ca,"searchByIndex");a(Pn,"findAttribute");a(dee,"joinTo");a(fee,"joinFrom");Ng={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(yg,"filterByType");a(Af,"estimateCondition");Eee=/[()[\]|!<>.]|(=\w*=)/,wa=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,hee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Of,"parseQuery");a(Xu,"parseBlock");a(Rf,"assignOperator");a(Zu,"decodeProperty");a(Iv,"typedDecoding");a(Cv,"wildcardDecoding");a(Dv,"toSortObject");a(Lv,"toSortEntry");Ia=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}};a(Ps,"flattenKey");a(Mn,"estimatedEntryCount");a(mee,"intersectionEstimate")});function Bv(e){let t={openapi:pee,info:{title:"HarperDB HTTP REST interface",version:(0,vv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,s]of e){if(!s.path)continue;let{path:n}=s,i=n.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=s.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:g,name:P,elements:H,relationship:v,definition:U}of o){if(v)g==="array"?_[P]={type:"array",items:{$ref:bi+H.type}}:_[P]={$ref:bi+g};else{let Y=U??H?.definition;if(Y){if(!t.components.schemas[Y.type]){let K={};Y.properties.forEach(z=>{K[z.name]=new Dg(wg[z.type],z.type)}),t.components.schemas[Y.type]=new Pv(K)}g==="array"?_[P]={type:"array",items:{$ref:bi+Y.type}}:_[P]={$ref:bi+Y.type}}else g==="array"?H.type==="Any"||H.type=="ID"?_[P]={type:"array",items:{format:H.type}}:_[P]={type:"array",items:new Dg(wg[H.type],H.type)}:g==="Any"||g=="ID"?_[P]={format:g}:_[P]=new Dg(wg[g],g)}l.push(new Lg(P,"query",_[P]))}let d=Object.keys(_),f=new Lg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Lg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new Pv(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",A=typeof u.delete=="function",R="/"+n+"/";h&&(t.paths[R]={},t.paths[R].post=new See(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new Ig(l,r,{200:new Cg({$ref:bi+i})},"search for records by the specified property name and value pairs")),A&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new Mv(l,r,"delete all the records that match the provided query",{204:new Uv})),R="/"+n+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new Ig([f],r,{200:new Cg({$ref:bi+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new Tee([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),A&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new Mv([f],r,"delete a record with the given primary key",{204:new Uv})),S&&E.schema.enum.length>0&&(R="/"+n+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new Ig([f,E],r,{200:new Cg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function See(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:bi+e}}}},this.security=t,this.responses={200:{description:Ug,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Ig(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.responses=r}function Cg(e){this.description=Ug,this.content={"application/json":{schema:e}}}function Uv(){this.description="successfully processed request, no content returned to client"}function Tee(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:bi+r}}}},this.responses={200:{description:Ug}}}function Mv(e,t,r,s){this.description=r,this.parameters=e,this.security=t,this.responses=s}function Pv(e){this.type="object",this.properties=e}function Dg(e,t){this.type=e,this.format=t}function Lg(e,t,r){this.name=e,this.in=t,this.schema=r}var vv,pee,wg,bi,Ug,Hv=Re(()=>{vv=x(Od()),pee="3.0.3",wg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},bi="#/components/schemas/",Ug="successful operation";a(Bv,"generateJsonApi");a(See,"Post");a(Ig,"Get");a(Cg,"Response200");a(Uv,"Response204");a(Tee,"Put");a(Mv,"Delete");a(Pv,"ResourceSchema");a(Dg,"Type");a(Lg,"Parameter")});var yf={};Ye(yf,{start:()=>Aee});async function Ree(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Of(e);let n=new Si;try{e.responseHeaders=n;let i=e.url.slice(1),o,c;if(i!==xv){let h=Nf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Xe(e,()=>{if(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=So(r["content-type"],!0)(e.body)}catch(h){throw new Da.ClientError(h,400)}if(e.authorize=!0,i===xv&&s==="GET"){if(e?.user?.role?.permission?.super_user)return Bv(Nf);throw new Da.ServerError("Forbidden",403)}switch(s){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":n.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new Da.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Da.ServerError(`Method ${s} is not recognized`,501)}}),l=200,d;if(_==null)l=s==="GET"||s==="HEAD"?404:204,Mg.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){gee[0]=d;let h=String.fromCharCode(34,(Vt[0]&63)+62,(Vt[0]>>6)+(Vt[1]<<2&63)+62,(Vt[1]>>4)+(Vt[2]<<4&63)+62,(Vt[2]>>2)+62,(Vt[3]&63)+62,(Vt[3]>>6)+(Vt[4]<<2&63)+62,(Vt[4]>>4)+(Vt[5]<<4&63)+62,(Vt[5]>>2)+62,(Vt[6]&63)+62,(Vt[6]>>6)+(Vt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):n.setIfNone("ETag",h),Mg.lastModified&&n.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&n.setIfNone("Location",e.newLocation);let f={status:l,headers:n,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&n.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=gf(_,e,f),s==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?To.warn(i):To.info(i):To.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),n.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:n,body:void 0};return o.body=gf(i.contentType?i:i.toString(),e,o),o}}function Aee(e){Mg=e,!qv&&(qv=!0,Nf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Ree(t,r)}),e.server.ws(async(t,r,s)=>{el++;let n=new Rs;Fv||(Fv=!0,ru(l=>{el>0&&l.push({metric:"ws-connections",connections:el,byThread:!0})}));let i;t.on("error",l=>{i=!0,To.warn(l)});let o;t.on("message",a(function(d){o||(o=So(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{el--,rs(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=Nf.getMatch(u);if(rs(!!_,"connection","ws","connect"),!_)t.send(Ti(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Hr(h=>({count:h.count,total:el}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ti(E.value,r);t.send(h),Hr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var To,Da,Vt,gee,Mg,xv,qv,Nf,Fv,el,Gv=Re(()=>{ga();bn();To=x(V()),Da=x(re());bf();Ec();Zi();Bu();Hv();Vt=new Uint8Array(8),gee=new Float64Array(Vt.buffer,0,1),Mg={},xv="openapi";a(Ree,"http");el=0;a(Aee,"start")});var Pg=T((sme,kv)=>{var{recordAction:wf,recordActionBinary:Oee}=(bn(),se(su)),bee=require("fastify-plugin"),Nee=200;kv.exports=bee(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let o=n.getResponseTime(),c=performance.now(),u=n.request.routeOptions,_,l,d;u.config?.isOperation?(_=s.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),wf(o,"duration",_,d,l),Oee(n.raw.statusCode<400,"success",_,d,l);let f=Nee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{wf(performance.now()-c,"transfer",_,d,l),wf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,wf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Fg=T((ome,Kv)=>{var Lf=require("clone"),Uf=je(),yee=J(),Cf=L(),nme=V(),vg=require("fs"),Hg=require("joi"),{string:Df}=Hg.types(),{hdb_errors:wee,handleHDBError:If}=re(),{HDB_ERROR_MSGS:ime,HTTP_STATUS_CODES:Bg}=wee,{common_validators:La}=Ys(),Vv=" is required",Iee=["insert","update","upsert"],xg={database:{presence:!1,format:La.schema_format,length:La.schema_length},schema:{presence:!1,format:La.schema_format,length:La.schema_length},table:{presence:!0,format:La.schema_format,length:La.schema_length},action:{inclusion:{within:Iee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Cee={schema:Df.required(),table:Df.required(),action:Df.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Dee,AWS_SECRET:Lee,AWS_BUCKET:Uee,AWS_FILE_KEY:Mee,REGION:Pee}=Cf.S3_BUCKET_AUTH_KEYS,vee={s3:{presence:!0},[`s3.${Dee}`]:{presence:!0,type:"String"},[`s3.${Lee}`]:{presence:!0,type:"String"},[`s3.${Uee}`]:{presence:!0,type:"String"},[`s3.${Mee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Pee}`]:{presence:!0,type:"String"}},$v=Lf(xg);$v.data.presence={message:Vv};var Yv=Lf(xg);Yv.file_path.presence={message:Vv};var Bee=Object.assign(Lf(xg),vee),qg=Lf(Cee);qg.csv_url=Df.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();qg.passthrough_headers=Hg.object();function Hee(e){let t=Uf.validateObject(e,$v);return Mf(e,t)}a(Hee,"dataObject");function xee(e){let t=Uf.validateBySchema(e,Hg.object(qg));return Mf(e,t)}a(xee,"urlObject");function qee(e){let t=Uf.validateObject(e,Yv);return Mf(e,t)}a(qee,"fileObject");function Fee(e){let t=Uf.validateObject(e,Bee);return Mf(e,t)}a(Fee,"s3FileObject");function Mf(e,t){if(!t){let r=yee.checkGlobalSchemaTable(e.schema,e.table);if(r)return If(new Error,r,Bg.BAD_REQUEST);if(e.operation===Cf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{vg.accessSync(e.file_path,vg.constants.R_OK|vg.constants.F_OK)}catch(s){return s.code===Cf.NODE_ERROR_CODES.ENOENT?If(s,`No such file or directory ${s.path}`,Bg.BAD_REQUEST):s.code===Cf.NODE_ERROR_CODES.EACCES?If(s,`Permission denied ${s.path}`,Bg.BAD_REQUEST):If(s)}}return t}a(Mf,"postValidateChecks");Kv.exports={dataObject:Hee,urlObject:xee,fileObject:qee,s3FileObject:Fee}});var Gg=T((cme,Wv)=>{"use strict";var tl=V(),Pf=L();async function Gee(e,t,r,s=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===Pf.OPERATIONS_ENUM.INSERT||t.operation===Pf.OPERATIONS_ENUM.UPDATE||t.operation===Pf.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===Pf.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(tl.info(i.message),i):i.http_resp_msg?(tl.error(`Error calling operation: ${e.name}`),tl.error(i.http_resp_msg),i):(tl.error(`Error calling operation: ${e.name}`),tl.error(i),i)}}a(Gee,"callOperationFunctionAsAwait");Wv.exports={callOperationFunctionAsAwait:Gee}});var zv=T((lme,Qv)=>{"use strict";var kg=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}},Vg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};Qv.exports={BulkLoadFileObject:kg,BulkLoadDataObject:Vg}});var jv=T((dme,Jv)=>{"use strict";var $g=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};Jv.exports=$g});var Jg=T((Sme,E0)=>{"use strict";var vf=Cr(),Hf=Fg(),kee=require("needle"),vs=L(),Eme=Ge(),Ua=J(),{handleHDBError:it,hdb_errors:o0}=re(),{HTTP_STATUS_CODES:$t,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:Ro}=o0,Ma=V(),Yg=require("papaparse");Ua.promisifyPapaParse();var Bs=require("fs-extra"),Vee=require("path"),{chain:Xv}=require("stream-chain"),Zv=require("stream-json/streamers/StreamArray"),e0=require("stream-json/utils/Batch"),t0=require("stream-chain/utils/comp"),{finished:r0}=require("stream"),$ee=Z(),a0=Gg(),Yee=fg(),{BulkLoadFileObject:Wg,BulkLoadDataObject:Kee}=zv(),Qg=sg(),{verifyBulkLoadAttributePerms:c0}=Ef(),hme=jv(),mme=st(),pme=Sn(),{databases:Wee}=(Ae(),se(Fe)),{coerceType:Qee}=(xf(),se(jg)),s0="No records parsed from csv file.",go=`${$ee.get("HDB_ROOT")}/tmp`,{schema_regex:zee}=Ys(),n0=1024*1024*2,i0=5e3,Jee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};E0.exports={csvDataLoad:jee,csvURLLoad:Xee,csvFileLoad:Zee,importFromS3:ete};async function jee(e,t){let r=Hf.dataObject(e);if(r)throw it(r,r.message,$t.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=_0(e.schema,e.table),i=Yg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Kg.bind(null,n),dynamicTyping:!1}),o=new Qg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&c0(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw it(new Error,c,$t.BAD_REQUEST,void 0,void 0,!0);let u=new Kee(e.action,e.schema,e.table,i.data);return s=await a0.callOperationFunctionAsAwait(d0,u,null),s.message===s0?s0:f0(s.records,s.number_written)}catch(n){throw Ao(n)}}a(jee,"csvDataLoad");async function Xee(e){let t=Hf.urlObject(e);if(t)throw it(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${go}/${r}`;try{await tte(e,r)}catch(n){throw Ma.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+n),it(n,Ro(wt.DOWNLOAD_FILE_ERR(r)))}try{let n=new Wg(this.job_operation_function.name,e.action,e.schema,e.table,s,vs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await zg(n);return await Bf(s),i}catch(n){throw await Bf(s),Ao(n)}}a(Xee,"csvURLLoad");async function Zee(e){let t=Hf.fileObject(e);if(t)throw it(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r=new Wg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,vs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await zg(r)}catch(s){throw Ao(s)}}a(Zee,"csvFileLoad");async function ete(e){let t=Hf.s3FileObject(e);if(t)throw it(t,t.message,$t.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=Vee.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${go}/${n}`;let i=new Wg(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await rte(n,e);let o=await zg(i);return await Bf(r),o}catch(s){throw await Bf(r),Ao(s)}}a(ete,"importFromS3");async function tte(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await kee("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw it(s,n,s.statusCode,vs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}nte(r,e.csv_url),await ste(t,r.raw)}a(tte,"downloadCSVFile");async function rte(e,t){try{let r=`${go}/${e}`;await Bs.mkdirp(go),await Bs.writeFile(`${go}/${e}`,"",{flag:"a+"});let s=await Bs.createWriteStream(r),n=await Yee.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){Ma.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ma.error(wt.S3_DOWNLOAD_ERR+" - "+r),it(r,Ro(wt.S3_DOWNLOAD_ERR))}}a(rte,"downloadFileFromS3");async function ste(e,t){try{await Bs.mkdirp(go),await Bs.writeFile(`${go}/${e}`,t)}catch(r){throw Ma.error(wt.WRITE_TEMP_FILE_ERR),it(r,Ro(wt.DEFAULT_BULK_LOAD_ERR))}}a(ste,"writeFileToTempFolder");async function Bf(e){if(e)try{await Bs.access(e),await Bs.unlink(e)}catch{Ma.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Bf,"deleteTempFile");function nte(e,t){if(e.statusCode!==o0.HTTP_STATUS_CODES.OK)throw it(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,$t.BAD_REQUEST);if(!Jee[e.headers["content-type"]])throw it(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,$t.BAD_REQUEST);if(!e.raw)throw it(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,$t.BAD_REQUEST)}a(nte,"validateURLResponse");async function zg(e){try{let t;switch(e.file_type){case vs.VALID_S3_FILE_TYPES.CSV:t=await ite(e);break;case vs.VALID_S3_FILE_TYPES.JSON:t=await ote(e);break;default:throw it(new Error,wt.DEFAULT_BULK_LOAD_ERR,$t.BAD_REQUEST,vs.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return f0(t.records,t.number_written)}catch(t){throw Ao(t)}}a(zg,"fileLoad");async function u0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await vf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&c0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=it(c);r(u)}}a(u0,"validateChunk");async function l0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Ua.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!Ua.isEmpty(c)&&!Ua.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await a0.callOperationFunctionAsAwait(d0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=it(c,Ro(wt.INSERT_CSV_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(l0,"insertChunk");async function ite(e){let t={records:0,number_written:0},r=_0(e.schema,e.table);try{let s=new Qg,n=Bs.createReadStream(e.file_path,{highWaterMark:n0});n.setEncoding("utf8"),await Yg.parsePromise(n,u0.bind(null,e,s),Kg.bind(null,r));let i=s.getPermsResponse();if(i)throw it(new Error,i,$t.BAD_REQUEST);return n=Bs.createReadStream(e.file_path,{highWaterMark:n0}),n.setEncoding("utf8"),await Yg.parsePromise(n,l0.bind(null,e,t),Kg.bind(null,r)),n.destroy(),t}catch(s){throw it(s,Ro(wt.PAPA_PARSE_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+s)}}a(ite,"callPapaParse");function _0(e,t){let r=Wee[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>Qee(i,n));return s}a(_0,"createTransformMap");function Kg(e,t,r){let s=e.get(r);return s?s(t):Ua.autoCast(t)}a(Kg,"typeFunction");async function ote(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Qg,n=Xv([Bs.createReadStream(e.file_path,{encoding:"utf-8"}),Zv.withParser(),c=>c.value,new e0({batchSize:i0}),t0(async c=>{await u0(e,s,r,c)})]);await new Promise((c,u)=>{r0(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw it(new Error,i,$t.BAD_REQUEST);let o=Xv([Bs.createReadStream(e.file_path,{encoding:"utf-8"}),Zv.withParser(),c=>c.value,new e0({batchSize:i0}),t0(async c=>{await l0(e,t,r,c)})]);return await new Promise((c,u)=>{r0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw it(s,Ro(wt.INSERT_JSON_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+s)}}a(ote,"insertJson");async function d0(e){let t={};try{e.data&&e.data.length>0&&ate(e.data[0])?t=await cte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ma.info(t.message))}catch(r){throw Ao(r)}return t}a(d0,"callBulkFileLoad");function ate(e){let t=Object.keys(e);for(let r of t)if(!zee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(ate,"validateColumnNames");async function cte(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=vf.insert;break;case"update":i=vf.update;break;case"upsert":i=vf.upsert;break;default:throw it(new Error,wt.INVALID_ACTION_PARAM_ERR(s),$t.BAD_REQUEST,vs.LOG_LEVELS.ERROR,wt.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Ua.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Ao(o)}}a(cte,"bulkFileLoad");function f0(e,t){return`successfully loaded ${t} of ${e} records`}a(f0,"buildResponseMsg");function Ao(e){return it(e,Ro(wt.DEFAULT_BULK_LOAD_ERR),$t.INTERNAL_SERVER_ERROR,vs.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Ao,"buildTopLevelErrMsg")});var m0=T((gme,h0)=>{"use strict";var Xg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};h0.exports=Xg});var T0=T((Ame,S0)=>{"use strict";var ute=L(),p0=require("moment"),lte=require("uuid").v4,Zg=class{static{a(this,"JobObject")}constructor(){this.id=lte(),this.type=void 0,this.start_datetime=p0().valueOf(),this.created_datetime=p0().valueOf(),this.end_datetime=void 0,this.status=ute.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};S0.exports=Zg});var eR=T((bme,N0)=>{"use strict";var _te=require("uuid").v4,A0=Cr(),O0=es(),dte=Js(),fte=ta(),Ete=m0(),ot=L(),hte=T0(),mte=md(),_s=V(),pte=Ic(),Pa=J(),{promisify:Ste}=require("util"),Oo=require("moment"),Tte=mf(),qf=Fg(),g0=Im(),{deleteTransactionLogsBeforeValidator:gte}=XT(),{handleHDBError:Rte,hdb_errors:Ate}=re(),{HTTP_STATUS_CODES:Ote}=Ate,R0=O0.searchByValue,bte=O0.searchByHash,Nte=A0.insert,yte=Ste(Tte.evaluateSQL),wte=A0.update;N0.exports={addJob:Dte,updateJob:Ute,handleGetJob:Ite,handleGetJobsByStartDate:Cte,getJobById:b0};async function Ite(e){try{let t=await b0(e.id);return Pa.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw _s.error("There was an error getting job",t),new Error(r)}}a(Ite,"handleGetJob");async function Cte(e){try{let t=await Lte(e);if(_s.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=Oo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Oo(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw _s.error(r),new Error(r)}}a(Cte,"handleGetJobsByStartDate");async function Dte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Pa.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return _s.info(l),t.error=l,t}if(!ot.JOB_TYPE_ENUM[e.operation])return _s.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case ot.OPERATIONS_ENUM.CSV_FILE_LOAD:s=qf.fileObject(e);break;case ot.OPERATIONS_ENUM.CSV_URL_LOAD:s=qf.urlObject(e);break;case ot.OPERATIONS_ENUM.CSV_DATA_LOAD:s=qf.dataObject(e);break;case ot.OPERATIONS_ENUM.IMPORT_FROM_S3:s=qf.s3FileObject(e);break;case ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=g0(e,"date");break;case ot.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=g0(e,"timestamp");break;case ot.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=gte(e);break;default:break}if(s)throw Rte(s,s.message,Ote.BAD_REQUEST,void 0,void 0,!0);let n=new hte;n.type=e.operation===ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new dte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await R0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return _s.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=_te();try{o=await R0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return _s.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return _s.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new pte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await Nte(u)}catch(l){return _s.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,_s.trace(l)}return t}a(Dte,"addJob");async function Lte(e){let t=Oo(e.from_date,Oo.ISO_8601),r=Oo(e.to_date,Oo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new Ete(s,e.hdb_user);try{return await yte(n)}catch(i){throw _s.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(Lte,"getJobsInDateRange");async function b0(e){if(Pa.isEmptyOrZeroLength(e))return Pa.errorizeMessage("Invalid job ID specified.");let t=new fte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await bte(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return _s.error(s),Pa.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(b0,"getJobById");async function Ute(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Pa.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ot.JOB_STATUS_ENUM.COMPLETE||e.status===ot.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Oo().valueOf());let t=new mte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await wte(t),r}a(Ute,"updateJob")});var L0=T((yme,D0)=>{"use strict";var y0=J(),Rr=L(),Mte=require("moment"),Ff=Jg(),Gf=V(),w0=eR(),I0=pf(),C0=ti(),Pte=Ke(),vte=lf(),tR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Bte(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(y0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(y0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Rr.JOB_TYPE_ENUM.csv_file_load:await vn(e,Ff.csvFileLoad);break;case Rr.JOB_TYPE_ENUM.csv_url_load:await vn(e,Ff.csvURLLoad);break;case Rr.JOB_TYPE_ENUM.csv_data_load:await vn(e,Ff.csvDataLoad);break;case Rr.JOB_TYPE_ENUM.import_from_s3:await vn(e,Ff.importFromS3);break;case Rr.JOB_TYPE_ENUM.empty_trash:break;case Rr.JOB_TYPE_ENUM.export_local:await vn(e,I0.export_local);break;case Rr.JOB_TYPE_ENUM.export_to_s3:await vn(e,I0.export_to_s3);break;case Rr.JOB_TYPE_ENUM.delete_files_before:case Rr.JOB_TYPE_ENUM.delete_records_before:await vn(e,C0.deleteFilesBefore);break;case Rr.JOB_TYPE_ENUM.delete_audit_logs_before:await vn(e,C0.deleteAuditLogsBefore);break;case Rr.JOB_TYPE_ENUM.delete_transaction_logs_before:await vn(e,vte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Bte,"parseMessage");async function vn(e,t){try{e.job.status=Rr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Mte().valueOf(),await w0.updateJob(e.job),await Hte(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):Gf.error(`There was an error running ${t.name} job with id ${e.job.id}`),Gf.error(s),e.job.message=s,e.job.status=Rr.JOB_STATUS_ENUM.ERROR;try{await w0.updateJob(e.job)}catch(n){throw Gf.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(vn,"runJob");async function Hte(e){Gf.trace("launching job thread:",e),Pte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Rr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Hte,"launchJobThread");D0.exports={parseMessage:Bte,RunnerMessage:tR}});var M0=T((Ime,U0)=>{"use strict";var rR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};U0.exports=rR});var J0=T((Dme,cR)=>{"use strict";var Yf=es(),iR=mf(),kf=Jg(),Bn=lu(),Vf=Xn(),sl=ti(),xte=pS(),rl=ts(),$f=yS(),Yt=jT(),It=V(),qte=CS(),Fte=Id(),P0=lT(),Gte=Dd(),kte=_T(),Vte=dT(),$te=hT(),Yte=pT(),sR=gT(),v0=pf(),Kte=Ef(),oR=eR(),q=L(),{hdb_errors:il,handleHDBError:nl}=re(),{HTTP_STATUS_CODES:B0}=il,nR=NT(),H0=Wd(),K0=require("util"),va=Cr(),Wte=Tn(),Qte=da(),x0=L0(),q0=mu(),F0=(Xd(),se(Hu)),G0=Ur(),k0=lf(),V0=sf(),{setServerUtilities:zte}=(xf(),se(jg)),{CONTEXT:Jte}=(As(),se(Op)),{_assignPackageExport:jte}=require("../index"),{transformReq:Xte}=J(),{server:Zte}=(rr(),se(Mi)),ere=Gg(),$0=Yf.searchByHash,tre=Yf.searchByValue,rre=K0.promisify(Yf.search),sre=K0.promisify(iR.evaluateSQL),nre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},$=M0();async function W0(e,t){try{if(e.body.operation!=="read_log"&&(It.log_level===q.LOG_LEVELS.INFO||It.log_level===q.LOG_LEVELS.DEBUG||It.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;It.info(o)}}catch(s){It.error(s)}let r=await ere.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return nre[e.body.operation]&&Wte.setSchemaDataToGlobal(s=>{s&&It.error(s)}),r}a(W0,"processLocalTransaction");var Y0=ore();cR.exports={chooseOperation:Q0,getOperationFunction:z0,operation:aR,processLocalTransaction:W0};zte(cR.exports);Zte.operation=aR;function Q0(e){let t;try{t=z0(e)}catch(n){throw It.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=iR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=iR.checkASTPermissions(e,i);if(o)throw It.error(`${B0.FORBIDDEN} from operation ${e.operation}`),It.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),nl(new Error,o,il.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Kte.verifyPerms(i,n);if(o)throw It.error(`${B0.FORBIDDEN} from operation ${e.operation}`),It.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),nl(new Error,o,il.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw nl(n,"There was an error when trying to choose an operation path")}return r}a(Q0,"chooseOperation");function z0(e){if(It.trace(`getOperationFunction with operation: ${e.operation}`),Y0.has(e.operation))return Y0.get(e.operation);throw nl(new Error,il.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),il.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(z0,"getOperationFunction");jte("operation",aR);function aR(e,t){e.hdb_user=this[Jte]?.user,e.bypass_auth=!t;let r=Q0(e);return W0({body:e},r)}a(aR,"operation");async function ire(e){It.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await va.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await va.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await va.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await sl.deleteRecord(i);break;default:It.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){It.info("Invalid operation in transaction"),It.error(o)}}a(ire,"catchup");async function cn(e){Xte(e);let t,r;try{r=await oR.addJob(e),t=r.createdJob,It.info("addJob result",r);let s=new x0.RunnerMessage(t,e);return await x0.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw It.error(n),nl(s,n)}}a(cn,"executeJob");function ore(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new $(va.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new $(va.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new $(va.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new $(Yf.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new $($0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new $($0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(tre)),e.set(q.OPERATIONS_ENUM.SEARCH,new $(rre)),e.set(q.OPERATIONS_ENUM.SQL,new $(sre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new $(cn,kf.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new $(cn,kf.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new $(cn,kf.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new $(cn,kf.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new $(Bn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new $(Bn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new $(Bn.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new $(Bn.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new $(Bn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new $(Bn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new $(Bn.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new $(Bn.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new $(Vf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new $(Vf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new $(Vf.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new $(Vf.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new $(sl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new $(rl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new $(rl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new $(rl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new $(rl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new $($f.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new $($f.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new $($f.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new $($f.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new $(rl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new $(qte)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new $(Fte)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new $(P0)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(P0)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new $(Gte)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(kte)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new $(Vte)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new $(G0.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new $($te.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new $(Yte)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(sR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(sR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(sR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new $(cn,v0.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new $(cn,sl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new $(cn,sl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new $(cn,v0.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(oR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new $(oR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new $(nR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new $(nR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new $(nR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new $(H0.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new $(H0.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new $(ire)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $(Qte.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(cn,sl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(xte)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(q0.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(q0.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new $(F0.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new $(F0.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new $(G0.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $(Yt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $(Yt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $(Yt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new $(Yt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $(Yt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new $(Yt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $(Yt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $(Yt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $(Yt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $(Yt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new $(Yt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $(Yt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $(Yt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $(Yt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $(Yt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $(Yt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(k0.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(cn,k0.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $(V0.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $(V0.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new $(Bn.getBackup)),e}a(ore,"initializeOperationFunctionMap")});var Wf=T((Ume,Z0)=>{"use strict";var uR=L(),are=J(),ol=V(),{handleHDBError:lR,hdb_errors:Kf}=re(),{isMainThread:cre}=require("worker_threads"),{Readable:ure}=require("stream"),j0=require("os"),lre=require("util"),_re=qS(),dre=lre.promisify(_re.authorize),X0=J0(),{createGzip:fre,constants:Ere}=require("zlib");function hre(e){let t=`Found an uncaught exception with message: ${e.message}. ${j0.EOL}Stack: ${e.stack} ${j0.EOL}Terminating ${cre?"HDB":"thread"}.`;console.error(t),ol.fatal(t),process.exit(1)}a(hre,"handleServerUncaughtException");function mre(e,t,r){if(ol[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Kf.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(mre,"serverErrorHandler");function pre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=lR(new Error,"Invalid JSON.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(are.isEmpty(e.body.operation)){let s=lR(new Error,"Request body must include an 'operation' property.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(pre,"reqBodyValidationHandler");function Sre(e,t,r){let s;e.body.operation!==uR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==uR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==uR.OPERATIONS_ENUM.LOGOUT?dre(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{ol.warn(n),ol.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(lR(n,i,Kf.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(Sre,"authHandler");async function Tre(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=X0.chooseOperation(e.body);let n=await X0.processLocalTransaction(e,s);if(n instanceof ure&&n.headers){for(let[i,o]of n.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(fre({level:Ere.Z_BEST_SPEED})))}return n}catch(n){throw ol.error(n),n}}a(Tre,"handlePostRequest");Z0.exports={authHandler:Sre,handlePostRequest:Tre,handleServerUncaughtException:hre,serverErrorHandler:mre,reqBodyValidationHandler:pre}});var sB=T((Pme,rB)=>{"use strict";var gre=require("fastify-plugin"),{handlePostRequest:eB,authHandler:Rre,reqBodyValidationHandler:Are}=Wf();async function Ore(e){e.decorate("hdbCore",{preValidation:[Are,Rre],request:t=>tB(eB(t,response)),requestWithoutAuthentication:(t,r)=>tB(eB(t,r,!0))})}a(Ore,"hdbCore");async function tB(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(tB,"convertAsyncIterators");rB.exports=gre(Ore)});var oB=T((Hme,iB)=>{"use strict";var Bme=require("fs"),_R=Z();_R.initSync();var{CONFIG_PARAMS:nB}=L(),bre=1024*1024*1024;function Nre(e){let t=_R.get(nB.HTTP_TIMEOUT),r=_R.get(nB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:bre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Nre,"getServerOptions");iB.exports=Nre});var uB=T((qme,cB)=>{"use strict";var dR=Z();dR.initSync();var{CONFIG_PARAMS:aB}=L();function yre(){let e=dR.get(aB.HTTP_CORSACCESSLIST),t=dR.get(aB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(yre,"getCORSOptions");cB.exports=yre});var dB=T((Gme,_B)=>{"use strict";var lB=Z();lB.initSync();var wre=L();function Ire(){return lB.get(wre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Ire,"getHeaderTimeoutConfig");_B.exports=Ire});var ER={};Ye(ER,{customFunctionsServer:()=>Lre,ready:()=>wB,start:()=>Dre});function Dre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){Hn||(Hn=yB(t),tt.http((await Hn).server));let o=await Hn,c=(0,fR.dirname)(n),u=(0,fR.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!fB.has(c)){fB.add(c);try{o.register(Mre(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}},ready:wB}}async function Lre(){try{Ve.info("In Custom Functions Fastify server"+process.cwd()),Ve.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ve.debug(`Custom Functions server process ${process.pid} starting up.`),await Ure();let e=TB.get(gB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Hn=await yB(e)}catch(r){throw Ve.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ve.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ve.error(`Custom Functions ${process.pid} Error: ${e}`),Ve.error(e),process.exit(1)}}async function Ure(){try{Ve.info("Custom Functions starting configuration."),await RB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function Mre(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,EB.existsSync)(e)&&r.register(SB.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ve.error(n.message):n&&Ve.error(n),o()})}catch(s){Ve.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function yB(e){Ve.info("Custom Functions starting buildServer.");let t=(0,AB.default)(e),r=(0,hB.default)(t);r.server.headersTimeout=(0,bB.default)(),r.setErrorHandler(NB.serverErrorHandler);let s=(0,OB.default)();return s&&r.register(mB.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(pB.default),await r.register(Cre),await r.after(),Rg(r),Ve.info("Custom Functions completed buildServer."),r}function wB(){if(Hn)return Hn.then?Hn.then(e=>e.ready()):Hn.ready()}var fR,EB,hB,mB,pB,SB,TB,gB,Ve,Cre,RB,AB,OB,bB,NB,Hn,fB,IB=Re(()=>{fR=require("path"),EB=require("fs"),hB=x(require("fastify")),mB=x(require("@fastify/cors")),pB=x(Pg()),SB=x(require("@fastify/autoload")),TB=x(Z()),gB=x(L()),Ve=x(V()),Cre=x(sB()),RB=x(ts()),AB=x(oB()),OB=x(uB()),bB=x(dB()),NB=x(Wf());ga();rr();fB=new Set;a(Dre,"start");a(Lre,"customFunctionsServer");a(Ure,"setUp");a(Mre,"buildRouteFolder");a(yB,"buildServer");a(wB,"ready")});var hR={};Ye(hR,{start:()=>Pre});function Pre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,MB.default)(r,e);return e.server.http(async(n,i)=>{if(!n.isWebSocket)return new Promise(o=>s(n._nodeRequest,n._nodeResponse,()=>{o(i(n))}))}),!0}},handleFile(t,r,s){DB||(DB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=CB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,LB.default)(n,(0,UB.realpathSync)(o))}}return i(n)},{runFirst:!0})),CB.set(r,s)}}}var LB,UB,MB,CB,DB,PB=Re(()=>{LB=x(require("send")),UB=require("fs"),MB=x(require("serve-static")),CB=new Map;a(Pre,"start")});function Hre(e,t=1,r){if(mR++,(0,bo.startWorker)("server/threads/threadServer.js",{name:Jf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===Jf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});Bre.push(n),await n,Ba.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=zf.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Ba.indexOf(s);o>-1&&Ba.splice(o,1)}if(a(i,"removeWorker"),Ha){let o=Ha;Ha=[];for(let c of o)xB[c.localPort](null,c)}}}),r){let s=setInterval(()=>{pR?pR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,bo.shutdownWorkers)(),mR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function qB(e=0,t){if(typeof e=="string")try{(0,jf.existsSync)(e)&&(0,jf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=xre:r=qre(t):r=TR;let s=(0,xa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=xB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),pR=!0,r(o,(c,u)=>{if(!c){if(vB){let l=o._socket||new xa.Socket({handle:o,writable:!0,readable:!0});vB.deliverSocket(l,e,u),l.resume()}else mR>0?(Ha.length===0&&setTimeout(()=>{Ha.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Ha.push(o)):(console.log("start up a dynamic thread to handle request"),Hre(0));Hr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new xa.Socket({handle:o,writable:!0,readable:!0});Vre(l,c,e)}Hr(!0,"socket-routed")})};let n=Zc();SR.info(`HarperDB ${n.version} Server running on port ${e}`)}return s.on("error",n=>{console.error("Error in socket server",n)}),process.env._UNREF_SERVER&&s.unref(),s}function TR(e,t){let r,s=0;for(let n of Ba){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=Qf)return Qf=i,t(r);s=i}Qf=0,t(r)}function xre(e,t){let r={};e.getpeername(r);let s=r.address,n=qa.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);TR(e,o=>{qa.set(s,{worker:o,lastUsed:i}),t(o)})}function qre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new xa.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=qa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);TR(s,d=>{qa.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function Gre(){Qf=0;for(let e of Ba)e.expectedIdle=e.recentELU.idle+Fre,e.requests=1;Ba.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Vre(e,t,r){let s=kre++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),zf.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),zf.delete(s)),n.event=="destroy"&&(e.destroy(),zf.delete(s))})}var bo,xa,Jf,SR,jf,HB,vre,Ba,Ha,xB,vB,mR,Bre,pR,Qf,BB,qa,Fre,zf,kre,FB=Re(()=>{bo=x(Ke()),xa=require("net"),Jf=x(L()),SR=x(V()),jf=require("fs");bn();HB=require("worker_threads"),vre=x(Wi()),Ba=[],Ha=[],xB=[],mR=0,Bre=[];HB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Hre,"startHTTPWorker");a(qB,"startSocketServer");Qf=0;a(TR,"findMostIdleWorker");BB=36e5,qa=new Map;a(xre,"findByRemoteAddressAffinity");a(qre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of qa)r.lastUsed+BB<e&&qa.delete(t)},BB).unref();Fre=1e3;a(Gre,"updateWorkerIdleness");(0,bo.setMonitorListener)(Gre);zf=new Map,kre=1;a(Vre,"proxySocket")});var OR={};Ye(OR,{Request:()=>gR,createReuseportFd:()=>Xf});var GB,gR,RR,AR,Xf,Zf=Re(()=>{GB=require("os"),gR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let s=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=s,this.headers=new AR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new RR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},RR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},AR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,s]of this)t(s,r,this)}};(0,GB.platform)()!="win32"&&(Xf=require("node-unix-socket").createReuseportFd)});var YB=T((rpe,$B)=>{"use strict";var $re=require("cluster"),No=Z();No.initSync();var VB=L(),jme=require("util"),xn=V(),Xme=require("fs"),Yre=require("fastify"),Zme=Zc(),Kre=require("@fastify/cors"),Wre=require("@fastify/compress"),Qre=require("@fastify/static"),zre=Pg(),Jre=require("path"),{PACKAGE_ROOT:jre}=L(),Xre=Tn(),Zre=J(),ese=ts(),tse=Wi(),{server:rse}=(rr(),se(Mi)),{node_request_key:epe}=(Zf(),se(OR)),{authHandler:sse,handlePostRequest:nse,serverErrorHandler:ise,reqBodyValidationHandler:ose}=Wf(),tpe=require("net"),{registerContentHandlers:ase}=(ga(),se(wv)),cse=6e4,use=1024*1024*1024,lse="TRUE",{CONFIG_PARAMS:al}=VB,Fa;$B.exports={hdbServer:kB,start:kB};async function kB(e){try{xn.info("In Fastify server"+process.cwd()),xn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),xn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=$re.isMaster,await _se();let t=e.securePort>0;Fa=dse(t),await Fa.ready(),e||(e={}),e.isOperationsServer=!0;try{rse.http(Fa.server,e),Fa.server.closeIdleConnections||await Fa.listen({port:0,host:"::"})}catch(r){throw Fa.close(),xn.error(r),xn.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),xn.fatal(t),process.exit(1)}}a(kB,"operationsServer");async function _se(){xn.trace("Configuring HarperDB process."),Xre.setSchemaDataToGlobal(),await ese.setUsersToGlobal(),await tse.getLicense()}a(_se,"setUp");function dse(e){xn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=fse(e),r=Yre(t);r.server.headersTimeout=hse(),r.setErrorHandler(ise);let s=Ese();s&&r.register(Kre,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(zre),r.register(Wre),r.register(Qre,{root:Jre.join(jre,"studio/build-local")}),ase(r);let n=No.get(VB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Zre.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[ose,sse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),nse(i,o)}),r.get("/health",()=>"HarperDB is running."),xn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(dse,"buildServer");function fse(e){let t=No.get(al.OPERATIONSAPI_NETWORK_TIMEOUT),r=No.get(al.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:use,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(fse,"getServerOptions");function Ese(){let e=No.get(al.OPERATIONSAPI_NETWORK_CORS),t=No.get(al.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===lse)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(Ese,"getCORSOpts");function hse(){return No.get(al.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??cse}a(hse,"getHeaderTimeoutConfig")});var tH=T((ape,eH)=>{"use strict";var{decode:mse}=require("msgpackr"),{isMainThread:npe,parentPort:pse,threadId:ipe}=require("worker_threads"),NR=st(),qn=Ge(),Sse=L(),Ni=V(),KB=Z(),QB=L();Ke();var Tse=Sn(),{recordAction:gse,recordActionBinary:Rse}=(bn(),se(su)),{publishToStream:Ase}=NR,{ConsumerEvents:Ose}=require("nats"),ope={durable:qn.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qn.WORK_QUEUE_CONSUMER_NAMES.deliver_group},bse,Nse,yse,zB,JB;eH.exports={initialize:yR,workQueueListener:ZB,setSubscription:wse,setIgnoreOrigin:Cse,getDatabaseSubscriptions:Ise};async function yR(){JB=!0,Ni.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await NR.getNATSReferences();bse=e,Nse=e.info.server_name,yse=t,zB=r}a(yR,"initialize");var tE=new Map;function wse(e,t,r){let s=tE.get(e);s||tE.set(e,s=new Map),s.set(t,r),JB||yR().then(ZB)}a(wse,"setSubscription");function Ise(){return tE}a(Ise,"getDatabaseSubscriptions");var jB;function Cse(e){jB=e}a(Cse,"setIgnoreOrigin");var XB=100,WB=new Array(XB),eE=0;async function ZB(){let e=await zB.consumers.get(qn.WORK_QUEUE_CONSUMER_NAMES.stream_name,qn.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(pse?.on("message",async s=>{let{type:n}=s;n===QB.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let s of await r.status())if(s.type===Ose.HeartbeatsMissed){let n=s.data;Ni.trace(`${n} clustering ingest consumer heartbeats missed`),n===2&&(Ni.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let s of r)await WB[eE],WB[eE]=Dse(s).catch(n=>{Ni.error(n)}),++eE>=XB&&(eE=0)}catch(s){Ni.error("Error consuming clustering ingest, restarting consumer",s)}NR.clearClientCache(),await yR()}}a(ZB,"workQueueListener");async function Dse(e){let t=mse(e.data);gse(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,s=!1,n=KB.get(Sse.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(qn.MSG_HEADERS.TRANSACTED_NODES)&&r.values(qn.MSG_HEADERS.TRANSACTED_NODES).indexOf(n)>-1&&(s=!0);let i=r.get(qn.MSG_HEADERS.ORIGIN);if(s||(s=i===n&&!jB),Rse(s,"echo",e.subject,t.operation,"ingest"),s){e.ack();return}r.append(qn.MSG_HEADERS.TRANSACTED_NODES,n);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Ni.trace("processing message:",o,c,_,(l?"records: "+l.map(g=>g?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Ni.trace(`messageProcessor nats msg id: ${e.headers.get(qn.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:A}=f||{},R=tE.get(c)?.get(_);if(!R)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,R.send(t);else if(l.length===1&&!u)R.send({type:bR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:A});else{let g=l.map((P,H)=>({type:bR(o),value:P,expiresAt:E,id:d?.[H],table:_}));for(;u;)g.push({type:bR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;R.send({type:"transaction",writes:g,table:_,timestamp:p,onCommit:h,user:S,nodeName:A})}KB.get(QB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Ase(e.subject.split(".").slice(0,-1).join("."),Tse.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ni.error(o)}e.ack()}a(Dse,"messageProcessor");function bR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(bR,"convertOperation")});var UR={};Ye(UR,{disableNATS:()=>Use,publishToStream:()=>oE,setNATSReplicator:()=>wR,setPublishToStream:()=>Mse,setSubscription:()=>LR,start:()=>Lse});function Lse(){sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&vse()}function Use(e=!0){oH=e}function Mse(e,t){oE=e,LR=t}function vse(){if(oH||process.env._DISABLE_NATS)return;let e=Ds(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];wR(n,r,i)}}MR((r,s)=>{wR(r.tableName,r.databaseName,r),s&&cH(r)}),!rH&&(rH=!0)}function wR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(n=>n?.isNATSReplicator))return;r.sourcedFrom(class extends xt{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){cH(i)}static subscribe(){let i=new Rs;return LR(t,e,i),i}static subscribeOnThisThread(i){return i<Pse}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function s(n){let i=n?.transaction?.nats;if(!i)if(n?.transaction){n.transaction.nats=i=new rE(n.transaction,n);let o=n.transaction;for(;o.next;)o=o.next;o.next=n.transaction.nats,i.user=n.user,i.context=n}else i=aH;return i}a(s,"getNATSTransaction")}function cH(e){let t=sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);oE(`${CR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,DR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var sH,CR,DR,nH,iH,sE,nE,iE,oH,oE,LR,Pse,aH,rH,rE,IR,uH=Re(()=>{Ae();As();sH=x(st()),CR=x(Ge()),DR=x(Sn());Ec();nH=x(tH()),iH=x(yr()),sE=x(Z()),nE=x(L()),iE=x(V());a(Lse,"start");a(Use,"disableNATS");oE=sH.publishToStream,LR=nH.setSubscription;a(Mse,"setPublishToStream");Pse=2;a(vse,"assignReplicationSource");a(wR,"setNATSReplicator");a(cH,"publishSchema");rE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let s=this.writes_by_db.get(t);s||this.writes_by_db.set(t,s=[]),s.push(r)}commit({timestamp:t}){let r=sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(iE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&s.push(oE(`${CR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,DR.createNatsTableStreamName)(n,u.table),void 0,u)?.catch(l=>{throw iE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(s)}},IR=class extends rE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,iH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};aH=new IR});var bH=T(yo=>{"use strict";var{isMainThread:hH,parentPort:ul,threadId:aE}=require("worker_threads"),{Socket:Bse,createServer:Hse}=require("net"),{createServer:xse,IncomingMessage:qse}=require("http"),{createServer:Fse}=require("https"),{readFileSync:Ga,unlinkSync:lH,existsSync:Gse}=require("fs"),jt=V(),De=Z(),Tt=L(),{server:_E}=(rr(),se(Mi)),{WebSocketServer:kse}=require("ws"),{createServer:Vse}=require("tls"),{getTicketKeys:$se,restartNumber:Yse,getWorkerIndex:uE}=Ke(),{Headers:mH,appendHeader:Kse}=(Bu(),se(jM)),{recordAction:cl,recordActionBinary:Wse}=(bn(),se(su)),{Request:pH,createReuseportFd:_H}=(Zf(),se(OR)),{checkMemoryLimit:Qse}=Wi(),SH=require("tls"),dH=SH.createSecureContext;SH.createSecureContext=function(e){if(!e.cert||!e.key)return dH(e);let t={...e};delete t.key,delete t.cert;let r=dH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var TH=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG);if(TH){let e;if(hH)e=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){jt.info("Could not close debugger",t)}});else{let t=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&uE()>=0&&(e=t+uE())}if(e){let t=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=De.get(Tt.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(s){jt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,s.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){Yse<=1&&jt.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:Epe,CONFIG_PARAMS:zse}=Tt;De.initSync();var Jse=De.get(zse.HTTP_SESSIONAFFINITY),un={};yo.registerServer=xR;yo.httpServer=qR;yo.deliverSocket=HR;yo.startServers=gH;yo.when_components_loaded=null;_E.http=qR;_E.request=ene;_E.socket=tne;_E.ws=rne;var PR={},cE={},jse,yi={},lE={},Xse=[],vR=[];function gH(){return yo.when_components_loaded=FR().loadRootComponents(!0).then(()=>{ul?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)HR(s,r,n);else if(t.requestId)Zse(t);else if(t.type===Tt.ITC_EVENT_TYPES.SHUTDOWN){jt.trace("received shutdown request",aE);for(let i in un){let o=un[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(f=>f.description.includes("connections")),l=0,d=setInterval(()=>{l++;let f=l>=100,E=o[_][f?"all":"idle"]();if(E.length===0){f&&clearInterval(d);return}l===1?jt.info(`Closing ${E.length} idle connections`):f&&jt.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,p=E.length;h<p;h++){let S=E[h].socket;S._httpMessage&&!S._httpMessage.finished&&!f||(f?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
|
|
27
27
|
Connection: close\r
|
|
28
28
|
\r
|
|
29
|
-
`))}},25).unref()}o.close?.(()=>{if(
|
|
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: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"&&!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(De.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&uE()==0)try{lH(De.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,aE),o.cantCleanupProperly||jt.warn("Had to forcefully exit the thread",aE),process.exit(0)},5e3).unref()})}if(TH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){jt.info("Could not close debugger",i)}}}).ref();let e=[];if(_H&&!Jse)for(let t in un){let r=un[t];if(isNaN(t)&&uE()==0){Gse(t)&&lH(t),e.push(new Promise((n,i)=>{r.listen({path:t},()=>{n(),jt.info("Domain socket listening on "+t)}).on("error",i)}));continue}let s;try{s=_H(+t,"::")}catch(n){console.error(`Unable to bind to port ${t}`,n);continue}e.push(new Promise((n,i)=>{r.listen({fd:s},()=>{n(),jt.trace("Listening on port "+t,aE)}).on("error",i)}))}Promise.all(e).then(()=>{ul?.postMessage({type:Tt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(gH,"startServers");hH||gH();function HR(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):(jt.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(HR,"deliverSocket");var fH=new Map;function Zse(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=fH.get(n),r){case"connection":i=HR(void 0,t),fH.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 xR(e,t,r=!0){!+t&&t!==De.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(De.get(Tt.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",EH),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",EH)}a(xR,"registerServer");function RH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],De.get(Tt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:De.get(Tt.CONFIG_PARAMS.HTTP_PORT),secure:De.get(Tt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),De.get(Tt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:De.get(Tt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&De.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:De.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(RH,"getPorts");function qR(e,t){for(let{port:r,secure:s}of RH(t))AH(r,s,t?.isOperationsServer),typeof e=="function"?vR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=s,xR(e,r,!1)),lE[r]=BR(vR,r),jse=BR(Xse,r)}a(qR,"httpServer");function AH(e,t,r){if(!yi[e]){let s=r?"operationsApi_network":"http",n={keepAliveTimeout:De.get(s+"_keepAliveTimeout"),headersTimeout:De.get(s+"_headersTimeout"),requestTimeout:De.get(s+"_timeout")},i=De.get(s+"_mtls"),o=De.get(s+"_mtls_required");if(t){s=r?"operationsApi_":"";let u=De.get(s+"tls_privateKey"),_=De.get(s+"tls_certificate"),l=De.get(s+"tls_certificateAuthority");Object.assign(n,{allowHTTP1:!0,key:Ga(u),ciphers:De.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 lE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=OH(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?jt.warn(d):jt.info(d):jt.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),xR(yi[e],e)}return yi[e]}a(AH,"getHTTPServer");function BR(e,t){let r=OH;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(BR,"makeCallbackChain");function OH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new mH}}a(OH,"unhandled");function ene(e,t){qR(e,{requestOnly:!0,...t})}a(ene,"onRequest");function tne(e,t){let r;if(t.securePort){let s=De.get("tls_privateKey"),n=De.get("tls_certificate"),i=t.mtls?.certificateAuthority||De.get("tls_certificateAuthority");r=Vse({ciphers:De.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 RH(t)){cE[s]||(cE[s]=new kse({server:r=AH(s,n)}),cE[s].on("connection",async(c,u)=>{try{let _=new pH(u);_.isWebSocket=!0;let l=lE[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(_){jt.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}),lE[s]=BR(vR,s)}return r}a(rne,"onWebSocket");function EH(e,t){t.writeHead(404),t.end(`Not found
|
|
30
|
+
`)}a(EH,"defaultNotFound")});async function IH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await GR.get(e,{returnNonexistent:!0});n=new $R(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await GR.get(e);i&&i.delete()}n=new fE(e,t)}return s&&(s.id=e,s.user={username:t?.username},ll.put(s)),n}function kR(){return dE++,dE>65500&&(dE=1),dE}function VR(e,t,r=e){let{topic:s,retain:n}=e;e.data=t,e.async=!0,e.authorize=!0;let i=pi.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Xe(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var NH,wi,yH,wH,GR,ll,dE,fE,$R,CH=Re(()=>{Ae();vu();NH=x(yr()),wi=x(V());Zi();yH=x(Ke()),wH=x(bH());rr();GR=ct({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),ll=ct({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,yH.getWorkerIndex)()===0&&(async()=>{await wH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of ll.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await tt.getUser(r.user.username)),Xe(r,()=>{try{VR(r,t)}catch{(0,wi.warn)("Failed to publish will",t)}ll.delete(e.id,r)})}})();a(IH,"getSession");dE=1;a(kR,"getNextMessageId");fE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,rh:i,startTime:o}=t,c=n.indexOf("?"),u,_;if(c>-1?(u=n.slice(c),_=n.slice(0,c)):_=n,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(A=>A.topic===n),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,wi.trace)("Resuming subscription from",n,"from",o);let E=pi.getMatch(_);if(!E){let A=new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);throw A.statusCode=404,A}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let A=f.url.slice(1);if(A.indexOf("#")>-1&&A.indexOf("#")!==A.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,A.indexOf("+")===A.length-1)f.onlyChildren=!0,f.url="/"+A.slice(0,A.length-1);else{let R=A.split("/"),g;for(let v=0;v<R.length;v++)if(R[v].indexOf("+")>-1)if(R[v]==="+")g=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(s&&g)throw new Error("Filters can not be combined");let P=!0;R[R.length-1]==="#"&&(R.length--,P=!1),g&&(s=a(v=>{let U=v.id;if(!Array.isArray(U)||P&&U.length!==R.length)return!1;for(let Y=0;Y<R.length;Y++)if(R[Y]!=="+"&&R[Y]!==U[Y])return!1;return!0},"filter"));let H=R.indexOf("+");f.url="/"+(H>-1?R.slice(0,H):R).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Xe(f,async()=>{let A=await p.subscribe(f);if(!A)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!A[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let R of A)try{let g;if(R.type&&R.type!=="put"&&R.type!=="delete"&&R.type!=="message"&&R.type!=="patch"||s&&!s(R))continue;r?(R.topic=n,g=this.needsAcknowledge(R)):(R.acknowledge?.(),g=kR());let P=R.id;Array.isArray(P)&&(P=Ta(P)),P==null&&(P=""),this.listener(h+"/"+P,R.value,g,t)}catch(g){(0,wi.warn)(g)}})(),A});return S.topic=n,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=kR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,VR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Xe(r,async()=>{if(!t){let s=await ll.get(this.sessionId,r);s?.doesExist()&&await VR(s,s.data,r)}await ll.delete(this.sessionId,r)}).catch(s=>{(0,wi.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(VR,"publish");$R=class extends fE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=kR(),s={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(s.acknowledge=t.acknowledge),this.awaitingAcks.set(r,s),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,wi.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,NH.getNextMonotonicTime)()),(0,wi.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),GR.put(this.sessionRecord)),t.qos}}});var YR={};Ye(YR,{bypassAuth:()=>sne,start:()=>nne});function sne(){PH=!0}function nne({server:e,port:t,network:r,webSocket:s,securePort:n,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return s&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=UH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Ar.info)("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},s))),(t||n)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Ar.error)(E)}else if(u.required)return(0,Ar.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&PH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,MH.getSuperUser)());let{onMessage:d,onClose:f}=UH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Ar.info)("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function UH(e,t,r,s,n){LH||(LH=!0,ru(d=>{EE>0&&d.push({metric:"mqtt-connections",connections:EE,byThread:!0})}));let i;EE++;let o,c={protocolVersion:4},u=(0,mE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){EE--,i||(i=!0,o?.disconnect(),n.sessions.delete(o),rs(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{s?.then&&(s=await s),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{s=await tt.getUser(d.username,d.password.toString(),r),(0,hE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&DH.notify({username:s.username,status:ln.AUTH_AUDIT_STATUS.SUCCESS,type:ln.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,hE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&DH.error({username:s.username,status:ln.AUTH_AUDIT_STATUS.FAILURE,type:ln.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return rs(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let g=e.deserialize||(e.deserialize=So(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?g(d.will.payload):void 0,delete d.will.payload}o=IH({user:s,...d}),o=await o,n.sessions.add(o)}catch(g){return(0,Ar.error)(g),rs(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:g.code||5,returnCode:g.code||128})}rs(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((g,P,H,v)=>{try{let U=g.indexOf("/",1),Y=U>0?g.slice(0,U):g;f({cmd:"publish",topic:g,payload:E(P),messageId:H||Math.floor(Math.random()*1e8),qos:v.qos},Y)}catch(U){(0,Ar.error)(U),o?.disconnect(),n.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let g of d.subscriptions){let P;try{P=(await o.addSubscription(g,g.qos>=1)).qos||0}catch(H){(0,Ar.error)(H),P=c.protocolVersion<5?128:H.statusCode===403?135:H.statusCode===404?143:128}h.push(P)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let g=[];for(let P of d.unsubscriptions)g.push(o.removeSubscription(P)?0:17);f({cmd:"unsuback",granted:g,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=So(r?.headers.get?.("content-type"))),A=d.payload?.length>0?S(d.payload):void 0,R;try{R=await o.publish(d,A)}catch(g){(0,Ar.warn)(g),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:R===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),n.sessions.delete(o),rs(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Ar.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,mE.generate)(h,c);t(S),Hr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ti(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var mE,MH,hE,ln,Ar,DH,PH,LH,EE,vH=Re(()=>{mE=require("mqtt-packet");CH();MH=x(ts());ga();bn();rr();hE=x(Z()),ln=x(L()),Ar=x(V()),DH=(0,Ar.loggerWithTag)("auth-event"),PH=(0,hE.get)(ln.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(sne,"bypassAuth");a(nne,"start");EE=0;a(UH,"onSocket")});var af={};Ye(af,{component_errors:()=>Va,loadComponent:()=>pE,loadComponentDirectories:()=>$H,setErrorReporter:()=>cne});function $H(e,t){t&&(WR=t),e&&(QR=e);let r=[];if((0,Hs.existsSync)(KR)){let n=(0,Hs.readdirSync)(KR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,gt.join)(KR,o);r.push(pE(c,WR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(pE(s,WR,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{VH=!0})}function cne(e){dl=e}async function pE(e,t,r,s,n,i){if(!HH.has(e)){HH.set(e,!0),n&&(QR=n);try{let o;s&&(Va=new Map);let c=(0,gt.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Hs.existsSync)(c)?o=s?(0,kH.getConfigObj)():(0,xH.parseDocument)((0,Hs.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=zR;let u=[],_=s;for(let l in o){let d=o[l];if(Va.set(s?l:(0,gt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let R=e,g;for(;!(0,Hs.existsSync)(g=(0,gt.join)(R,"node_modules",l));)if(R=(0,gt.dirname)(R),R.length<(0,GH.getHdbBasePath)().length){g=null;break}if(g)f=await pE(g,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=ane[l];if(!f)continue;u.push(f);let h=a(R=>(R.origin=r,ct(R)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,A=!p?.https&&p?.port;if(ka.isMainThread&&(f=await f.startOnMainThread?.({server:tt,ensureTable:h,port:A,securePort:S,resources:t,...d})||f,s&&p))for(let R of[A,S])try{if(+R&&!BH.includes(R)){let g=JR.get(jR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&_l.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!Xf)&&(BH.push(R),qB(R,g))}}catch(g){console.error("Error listening on socket",R,g,l)}if(t.isWorker&&(f=await f.start?.({server:tt,ensureTable:h,port:A,securePort:S,resources:t,...d})||f),QR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,FH.handleHDBError)("Can not reference parent directories");let R=(0,gt.join)(e,d.files).replace(/\\/g,"/"),g=R.indexOf("/*");if(g>-1&&d.files!==zR[l]?.files&&!(0,Hs.existsSync)(R.slice(0,g)))throw new Error(`The path '${R.slice(0,g)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let P=(0,gt.basename)(e),H=d.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+P+H.slice(2):H==="."?"/"+P:"/"+P+"/"+H;let v,U,Y;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",U=(0,gt.join)(e,z)}else(Y=R.indexOf("/*"))>-1&&(U=R.slice(0,Y+1),v=(0,gt.relative)(e,U));let K=!1;if(ka.isMainThread&&f.setupDirectory&&(K=await f.setupDirectory?.(H,U,t)),t.isWorker&&f.handleDirectory&&(K=await f.handleDirectory?.(H,U,t)),K)continue;for(let z of await(0,qH.default)(R,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:me}=z;_=!0;let ce=(0,gt.relative)(e,ne).replace(/\\/g,"/");if(v)if(ce.startsWith(v))ce=ce.slice(v.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${ce}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let xe=H+(H.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let le=await one(ne);ka.isMainThread&&await f.setupFile?.(le,xe,ne,t),t.isWorker&&await f.handleFile?.(le,xe,ne,t)}else ka.isMainThread&&await f.setupDirectory?.(xe,ne,t),t.isWorker&&await f.handleDirectory?.(xe,ne,t)}catch(le){le.message=`Could not load ${me.isFile()?"file":"directory"} '${ne}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${le.message}`,dl?.(le),((0,$a.getWorkerIndex)()===0?console:_l.default).error(le),t.set(d.path||"/",new fl(le)),Va.set(s?l:(0,gt.basename)(e),le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,gt.basename)(e)}' due to: ${h.message}`,dl?.(h),((0,$a.getWorkerIndex)()===0?console:_l.default).error(h),t.set(d.path||"/",new fl(h),null,!0),Va.set(s?l:(0,gt.basename)(e),h.message)}}if(ka.isMainThread&&!VH&&i&&(0,$a.watchDir)(e,async()=>$H()),o.extensionModule)return await Ql((0,gt.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;dl?.(new Error(l)),((0,$a.getWorkerIndex)()===0?console:_l.default).error(l),Va.set((0,gt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,dl?.(o),t.set("",new fl(o))}}}var Hs,gt,ka,xH,JR,jR,qH,$a,_l,FH,GH,ine,kH,one,KR,QR,VH,WR,Va,ane,zR,BH,HH,dl,fl,cf=Re(()=>{Hs=require("fs"),gt=require("path"),ka=require("worker_threads"),xH=require("yaml"),JR=x(Z()),jR=x(L());jO();tb();rb();Gv();IB();PB();qH=x(require("fast-glob")),$a=x(Ke()),_l=x(V());yh();rr();FH=x(re());As();Ae();FB();GH=x(Z()),ine=x(YB());Xd();uH();vH();kH=x(Ur());Zf();({readFile:one}=Hs.promises),KR=JR.get(jR.CONFIG_PARAMS.COMPONENTSROOT),QR=new Map,Va=new Map;a($H,"loadComponentDirectories");ane={REST:yf,rest:yf,graphqlSchema:Nh,jsResource:Ih,fastifyRoutes:ER,login:Dh,static:hR,operationsApi:ine,customFunctions:{},http:{},clustering:UR,authentication:Hu,mqtt:YR},zR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(zR,"static",{value:{files:"web/**"}});BH=[],HH=new Map;a(cne,"setErrorReporter");a(pE,"loadComponent");fl=class extends xt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var FR=T((Fpe,KH)=>{var{isMainThread:YH}=require("worker_threads"),{getTables:une}=(Ae(),se(Fe)),{loadComponentDirectories:lne,loadComponent:_ne}=(cf(),se(af)),{resetResources:dne}=(vu(),se(JM)),fne=QT(),Ene=Ur(),{dirname:hne}=require("path"),{getConnection:mne}=st(),pne=Z(),Sne=L(),XR=new Map;async function Tne(e=!1){!YH&&pne.get(Sne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&mne();try{YH&&await fne()}catch(s){console.error(s)}let t=dne();une(),t.isWorker=e,await _ne(hne(Ene.getConfigFilePath()),t,"hdb",!0,XR),await lne(XR,t);let r=[];for(let[s]of XR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Tne,"loadRootComponents");KH.exports.loadRootComponents=Tne});var Ke=T((kpe,Ci)=>{"use strict";var{Worker:gne,MessageChannel:Rne,parentPort:_n,isMainThread:sA,threadId:Ane,workerData:Fn}=require("worker_threads"),{PACKAGE_ROOT:One}=L(),{join:JH,isAbsolute:bne,extname:Nne}=require("path"),{server:jH}=(rr(),se(Mi)),{watch:yne,readdir:wne}=require("fs/promises"),{totalmem:WH}=require("os"),El=L(),XH=Z(),Gn=V(),{randomBytes:Ine}=require("crypto"),{_assignPackageExport:Cne}=require("../index"),Dne=L(),QH=1024*1024,Ii=[],ds=[],Lne=50,nA=1e4,Une="restart",ZH="request_thread_info",ex="resource_report",tx="thread_info",rx="added-port",Mne="ack",ZR;Cne("threads",ds);Ci.exports={startWorker:eA,restartWorkers:oA,shutdownWorkers:xne,workers:Ii,setMonitorListener:Kne,onMessageFromWorkers:qne,onMessageByType:ux,broadcast:Gne,broadcastWithAcknowledgement:Vne,setChildListenerByType:Hne,getWorkerIndex:sx,getWorkerCount:nx,getTicketKeys:ox,setMainIsWorker:vne,setTerminateTimeout:Pne,restartNumber:Fn?.restartNumber||1};ds.onMessageByType=ux;ds.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ds.find(s=>s.threadId===e);if(r)return r.postMessage(t),!0};var iA;function Pne(e){nA=e}a(Pne,"setTerminateTimeout");function sx(){return Fn?Fn.workerIndex:iA?0:void 0}a(sx,"getWorkerIndex");function nx(){return Fn?Fn.workerCount:iA?1:void 0}a(nx,"getWorkerCount");function vne(e){iA=e}a(vne,"setMainIsWorker");var ix=1,SE;function ox(){return SE||(SE=sA?Ine(48):Fn.ticketKeys,SE)}a(ox,"getTicketKeys");Object.defineProperty(jH,"workerIndex",{get(){return sx()}});Object.defineProperty(jH,"workerCount",{get(){return nx()}});var ax={[ZH](e,t){$ne(t)},[ex](e,t){Yne(t,e)}};function eA(e,t={}){let r=process.constrainedMemory?.()||WH();r=Math.min(r,WH(),2e4*QH);let s=XH.get(El.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/QH/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of ds){let _=new Rne;_.existingPort=u,i.push(_),o.push(_.port2)}Nne(e)||(e+=".js");let c=new gne(bne(e)?e:JH(One,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:ix=t.threadCount,name:t.name,restartNumber:Ci.exports.restartNumber,ticketKeys:ox()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:rx,port:u,threadId:c.threadId},[u]);return gE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>eA(e,t),c.on("error",u=>{console.error("Worker error:",u),Gn.error("Worker error:",u)}),c.on("exit",u=>{Ii.splice(Ii.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Lne?(t.unexpectedRestarts=c.unexpectedRestarts+1,eA(e,t)):Gn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{ax[u.type]?.(u,c)}),Ii.push(c),Qne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(eA,"startWorker");var Bne=[El.THREAD_TYPES.HTTP];async function oA(e=null,t=Math.max(ix>3,1),r=!0){if(sA){if(r){let{loadRootComponents:o}=FR();await o()}Ci.exports.restartNumber++,t<1&&(t=t*Ii.length);let s=[],n=[];for(let o of Ii.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Gn.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ci.exports.restartNumber,type:El.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Bne.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),nA*2).unref();o.on("exit",()=>{clearTimeout(l),s.splice(s.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(s.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===Dne.ITC_EVENT_TYPES.CHILD_STARTED&&(Gn.trace("Worker has started",_.threadId),d(),n.splice(n.indexOf(l)),_.off("message",f))},"startListener");Gn.trace("Waiting for worker to start",_.threadId),_.on("message",f)});n.push(l),s.length>=t&&await Promise.race(s),n.length>=t&&await Promise.race(n)}}await Promise.all(s),await Promise.all(n);let{restartService:i}=Wd();r&&(e==="http"||!e)&&XH.get(El.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else _n.postMessage({type:Une,workerType:e})}a(oA,"restartWorkers");function Hne(e,t){ax[e]=t}a(Hne,"setChildListenerByType");function xne(e){return oA(e,1/0,!1)}a(xne,"shutdownWorkers");var cx=[];function qne(e){cx.push(e)}a(qne,"onMessageFromWorkers");var tA=new Map;function ux(e,t){let r=tA.get(e);r||tA.set(e,r=[]),r.push(t)}a(ux,"onMessageByType");var Fne=10;async function Gne(e){let t=0;for(let r of ds)try{r.postMessage(e),t++>Fne&&(t=0,await new Promise(setImmediate))}catch(s){Gn.error("Unable to send message to worker",s)}}a(Gne,"broadcast");var TE=new Map,kne=1;function Vne(e){return new Promise(t=>{let r=0;for(let s of ds)try{let n=kne++,i=a(()=>{TE.delete(n),--r===0&&t(),s!==_n&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,TE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of TE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){Gn.error("Unable to send message to worker",n)}r===0&&t()})}a(Vne,"broadcastWithAcknowledgement");function $ne(e){e.postMessage({type:tx,workers:lx()})}a($ne,"sendThreadInfo");function lx(){let e=Date.now();return Ii.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(lx,"getChildWorkerInfo");function Yne(e,t){e.resources=t,e.resources.updated=Date.now()}a(Yne,"recordResourceReport");var rA;function Kne(e){rA=e}a(Kne,"setMonitorListener");var Wne=1e3,zH=!1;function Qne(){zH||(zH=!0,setInterval(()=>{for(let e of Ii){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}rA&&rA()},Wne).unref())}a(Qne,"startMonitoring");var zne=1e3;if(_n){gE(_n);for(let e=0,t=Fn.addPorts.length;e<t;e++){let r=Fn.addPorts[e];r.threadId=Fn.addThreadIds[e],gE(r)}setInterval(()=>{let e=process.memoryUsage();_n.postMessage({type:ex,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},zne).unref(),ZR=a(()=>new Promise((e,t)=>{_n.on("message",r),_n.postMessage({type:ZH});function r(s){s.type===tx&&(_n.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else ZR=lx;Ci.exports.getThreadInfo=ZR;function gE(e,t){ds.push(e),e.on("message",r=>{if(r.type===rx)r.port.threadId=r.threadId,gE(r.port);else if(r.type===Mne){let s=TE.get(r.id);s&&s()}else{for(let n of cx)n(r,e);let s=tA.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){Gn.error(i)}}}).on("close",()=>{ds.splice(ds.indexOf(e),1)}).on("exit",()=>{ds.splice(ds.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(gE,"addPort");if(sA){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await wne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(JH(s,i.name));try{for await(let{filename:i}of yne(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await oA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");Ci.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else _n.on("message",async e=>{let{type:t}=e;t===El.ITC_EVENT_TYPES.SHUTDOWN&&(Ci.exports.restartNumber=e.restartNumber,_n.unref(),setTimeout(()=>{Gn.warn("Thread did not voluntarily terminate",Ane),process.exit(0)},nA).unref())})});var aC={};Ye(aC,{AUDIT_STORE_OPTIONS:()=>gx,createAuditEntry:()=>Zl,openAuditStore:()=>bE,readAuditEntry:()=>Lt,setAuditRetention:()=>jne,transactionKeyEncoder:()=>Tx});function bE(e){let t=e.auditStore=e.openDB(mx.AUDIT_STORE_NAME,gx);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=RE){clearTimeout(s),s=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-aA})){if((_[0]&15)===lA){let l=Lt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Jne){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,aA/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,OE.getWorkerIndex)()===(0,OE.getWorkerCount)()-1&&n(RE),t}function jne(e,t=RE){aA=e,RE=t}function Zl(e,t,r,s,n,i,o){let c=Rx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?Ya.setFloat64(0,s):Es.set(Wh),u=9),f(0),f(t),d(r),Ya.setFloat64(u,e),u+=8,n?d(n):Es[u++]=0,Es[s?8:0]=c;let l=Es.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Ka.writeKey)(E,Es,u);let p=u-h-1;p>127?p>16383?(dA.error("Key or username was too large for audit entry",E),u=h+1,Es[h]=0):(Es.copyWithin(h+2,h+1,u),Ya.setUint16(h,p|32768),u++):Es[h]=p}function f(E){E<128?Es[u++]=E:E<16384?(Ya.setUint16(u,E|32768),u+=2):E<1056964608?(Ya.setUint32(u,E|3221225472),u+=4):(Es[u]=255,Ya.setUint32(u+1,E),u+=5)}}function Lt(e){try{let t=e.dataView||(e.dataView=new _A(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let s=t.readInt(),n=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:Rx[s&7],tableId:i,get recordId(){return hx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?hx(e,l,d):void 0},getValue(f,E,h){if(s&cA||s&uA&&!E)return f.decoder.decode(e.subarray(t.position));if(s&uA&&h)return fA(f.getEntry(this.recordId),h,f)}}}catch{return dA.error("Reading audit entry error",e),{}}}function hx(e,t,r){let s=e.subarray(t,r);return(0,Ka.readKey)(s,0,r-t)}var Ka,AE,mx,px,OE,Sx,dA,Es,Ya,Tx,gx,aA,Jne,RE,cA,uA,_x,lA,dx,fx,Ex,Rx,_A,Bi=Re(()=>{Ka=require("ordered-binary"),AE=x(Z()),mx=x(dt()),px=x(L()),OE=x(Ke()),Sx=x(J());qo();dA=x(V());NE();(0,AE.initSync)();Es=Buffer.alloc(1024),Ya=new DataView(Es.buffer,Es.byteOffset,1024),Tx={writeKey(e,t,r){return e===gc?(t.set(gc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Ka.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Ka.readKey)(e,t,r)}},gx={encoding:"binary",keyEncoder:Tx},aA=(0,Sx.convertToMS)((0,AE.get)(px.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Jne=1e3,RE=1e4;a(bE,"openAuditStore");a(jne,"setAuditRetention");cA=16,uA=32,_x=1,lA=2,dx=3,fx=4,Ex=5,Rx={put:_x|cA,[_x]:"put",delete:lA,[lA]:"delete",message:dx|cA,[dx]:"message",invalidate:fx,[fx]:"invalidate",patch:Ex|uA,[Ex]:"patch"};a(Zl,"createAuditEntry");a(Lt,"readAuditEntry");_A=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(hx,"readKeySafely")});var EA={};Ye(EA,{add:()=>yE,applyReverse:()=>Ax,getRecordAtTime:()=>fA,rebuildUpdateBefore:()=>wE});function yE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function wE(e,t){let r=null;for(let s in e)if(s in t){let n=t[s];if(n?.__op__){let i=e[s];if(i?.__op__)if(i.__op__===n.__op__)r||(r={}),r[s]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[s]=i,yE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function Ax(e,t){for(let r in t){let s=t[r];if(s?.__op__){let n=Xne[s.__op__]?.reverse;if(n)n(e,r,{value:s.value});else throw new Error(`Unsupported operation ${s.__op__}`)}else e[r]=Ox}}function fA(e,t,r){let s=r.rootStore.auditStore,n=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=s.get(i),_=Lt(u);switch(_.type){case"put":n=_.getValue(r);break;case"patch":Ax(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===Ox&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=s.get(i),_=Lt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(n[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)n[u]=null;return n}var Xne,Ox,NE=Re(()=>{Bi();a(yE,"add");yE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Xne={add:yE};a(wE,"rebuildUpdateBefore");a(Ax,"applyReverse");Ox={};a(fA,"getRecordAtTime")});function $r(e){return e[Ct]||(e[Ct]=Object.create(null))}function UE(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Oe])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a string, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a string, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a number, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new hs.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new hs.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new hs.ClientError(`${c} must be a number, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a boolean, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new hs.ClientError(`${c} must be a Date, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);$r(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){$r(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new hs.ClientError(`${c} must be an object, attempt to assign ${l}`);$r(this)[c]=l},"set")}_={get(){let l=this[Ct];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[de]?.[c];return f.update(E)}return f}let d=this[de]?.[c];if(d&&typeof d=="object"){let f=Nx(d,o);if(f)return l||(l=this[Ct]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,s[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Ct];return u?.[o]!==void 0?u[o]:this[de]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new hs.ClientError("Can not add a property to a sealed table schema");$r(this)[o]=c}),i("deleteProperty",function(o){$r(this)[o]=void 0}),i("toJSON",function(){let o=this[Ct],c;for(let _ in o){c||(c=Object.assign({},this[de]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[de])),Object.assign(c,this)),c||this[de]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function Nx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){if(n?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=n}},UE(r,t)),new r(e)):new IE(e);case Array:let s=new DE(e.length);s[de]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=Nx(o,t?.elements)),s[n]=o}return s;default:return e}}function z_(e){let t=e[Ct],r;for(let n in t){r||(r=Object.assign({},e[de]));let i=t[n];if(i&&typeof i=="object")if(i.__op__){let o=r[n];i=i.update(o)}else i=z_(i);r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[de])),Object.assign(r,e)),r||e[de]}function Io(e,t=e[Ct]){let r;if(bx.call(e,de)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=Io(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[s]=i}return Object.freeze(r)}for(let s in t){r||(r=Object.assign({},e[de]));let n=t[s];if(n&&typeof n=="object")if(n.__op__){let i=EA[n?.__op__];if(i)i(r,s,n);else throw new Error("Invalid CRDT operation "+n.__op__);continue}else n=Io(n);r[s]=n}return r?Object.freeze(r):bx.call(e,de)?e[de]:e}function CE(e){let t=e[de];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[wo]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[de]===n){if(CE(i))return!0}else return!0}}else{let r=e[Ct];if(r&&!t)return!0;for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[de]===i){if(CE(n))return!0}else return!0}else return!0}}return!1}var hs,Ct,IE,bx,wo,DE,LE,J_=Re(()=>{As();hs=x(re());NE();Ct=Symbol("own-data");a($r,"getChanges");a(UE,"assignTrackedAccessors");a(Nx,"trackObject");IE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=t}};UE(IE,{});a(z_,"collapseData");bx=Object.prototype.hasOwnProperty;a(Io,"deepFreeze");a(CE,"hasChanges");wo=Symbol.for("has-array-changes"),DE=class extends Array{static{a(this,"TrackedArray")}[wo];constructor(t){super(t)}splice(...t){return this[wo]=!0,super.splice(...t)}push(...t){return this[wo]=!0,super.push(...t)}pop(){return this[wo]=!0,super.pop()}unshift(...t){return this[wo]=!0,super.unshift(...t)}shift(){return this[wo]=!0,super.shift()}};DE.prototype.constructor=Array;LE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Op={};Ye(Op,{CONTEXT:()=>Oe,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>ms,RECORD_PROPERTY:()=>de,Resource:()=>xt,snake_case:()=>eie,transformForSelect:()=>PE});function eie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function yx(e,t){if(hl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(hl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),s=new mA;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){hl=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function Yr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Oe]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Oe]||i):l=i:(l=n,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Oe]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[],_=!0;for(let E of n){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=n.id??null,c==null&&(_=!0))}else c=n??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return Xe(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new ME(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new ME(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Kr(e,t){let r=new Cx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function hA(e,t,r){let s=e[de];if(s){let n=e[Ct];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:n&&i in n?n[i]:(c=t?.[i])?c(e,r):s[i]}}else return t?n=>{let i=t[n];return i?i(e,r):e[n]}:n=>e[n]}function PE(e,t){let r=t?.propertyResolvers,s=t[Oe],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):hA(c,r,s)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(hA(u,r,s));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(hA(u,r,s)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){n||(n={});let u=n[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=n[c.name]=PE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var wx,Ix,Cx,Oe,Le,ms,de,Zne,xt,ME,hl,mA,As=Re(()=>{wx=require("crypto");Ec();Ix=require("../index"),Cx=x(re());J_();Zi();bf();Oe=Symbol.for("context"),Le=Symbol.for("primary-key"),ms=Symbol("is-collection"),de=Symbol("stored-record"),Zne={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},xt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let s=r?.[Oe];this[Oe]=s!==void 0?s:r||null}static get=Yr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=PE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Yr(function(t,r,s,n){if(Array.isArray(n)&&t[ms]){let i=[],o=s.authorize;for(let c of n){let u=t.constructor,_=u.getResource(c[u.primaryKey],s,{async:!0});_.then?i.push(_.then(l=>l.put(c,s))):i.push(_.put(c,s))}return Promise.all(i)}return t.put?t.put(n,r):Kr(t,"put")},{hasContent:!0,type:"update"});static patch=Yr(function(t,r,s,n){return t.patch?t.patch(n,r):Kr(t,"patch")},{hasContent:!0,type:"update"});static delete=Yr(function(t,r,s,n){return t.delete?t.delete(r):Kr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,wx.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),Xe(s,()=>{let i=new this(n,s),o=i.update?i.update(r):Kr(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=Yr(function(t,r,s,n){return t.invalidate?t.invalidate(r):Kr(t,"delete")},{hasContent:!1,type:"update"});static post=Yr(function(t,r,s,n){return t[Le]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Yr(function(t,r,s,n){return t.connect?t.connect(n,r):Kr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Yr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Kr(t,"subscribe")},{type:"read"});static publish=Yr(function(t,r,s,n){return t[Le]!=null&&t.update?.(),t.publish?t.publish(n,r):Kr(t,"publish")},{hasContent:!0,type:"create"});static search=Yr(function(t,r,s,n){let i=t.search?t.search(r):Kr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=PE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Yr(function(t,r,s,n){return t.search?t.search(n,r):Kr(t,"search")},{hasContent:!0,type:"read"});static copy=Yr(function(t,r,s,n){return t.copy?t.copy(n,r):Kr(t,"copy")},{type:"create"});static move=Yr(function(t,r,s,n){return t.move?t.move(n,r):Kr(t,"move")},{type:"delete"});post(t){if(this[ms])return this.constructor.create(this[Le],t,this[Oe]);Kr(this,"post")}static isCollection(t){return t?.[ms]}static coerceId(t){return t}static parseQuery(t){return Of(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let o=t.slice(n+1);t=t.slice(0,n);let c=r?.headers&&Zne[o];if(c)r.headers.set("accept",c);else if(s)s.property=o;else return{query:{property:o},id:yx(t,this),isCollection:hl}}let i=yx(t,this);return hl?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[Oe],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[Le]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[ms]=!0),n}subscribe(t){return new Rs}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Rs}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Le]}getContext(){return this[Oe]}};xt.prototype[Oe]=null;(0,Ix._assignPackageExport)("Resource",xt);a(eie,"snake_case");ME=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(yx,"pathToId");mA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Yr,"transactional");a(Kr,"missingMethod");a(hA,"selectFromObject");a(PE,"transformForSelect")});function Lx(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;Wa||((0,vE.onMessageByType)(Dx,l=>{Ux(l.path)}),Wa=Object.create(null));let o=Wa[n]||(Wa[n]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Ta(t);let u=new SA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function Ux(e,t){if(!Wa)return;let r=Wa[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(n){throw n.message+=" in "+e,n}let s;for(let{key:n,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=n;let o=Lt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Ta(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=n){(0,pA.info)("omitting",u,h.startTime,n);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(s?s.push(h):s=[h]),h.txnInProgress=o.version),h.listener(u,o,n,p)}catch(p){console.error(p),(0,pA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(s)for(let n of s)n.txnInProgress=null,n.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Mx(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",()=>{(0,vE.broadcast)({type:Dx,path:n}),Ux(n,!0)})}}var pA,vE,Dx,Wa,lSe,SA,Px=Re(()=>{pA=x(V()),vE=x(Ke());Ec();vu();Bi();Dx="transaction",lSe=Buffer.alloc(4096);a(Lx,"addSubscription");SA=class extends Rs{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(Ux,"notifyFromTransactionData");a(Mx,"listenToCommits")});var jg={};Ye(jg,{coerceType:()=>BE,makeTable:()=>qE,setServerUtilities:()=>uie,updateResource:()=>HE});function qE(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:p}=e;p||(p=[]),Mx(i,u);let S=Jh(i,s,u),A=0,R,g,P={},H=Promise.resolve(),v,U,Y;for(let W of p)(W.assignCreatedTime||W.name==="__createdtime__")&&(v=W),(W.assignUpdatedTime||W.name==="__updatedtime__")&&(U=W),W.expiresAt&&(Y=W),W.isPrimaryKey&&(P=W);let K,z=[],ne=[],me=1,ce=2,xe={},le={},Dt=864e5,Ul,Ml,$n,qA=!1,rh,xq=i.getRange({start:!1,end:!1}).constructor,qq=10,Fq=6;E&&kA();class ze extends xt{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=v;static updatedTimeProperty=U;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),g=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(D=>{let y=this.sources.slice(0,-1);if(y=y.filter(M=>M[D]&&(!M[D].reliesOnPrototype||M.prototype[D])),y.length>0)if(y.length===1){let M=y[0];return(G,C,B)=>{if(G?.source!==M)return M[D](C,B,G)}}else return(M,G,C)=>{let B=[];for(let F of y){if(M?.source===F)break;B.push(F[D](G,C,M))}return Promise.all(B)}},"getApplyToIntermediateSource"),N=this.sources[this.sources.length-1],b=a(D=>{if(N[D]&&(!N[D].reliesOnPrototype||N.prototype[D]))return(y,M,G)=>{if(!y?.source)return N[D](M,G,y)}},"getApplyToCanonicalSource");return xe={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},le={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let D=!1,y=a(async(M,G)=>{let C=M.value,B=M.table?rt[c][M.table]:ze;if(c===qs.SYSTEM_SCHEMA_NAME&&(M.table===qs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||M.table===qs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),M.id===void 0&&(M.id=C[B.primaryKey],M.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(M));M.source=m;let F=await B.getResource(M.id,G,Qa);switch(M.type){case"put":return F._writeUpdate(C,!0,Qa);case"patch":return F._writeUpdate(C,!1,Qa);case"delete":return F._writeDelete(Qa);case"publish":return F._writePublish(C,Qa);case"invalidate":return F.invalidate(Qa);default:Ze.error("Unknown operation",M.type,M.id)}},"writeUpdate");try{let M=m.subscribe;M&&h==null&&(h=!0);let G=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Do.getWorkerIndex)()):(0,Do.getWorkerIndex)()===0,C=M&&G&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let B;for await(let F of C)try{if(!(F.type==="transaction"?F.writes[0]:F)){Ze.error("Bad subscription event",F);continue}if(F.source=m,B)if(F.beginTxn)B.resolve();else{y(F,B);continue}if(F.type==="end_txn")continue;let be=Xe(F,()=>{if(F.type==="transaction"){let ee=[];for(let Me of F.writes)try{ee.push(y(Me,F))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Me)+" of event "+JSON.stringify(F),ae}return Promise.all(ee)}else if(F.type==="define_schema"){let ee=this.attributes.slice(0),Me;for(let ae of F.attributes)ee.find(qe=>qe.name===ae.name)||(ee.push(ae),Me=!0);Me&&(ct({table:n,database:c,attributes:ee,origin:"cluster"}),Al.signalSchemaChange(new Ol.SchemaEventMsg(process.pid,qs.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return F.beginTxn?(B=F,y(F,F),new Promise(ee=>{B.resolve=ee})):y(F,F)});D&&(await be,Al.signalUserChange(new Ol.UserEventMsg(process.pid))),F.onCommit&&(be?.then?be.then(F.onCommit):F.onCommit())}catch(oe){Ze.error("error in subscription handler",oe)}}}catch(M){Ze.error(M)}})(),this}static getResource(m,O,w){let N=super.getResource(m,O,w);if(m!=null){Za(m);try{if(N.hasOwnProperty(de))return N;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!w?.async||i.cache?.get(m),D=Ts(O),y=D.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return sh(m,O,{transaction:y},b,M=>{if(M?HE(N,M):N[de]=null,O.onlyIfCached&&O.noCacheStore){if(!N.doesExist())throw new ps.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let G=nh(m,M,O,N);if(G)return D?.disregardReadTxn(),N[TA]=!0,RA(G,C=>(HE(N,C),N))}return N})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return N}ensureLoaded(){let m=nh(this[Le],this[Wr],this[Oe]);if(m)return this[TA]=!0,RA(m,O=>{this[Wr]=O,this[de]=O.value,this[gl]=O.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,Dt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");Dt=Dt||(d+f)/4,oh()}static enableAuditing(m=!0){E=m,m&&kA(),ze.audit=m}static coerceId(m){return m===""?null:BE(m,P)}static async dropTable(){if(delete rt[c][n],c===o){for(let m of p)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Al.signalSchemaChange(new Ol.SchemaEventMsg(process.pid,qs.OPERATIONS_ENUM.DROP_TABLE,c,n))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[ms])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let O=ze.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:n,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Oe]?.returnNonexistent)return this}allowRead(m,O){let w=vl(m);if(w?.read){if(w.isSuperUser)return!0;let N=w.attribute_permissions,b=O?.select;if(N?.length>0||qA&&b){if(O||(O={}),b){let D=N?.length>0&&gA(N,"read");O.select=b.map(y=>{let M=y.name||y;if(!D||D[M]){let G=$n[M]?.definition?.tableClass;if(G){if(y.name||(y={name:y}),!G.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else O.select=N.filter(D=>D.read&&!$n[D.attribute_name]).map(D=>D.attribute_name);return O}else return!0}}allowUpdate(m,O){let w=vl(m);if(w?.update){let N=w.attribute_permissions;if(N?.length>0){let b=gA(N,"update");for(let D in O)if(!b[D])return!1;for(let D of N){let y=D.attribute_name;!D.update&&!(y in O)&&(O[y]=this.getProperty(y))}}return!0}}allowCreate(m,O){if(this[ms]){let w=vl(m);if(w?.insert){let N=w.attribute_permissions;if(N?.length>0){let b=gA(N,"insert");for(let D in O)if(!b[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return vl(m)?.delete}update(m,O){if(!Ts(this[Oe]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let N;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[de]={},this[Ct]=m):(N=this[Ct],N&&(m=Object.assign(N,m)),this[Ct]=N=m)),this._writeUpdate(this[Ct],O),this}addTo(m,O){if(typeof O=="number")this[ml]===Bx?this.set(m,(+this.getProperty(m)||0)+O):(this[ml]||this.update(),this.set(m,new LE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let O=this[Oe],w=this[Le];Za(w),Ts(this[Oe]).addWrite({key:w,store:i,invalidated:!0,entry:this[Wr],nodeName:this[Oe]?.nodeName,before:xe.invalidate?.bind(this,O,w),beforeIntermediate:le.invalidate?.bind(this,O,w),commit:(b,D)=>{if(D?.version>b)return;let y=null;for(let M in r)y||(y={}),y[M]=this.getProperty(M);S(w,y,this[Wr],b,pl,E,this[Oe],0,"invalidate")}})}static evict(m,O,w){let N=this.Source,b;if(!((g||E)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==w))){if(g){if(i.hasLock(m,b.version))return;let D;for(let y in r)D||(D={}),D[y]=O[y];if(D)return S(m,D,b,w,Sl,null,null,0,null,!0)}return i.ifVersion(w,()=>{Pl(m,O,null)}),E?S(m,null,b,w,Sl,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=n,m.schema||=c,kx.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,w){let N=this[Oe],b=Ts(N),D=this[Le];Za(D);let y=this[Wr];this[ml]=O?Bx:oie;let M={key:D,store:i,entry:y,nodeName:N?.nodeName,validate:G=>{m||(m=this[Ct]),O||m&&CE(m)?(this.validate(m,!O),N?.source||(U&&(m[U.name]=U.type==="Date"?new Date(G):U.type==="String"?new Date(G).toISOString():G),O&&(t&&m[t]!==D&&(m[t]=D),v&&(y?.value?m[v.name]=y?.value[v.name]:m[v.name]=v.type==="Date"?new Date(G):v.type==="String"?new Date(G).toISOString():G),m=Io(m)))):b.removeWrite(M)},before:O?xe.put?()=>xe.put(N,D,m):null:xe.patch?()=>xe.patch(N,D,m):xe.put?()=>xe.put(N,D,Io(this)):null,beforeIntermediate:O?le.put?()=>le.put(N,D,m):null:le.patch?()=>le.patch(N,D,m):le.put?()=>le.put(N,D,Io(this)):null,commit:(G,C,B)=>{if(B){if(N&&C?.version>(N.lastModified||0)&&(N.lastModified=C.version),this[Wr]=C,C?.value?.[de])throw new Error("Can not assign a record to a record, check for circular references");O||(this[de]=C?.value??null)}this[Ct]=m,this[gl]=G;let F=C?.value,oe=m;if(this[ml]=0,C?.version>=G)if(E){let ae=C.localTime,qe=C.version;for(;oe&&(ae>G||qe>=G&&ae>0);){let te=u.get(ae),j=Lt(te);if(qe=j.version,qe>G){if(j.type==="patch"){let ge=j.getValue(i);oe=wE(oe,ge)}else if(j.type==="put"||j.type==="delete")return}else if(qe===G)return;ae=j.previousLocalTime}}else{if(O)return;oe=wE(oe,F)}let be;if(O?be=oe:(this[de]=F,be=O?oe:Io(this,oe)),this[de]=be,be?.[de])throw new Error("Can not assign a record to a record, check for circular references");let ee;O||(ee=m),Pl(D,F,be);let Me=O?"put":"patch";S(D,be,C,G,0,E,N,N.expiresAt||(d?d+Date.now():0),Me,!1,ee)}};b.addWrite(M)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[ms]){for await(let O of this.search(m))(await ze.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[de]?this._writeDelete(m):!1}_writeDelete(m){let O=Ts(this[Oe]),w=this[Le];Za(w);let N=this[Oe];return O.addWrite({key:w,store:i,resource:this,nodeName:N?.nodeName,before:xe.delete?.bind(this,N,w),beforeIntermediate:le.delete?.bind(this,N,w),commit:(b,D,y)=>{let M=D?.value;y&&(N&&D?.version>(N.lastModified||0)&&(N.lastModified=D.version),HE(this,D)),!(D?.version>b)&&(Pl(this[Le],M),Ze.trace("Write delete entry",w,b),E||h?(S(w,null,this[Wr],b,0,E,this[Oe],0,"delete"),E||oh()):i.remove(this[Le]))}}),!0}search(m){let O=this[Oe],w=Ts(O);if(!m)throw new Error("No query provided");let N=m.conditions;N?N.length===void 0&&(N=N[Symbol.iterator]?Array.from(N):[N]):N=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(N=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(N));let b,D={};function y(j,ge){let Be;switch(ge){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+ge)}let Fs=Be&&{},Yn;for(let $e of j){if($e.conditions){$e.conditions=y($e.conditions,$e.operator);continue}let Bt=$e[0]??$e.attribute,jr=Bt==null?P:Pn(p,Bt);if(jr){if(Be){let Gs=Ps(Bt),Ht=Fs[Gs];Ht?(Ht.push($e),Yn=!0):Fs[Gs]=[$e]}(jr.type||Og[$e.comparator])&&($e[1]===void 0?$e.value=G($e.value,jr):$e[1]=G($e[1],jr))}else if(Bt!=null)throw(0,ps.handleHDBError)(new Error,`${Bt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(Yn)for(let $e in Fs){let Bt=Fs[$e],jr=Bt.length;if(jr>1)for(let Gs=0;Gs<jr;Gs++){let Ht=Bt[Gs];if(Ht.comparator==="ge"||Ht.comparator==="greater_than_equal")for(let Kn=0;Kn<jr;Kn++){let Po=Bt[Kn];(Po.comparator==="le"||Po.comparator==="less_than_equal")&&(Ht.comparator="between",Ht.value=[Ht.value,Po.value],j.splice(j.indexOf(Po),1))}if(Ht.comparator==="equals"||!Ht.comparator){for(let Kn=0;Kn<jr;Kn++)if(Kn!==Gs){let Po=Bt[Kn];j.splice(j.indexOf(Po),1)}break}}}return j}a(y,"prepareConditions");function M(j,ge){if(m.enforceExecutionOrder)return j;for(let Be of j)Be.conditions&&(Be.conditions=M(Be.conditions,Be.operator));return j.length>1&&ge!=="or"?(0,Gx.sortBy)(j,Af(ze)):j}a(M,"orderConditions");function G(j,ge){return Array.isArray(j)?j.map(Be=>BE(Be,ge)):BE(j,ge)}a(G,"coerceTypedValues");let C=m.operator;(N.length>0||C)&&(N=y(N,C));let B=typeof m.sort=="object"&&m.sort,F;if(B&&C!=="or"){let j=B.attribute;if(b=N.find(ge=>Ps(ge.attribute)===Ps(j)),!b){if(!Pn(p,j))throw(0,ps.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);b={attribute:j,comparator:"sort"},N.push(b)}b.descending=!!B.descending}N=M(N,C),B&&(N[0]===b?B.next&&(F={dbOrderedAttribute:B.attribute,attribute:B.next.attribute,descending:B.next.descending,next:B.next.next}):(b&&N.splice(N.indexOf(b),1),F=B));let oe=m.select;if(N.length===0&&(N=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:N,operator:C,postOrdering:F,selectApplied:!!oe};let be=w.useReadTxn(),ee=bg(N,C,ze,be,m,O,(j,ge)=>FA(j,oe,O,be,ge),D),Me=m.ensureLoaded!==!1;F||(ee=te(ee));let ae=ze.transformEntryForSelect(oe,O,be,D,Me,!0),qe=ze.transformToOrderedSelect(ee,oe,F,be,O,ae);function te(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(te,"applyOffset"),F&&(qe=te(qe)),qe.onDone=()=>{qe.onDone=null,w.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(oe){let j=[];for(let ge of oe)ge==="*"?j.push(...p.map(Be=>Be.name)):j.push(ge.name||ge);return j}return p.map(j=>j.name)},qe}static transformToOrderedSelect(m,O,w,N,b,D){let y=new xq;if(w){m=FA(m,O,N,b,null);let M;y.iterate=function(){let C,B=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),F,oe=w.dbOrderedAttribute,be,ee,Me=!0;function ae(te){let j=te.next&&ae(te.next),ge=te.descending;return(Be,Fs)=>{let Yn=ih(Be,te.attribute,N),$e=ih(Fs,te.attribute,N),Bt=ge?(0,Lo.compareKeys)($e,Yn):(0,Lo.compareKeys)(Yn,$e);return Bt===0?j?.(Be,Fs)||0:Bt}}a(ae,"createComparator");let qe=ae(w);return{async next(){let te;if(C)if(te=C.next(),te.done){if(F)return y.onDone&&y.onDone(),te}else return{value:await D.call(this,te.value)};M=[],be&&M.push(be);do if(te=await B.next(),te.done){if(F=!0,M.length)break;return y.onDone&&y.onDone(),te}else{let j=te.value;if(j?.then&&(j=await j),oe){let ge=ih(j,oe,N);if(Me)Me=!1,ee=ge;else if(ge!==ee){ee=ge,be=j;break}}M.push(j)}while(!0);return w.isGrouped,M.sort(qe),C=M[Symbol.iterator](),te=C.next(),te.done?(y.onDone&&y.onDone(),te):{value:await D.call(this,te.value)}},return(){y.onDone&&y.onDone(),B.return()},throw(){y.onDone&&y.onDone(),B.throw()}}};let G=a(C=>{if(typeof O=="object"&&Array.isArray(C.attribute))for(let B=0;B<O.length;B++){let F=O[B],oe;if(F.name===C.attribute[0]){for(oe=F.sort||(F.sort={});oe.next;)oe=oe.next;oe.attribute=C.attribute.slice(1),oe.descending=C.descending}else F===C.attribute[0]&&(O[B]=oe={name:F,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&G(C.next)},"applySortingOnSelect");G(w)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(D);return y}static transformEntryForSelect(m,O,w,N,b,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(B=>B?.key??B,"transform");return m===t?C:m.asArray?B=>[C(B)]:B=>({[t]:C(B)})}let y;b&&g&&!m?.every(C=>{let B;return typeof C=="object"?B=C.name:B=C,r[B]||B===t})&&(y=!0);let M,G=a(function(C){let B;if(C!=null){if(rh=C,B=C.value||C.deref?.(),!B&&(C.key===void 0||C.deref)){if(C=sh(C.key??C,O,{transaction:w,lazy:m?.length<4},this.isSync,F=>F),C?.then)return C.then(G.bind(this));B=C?.value}if(y&&(C.metadataFlags&(pl|Sl)||C.expiresAt&&C.expiresAt<Date.now())){let F=nh(C.key??C,C,O);if(F?.then)return F.then(G)}}if(B==null)return D?Co.SKIP:B;if(m&&!(m[0]==="*"&&m.length===1)){let F,oe=a((ee,Me)=>{let ae;typeof ee=="object"?ae=ee.name:ae=ee;let qe=$n?.[ae],te;if(qe){let j=N?.[ae];if(j)if(j.hasMappings){let Be=qe.from?B[qe.from]:Ps(C.key);te=j.get(Be),te||(te=[])}else te=j.fromRecord?.(B);else te=qe(B,O,C);let ge=a(Be=>{if(Be&&typeof Be=="object"){let Fs=qe.definition?.tableClass||ze;M||(M={});let Yn=M[ae]||(M[ae]=Fs.transformEntryForSelect(ae===ee?null:ee.select||(Array.isArray(ee)?ee:null),O,w,j,b));if(Array.isArray(Be)){let $e=[],Bt=Fs.transformToOrderedSelect(Be,ee.select,typeof ee.sort=="object"&&ee.sort,O,w,Yn)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),jr=a(Ht=>{for(;!Ht.done;){if(Ht?.then)return Ht.then(jr);$e.push(Ht.value),Ht=Bt.next()}Me($e,ae)},"nextValue"),Gs=jr(Bt.next());Gs&&(F||(F=[]),F.push(Gs));return}else if(Be=Yn.call(this,Be),Be?.then){F||(F=[]),F.push(Be.then($e=>Me($e,ae)));return}}Me(Be,ae)},"handleResolvedValue");te?.then?(F||(F=[]),F.push(te.then(ge))):ge(te);return}else te=B[ae],te&&typeof te=="object"&&ae!==ee&&(te=ze.transformEntryForSelect(ee.select||ee,O,w,null)({value:te}));Me(te,ae)},"selectAttribute"),be;if(typeof m=="string")oe(m,ee=>{be=ee});else if(Array.isArray(m))if(m.asArray)be=[],m.forEach((ee,Me)=>{ee==="*"?m[Me]=B:oe(ee,ae=>be[Me]=ae)});else{be={};let ee=m.forceNulls;for(let Me of m)if(Me==="*")for(let ae in B)be[ae]=B[ae];else oe(Me,(ae,qe)=>{ae===void 0&&ee&&(ae=null),be[qe]=ae})}else throw new ps.ClientError("Invalid select"+m);return F?Promise.all(F).then(()=>be):be}return B},"transform");return G}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||ct({table:n,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let O=!m.rawEvents,w=Lx(ze,this[Le]??null,function(y,M,G,C){try{let B=M.getValue?.(i,O);if(!B&&M.type==="patch"&&O){let F=i.getEntry(y);F?.version===M.version?B=F.value:B=M.getValue?.(i,!0,G),M.type="put"}this.send({id:y,timestamp:G,value:B,version:M.version,type:M.type,beginTxn:C})}catch(B){Ze.error(B)}},m.startTime||0,this[ms]);this[ms]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.crossThreads===!1&&(w.crossThreads=!1),m.supportsTransactions&&(w.supportsTransactions=!0);let N=this[Le],b=m.previousCount;b>1e3&&(b=1e3);let D=m.startTime;if(this[ms]){if(D){if(b)throw new ps.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:M}of u.getRange({start:D,exclusiveStart:!0})){let G=Lt(M);if(G.tableId!==s)continue;let C=G.recordId;if(N==null||qx(N,C)){let B=G.getValue(i,O,y);w.send({id:C,timestamp:y,value:B,version:G.version,type:G.type})}w.startTime=y}}else if(b){let y=[];for(let{key:M,value:G}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Lt(G);if(C.tableId!==s)continue;let B=C.recordId;if(N==null||qx(N,B)){let F=C.getValue(i,O,M);if(y.push({id:B,timestamp:M,value:F,version:C.version,type:C.type}),--b<=0)break}}catch(C){Ze.error("Error getting history entry",M,C)}for(let M=y.length;M>0;)w.send(y[--M]);y[0]&&(w.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:M,version:G,localTime:C}of i.getRange({start:N??!1,end:N==null?void 0:[N,Lo.MAXIMUM_KEY],versions:!0}))M&&w.send({id:y,timestamp:C,value:M,version:G,type:"put"})}else{b&&!D&&(D=0);let y=this[Wr]?.localTime;if(y===zh&&(i.cache?.delete(N),this[Wr]=i.getEntry(N),Ze.trace("re-retrieved record",y,this[Wr]?.localTime),y=this[Wr]?.localTime),Ze.trace("Subscription from",D,"from",N,y),D<y){let M=[],G=y;do{let C=u.get(G);if(C){m.omitCurrent=!0;let B=Lt(C),F=B.getValue(i,O,G);O&&(B.type="put"),M.push({id:N,value:F,timestamp:G,...B}),G=B.previousLocalTime}else break;b&&b--}while(G>D&&b!==0);for(let C=M.length;C>0;)w.send(M[--C]);w.startTime=y}!m.omitCurrent&&this.doesExist()&&w.send({id:N,timestamp:y,value:this,version:this[gl],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[de]||this[ml])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let w=Ts(this[Oe]),N=this[Le]||null;Za(N);let b=this[Oe];w.addWrite({key:N,store:i,entry:this[Wr],nodeName:b?.nodeName,validate:()=>{this.validate(m)},before:xe.publish?.bind(this,b,N,m),beforeIntermediate:le.publish?.bind(this,b,N,m),commit:(D,y,M)=>{y===void 0&&h&&!E&&oh(),S(N,y?.value??null,y,y?.version||D,0,!0,b,y?.expiresAt,"message",!1,m)}})}validate(m,O){let w,N=a((b,D,y)=>{if(D.type&&b!=null)if(O&&b.__op__&&(b=b.value),D.properties){typeof b!="object"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be an object${D.type?" ("+D.type+")":""}`);let M=D.properties;for(let G=0,C=M.length;G<C;G++){let B=M[G],F=N(b[B.name],B,y+"."+B.name);F&&(b[B.name]=F)}}else switch(D.type){case"Int":(typeof b!="number"||b>>0!==b)&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(M=>typeof M=="string")||(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a string`);break;case"Boolean":typeof b!="boolean"&&(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(b)){if(D.elements)for(let M=0,G=b.length;M<G;M++){let C=b[M],B=N(C,D.elements,y+"[*]");B&&(b[M]=B)}}else(w||(w=[])).push(`Value ${xs(b)} in property ${y} must be a Buffer or Uint8Array`);break}D.nullable===!1&&b==null&&(w||(w=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let b=0,D=p.length;b<D;b++){let y=p[b];if(!y.relationship&&(!O||y.name in m)){let M=N(m[y.name],y,y.name);M&&(m[y.name]=M)}}if(w)throw new ps.ClientError(w.join(". "))}getUpdatedTime(){return this[gl]}wasLoadedFromSource(){return g?!!this[TA]:void 0}static async addAttributes(m){let O=p.slice(0);for(let w of m){if(!w.name)throw new ps.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new ps.ClientError("Attribute names cannot include backticks or forward slashes");O.push(w)}return ct({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static async removeAttributes(m){let O=p.filter(w=>!m.includes(w.name));return ct({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,w=5e3,N=1e3,b;O>w&&!m?.exactCount&&(b=N);let D=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:b}))y!=null&&D++;if(b){let y=D;D=0;for(let{value:Me}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Me!=null&&D++;let M=b*2,G=(D+y)/M,C=Math.pow((D-y+1)/b/2,2)+G*(1-G)/M,B=Math.max(Math.sqrt(C)*O,1),F=Math.round(G*O),oe=Math.max(F-1.96*B,0),be=Math.min(F+1.96*B,O),ee=Math.pow(10,Math.round(Math.log10(B)));return ee>F&&(ee=ee/10),D=Math.round(F/ee)*ee,{recordCount:D,estimatedRange:[Math.round(oe),Math.round(be)]}}return{recordCount:D}}static updatedAttributes(){$n=this.propertyResolvers={$id:(m,O,w)=>({value:w.key}),$updatedtime:(m,O,w)=>w.version,$record:(m,O,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),qA=!0,O.to)m.elements?.definition?($n[m.name]=m.resolve=(w,N,b)=>{let D=w[O.from?O.from:t],y=m.elements.definition.tableClass;return b?Ca({attribute:O.to,value:D},Ts(N).getReadTxn(),!1,y,!1).asArray:y.search([{attribute:O.to,value:D}],N).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${n}" must have an array type referencing a table as the elements`);else if(O.from){let w=m.definition||m.elements?.definition;w?($n[m.name]=m.resolve=(N,b,D)=>{let y=N[O.from];if(y!==void 0){if(m.elements){let M,G=y.map(C=>{let B=D?w.tableClass.primaryStore.getEntry(C,{transaction:Ts(b).getReadTxn()}):w.tableClass.get(C,b);return B?.then&&(M=!0),B});return O.filterMissing?M?Promise.all(G).then(C=>C.filter(Fx)):G.filter(Fx):M?Promise.all(G):G}return D?w.tableClass.primaryStore.getEntry(y,{transaction:Ts(b).getReadTxn()}):w.tableClass.get(y,b)}},m.set=(N,b)=>{if(Array.isArray(b)){let D=b.map(y=>y[Le]||y[w.tableClass.primaryKey]);N[O.from]=D}else{let D=b[Le]||b[w.tableClass.primaryKey];N[O.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.from):console.error(`The relationship property "${m.name}" in table "${n}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${n}" must use either "from" or "to" arguments`)}UE(this,this)}static async deleteHistory(m=0){let O;for(let{key:w,value:N}of u.getRange({start:0,end:m}))await Tl(),Lt(N).tableId===s&&(O=u.remove(w));await O}static async*getHistory(m=0,O=1/0){for(let{key:w,value:N}of u.getRange({start:m,end:O})){await Tl();let b=Lt(N);b.tableId===s&&(yield{id:b.recordId,localTime:w,version:b.version,type:b.type,value:b.getValue(i,!0,w),user:b.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return O;let N=w.localTime;if(!N)throw new Error("The entry does not have a local audit time");let b=0;do{await Tl();let D=u.get(N);if(D){let y=Lt(D);O.push({id:y.recordId,localTime:N,version:y.version,type:y.type,value:y.getValue(i,!0,N),user:y.user}),N=y.previousLocalTime}else break}while(b<1e3&&N);return O.reverse()}static cleanup(){K?.remove()}}ze.updatedAttributes();let Gq=ze.prototype;return Gq[iie]=!0,d&&ze.setTTLExpiration(d/1e3),Y&&kq(),ze;function Pl(W,m,O){let w;for(let N in r){let b=r[N],D=b.isIndexing,y=O?.[N],M=m?.[N];if(y===M&&!D)continue;w=!0;let G=b.indexNulls,C=(0,Rl.getIndexedValues)(M,G);if(C){vx&&b.prefetch(C.map(B=>({key:B,value:W})),xx);for(let B=0,F=C.length;B<F;B++)b.remove(C[B],W)}if(C=(0,Rl.getIndexedValues)(y,G),C){vx&&b.prefetch(C.map(B=>({key:B,value:W})),xx);for(let B=0,F=C.length;B<F;B++)b.put(C[B],W)}}return w}a(Pl,"updateIndices");function Za(W){switch(typeof W){case"number":return!0;case"string":if(W.length<659)return!0;if(W.length>Hx)throw new Error("Primary key size is too large: "+W.length);break;case"object":if(W===null)return!0;break;case"bigint":if(W<2n**64n&&W>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof W)}if((0,Lo.writeKey)(W,aie,0)>Hx)throw new Error("Primary key size is too large: "+W.length);return!0}a(Za,"checkValidId");function sh(W,m,O,w,N){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return N(null,W);let D=i.getEntry(W,O);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),N(D,W)},"whenPrefetched");return w?b():me>0?(me--,b()):new Promise((D,y)=>{me===0?(me--,i.prefetch([W],()=>{M(),G()})):(z.push(W),ne.push(G),z.length>Fq&&(me--,M()));function M(){if(z.length>0){let C=ne;i.prefetch(z,()=>{me===-1?M():me++;for(let B of C)B()}),z=[],ne=[],ce>2&&ce--}else me=ce,ce<qq&&ce++}a(M,"prefetch");function G(){try{D(b())}catch(C){y(C)}}a(G,"load")})}a(sh,"loadLocalRecord");function vl(W){if(!W?.role)return;let m=W.role.permission;if(m.super_user)return cie;let O=m[c],w,N=O?.tables;if(N)return N[n];if(c==="data"&&(w=m[n])&&!w.tables)return w}a(vl,"getTablePermissions");function nh(W,m,O,w){if(g){let N;if(O.noCache?N=!0:(m?(!m.value||m.metadataFlags&(pl|Sl)||m.expiresAt&&m.expiresAt<Date.now())&&(N=!0):N=!0,rs(!N,"cache-hit",n)),N){let b=GA(W,m,O).then(D=>(D?.value?.[de]&&Ze.error("Can not assign a record with a record property"),O&&(D?.version>(O.lastModified||0)&&(O.lastModified=D.version),O.lastRefreshed=Date.now()),D));if(O?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,W)){if(b.catch(D=>Ze.warn(D)),O?.onlyIfCached&&!w.doesExist())throw new ps.ServerError("Entry is not cached",504);return}else return b}}}a(nh,"ensureLoadedFromSource");function Ts(W){let m=W?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new Xi,m.lmdbDb=i,m;m=O}while(!0)}else return new W_}a(Ts,"txnForContext");function ih(W,m,O){if(!W)return;rh=W;let w=W.value||W.deref?.()||(rh=i.getEntry(W.key))?.value;if(typeof m=="object"){let b=$n,D=w;for(let y=0,M=m.length;y<M;y++){let G=m[y],C=b?.[G];D=C&&D?C(D,O,!0)?.value:D?.[G],b=C?.definition?.tableClass?.propertyResolvers}return D}let N=$n[m];return N?N(w,O):w[m]}a(ih,"getAttributeValue");function FA(W,m,O,w,N){let b=N?.length,D={transaction:w,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function M(G,C){let B=G?.value;if(!B)return Co.SKIP;for(let F=0;F<b;F++)if(!y?.includes(F)&&!N[F](B,G))return Co.SKIP;return C!==void 0&&(G.key=C),G}if(a(M,"processEntry"),b>0||!W.hasEntries){let G=W.map(C=>{if(y=null,typeof C=="object"&&C.key!==void 0)return b>0?M(C):C;if(C==null)return Co.SKIP;for(let B=0;B<b;B++){let oe=N[B].idFilter;if(oe){if(!oe(C))return Co.SKIP;y||(y=[]),y.push(B)}}return sh(C,O,D,!1,M)});return Array.isArray(W)&&(G=G.filter(C=>C!==Co.SKIP)),G.hasEntries=!0,G}return W}a(FA,"transformToEntries");async function GA(W,m,O){let w=m?.metadataFlags,N=m?.version,b,D;if(!i.attemptLock(W,N,()=>{clearTimeout(D);let C=i.getEntry(W);!C||!C.value||C.metadataFlags&(pl|Sl)?b(GA(W,i.getEntry(W),O)):b(C)}))return new Promise(C=>{b=C,D=setTimeout(()=>{i.unlock(W,N)},nie)});let y=m?.value,M={requestContext:O,replacingRecord:y,replacingVersion:N,source:null,resourceCache:O?.resourceCache},G=O?.responseHeaders;return new Promise((C,B)=>{let F;RA(Xe(M,async oe=>{let be=performance.now(),ee,Me,ae;try{for(let ge of ze.sources)if(ge.get&&(!ge.get.reliesOnPrototype||ge.prototype.get)&&(M.source=ge,ee=await ge.get(W,M),ee))break;ae=w&pl;let te=M.lastModified||ae&&N;Me=ae||te>N||!y,te||(te=(0,Rl.getNextMonotonicTime)());let j=performance.now()-be;if(Hr(j,"cache-resolution",n),G&&YT(G,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),oe.timestamp=te,d&&!M.expiresAt&&(M.expiresAt=Date.now()+d),ee){if(typeof ee!="object")throw new Error("Only objects can be cached and stored in tables");typeof ee.toJSON=="function"&&(ee=ee.toJSON()),t&&ee[t]!==W&&(ee[t]=W)}F=!0,C({version:te,value:ee})}catch(te){te.message+=` while resolving record ${W} for ${n}`,y&&((te.code==="ECONNRESET"||te.code==="ECONNREFUSED"||te.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(te.statusCode===500||te.statusCode===502||te.statusCode===503||te.statusCode===504))?(C({version:N,value:y}),Ze.trace(te.message,"(returned stale record)")):B(te),M.transaction.abort();return}if(O?.noCacheStore){M.transaction.abort();return}Ts(M).addWrite({key:W,store:i,entry:m,nodeName:"source",commit:(te,j)=>{if(j?.version!==N)return;let ge=Pl(W,y,ee);ee?(le.put?.(M,W,ee),S(W,ee,j,te,0,E&&Me||null,M,M.expiresAt,"put",!!ae)):(le.delete?.(M,W),E||h?S(W,null,j,te,0,E&&Me||null,M,0,"delete",!!ae):i.remove(W,N))}})}),()=>{i.unlock(W,N)},oe=>{i.unlock(W,N),F&&Ze.error("Error committing cache update",oe)})})}a(GA,"getFromSource");function oh(){if(Dt!==Ul&&(Ul=Dt,(0,Do.getWorkerIndex)()===(0,Do.getWorkerCount)()-1)){if(Ml&&clearTimeout(Ml),!Dt)return;let W=new Date;W.setMonth(0),W.setDate(1),W.setHours(0),W.setMinutes(0),W.setSeconds(0);let m=Math.ceil((Date.now()-W.getTime())/Dt)*Dt+W.getTime(),O=a(w=>{Ze.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),Ml=setTimeout(()=>H=H.then(async()=>{if(O(Math.max(w+Dt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ml);return}let N=50,b=new Array(N),D=0;Ze.trace(`Starting cleanup scan for ${n}`);try{let y=0;for(let{key:M,value:G,version:C,expiresAt:B}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let F;G===null&&!E&&C+sie<Date.now()?F=i.remove(M,C):B&&B+f<Date.now()&&(F=ze.evict(M,G,C),y++),F&&(await b[D],b[D]=F.catch(oe=>{Ze.error("Cleanup error",oe)}),++D>=N&&(D=0)),await Tl()}Ze.trace(`Finished cleanup scan for ${n}, evicted ${y} entries`)}catch(y){Ze.trace(`Error in cleanup scan for ${n}:`,y)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(oh,"scheduleCleanup");function kA(){K=u?.addDeleteRemovalCallback(s,W=>{let m=i.getEntry(W);m?.value===null&&i.remove(W,m.version)})}a(kA,"addDeleteRemoval");function kq(){(0,Do.getWorkerIndex)()===0&&setInterval(async()=>{try{let W=Y.name,m=r[W];if(!m)throw new Error(`expiresAt attribute ${Y} must be indexed`);for(let{value:O}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let w=i.getEntry(O);w?.value?.[W]<Date.now()&&ze.evict(O,w.value,w.version),await Tl()}}catch(W){Ze.error("Error in evicting old records",W)}},rie).unref()}a(kq,"runRecordExpirationEviction")}function gA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function xx(){}function uie(e){kx=e}function BE(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?(typeof e!="number"&&!lie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,xE.autoCast)(e):e}function qx(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}function RA(e,t,r){return e?.then?e.then(t,r):t(e)}function HE(e,t){e[Wr]=t,e[de]=t?.value??null,e[gl]=t?.version}function Fx(e){return e!=null}function xs(e){try{return JSON.stringify(e)}catch{return e}}var qs,Co,Rl,Gx,bl,ps,Al,Ol,Ze,Lo,Do,xE,tie,kx,rie,sie,vx,nie,gl,iie,Wr,ml,Bx,oie,TA,Qa,pl,Sl,aie,Hx,cie,ISe,lie,Tl,xf=Re(()=>{qs=x(L()),Co=require("lmdb"),Rl=x(yr()),Gx=require("lodash");As();$p();bl=x(Z());Px();ps=x(re()),Al=x(gn()),Ol=x(Is());Ae();bf();Ze=x(V());J_();Zi();Lo=require("ordered-binary"),Do=x(Ke());Bi();xE=x(J());qo();bn();NE();Bu();tie=new Uint8Array(9);tie[8]=192;rie=6e4,sie=864e5;bl.initSync();vx=bl.get(qs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),nie=1e4,gl=Symbol.for("version"),iie=Symbol.for("incremental-update"),Wr=Symbol("entry"),ml=Symbol("is-saving"),Bx=1,oie=2,TA=Symbol("loaded-from-source"),Qa={isNotification:!0,ensureLoaded:!1},pl=1,Sl=8,aie=Buffer.allocUnsafeSlow(8192),Hx=1978,cie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},ISe=(0,xE.convertToMS)(bl.get(qs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(qE,"makeTable");a(gA,"attributesAsObject");a(xx,"noop");a(uie,"setServerUtilities");lie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(BE,"coerceType");a(qx,"isDescendantId");Tl=a(()=>new Promise(setImmediate),"rest");a(RA,"when");a(HE,"updateResource");a(Fx,"exists");a(xs,"stringify")});var Fe={};Ye(Fe,{database:()=>zc,databases:()=>rt,dropDatabase:()=>zp,dropTableMeta:()=>mie,getDatabases:()=>Ds,getTables:()=>_ie,onUpdatedTable:()=>MR,readMetaDb:()=>Nl,resetDatabases:()=>die,table:()=>ct,tables:()=>wr});function _ie(){return $E||Ds(),wr||{}}function Ds(){if($E)return rt;$E=!0,ja=new Map;let e=(0,Xt.getHdbBasePath)()&&(0,et.join)((0,Xt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),t=(0,Xt.get)(zr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Xt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Qr.existsSync)(e)?e:(0,et.join)((0,Xt.getHdbBasePath)(),zr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Qr.existsSync)(e))for(let r of(0,Qr.readdirSync)(e,{withFileTypes:!0})){let s=(0,et.basename)(r.name,".mdb");r.isFile()&&(0,et.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Nl((0,et.join)(e,r.name),null,s)}if((0,Qr.existsSync)((0,Ja.getBaseSchemaPath)())){for(let r of(0,Qr.readdirSync)((0,Ja.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,et.join)((0,Ja.getBaseSchemaPath)(),r.name),n=(0,et.join)((0,Ja.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Qr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,et.extname)(i.name).toLowerCase()===".mdb"){let o=(0,et.join)(n,i.name);Nl((0,et.join)(s,i.name),(0,et.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,Qr.existsSync)(n))for(let o of(0,Qr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,et.extname)(o.name).toLowerCase()===".mdb"&&Nl((0,et.join)(n,o.name),(0,et.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,et.join)(c.path,(0,et.basename)(o+".mdb"));(0,Qr.existsSync)(u)&&Nl(u,o,r,null,!0)}}for(let r in rt){let s=ja.get(r);if(s){let n=rt[r];r.includes("delete")&&Ss.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Ss.trace(`delete table class ${i}`),delete n[i])}else if(delete rt[r],r==="data"){for(let n in wr)delete wr[n];delete wr[YE]}}return ja=null,rt}}function die(){$E=!1;for(let[,e]of Di)e.needsDeletion=!0;Ds();for(let[e,t]of Di)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Di.delete(e));return rt}function Nl(e,t,r=bA,s,n){let i=new AA.default(e,!1);try{let o=Di.get(e);o?o.needsDeletion=!1:(o=(0,GE.open)(i),Di.set(e,o));let c=new Uo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(FE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,Qr.existsSync)(s)&&(i.path=s,_=(0,GE.open)(i),_.isLegacy=!0):_=bE(o));let l=Kx(r),d=l[YE],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[p,S]=E.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let A=f.get(p);A||f.set(p,A={attributes:[]}),(S==null||h.is_hash_attribute)&&(A.primary=h),S!=null&&A.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let z of p)if(z.is_hash_attribute||z.isPrimaryKey){S=z;break}if(!S){Ss.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let A=l[E],R={},g=[],P,H,v=typeof S.audit=="boolean"?S.audit:(0,Xt.get)(zr.CONFIG_PARAMS.LOGGING_AUDITLOG),U=S.trackDeletes,Y=S.expiration,K=S.eviction;if(A)R=A.indices,g=A.attributes,A.schemaVersion++;else{P=S.tableId,P?P>=(u.get(za)||0)&&u.putSync(za,P+1):(S.tableId=P=u.get(za),P||(P=1),u.putSync(za,P+1),u.putSync(S.key,S));let z=new Uo.default(!S.is_hash_attribute,S.is_hash_attribute);H=t_(o.openDB(S.key,z)),H.rootStore=o,H.tableId=P}for(let z of p){z.attribute=z.name;try{if(!z.is_hash_attribute&&(z.indexed||z.attribute&&!z.name)){if(!R[z.name]){let me=new Uo.default(!z.is_hash_attribute,z.is_hash_attribute);R[z.name]=o.openDB(z.key,me),R[z.name].indexNulls=z.indexNulls}let ne=g.find(me=>me.name===z.name);ne?g.splice(g.indexOf(ne),1,z):g.push(z)}}catch(ne){Ss.error("Error trying to update attribute",z,g,R,ne)}}if(!A){A=Wx(l,E,qE({primaryStore:H,auditStore:_,audit:v,expirationMS:Y&&Y*1e3,evictionMS:K&&K*1e3,trackDeletes:U,tableName:E,tableId:P,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),A.schemaVersion=1;for(let z of NA)z(A)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Kx(e){let t=rt[e];if(t||(e==="data"?t=rt[e]=wr:e==="system"?Object.defineProperty(rt,"system",{value:t=Object.create(null),configurable:!0}):t=rt[e]=Object.create(null)),ja&&!ja.has(e)){let r=new Set;t[YE]=r,ja.set(e,r)}return t}function Wx(e,t,r){return e[t]=r,r}function zc({database:e,table:t}){e||(e=bA),Ds();let r=Kx(e),s=(0,et.join)((0,Xt.getHdbBasePath)(),zr.DATABASES_DIR_NAME),n=(0,Xt.get)(zr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(n.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&n[e]?.tables?.[t]?.path;s=i||n[e]?.path||process.env.STORAGE_PATH||(0,Xt.get)(zr.CONFIG_PARAMS.STORAGE_PATH)||((0,Qr.existsSync)(s)?s:(0,et.join)((0,Xt.getHdbBasePath)(),zr.LEGACY_DATABASES_DIR_NAME));let o=(0,et.join)(s,(i?t:e)+".mdb"),c=Di.get(o);if(!c){let u=new AA.default(o,!1);c=(0,GE.open)(u),Di.set(o,c)}return c}async function zp(e){if(!rt[e])throw new Error("Schema does not exist");let t=rt[e];for(let r in t){let n=t[r].primaryStore.rootStore;Di.delete(n.path),n.status==="open"&&(await n.close(),await Vx.remove(n.path))}if(e==="data"){for(let r in wr)delete wr[r];delete wr[YE]}delete rt[e]}function ct({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=bA);let l=zc({database:t,table:e}),d=rt[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,p,S;u==null&&(u=!0);let A=new Uo.default(!1);for(let U of i)U.attribute?(U.name=U.attribute,U.indexed=!0):U.attribute=U.name,U.expiresAt&&(U.indexed=!0);let R,g;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let U=l.auditStore;U||(U=bE(l)),h=i.find(ne=>ne.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Xt.get)(zr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),s&&(h.eviction=s),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),Ss.trace(`${e} table loading, opening primary store`);let Y=new Uo.default(!1,!0),K=e+"/",z=t_(l.openDB(K,Y));z.rootStore=l,S=l.dbisDb=l.openDB(FE.INTERNAL_DBIS_NAME,A),z.tableId=S.get(za),z.tableId||(z.tableId=1),S.putSync(za,z.tableId+1),h.tableId=z.tableId,f=Wx(d,e,qE({primaryStore:z,auditStore:U,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:s&&s*1e3,primaryKey:E,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,R=!0,v(),S.put(K,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(FE.INTERNAL_DBIS_NAME,A)),f.dbisDB=S;let P=[];for(let{key:U,value:Y}of S.getRange({start:!0})){let[K,z]=U.toString().split("/");if(z===""&&(z=Y.name),z){if(K!==e)continue}else z=K;if(!i.find(me=>me.name===z)?.indexed&&Y.indexed&&!Y.isPrimaryKey){v(),R=!0,S.remove(U);let me=f.indices[K];me&&P.push(me)}}let H=[];try{for(let U of i||[]){if(U.relationship)continue;let Y=e+"/"+(U.name||"");Object.defineProperty(U,"key",{value:Y,configurable:!0});let K=S.get(Y);if(U.isPrimaryKey){if(K=K||S.get(Y=e+"/")||{},o!==f.audit||(+r||void 0)!==(+K.expiration||void 0)||(+s||void 0)!==(+K.eviction||void 0)){let ne=Object.assign({},K);typeof o=="boolean"&&(o&&f.enableAuditing(o),ne.audit=o),r&&(ne.expiration=+r),s&&(ne.eviction=+s),R=!0,v(),S.put(Y,ne)}continue}K?.attribute&&!K.name&&(K.indexed=!0);let z=!K||K.type!==U.type||K.indexed!==U.indexed||K.nullable!==U.nullable||JSON.stringify(K.attributes)!==JSON.stringify(U.attributes)||JSON.stringify(K.elements)!==JSON.stringify(U.elements);if(U.indexed){let ne=new Uo.default(!0,!1),me=l.openDB(Y,ne);(z||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<yl.workerData?.restartNumber)&&(R=!0,v(),K=S.get(Y),(z||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<yl.workerData?.restartNumber)&&(R=!0,U.lastIndexedKey=K?.lastIndexedKey||!1,U.indexingPID=process.pid,me.isIndexing=!0,Object.defineProperty(U,"dbi",{value:me}),U.indexNulls===void 0&&(U.indexNulls=!0),H.push(U)),S.put(Y,U)),K?.indexNulls&&U.indexNulls===void 0&&(U.indexNulls=!0),me.indexNulls=U.indexNulls,p[U.name]=me}else z&&(R=!0,v(),S.put(Y,U))}}finally{g&&g()}if(R&&(f.schemaVersion++,f.updatedAttributes()),Ss.trace(`${e} table loading, running index`),H.length>0||P.length>0?f.indexingOperation=hie(f,H,P):R&&kE.signalSchemaChange(new VE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,R)for(let U of NA)U(f,_!=="cluster");return(r||s||n)&&f.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),Ss.trace(`${e} table loaded`),f;function v(){g||l.transactionSync(()=>({then(U){g=U}}))}a(v,"startTxn")}async function hie(e,t,r){try{let s=e.schemaVersion;await kE.signalSchemaChange(new VE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,n=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,$x.getIndexedValues)(l[h]);if(p)for(let S=0,A=p.length;S<A;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,Ss.error(f)}),yl.workerData&&yl.workerData.restartNumber!==Yx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>fie?await n:u>Eie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,n=e.dbisDB.put(_.key,_)}await n,await kE.signalSchemaChange(new VE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Ss.error("Error in indexing",s)}}function mie({table:e,database:t}){let r=zc({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function MR(e){NA.push(e)}var Xt,FE,GE,et,Qr,Ja,Uo,AA,zr,Vx,OA,$x,kE,VE,yl,Ss,Yx,bA,YE,wr,rt,za,NA,$E,Di,ja,fie,Eie,Ae=Re(()=>{Xt=x(Z()),FE=x(dt()),GE=require("lmdb"),et=require("path"),Qr=require("fs"),Ja=x(Je());xf();Uo=x(r_()),AA=x(n_()),zr=x(L()),Vx=x(require("fs-extra")),OA=require("../index"),$x=x(yr()),kE=x(gn()),VE=x(Is()),yl=require("worker_threads"),Ss=x(V()),Yx=x(Ke());Bi();qo();bA="data",YE=Symbol("defined-tables");(0,Xt.initSync)();wr=Object.create(null),rt=Object.create(null);(0,OA._assignPackageExport)("databases",rt);(0,OA._assignPackageExport)("tables",wr);za=Symbol.for("next-table-id"),NA=[],Di=new Map;a(_ie,"getTables");a(Ds,"getDatabases");a(die,"resetDatabases");a(Nl,"readMetaDb");a(Kx,"ensureDB");a(Wx,"setTable");a(zc,"database");a(zp,"dropDatabase");a(ct,"table");fie=1e3,Eie=10;a(hie,"runIndexing");a(mie,"dropTableMeta");a(MR,"onUpdatedTable")});var J=T((HSe,aq)=>{"use strict";var Li=require("path"),Xx=require("fs-extra"),Or=V(),Qx=require("fs-extra"),KE=require("os"),pie=require("net"),Sie=require("recursive-iterator"),at=L(),Tie=RO(),zx=require("papaparse"),WE=require("moment"),{inspect:gie}=require("util"),Jx=require("is-number"),BSe=require("lodash"),Rie=require("minimist"),Aie=require("https"),Oie=require("http"),{hdb_errors:QE}=re(),bie=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Zx=require("util").promisify(setTimeout),Nie=100,yie=5,wie="",Iie=4,jx={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};aq.exports={isEmpty:Jr,isEmptyOrZeroLength:dn,arrayHasEmptyValues:Lie,arrayHasEmptyOrZeroLengthValues:Uie,buildFolderPath:Mie,isBoolean:eq,errorizeMessage:Cie,stripFileExtension:vie,autoCast:Bie,autoCastJSON:tq,autoCastJSONDeep:wA,removeDir:Hie,compareVersions:xie,isCompatibleDataVersion:qie,escapeRawValue:Fie,unescapeValue:Gie,stringifyProps:kie,timeoutPromise:$ie,isClusterOperation:Kie,getClusterUser:Qie,checkGlobalSchemaTable:Wie,getHomeDir:sq,getPropsFilePath:Vie,promisifyPapaParse:zie,removeBOM:nq,createEventPromise:Jie,checkProcessRunning:jie,checkSchemaTableExist:Xie,checkSchemaExists:iq,checkTableExists:oq,getStartOfTomorrowInSeconds:Zie,getLimitKey:eoe,isObject:Pie,isNotEmptyAndHasValue:Die,autoCasterIsNumberCheck:rq,backtickASTSchemaItems:toe,isPortTaken:Yie,createForkArgs:roe,autoCastBoolean:soe,async_set_timeout:Zx,getTableHashAttribute:noe,doesSchemaExist:ioe,doesTableExist:ooe,stringifyObj:aoe,ms_to_time:coe,changeExtension:uoe,getEnvCliRootPath:IA,noBootFile:loe,httpRequest:_oe,transformReq:doe,convertToMS:foe,PACKAGE_ROOT:at.PACKAGE_ROOT};function Cie(e){return e instanceof Error?e:new Error(e)}a(Cie,"errorizeMessage");function Jr(e){return e==null}a(Jr,"isEmpty");function Die(e){return!Jr(e)&&(e||e===0||e===""||eq(e))}a(Die,"isNotEmptyAndHasValue");function dn(e){return Jr(e)||e.length===0||e.size===0}a(dn,"isEmptyOrZeroLength");function Lie(e){if(Jr(e))return!0;for(let t=0;t<e.length;t++)if(Jr(e[t]))return!0;return!1}a(Lie,"arrayHasEmptyValues");function Uie(e){if(dn(e))return!0;for(let t=0;t<e.length;t++)if(dn(e[t]))return!0;return!1}a(Uie,"arrayHasEmptyOrZeroLengthValues");function Mie(...e){try{return e.join(Li.sep)}catch{console.error(e)}}a(Mie,"buildFolderPath");function eq(e){return Jr(e)?!1:e===!0||e===!1}a(eq,"isBoolean");function Pie(e){return Jr(e)?!1:typeof e=="object"}a(Pie,"isObject");function vie(e){return dn(e)?wie:e.slice(0,-Iie)}a(vie,"stripFileExtension");function Bie(e){return Jr(e)||e===""||typeof e!="string"?e:jx[e]!==void 0?jx[e]:rq(e)===!0?Number(e):bie.test(e)?new Date(e):e}a(Bie,"autoCast");function tq(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(tq,"autoCastJSON");function wA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=wA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=wA(r);s!==r&&(e[t]=s)}return e}else return tq(e)}a(wA,"autoCastJSONDeep");function rq(e){if(e.startsWith("0.")&&Jx(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Jx(e))}a(rq,"autoCasterIsNumberCheck");async function Hie(e){if(dn(e))throw new Error(`Directory path: ${e} does not exist`);try{await Qx.emptyDir(e),await Qx.remove(e)}catch(t){throw Or.error(`Error removing files in ${e} -- ${t}`),t}}a(Hie,"removeDir");function xie(e,t){if(dn(e)){Or.info("Invalid current version sent as parameter.");return}if(dn(t)){Or.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(xie,"compareVersions");function qie(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(qie,"isCompatibleDataVersion");function Fie(e){if(Jr(e))return e;let t=String(e);return t==="."?at.UNICODE_PERIOD:t===".."?at.UNICODE_PERIOD+at.UNICODE_PERIOD:t.replace(at.FORWARD_SLASH_REGEX,at.UNICODE_FORWARD_SLASH)}a(Fie,"escapeRawValue");function Gie(e){if(Jr(e))return e;let t=String(e);return t===at.UNICODE_PERIOD?".":t===at.UNICODE_PERIOD+at.UNICODE_PERIOD?"..":String(e).replace(at.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Gie,"unescapeValue");function kie(e,t){if(Jr(e))return Or.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+KE.EOL}!dn(s)&&s[0]===";"?r+=" "+s+n+KE.EOL:dn(s)||(r+=s+"="+n+KE.EOL)}catch{Or.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(kie,"stringifyProps");function sq(){let e;try{e=KE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(sq,"getHomeDir");function Vie(){let e=Li.join(sq(),at.HDB_HOME_DIR_NAME,at.BOOT_PROPS_FILE_NAME);return Xx.existsSync(e)||(e=Li.join(__dirname,"../","hdb_boot_properties.file")),e}a(Vie,"getPropsFilePath");function $ie(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a($ie,"timeoutPromise");async function Yie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=pie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(Yie,"isPortTaken");function Kie(e){try{return at.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Or.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Kie,"isClusterOperation");function Wie(e,t){let r=(Ae(),se(Fe)).getDatabases();if(!r[e])return QE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return QE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Wie,"checkGlobalSchemaTable");function Qie(e,t){if(Jr(t)){Or.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Jr(e)||dn(e)){Or.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){Or.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Or.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Qie,"getClusterUser");function zie(){zx.parsePromise=function(e,t,r){return new Promise(function(s,n){zx.parse(e,{header:!0,transformHeader:nq,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(zie,"promisifyPapaParse");function nq(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(nq,"removeBOM");function Jie(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Or.info(`Got cluster status event response: ${gie(n)}`);try{i.cancel()}catch{Or.error("Error trying to cancel timeout.")}s(n)})})}a(Jie,"createEventPromise");async function jie(e){let t=!0,r=0;do await Zx(Nie*r++),(await Tie.findPs(e)).length>0&&(t=!1);while(t&&r<yie);if(t)throw new Error(`process ${e} was not started`)}a(jie,"checkProcessRunning");function Xie(e,t){let r=iq(e);if(r)return r;let s=oq(e,t);if(s)return s}a(Xie,"checkSchemaTableExist");function iq(e){let{getDatabases:t}=(Ae(),se(Fe));if(!t()[e])return QE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(iq,"checkSchemaExists");function oq(e,t){let{getDatabases:r}=(Ae(),se(Fe));if(!r()[e][t])return QE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(oq,"checkTableExists");function Zie(){let e=WE().utc().add(1,at.MOMENT_DAYS_TAG).startOf(at.MOMENT_DAYS_TAG).unix(),t=WE().utc().unix();return e-t}a(Zie,"getStartOfTomorrowInSeconds");function eoe(){return WE().utc().format("DD-MM-YYYY")}a(eoe,"getLimitKey");function toe(e){try{let t=new Sie(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){Or.error("Got an error back ticking items."),Or.error(t)}}a(toe,"backtickASTSchemaItems");function roe(e){return[e]}a(roe,"createForkArgs");function soe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(soe,"autoCastBoolean");function noe(e,t){let{getDatabases:r}=(Ae(),se(Fe)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(noe,"getTableHashAttribute");function ioe(e){let{getDatabases:t}=(Ae(),se(Fe));return t()[e]!==void 0}a(ioe,"doesSchemaExist");function ooe(e,t){let{getDatabases:r}=(Ae(),se(Fe));return r()[e]?.[t]!==void 0}a(ooe,"doesTableExist");function aoe(e){try{return JSON.stringify(e)}catch{return e}}a(aoe,"stringifyObj");function coe(e){let t=WE.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(coe,"ms_to_time");function uoe(e,t){let r=Li.basename(e,Li.extname(e));return Li.join(Li.dirname(e),r+t)}a(uoe,"changeExtension");function IA(){if(process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Rie(process.argv);if(e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(IA,"getEnvCliRootPath");var yA;function loe(){if(yA)return yA;let e=IA();IA()&&Xx.pathExistsSync(Li.join(e,at.HDB_CONFIG_FILE))&&(yA=!0)}a(loe,"noBootFile");function _oe(e,t){let r;return e.protocol==="http:"?r=Oie:r=Aie,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(_oe,"httpRequest");function doe(e){if(!e.schema&&!e.database){e.schema=at.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(doe,"transformReq");function foe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(foe,"convertToMS")});var Z=T((qSe,_q)=>{"use strict";var CA=require("fs-extra"),Mo=require("path"),cq=require("os"),Eoe=require("properties-reader"),Il=V(),wl=J(),ue=L(),zE=Ur(),hoe="Error initializing environment manager",JE="BOOT_PROPS_FILE_PATH",uq=!1,moe={[ue.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},kn={};_q.exports={BOOT_PROPS_FILE_PATH:JE,getHdbBasePath:poe,setHdbBasePath:Soe,get:lq,initSync:goe,setProperty:Ue,initTestEnvironment:Roe};function poe(){return kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(poe,"getHdbBasePath");function Soe(e){kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Soe,"setHdbBasePath");function lq(e){let t=zE.getConfigValue(e);return t===void 0?kn[e]:t}a(lq,"get");function Ue(e,t){moe[e]&&(kn[e]=t),zE.updateConfigObject(e,t)}a(Ue,"setProperty");function Toe(){let e;try{e=wl.getPropsFilePath(),CA.accessSync(e,CA.constants.F_OK|CA.constants.R_OK),uq=!0;let t=Eoe(e);return kn[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),kn[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),kn[JE]=e,!0}catch{return Il.trace(`Environment manager found no properties file at ${e}`),!1}}a(Toe,"doesPropFileExist");function goe(e=!1){try{(uq||Toe()||wl.noBootFile())&&(zE.initConfig(e),kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=zE.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Il.error(hoe),Il.error(t),console.error(t),process.exit(1)}}a(goe,"initSync");function Roe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Mo.join(__dirname,"../../","unitTests");kn[JE]=Mo.join(u,"hdb_boot_properties.file"),Ue(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Mo.join(u,"settings.test")),Ue(ue.HDB_SETTINGS_NAMES.INSTALL_USER,cq.userInfo()?cq.userInfo().username:void 0),Ue(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ue(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Mo.join(u,"envDir","log")),Ue(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Mo.join(u,"envDir")),Ue(ue.CONFIG_PARAMS.STORAGE_PATH,Mo.join(u,"envDir")),n&&(Ue(ue.CONFIG_PARAMS.HTTP_SECUREPORT,lq(ue.CONFIG_PARAMS.HTTP_PORT)),Ue(ue.CONFIG_PARAMS.HTTP_PORT,null)),Ue(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Ue(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ue(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,wl.isEmpty(i)?!1:i),Ue(ue.CONFIG_PARAMS.HTTP_CORS,wl.isEmpty(i)?!1:i),Ue(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ue(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Mo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ue(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,wl.isEmpty(c)?!1:c),o&&(Ue("CORS_ACCESSLIST",o),Ue(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ue(ue.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ue(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ue(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${JE}. Please check your boot props and settings files`;Il.fatal(r),Il.error(t)}}a(Roe,"initTestEnvironment")});var mq=T((GSe,hq)=>{"use strict";var Eq=require("joi"),{string:Cl,boolean:dq,array:Aoe}=Eq.types(),fq=L(),Ooe=je();hq.exports=boe;function boe(e){let t=Eq.object({operation:Cl.valid(fq.OPERATIONS_ENUM.ADD_NODE,fq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Cl.required(),subscriptions:Aoe.items({schema:Cl.required(),table:Cl.optional(),hash_attribute:Cl.optional(),subscribe:dq.required(),publish:dq.required()}).min(1).required()});return Ooe.validateBySchema(e,t)}a(boe,"updateRemoteSourceValidator")});var Dl=T((VSe,pq)=>{"use strict";var DA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};pq.exports=DA});var Aq=T((YSe,Rq)=>{"use strict";var Noe=mq(),Vn=V(),LA=Ge(),Sq=L(),UA=is(),MA=st(),Tq=lu(),yoe=$_(),{Node:woe,NodeSubscription:gq}=di(),PA=Dl(),vA=J(),Ioe=Z(),{cloneDeep:Coe}=require("lodash"),{broadcast:Doe}=Ke();Rq.exports=Loe;async function Loe(e){try{let t=Noe(e);if(t)return Vn.error(`Validation error in updateRemoteSource: ${t.message}`),new PA(LA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=Coe(await UA.getNodeRecord(s)),c=!vA.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Vn.trace(`Existing record found for ${s}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!vA.doesSchemaExist(f)){Vn.trace(`updateRemoteSource creating schema: ${f}`);try{await Tq.createSchema({operation:"create_schema",schema:f})}catch(h){Vn.error(h)}}if(E&&!vA.doesTableExist(f,E)){let h=new yoe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Vn.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await Tq.createTable(h)}catch(p){Vn.error(p)}Vn.trace(`Creating local stream for ${f}.${E}`),await MA.createLocalTableStream(f,E)}if(f===Sq.SYSTEM_SCHEMA_NAME&&await MA.createLocalTableStream(f,E),await MA.updateWorkStream(d,s),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let A=o.subscriptions[p];if(A.schema===f&&A.table===E){A.publish=d.publish,A.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new gq(f,E,d.publish,d.subscribe))}else i.push(new gq(f,E,d.publish,d.subscribe))}c||(o=new woe(s,i,void 0),Vn.trace(`No record found for ${s}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=n,await UA.upsertNodeRecord(u),Doe({type:"nats_update"}),new PA(LA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Ioe.get(Sq.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await UA.getSystemInfo())}catch(t){Vn.error(t);let r=t.message?t.message:t;return new PA(LA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Loe,"updateRemoteSource")});var yq=T((WSe,Nq)=>{"use strict";var bq=require("joi"),{string:Oq}=bq.types(),Uoe=L(),Moe=je();Nq.exports=Poe;function Poe(e){let t=bq.object({operation:Oq.valid(Uoe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:Oq.required()});return Moe.validateBySchema(e,t)}a(Poe,"removeRemoteSourceValidator")});var Iq=T((zSe,wq)=>{"use strict";var voe=yq(),jE=V(),XE=Ge(),BA=L(),Boe=is(),Hoe=J(),xoe=st(),qoe=Z(),ZE=Dl(),{NodeSubscription:Foe}=di(),Goe=ra(),koe=ti(),{broadcast:Voe}=Ke(),$oe=qoe.get(BA.CONFIG_PARAMS.CLUSTERING_NODENAME);wq.exports=Yoe;async function Yoe(e){try{let t=voe(e);if(t)return jE.error(`Validation error in removeRemoteSource: ${t.message}`),new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,s=await Boe.getNodeRecord(r);if(Hoe.isEmptyOrZeroLength(s)){let i=`No record found for node '${r}'`;return jE.error(i),new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}s=s[0];for(let i=0,o=s.subscriptions.length;i<o;i++){let c=s.subscriptions[i];jE.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Foe(c.schema,c.table,!1,!1);await xoe.updateWorkStream(u,r)}let n=new Goe(BA.SYSTEM_SCHEMA_NAME,BA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await koe.deleteRecord(n),Voe({type:"nats_update"}),new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${$oe} successfully removed node '${r}'.`)}catch(t){jE.error(t);let r=t.message?t.message:t;return new ZE(XE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Yoe,"removeRemoteSource")});var Mq=T((jSe,Uq)=>{"use strict";var eh=V(),th=L(),Cq=Ge(),Dq=Z(),Koe=J(),Lq=Dl(),Woe=is(),Qoe=md(),zoe=Cr();Uq.exports=Joe;async function Joe(e){try{eh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Koe.ms_to_time(t),s=new joe(Dq.get(th.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),Dq.get(th.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT),r,await Woe.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new Qoe(th.SYSTEM_SCHEMA_NAME,th.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await zoe.update(i)}catch(n){eh.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return eh.trace("getRemoteSourceConfig response:",s),new Lq(Cq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){eh.error(t);let r=t.message?t.message:t;return new Lq(Cq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Joe,"getRemoteSourceConfig");function joe(e,t,r,s){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=s}a(joe,"ConfigResponseObject")});var Hq=T((ZSe,Bq)=>{"use strict";var Pq=Z();Pq.initSync();var vq=st(),Ll=V(),Xa=L(),HA=Ge(),Xoe=Aq(),Zoe=Iq(),eae=Mq(),tae=Dl(),{encode:rae,decode:sae}=require("msgpackr"),nae=Tn(),iae=Xn(),oae=require("util"),aae=L(),{isMainThread:cae,parentPort:uae}=require("worker_threads");Ke();var lae=oae.promisify(nae.setSchemaDataToGlobal),xA=Pq.get(Xa.CONFIG_PARAMS.CLUSTERING_NODENAME);Bq.exports=_ae;async function _ae(){try{Ll.notify("Starting reply service."),await lae();let e=await vq.getConnection(),t=`${xA}.__request__`,r=e.subscribe(t,{queue:xA});await dae(r)}catch(e){Ll.error(e)}}a(_ae,"initialize");async function dae(e){for await(let t of e){let r=sae(t.data),s;switch(r.operation){case Xa.OPERATIONS_ENUM.ADD_NODE:case Xa.OPERATIONS_ENUM.UPDATE_NODE:s=await Xoe(r);break;case Xa.OPERATIONS_ENUM.REMOVE_NODE:s=await Zoe(r);break;case Xa.OPERATIONS_ENUM.CLUSTER_STATUS:s=await eae(r);break;case Xa.OPERATIONS_ENUM.DESCRIBE_ALL:s=await fae();break;default:let n=`node '${xA}' reply service received unrecognized request operation`;Ll.error(n),s=new tae(HA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}Ll.trace(s),t.respond(rae(s))}}a(dae,"handleRequest");async function fae(){try{return{status:HA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await iae.describeAll()}}catch(e){return Ll.error(e),{status:HA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(fae,"getRemoteDescribeAll");cae||uae.on("message",async e=>{let{type:t}=e;t===aae.ITC_EVENT_TYPES.SHUTDOWN&&vq.closeConnection()})});var Eae=Hq();(async()=>{try{await Eae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|