harperdb 4.3.2 → 4.3.4
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 +23 -23
- package/bin/lite.js +18 -18
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +18 -18
- package/launchServiceScripts/launchNatsReplyService.js +20 -20
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +18 -18
- package/npm-shrinkwrap.json +113 -106
- package/package.json +2 -2
- package/resources/Table.d.ts +3 -3
- package/resources/databases.d.ts +3 -3
- package/server/jobs/jobProcess.js +18 -18
- package/server/threads/threadServer.js +17 -17
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.a7ed3686.js → main.e68de7dd.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -19
- /package/studio/build-local/static/js/{main.a7ed3686.js.LICENSE.txt → main.e68de7dd.js.LICENSE.txt} +0 -0
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
"use strict";var UG=Object.create;var sc=Object.defineProperty;var PG=Object.getOwnPropertyDescriptor;var vG=Object.getOwnPropertyNames;var BG=Object.getPrototypeOf,HG=Object.prototype.hasOwnProperty;var a=(e,t)=>sc(e,"name",{value:t,configurable:!0});var ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fe=(e,t)=>{for(var r in t)sc(e,r,{get:t[r],enumerable:!0})},zA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of vG(t))!HG.call(e,s)&&s!==r&&sc(e,s,{get:()=>t[s],enumerable:!(n=PG(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?UG(BG(e)):{},zA(t||!e||!e.__esModule?sc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>zA(sc({},"__esModule",{value:!0}),e);var XA=R((Soe,jA)=>{var xG=require("fast-glob"),{statSync:Th,existsSync:gh,readFileSync:GG,writeFileSync:FG}=require("fs"),{spawnSync:qG,spawn:kG,execFileSync:poe}=require("child_process"),{isMainThread:VG}=require("worker_threads"),{join:zs,relative:JA}=require("path"),{PACKAGE_ROOT:On}=U(),{tmpdir:$G,platform:YG}=require("os");require("source-map-support").install();var KG=["resources","server","dataLayer","components"],ic="ts-build",Rh,WG=__filename.endsWith("tsBuild.js");if(WG){if(VG){let r;try{Th(zs(On,ic)),r=!0}catch{}if(r)for(let n of xG.sync(KG.map(s=>s+"/**/*.ts"),{cwd:On})){let s=0,i=0;try{s=Th(zs(On,n)).mtimeMs-5e3,i=Th(zs(On,ic,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Rh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Rh=!0;if(Rh){let n=zs(On,"node_modules/.bin/tsc");YG()==="win32"&&(n+=".cmd");let s=qG(n,{cwd:On});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=zs($G(),"harperdb-tsc.pid"),o;if(gh(i))try{process.kill(+GG(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=kG(n,["--watch"],{cwd:On,detached:!0,stdio:"ignore"});FG(i,c.pid.toString()),c.unref()}}}}let e=jA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(On)&&!n[0].includes("node_modules")){let i=JA(On,n[0]),o;i.startsWith(ic)?o=zs(On,JA(ic,i)):o=zs(On,ic,i);let c=zs(o,r),u=c+".js";if(gh(u))return u;if(c.includes(".")&&gh(c))return c}return t(r,n,s)}}});var U=R((Roe,dO)=>{"use strict";var nn=require("path"),QG=require("fs"),{relative:Toe,join:goe}=nn,{existsSync:zG}=QG;function JG(){let e=__dirname;for(;!zG(nn.join(e,"package.json"));){let t=nn.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(JG,"getHDBPackageRoot");var Js=JG(),ZA="js",Ql=ZA,jG="harperdb-config.yaml",XG="defaultConfig.yaml",ZG="hdb",eO=`harperdb.${Ql}`,tO=`customFunctionsServer.${Ql}`,eF=`restartHdb.${Ql}`,Oh="HarperDB",Wl="Custom Functions",zl="Clustering Hub",Jl="Clustering Leaf",tF="Clustering Ingest Service",rF="Clustering Reply Service",nF="foreground.pid",sF="hdb.pid",iF="data",oF={HDB:Oh,CLUSTERING_HUB:zl,CLUSTERING_LEAF:Jl,CLUSTERING_INGEST_SERVICE:tF,CLUSTERING_REPLY_SERVICE:rF,CUSTOM_FUNCTIONS:Wl,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"},aF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},cF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},uF={harperdb:Oh,"clustering hub":zl,"clustering leaf":Jl,"custom functions":Wl,custom_functions:Wl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},lF={CLUSTERING_HUB_PROC_DESCRIPTOR:zl,CLUSTERING_LEAF_PROC_DESCRIPTOR:Jl},Ah={HDB:nn.join(Js,"server/harperdb"),CUSTOM_FUNCTIONS:nn.join(Js,"server/customFunctions"),CLUSTERING_HUB:nn.join(Js,"server/nats"),CLUSTERING_LEAF:nn.join(Js,"server/nats")},_F={HDB:nn.join(Ah.HDB,eO),CUSTOM_FUNCTIONS:nn.join(Ah.CUSTOM_FUNCTIONS,tO)},dF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:nn.join(Js,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:nn.join(Js,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:nn.join(Js,"launchServiceScripts/launchUpdateNodes4-0-0.js")},fF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},rO="support@harperdb.io",EF="customer-success@harperdb.io",nO=1,hF=4141,sO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",mF="https://www.harperdb.io/product",pF=`For support, please submit a request at ${sO} or contact ${rO}`,iO=`For license support, please contact ${EF}`,SF="None of the specified records were found.",TF="hash attribute not found",gF=`Your current license only supports ${nO} role. ${iO}`,RF="Your current license only supports 3 connections to a node.",AF="127.0.0.1",OF=1,bF=/^\.$/,yF=/^\.\.$/,NF="U+002E",IF=/\//g,wF="U+002F",CF=/U\+002F/g,DF=/^U\+002E$/,LF=/^U\+002EU\+002E$/,MF="d",UF=999999,PF="*",vF="--max-old-space-size=",BF="system",HF="__hdb_hash",xF=".harperdb",GF=".hdb",FF="keys",qF="hdb_boot_properties.file",kF=".updateConfig.json",VF="SIGTSTP",$F=24,YF=6e4,KF=448,WF="blob",QF="trash",zF="database",JF="schema",jF="transactions",XF=".count",ZF="id",eq="PROCESS_NAME",oO={SETTINGS_PATH_KEY:"settings_path"},aO=require("lodash"),tq={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"},rq={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},nq={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},sq={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"},iq={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"},wr="hdb_internal:",oq={CREATE_SCHEMA:wr+"create_schema",CREATE_TABLE:wr+"create_table",CREATE_ATTRIBUTE:wr+"create_attribute",ADD_USER:wr+"add_user",ALTER_USER:wr+"alter_user",DROP_USER:wr+"drop_user",HDB_NODES:wr+"hdb_nodes",HDB_USERS:wr+"hdb_users",HDB_WORKERS:wr+"hdb_workers",CATCHUP:wr+"catchup",SCHEMA_CATCHUP:wr+"schema_catchup",WORKER_ROOM:wr+"cluster_workers"},aq={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"},cq="060493.ks",uq=".license",lq={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},Z={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"},_q={CSV:".csv",JSON:".json"},dq={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},fq={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},oc={};oc[Z.INSERT]=Z.INSERT;oc[Z.UPDATE]=Z.UPDATE;oc[Z.UPSERT]=Z.UPSERT;oc[Z.DELETE]=Z.DELETE;var xe=Object.create(null);xe[Z.DESCRIBE_ALL]=Z.DESCRIBE_ALL;xe[Z.DESCRIBE_TABLE]=Z.DESCRIBE_TABLE;xe[Z.DESCRIBE_SCHEMA]=Z.DESCRIBE_SCHEMA;xe[Z.READ_LOG]=Z.READ_LOG;xe[Z.ADD_NODE]=Z.ADD_NODE;xe[Z.LIST_USERS]=Z.LIST_USERS;xe[Z.LIST_ROLES]=Z.LIST_ROLES;xe[Z.USER_INFO]=Z.USER_INFO;xe[Z.SQL]=Z.SQL;xe[Z.GET_JOB]=Z.GET_JOB;xe[Z.SEARCH_JOBS_BY_START_DATE]=Z.SEARCH_JOBS_BY_START_DATE;xe[Z.DELETE_FILES_BEFORE]=Z.DELETE_FILES_BEFORE;xe[Z.EXPORT_LOCAL]=Z.EXPORT_LOCAL;xe[Z.EXPORT_TO_S3]=Z.EXPORT_TO_S3;xe[Z.CLUSTER_STATUS]=Z.CLUSTER_STATUS;xe[Z.REMOVE_NODE]=Z.REMOVE_NODE;xe[Z.RESTART]=Z.RESTART;xe[Z.CUSTOM_FUNCTIONS_STATUS]=Z.CUSTOM_FUNCTIONS_STATUS;xe[Z.GET_CUSTOM_FUNCTIONS]=Z.GET_CUSTOM_FUNCTIONS;xe[Z.GET_CUSTOM_FUNCTION]=Z.GET_CUSTOM_FUNCTION;xe[Z.SET_CUSTOM_FUNCTION]=Z.SET_CUSTOM_FUNCTION;xe[Z.DROP_CUSTOM_FUNCTION]=Z.DROP_CUSTOM_FUNCTION;xe[Z.ADD_CUSTOM_FUNCTION_PROJECT]=Z.ADD_CUSTOM_FUNCTION_PROJECT;xe[Z.DROP_CUSTOM_FUNCTION_PROJECT]=Z.DROP_CUSTOM_FUNCTION_PROJECT;xe[Z.PACKAGE_CUSTOM_FUNCTION_PROJECT]=Z.PACKAGE_CUSTOM_FUNCTION_PROJECT;xe[Z.DEPLOY_CUSTOM_FUNCTION_PROJECT]=Z.DEPLOY_CUSTOM_FUNCTION_PROJECT;var Eq={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",COPYDB:"copy-db"},hq={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},cO={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"},mq=aO.invert(cO),pq={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"},w={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_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_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",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",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",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",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",CLONED:"cloned"},uO={settings_path:oO.SETTINGS_PATH_KEY,hdb_root_key:w.ROOTPATH,hdb_root:w.ROOTPATH,rootpath:w.ROOTPATH,server_port_key:w.OPERATIONSAPI_NETWORK_PORT,server_port:w.OPERATIONSAPI_NETWORK_PORT,cert_key:w.TLS_CERTIFICATE,certificate:w.TLS_CERTIFICATE,private_key_key:w.TLS_PRIVATEKEY,private_key:w.TLS_PRIVATEKEY,http_secure_enabled_key:w.OPERATIONSAPI_NETWORK_HTTPS,https_on:w.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:w.OPERATIONSAPI_NETWORK_CORS,cors_on:w.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:w.LOGGING_LEVEL,log_level:w.LOGGING_LEVEL,log_path_key:w.LOGGING_ROOT,log_path:w.LOGGING_ROOT,clustering_node_name_key:w.CLUSTERING_NODENAME,node_name:w.CLUSTERING_NODENAME,clustering_enabled_key:w.CLUSTERING_ENABLED,clustering:w.CLUSTERING_ENABLED,max_http_threads:w.THREADS_COUNT,max_hdb_processes:w.THREADS_COUNT,server_timeout_key:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:w.LOGGING_AUDITLOG,disable_transaction_log:w.LOGGING_AUDITLOG,operation_token_timeout_key:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:w.HTTP_PORT,custom_functions_port:w.HTTP_PORT,custom_functions_directory_key:w.COMPONENTSROOT,custom_functions_directory:w.COMPONENTSROOT,max_custom_function_processes:w.THREADS_COUNT,log_to_file:w.LOGGING_FILE,log_to_stdstreams:w.LOGGING_STDSTREAMS,local_studio_on:w.LOCALSTUDIO_ENABLED,clustering_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:w.CLUSTERING_USER,clustering_enabled:w.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:w.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:w.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:w.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:w.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:w.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:w.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:w.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:w.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:w.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:w.CLUSTERING_NODENAME,clustering_tls_certificate:w.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:w.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:w.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:w.CLUSTERING_TLS_INSECURE,clustering_tls_verify:w.CLUSTERING_TLS_VERIFY,clustering_loglevel:w.CLUSTERING_LOGLEVEL,clustering_republishmessages:w.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:w.CLUSTERING_DATABASELEVEL,customfunctions_network_port:w.HTTP_PORT,customfunctions_tls_certificate:w.TLS_CERTIFICATE,customfunctions_network_cors:w.HTTP_CORS,customfunctions_network_corsaccesslist:w.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:w.HTTP_HEADERSTIMEOUT,customfunctions_network_https:w.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:w.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:w.HTTP_TIMEOUT,http_threads:w.THREADS_COUNT,threads:w.THREADS_COUNT,threads_count:w.THREADS_COUNT,threads_debug:w.THREADS_DEBUG,threads_debug_startingport:w.THREADS_DEBUG_STARTINGPORT,threads_debug_port:w.THREADS_DEBUG_PORT,threads_debug_host:w.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:w.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:w.THREADS_MAXHEAPMEMORY,http_session_affinity:w.HTTP_SESSIONAFFINITY,http_compressionthreshold:w.HTTP_COMPRESSIONTHRESHOLD,http_cors:w.HTTP_CORS,http_corsaccesslist:w.HTTP_CORSACCESSLIST,http_headerstimeout:w.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,http_timeout:w.HTTP_TIMEOUT,http_port:w.HTTP_PORT,http_secureport:w.HTTP_SECUREPORT,http_mtls:w.HTTP_MTLS,http_mtls_user:w.HTTP_MTLS_USER,http_mtls_required:w.HTTP_MTLS_REQUIRED,customfunctions_processes:w.THREADS_COUNT,customfunctions_root:w.COMPONENTSROOT,localstudio_enabled:w.LOCALSTUDIO_ENABLED,logging_file:w.LOGGING_FILE,logging_level:w.LOGGING_LEVEL,logging_root:w.LOGGING_ROOT,logging_rotation_enabled:w.LOGGING_ROTATION_ENABLED,logging_rotation_compress:w.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:w.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:w.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:w.LOGGING_ROTATION_PATH,logging_stdstreams:w.LOGGING_STDSTREAMS,logging_auditlog:w.LOGGING_AUDITLOG,logging_auditretention:w.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:w.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:w.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:w.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:w.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:w.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:w.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:w.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:w.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:w.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:w.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:w.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:w.ROOTPATH,databases:w.DATABASES,storage_path:w.STORAGE_PATH,ignorescripts:w.IGNORE_SCRIPTS,mqtt_network_port:w.MQTT_NETWORK_PORT,mqtt_websocket:w.MQTT_WEBSOCKET,mqtt_network_secureport:w.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:w.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:w.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:w.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:w.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:w.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:w.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:w.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:w.AUTHENTICATION_CACHETTL,authentication_enablesessions:w.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:w.COMPONENTSROOT,tls_certificate:w.TLS_CERTIFICATE,tls_privatekey:w.TLS_PRIVATEKEY,tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,tls_ciphers:w.TLS_CIPHERS};for(let e in w){let t=w[e];uO[t.toLowerCase()]=t}var Sq={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Tq={csv_file_load:"csv_file_load",csv_data_load:Z.CSV_DATA_LOAD,csv_url_load:Z.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"},gq={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"},Rq={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Aq={VERSION_DEFAULT:"2.2.0"},Oq={DEVELOPMENT:8192,DEFAULT:512},bq={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"},yq={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"},Nq={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},lO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Iq=Symbol("metadata"),wq="__clustering__",Cq=Object.values(lO),Dq=15984864e5,_O={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Lq=aO.invert(_O),Mq={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"},Uq=111,Pq=`\r
|
|
2
|
-
`,vq={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Bq=["*","%"],Hq="unauthorized_access",xq="func_val",Gq={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Fq={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},qq={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",NATS_CONSUMER_UPDATE:"nats_consumer_update"},kq={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Vq={HTTP:"http"},$q={STOPPED:"stopped",ONLINE:"online"},Yq="3.x.x",Kq={SUCCESS:"success",FAILURE:"failure"},Wq={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};dO.exports={LOCAL_HARPERDB_OPERATIONS:xe,HDB_SUPPORT_ADDRESS:rO,HDB_SUPPORT_URL:sO,HDB_PRICING_URL:mF,SUPPORT_HELP_MSG:pF,LICENSE_HELP_MSG:iO,HDB_PROC_NAME:eO,HDB_PROC_DESCRIPTOR:
|
|
3
|
-
`}a(ps,"createLogRecord");function
|
|
4
|
-
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:fk.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(pk,"findPs")});var ct=R((Coe,CO)=>{"use strict";var Sk="__dbis__",Tk="__txns__",gk="__environment_name__",Rk="__dbi_defintion__",Ak={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"},Ok=["__createdtime__","__updatedtime__"],bk="\uFFFF",wO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},yk=Object.values(wO);CO.exports={AUDIT_STORE_NAME:Tk,INTERNAL_DBIS_NAME:Sk,DBI_DEFINITION_NAME:Rk,SEARCH_TYPES:Ak,TIMESTAMP_NAMES:Ok,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:gk,TRANSACTIONS_DBI_NAMES_ENUM:wO,TRANSACTIONS_DBIS:yk,OVERFLOW_MARKER:bk}});var Cr=R((Doe,xO)=>{"use strict";var DO=U(),LO=ct(),MO={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},UO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),PO={500:UO("There was an error processing your request."),400:"Invalid request"},Nk=PO[MO.INTERNAL_SERVER_ERROR],Ik={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.`},wk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},Ck={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"},Dk={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 ${LO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${LO.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"},Lk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${DO.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 ${DO.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"},vO={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"},Mk={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."},Uk={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`},Pk={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"},vk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Bk={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`},BO={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.`},HO={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}`},Hk={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."},xk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Gk={...vO,...Ck,...Ik,...Mk,...Uk,...Pk,...vk,...Bk,...Lk,...BO,...HO,...Hk,...xk,...wk};xO.exports={CHECK_LOGS_WRAPPER:UO,HDB_ERROR_MSGS:Gk,DEFAULT_ERROR_MSGS:PO,DEFAULT_ERROR_RESP:Nk,HTTP_STATUS_CODES:MO,LMDB_ERRORS_ENUM:Dk,AUTHENTICATION_ERROR_MSGS:vO,VALIDATION_ERROR_MSGS:BO,ITC_ERRORS:HO}});var ne=R((Moe,qO)=>{"use strict";var Fo=Cr(),Fk=Y(),qk=U(),t_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,GO),this.statusCode=n||Fo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Fo.DEFAULT_ERROR_MSGS[n]?Fo.DEFAULT_ERROR_MSGS[n]:Fo.DEFAULT_ERROR_MSGS[Fo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&Fk[s](i)}},Mh=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}},Uh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function GO(e,t,r,n=qk.LOG_LEVELS.ERROR,s=null,i=!1){if(FO(e))return e;let o=new t_(e,t,r,n,s);return i&&delete o.stack,o}a(GO,"handleHDBError");function FO(e){return e.__proto__.constructor.name===t_.name}a(FO,"isHDBError");qO.exports={isHDBError:FO,handleHDBError:GO,ClientError:Mh,ServerError:Uh,hdb_errors:Fo}});var VO=R((Poe,kO)=>{"use strict";var kk={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 UG=Object.create;var ic=Object.defineProperty;var PG=Object.getOwnPropertyDescriptor;var vG=Object.getOwnPropertyNames;var BG=Object.getPrototypeOf,HG=Object.prototype.hasOwnProperty;var a=(e,t)=>ic(e,"name",{value:t,configurable:!0});var ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fe=(e,t)=>{for(var r in t)ic(e,r,{get:t[r],enumerable:!0})},zA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of vG(t))!HG.call(e,s)&&s!==r&&ic(e,s,{get:()=>t[s],enumerable:!(n=PG(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?UG(BG(e)):{},zA(t||!e||!e.__esModule?ic(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>zA(ic({},"__esModule",{value:!0}),e);var XA=R((Soe,jA)=>{var xG=require("fast-glob"),{statSync:gh,existsSync:Rh,readFileSync:GG,writeFileSync:FG}=require("fs"),{spawnSync:qG,spawn:kG,execFileSync:poe}=require("child_process"),{isMainThread:VG}=require("worker_threads"),{join:zs,relative:JA}=require("path"),{PACKAGE_ROOT:On}=U(),{tmpdir:$G,platform:YG}=require("os");require("source-map-support").install();var KG=["resources","server","dataLayer","components"],oc="ts-build",Ah,WG=__filename.endsWith("tsBuild.js");if(WG){if(VG){let r;try{gh(zs(On,oc)),r=!0}catch{}if(r)for(let n of xG.sync(KG.map(s=>s+"/**/*.ts"),{cwd:On})){let s=0,i=0;try{s=gh(zs(On,n)).mtimeMs-5e3,i=gh(zs(On,oc,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Ah=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Ah=!0;if(Ah){let n=zs(On,"node_modules/.bin/tsc");YG()==="win32"&&(n+=".cmd");let s=qG(n,{cwd:On});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=zs($G(),"harperdb-tsc.pid"),o;if(Rh(i))try{process.kill(+GG(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=kG(n,["--watch"],{cwd:On,detached:!0,stdio:"ignore"});FG(i,c.pid.toString()),c.unref()}}}}let e=jA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(On)&&!n[0].includes("node_modules")){let i=JA(On,n[0]),o;i.startsWith(oc)?o=zs(On,JA(oc,i)):o=zs(On,oc,i);let c=zs(o,r),u=c+".js";if(Rh(u))return u;if(c.includes(".")&&Rh(c))return c}return t(r,n,s)}}});var U=R((Roe,dO)=>{"use strict";var nn=require("path"),QG=require("fs"),{relative:Toe,join:goe}=nn,{existsSync:zG}=QG;function JG(){let e=__dirname;for(;!zG(nn.join(e,"package.json"));){let t=nn.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(JG,"getHDBPackageRoot");var Js=JG(),ZA="js",Ql=ZA,jG="harperdb-config.yaml",XG="defaultConfig.yaml",ZG="hdb",eO=`harperdb.${Ql}`,tO=`customFunctionsServer.${Ql}`,eF=`restartHdb.${Ql}`,bh="HarperDB",Wl="Custom Functions",zl="Clustering Hub",Jl="Clustering Leaf",tF="Clustering Ingest Service",rF="Clustering Reply Service",nF="foreground.pid",sF="hdb.pid",iF="data",oF={HDB:bh,CLUSTERING_HUB:zl,CLUSTERING_LEAF:Jl,CLUSTERING_INGEST_SERVICE:tF,CLUSTERING_REPLY_SERVICE:rF,CUSTOM_FUNCTIONS:Wl,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"},aF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},cF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},uF={harperdb:bh,"clustering hub":zl,"clustering leaf":Jl,"custom functions":Wl,custom_functions:Wl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},lF={CLUSTERING_HUB_PROC_DESCRIPTOR:zl,CLUSTERING_LEAF_PROC_DESCRIPTOR:Jl},Oh={HDB:nn.join(Js,"server/harperdb"),CUSTOM_FUNCTIONS:nn.join(Js,"server/customFunctions"),CLUSTERING_HUB:nn.join(Js,"server/nats"),CLUSTERING_LEAF:nn.join(Js,"server/nats")},_F={HDB:nn.join(Oh.HDB,eO),CUSTOM_FUNCTIONS:nn.join(Oh.CUSTOM_FUNCTIONS,tO)},dF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:nn.join(Js,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:nn.join(Js,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:nn.join(Js,"launchServiceScripts/launchUpdateNodes4-0-0.js")},fF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},rO="support@harperdb.io",EF="customer-success@harperdb.io",nO=1,hF=4141,sO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",mF="https://www.harperdb.io/product",pF=`For support, please submit a request at ${sO} or contact ${rO}`,iO=`For license support, please contact ${EF}`,SF="None of the specified records were found.",TF="hash attribute not found",gF=`Your current license only supports ${nO} role. ${iO}`,RF="Your current license only supports 3 connections to a node.",AF="127.0.0.1",OF=1,bF=/^\.$/,yF=/^\.\.$/,NF="U+002E",IF=/\//g,wF="U+002F",CF=/U\+002F/g,DF=/^U\+002E$/,LF=/^U\+002EU\+002E$/,MF="d",UF=999999,PF="*",vF="--max-old-space-size=",BF="system",HF="__hdb_hash",xF=".harperdb",GF=".hdb",FF="keys",qF="hdb_boot_properties.file",kF=".updateConfig.json",VF="SIGTSTP",$F=24,YF=6e4,KF=448,WF="blob",QF="trash",zF="database",JF="schema",jF="transactions",XF=".count",ZF="id",eq="PROCESS_NAME",oO={SETTINGS_PATH_KEY:"settings_path"},aO=require("lodash"),tq={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"},rq={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},nq={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},sq={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"},iq={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"},Dr="hdb_internal:",oq={CREATE_SCHEMA:Dr+"create_schema",CREATE_TABLE:Dr+"create_table",CREATE_ATTRIBUTE:Dr+"create_attribute",ADD_USER:Dr+"add_user",ALTER_USER:Dr+"alter_user",DROP_USER:Dr+"drop_user",HDB_NODES:Dr+"hdb_nodes",HDB_USERS:Dr+"hdb_users",HDB_WORKERS:Dr+"hdb_workers",CATCHUP:Dr+"catchup",SCHEMA_CATCHUP:Dr+"schema_catchup",WORKER_ROOM:Dr+"cluster_workers"},aq={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"},cq="060493.ks",uq=".license",lq={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},Z={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"},_q={CSV:".csv",JSON:".json"},dq={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},fq={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},ac={};ac[Z.INSERT]=Z.INSERT;ac[Z.UPDATE]=Z.UPDATE;ac[Z.UPSERT]=Z.UPSERT;ac[Z.DELETE]=Z.DELETE;var xe=Object.create(null);xe[Z.DESCRIBE_ALL]=Z.DESCRIBE_ALL;xe[Z.DESCRIBE_TABLE]=Z.DESCRIBE_TABLE;xe[Z.DESCRIBE_SCHEMA]=Z.DESCRIBE_SCHEMA;xe[Z.READ_LOG]=Z.READ_LOG;xe[Z.ADD_NODE]=Z.ADD_NODE;xe[Z.LIST_USERS]=Z.LIST_USERS;xe[Z.LIST_ROLES]=Z.LIST_ROLES;xe[Z.USER_INFO]=Z.USER_INFO;xe[Z.SQL]=Z.SQL;xe[Z.GET_JOB]=Z.GET_JOB;xe[Z.SEARCH_JOBS_BY_START_DATE]=Z.SEARCH_JOBS_BY_START_DATE;xe[Z.DELETE_FILES_BEFORE]=Z.DELETE_FILES_BEFORE;xe[Z.EXPORT_LOCAL]=Z.EXPORT_LOCAL;xe[Z.EXPORT_TO_S3]=Z.EXPORT_TO_S3;xe[Z.CLUSTER_STATUS]=Z.CLUSTER_STATUS;xe[Z.REMOVE_NODE]=Z.REMOVE_NODE;xe[Z.RESTART]=Z.RESTART;xe[Z.CUSTOM_FUNCTIONS_STATUS]=Z.CUSTOM_FUNCTIONS_STATUS;xe[Z.GET_CUSTOM_FUNCTIONS]=Z.GET_CUSTOM_FUNCTIONS;xe[Z.GET_CUSTOM_FUNCTION]=Z.GET_CUSTOM_FUNCTION;xe[Z.SET_CUSTOM_FUNCTION]=Z.SET_CUSTOM_FUNCTION;xe[Z.DROP_CUSTOM_FUNCTION]=Z.DROP_CUSTOM_FUNCTION;xe[Z.ADD_CUSTOM_FUNCTION_PROJECT]=Z.ADD_CUSTOM_FUNCTION_PROJECT;xe[Z.DROP_CUSTOM_FUNCTION_PROJECT]=Z.DROP_CUSTOM_FUNCTION_PROJECT;xe[Z.PACKAGE_CUSTOM_FUNCTION_PROJECT]=Z.PACKAGE_CUSTOM_FUNCTION_PROJECT;xe[Z.DEPLOY_CUSTOM_FUNCTION_PROJECT]=Z.DEPLOY_CUSTOM_FUNCTION_PROJECT;var Eq={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",COPYDB:"copy-db"},hq={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},cO={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"},mq=aO.invert(cO),pq={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"},w={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_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_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",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",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",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",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",CLONED:"cloned"},uO={settings_path:oO.SETTINGS_PATH_KEY,hdb_root_key:w.ROOTPATH,hdb_root:w.ROOTPATH,rootpath:w.ROOTPATH,server_port_key:w.OPERATIONSAPI_NETWORK_PORT,server_port:w.OPERATIONSAPI_NETWORK_PORT,cert_key:w.TLS_CERTIFICATE,certificate:w.TLS_CERTIFICATE,private_key_key:w.TLS_PRIVATEKEY,private_key:w.TLS_PRIVATEKEY,http_secure_enabled_key:w.OPERATIONSAPI_NETWORK_HTTPS,https_on:w.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:w.OPERATIONSAPI_NETWORK_CORS,cors_on:w.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:w.LOGGING_LEVEL,log_level:w.LOGGING_LEVEL,log_path_key:w.LOGGING_ROOT,log_path:w.LOGGING_ROOT,clustering_node_name_key:w.CLUSTERING_NODENAME,node_name:w.CLUSTERING_NODENAME,clustering_enabled_key:w.CLUSTERING_ENABLED,clustering:w.CLUSTERING_ENABLED,max_http_threads:w.THREADS_COUNT,max_hdb_processes:w.THREADS_COUNT,server_timeout_key:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:w.LOGGING_AUDITLOG,disable_transaction_log:w.LOGGING_AUDITLOG,operation_token_timeout_key:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:w.HTTP_PORT,custom_functions_port:w.HTTP_PORT,custom_functions_directory_key:w.COMPONENTSROOT,custom_functions_directory:w.COMPONENTSROOT,max_custom_function_processes:w.THREADS_COUNT,log_to_file:w.LOGGING_FILE,log_to_stdstreams:w.LOGGING_STDSTREAMS,local_studio_on:w.LOCALSTUDIO_ENABLED,clustering_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:w.CLUSTERING_USER,clustering_enabled:w.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:w.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:w.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:w.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:w.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:w.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:w.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:w.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:w.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:w.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:w.CLUSTERING_NODENAME,clustering_tls_certificate:w.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:w.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:w.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:w.CLUSTERING_TLS_INSECURE,clustering_tls_verify:w.CLUSTERING_TLS_VERIFY,clustering_loglevel:w.CLUSTERING_LOGLEVEL,clustering_republishmessages:w.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:w.CLUSTERING_DATABASELEVEL,customfunctions_network_port:w.HTTP_PORT,customfunctions_tls_certificate:w.TLS_CERTIFICATE,customfunctions_network_cors:w.HTTP_CORS,customfunctions_network_corsaccesslist:w.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:w.HTTP_HEADERSTIMEOUT,customfunctions_network_https:w.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:w.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:w.HTTP_TIMEOUT,http_threads:w.THREADS_COUNT,threads:w.THREADS_COUNT,threads_count:w.THREADS_COUNT,threads_debug:w.THREADS_DEBUG,threads_debug_startingport:w.THREADS_DEBUG_STARTINGPORT,threads_debug_port:w.THREADS_DEBUG_PORT,threads_debug_host:w.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:w.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:w.THREADS_MAXHEAPMEMORY,http_session_affinity:w.HTTP_SESSIONAFFINITY,http_compressionthreshold:w.HTTP_COMPRESSIONTHRESHOLD,http_cors:w.HTTP_CORS,http_corsaccesslist:w.HTTP_CORSACCESSLIST,http_headerstimeout:w.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,http_timeout:w.HTTP_TIMEOUT,http_port:w.HTTP_PORT,http_secureport:w.HTTP_SECUREPORT,http_mtls:w.HTTP_MTLS,http_mtls_user:w.HTTP_MTLS_USER,http_mtls_required:w.HTTP_MTLS_REQUIRED,customfunctions_processes:w.THREADS_COUNT,customfunctions_root:w.COMPONENTSROOT,localstudio_enabled:w.LOCALSTUDIO_ENABLED,logging_file:w.LOGGING_FILE,logging_level:w.LOGGING_LEVEL,logging_root:w.LOGGING_ROOT,logging_rotation_enabled:w.LOGGING_ROTATION_ENABLED,logging_rotation_compress:w.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:w.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:w.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:w.LOGGING_ROTATION_PATH,logging_stdstreams:w.LOGGING_STDSTREAMS,logging_auditlog:w.LOGGING_AUDITLOG,logging_auditretention:w.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:w.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:w.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:w.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:w.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:w.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:w.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:w.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:w.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:w.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:w.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:w.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:w.ROOTPATH,databases:w.DATABASES,storage_path:w.STORAGE_PATH,ignorescripts:w.IGNORE_SCRIPTS,mqtt_network_port:w.MQTT_NETWORK_PORT,mqtt_websocket:w.MQTT_WEBSOCKET,mqtt_network_secureport:w.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:w.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:w.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:w.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:w.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:w.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:w.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:w.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:w.AUTHENTICATION_CACHETTL,authentication_enablesessions:w.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:w.COMPONENTSROOT,tls_certificate:w.TLS_CERTIFICATE,tls_privatekey:w.TLS_PRIVATEKEY,tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,tls_ciphers:w.TLS_CIPHERS};for(let e in w){let t=w[e];uO[t.toLowerCase()]=t}var Sq={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Tq={csv_file_load:"csv_file_load",csv_data_load:Z.CSV_DATA_LOAD,csv_url_load:Z.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"},gq={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"},Rq={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Aq={VERSION_DEFAULT:"2.2.0"},Oq={DEVELOPMENT:8192,DEFAULT:512},bq={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"},yq={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"},Nq={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},lO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Iq=Symbol("metadata"),wq="__clustering__",Cq=Object.values(lO),Dq=15984864e5,_O={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Lq=aO.invert(_O),Mq={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"},Uq=111,Pq=`\r
|
|
2
|
+
`,vq={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Bq=["*","%"],Hq="unauthorized_access",xq="func_val",Gq={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Fq={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},qq={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",NATS_CONSUMER_UPDATE:"nats_consumer_update"},kq={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Vq={HTTP:"http"},$q={STOPPED:"stopped",ONLINE:"online"},Yq="3.x.x",Kq={SUCCESS:"success",FAILURE:"failure"},Wq={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};dO.exports={LOCAL_HARPERDB_OPERATIONS:xe,HDB_SUPPORT_ADDRESS:rO,HDB_SUPPORT_URL:sO,HDB_PRICING_URL:mF,SUPPORT_HELP_MSG:pF,LICENSE_HELP_MSG:iO,HDB_PROC_NAME:eO,HDB_PROC_DESCRIPTOR:bh,CLUSTERING_LEAF_PROC_DESCRIPTOR:Jl,CLUSTERING_HUB_PROC_DESCRIPTOR:zl,SYSTEM_SCHEMA_NAME:BF,HASH_FOLDER_NAME:HF,HDB_HOME_DIR_NAME:xF,UPDATE_FILE_NAME:kF,LICENSE_KEY_DIR_NAME:FF,BOOT_PROPS_FILE_NAME:qF,JOB_TYPE_ENUM:Tq,JOB_STATUS_ENUM:lq,SYSTEM_TABLE_NAMES:sq,SYSTEM_TABLE_HASH_ATTRIBUTES:iq,OPERATIONS_ENUM:Z,VALID_S3_FILE_TYPES:_q,S3_BUCKET_AUTH_KEYS:dq,VALID_SQL_OPS_ENUM:fq,GEO_CONVERSION_ENUM:hq,HDB_SETTINGS_NAMES:cO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:mq,SERVICE_ACTIONS_ENUM:Eq,CLUSTER_MESSAGE_TYPE_ENUM:gq,CLUSTER_CONNECTION_DIRECTION_ENUM:Rq,CLUSTER_EVENTS_DEFS_ENUM:bq,PERIOD_REGEX:bF,DOUBLE_PERIOD_REGEX:yF,UNICODE_PERIOD:NF,FORWARD_SLASH_REGEX:IF,UNICODE_FORWARD_SLASH:wF,ESCAPED_FORWARD_SLASH_REGEX:CF,ESCAPED_PERIOD_REGEX:DF,ESCAPED_DOUBLE_PERIOD_REGEX:LF,REG_KEY_FILE_NAME:cq,RESTART_TIMEOUT_MS:YF,HDB_FILE_PERMISSIONS:KF,DATABASES_DIR_NAME:zF,LEGACY_DATABASES_DIR_NAME:JF,TRANSACTIONS_DIR_NAME:jF,LIMIT_COUNT_NAME:XF,ID_ATTRIBUTE_STRING:ZF,INSERT_MODULE_ENUM:rq,UPGRADE_JSON_FIELD_NAMES_ENUM:nq,RESTART_CODE:VF,RESTART_CODE_NUM:$F,CLUSTER_OPERATIONS:ac,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:aq,HDB_INTERNAL_SC_CHANNEL_PREFIX:Dr,INTERNAL_SC_CHANNELS:oq,CLUSTERING_MESSAGE_TYPES:Mq,HDB_FILE_SUFFIX:GF,BLOB_FOLDER_NAME:WF,HDB_TRASH_DIR:QF,ORIGINATOR_SET_VALUE:Uq,LICENSE_VALUES:Aq,RAM_ALLOCATION_ENUM:Oq,TIME_STAMP_NAMES_ENUM:lO,TIME_STAMP_NAMES:Cq,PERMS_UPDATE_RELEASE_TIMESTAMP:Dq,SEARCH_NOT_FOUND_MESSAGE:SF,SEARCH_ATTRIBUTE_NOT_FOUND:TF,LICENSE_ROLE_DENIED_RESPONSE:gF,LICENSE_MAX_CONNS_REACHED:RF,BASIC_LICENSE_MAX_NON_CU_ROLES:nO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:hF,VALUE_SEARCH_COMPARATORS:_O,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Lq,LICENSE_FILE_NAME:uq,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:yq,NEW_LINE:Pq,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:OF,MOMENT_DAYS_TAG:MF,API_TURNOVER_SEC:UF,LOOPBACK:AF,CODE_EXTENSION:Ql,WILDCARD_SEARCH_VALUE:PF,NODE_ERROR_CODES:Nq,JAVASCRIPT_EXTENSION:ZA,PERMS_CRUD_ENUM:vq,UNAUTHORIZED_PERMISSION_NAME:Hq,SEARCH_WILDCARDS:Bq,FUNC_VAL:xq,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Gq,JWT_ENUM:Fq,CLUSTERING_FLAG:wq,ITC_EVENT_TYPES:qq,CUSTOM_FUNCTION_PROC_NAME:tO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Wl,SERVICES:kq,THREAD_TYPES:Vq,MEM_SETTING_KEY:vF,HDB_RESTART_SCRIPT:eF,PROCESS_DESCRIPTORS:oF,SERVICE_SERVERS:_F,SERVICE_SERVERS_CWD:Oh,PROCESS_DESCRIPTORS_VALIDATE:uF,LAUNCH_SERVICE_SCRIPTS:dF,LOG_LEVELS:cF,PROCESS_NAME_ENV_PROP:eq,LOG_NAMES:aF,PM2_PROCESS_STATUSES:$q,CONFIG_PARAM_MAP:uO,CONFIG_PARAMS:w,HDB_CONFIG_FILE:jG,HDB_DEFAULT_CONFIG_FILE:XG,ROLE_TYPES_ENUM:fF,BOOT_PROP_PARAMS:oO,INSTALL_PROMPTS:tq,HDB_ROOT_DIR_NAME:ZG,CLUSTERING_PROCESSES:lF,FOREGROUND_PID_FILE:nF,PACKAGE_ROOT:Js,PRE_4_0_0_VERSION:Yq,DATABASES_PARAM_CONFIG:Sq,METADATA_PROPERTY:Iq,AUTH_AUDIT_STATUS:Kq,AUTH_AUDIT_TYPES:Wq,HDB_PID_FILE:sF,DEFAULT_DATABASE_NAME:iF,LEGACY_CONFIG_PARAMS:pq};XA()});var yh=R((Ooe,hO)=>{"use strict";var fO=require("minimist");hO.exports=Qq;function Qq(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=EO(process.env),n=EO(fO(process.argv))):(r=process.env,n=fO(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(Qq,"assignCMDENVVariables");function EO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(EO,"objKeysToLowerCase")});var Y=R((yoe,Mh)=>{"use strict";var Ui=require("fs-extra"),{workerData:zq,threadId:Jq}=require("worker_threads"),ms=require("path"),SO=require("yaml"),TO=require("properties-reader"),ht=U(),mO=yh(),jq=require("os"),{PACKAGE_ROOT:Ih}=U(),{_assignPackageExport:Xq}=require("../../index"),uc={};for(let e in console)uc[e]||(uc[e]=console[e]);var or={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},gO={STDOUT:"stdOut",STDERR:"stdErr"},Zq=ms.join(Ih,"logs"),ek=ms.join(Ih,"config/yaml/",ht.HDB_DEFAULT_CONFIG_FILE),tk=1e4,hs,Yn,ir,jl,Xl,lc,Go,cc;cc===void 0&&RO();Mh.exports={notify:bO,fatal:yO,error:_c,warn:Lh,info:Zl,debug:Dh,trace:Ch,setLogLevel:ck,log_level:ir,loggerWithTag:rk,suppressLogging:nk,initLogSettings:RO,setupConsoleLogging:AO,logCustomLevel:ok,closeLogFile:wh,getLogFilePath:()=>lc,OUTPUTS:gO,AuthAuditLog:_k};Xq("logger",Mh.exports);function RO(e=!1){try{if(cc===void 0||e){wh();let t=ak(),r=mO(["ROOTPATH"]);try{cc=TO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Ui.pathExistsSync(ms.join(r.ROOTPATH,ht.HDB_CONFIG_FILE)))throw n}({level:ir,config_log_path:Xl,to_file:hs,to_stream:Yn}=uk(r.ROOTPATH?ms.join(r.ROOTPATH,ht.HDB_CONFIG_FILE):cc.get("settings_path"))),jl=ht.LOG_NAMES.HDB,lc=ms.join(Xl,jl)}}catch(t){if(cc=void 0,t.code===ht.NODE_ERROR_CODES.ENOENT||t.code===ht.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=mO(Object.keys(ht.CONFIG_PARAM_MAP),!0);for(let o in r){let c=ht.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===ht.CONFIG_PARAMS.LOGGING_LEVEL){ir=u;continue}if(c===ht.CONFIG_PARAMS.LOGGING_STDSTREAMS){Yn=u;continue}c===ht.CONFIG_PARAMS.LOGGING_FILE&&(hs=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=lk();hs=hs===void 0?s:hs,hs=pO(hs),Yn=Yn===void 0?i:Yn,Yn=pO(Yn),ir=ir===void 0?n:ir,Xl=Zq,jl=ht.LOG_NAMES.INSTALL,lc=ms.join(Xl,jl);return}throw _c("Error initializing log settings"),_c(t),t}process.env.DEV_MODE&&(Yn=!0),AO()}a(RO,"initLogSettings");var Nh=!0;function AO(){xo("error",_c),xo("warn",Lh),xo("log",Zl),xo("info",Zl),xo("debug",Dh),xo("trace",Ch)}a(AO,"setupConsoleLogging");function xo(e,t){console[e]=function(...r){if(Nh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return uc[e](...r)}}a(xo,"logConsole");function rk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(bO),fatal:r(yO),error:r(_c),warn:r(Lh),info:r(Zl),debug:r(Dh),trace:r(Ch)};function r(n){return function(...s){return n(t,...s)}}}a(rk,"loggerWithTag");function nk(e){try{Nh=!1,e()}finally{Nh=!0}}a(nk,"suppressLogging");var sk=zq?.name?.replace(/ /g,"-")||"main";function ps(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||sk+"/"+Jq);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
3
|
+
`}a(ps,"createLogRecord");function dc(e){hs&&OO(e),Yn&&process.stdout.write(e)}a(dc,"logStdOut");function e_(e){hs&&OO(e),Yn&&process.stderr.write(e)}a(e_,"logStdErr");function OO(e){ik(),Go?Ui.appendFileSync(Go,e):uc.log(e)}a(OO,"logToFile");function wh(){try{Ui.closeSync(Go)}catch{}Go=null}a(wh,"closeLogFile");function ik(){if(!Go){try{if(!lc)debugger;Go=Ui.openSync(lc,"a")}catch(e){uc.error(e)}setTimeout(()=>{wh()},tk).unref()}}a(ik,"openLogFile");function Zl(...e){or[ir]<=or.info&&dc(ps("info",e))}a(Zl,"info");function Ch(...e){or[ir]<=or.trace&&dc(ps("trace",e))}a(Ch,"trace");function _c(...e){or[ir]<=or.error&&e_(ps("error",e))}a(_c,"error");function Dh(...e){or[ir]<=or.debug&&dc(ps("debug",e))}a(Dh,"debug");function bO(...e){or[ir]<=or.notify&&dc(ps("notify",e))}a(bO,"notify");function yO(...e){or[ir]<=or.fatal&&e_(ps("fatal",e))}a(yO,"fatal");function Lh(...e){or[ir]<=or.warn&&e_(ps("warn",e))}a(Lh,"warn");function ok(e,t,...r){t===gO.STDERR?e_(ps(e,r)):dc(ps(e,r))}a(ok,"logCustomLevel");function ak(){let e;try{e=jq.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ms.join(e,ht.HDB_HOME_DIR_NAME,ht.BOOT_PROPS_FILE_NAME);return Ui.existsSync(t)||(t=ms.join(Ih,"utility/hdb_boot_properties.file")),t}a(ak,"getPropsFilePath");function ck(e){ir=e}a(ck,"setLogLevel");function pO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(pO,"autoCastBoolean");function uk(e){try{if(e.includes("config/settings.js")){let o=TO(e);return{level:o.get(ht.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ms.dirname(o.get(ht.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(ht.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(ht.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=SO.parseDocument(Ui.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===ht.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(uk,"getLogConfig");function lk(){try{let e=SO.parseDocument(Ui.readFileSync(ek,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(lk,"getDefaultConfig");function _k(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(_k,"AuthAuditLog")});var IO=R((Ioe,NO)=>{"use strict";var dk=require("util"),fk=require("path"),Ek=require("child_process"),hk=dk.promisify(Ek.execFile),mk=1e3*1e3*10;NO.exports={findPs:pk};async function pk(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await hk("ps",["wwxo",`pid,${r}`],{maxBuffer:mk});for(let s of n.trim().split(`
|
|
4
|
+
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:fk.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(pk,"findPs")});var ct=R((Coe,CO)=>{"use strict";var Sk="__dbis__",Tk="__txns__",gk="__environment_name__",Rk="__dbi_defintion__",Ak={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"},Ok=["__createdtime__","__updatedtime__"],bk="\uFFFF",wO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},yk=Object.values(wO);CO.exports={AUDIT_STORE_NAME:Tk,INTERNAL_DBIS_NAME:Sk,DBI_DEFINITION_NAME:Rk,SEARCH_TYPES:Ak,TIMESTAMP_NAMES:Ok,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:gk,TRANSACTIONS_DBI_NAMES_ENUM:wO,TRANSACTIONS_DBIS:yk,OVERFLOW_MARKER:bk}});var Lr=R((Doe,xO)=>{"use strict";var DO=U(),LO=ct(),MO={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},UO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),PO={500:UO("There was an error processing your request."),400:"Invalid request"},Nk=PO[MO.INTERNAL_SERVER_ERROR],Ik={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.`},wk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},Ck={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"},Dk={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 ${LO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${LO.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"},Lk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${DO.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 ${DO.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"},vO={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"},Mk={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."},Uk={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`},Pk={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"},vk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Bk={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`},BO={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.`},HO={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}`},Hk={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."},xk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Gk={...vO,...Ck,...Ik,...Mk,...Uk,...Pk,...vk,...Bk,...Lk,...BO,...HO,...Hk,...xk,...wk};xO.exports={CHECK_LOGS_WRAPPER:UO,HDB_ERROR_MSGS:Gk,DEFAULT_ERROR_MSGS:PO,DEFAULT_ERROR_RESP:Nk,HTTP_STATUS_CODES:MO,LMDB_ERRORS_ENUM:Dk,AUTHENTICATION_ERROR_MSGS:vO,VALIDATION_ERROR_MSGS:BO,ITC_ERRORS:HO}});var ne=R((Moe,qO)=>{"use strict";var Fo=Lr(),Fk=Y(),qk=U(),t_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,GO),this.statusCode=n||Fo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Fo.DEFAULT_ERROR_MSGS[n]?Fo.DEFAULT_ERROR_MSGS[n]:Fo.DEFAULT_ERROR_MSGS[Fo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&Fk[s](i)}},Uh=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}},Ph=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function GO(e,t,r,n=qk.LOG_LEVELS.ERROR,s=null,i=!1){if(FO(e))return e;let o=new t_(e,t,r,n,s);return i&&delete o.stack,o}a(GO,"handleHDBError");function FO(e){return e.__proto__.constructor.name===t_.name}a(FO,"isHDBError");qO.exports={isHDBError:FO,handleHDBError:GO,ClientError:Uh,ServerError:Ph,hdb_errors:Fo}});var VO=R((Poe,kO)=>{"use strict";var kk={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
|
-
`)},Vk="certificate.pem",$k="privateKey.pem",Yk="ca.pem";kO.exports={CERTIFICATE_VALUES:kk,CERTIFICATE_PEM_NAME:Vk,PRIVATEKEY_PEM_NAME:$k,CA_PEM_NAME:Yk}});var et=R((voe,$O)=>{"use strict";var ir=require("validate.js");ir.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||ir.validators.type.checks[t](e)?null:` must be a '${t}' value`};ir.validators.type.checks={Object:function(e){return ir.isObject(e)&&!ir.isArray(e)},Array:ir.isArray,Integer:ir.isInteger,Number:ir.isNumber,String:ir.isString,Date:ir.isDate,Boolean:function(e){return typeof e=="boolean"}};ir.validators.hasValidFileExt=function(e,t){return ir.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};$O.exports={validateObject:Kk,validateObjectAsync:Wk,validateBySchema:Qk};function Kk(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=ir(e,t,{format:"flat"});return r?new Error(r):null}a(Kk,"validateObject");async function Wk(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ir.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(Wk,"validateObjectAsync");function Qk(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(Qk,"validateBySchema")});var vh=R((xoe,JO)=>{"use strict";var QO=require("fs-extra"),oe=require("joi"),zk=require("os"),{boolean:be,string:Qt,number:Je,array:Ph}=oe.types(),{totalmem:YO}=require("os"),Pi=require("path"),Jk=Y(),r_=Q(),Hoe=VO(),KO=U(),jk=et(),WO="log",Xk="components",Zk="Invalid logging.rotation.maxSize unit. Available units are G, M or K",eV="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",tV="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",rV="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",nV="rootPath config parameter is undefined",sV="clustering.enabled config parameter is undefined",vi=Je.min(0).required(),n_=Ph.items({host:Qt.required(),port:vi}).empty(null),Kn,zO=!1;JO.exports={configValidator:iV,routesValidator:_V,route_constraints:n_};function iV(e,t=!1){if(zO=t,Kn=e.rootPath,r_.isEmpty(Kn))throw nV;let r=be.required(),n=Je.min(0).max(1e3).empty(null).default(lV),s=Qt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(dc),i=Qt.optional().empty(null),o=Qt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(dc),u=oe.custom(aV).empty(null).default(dc),_=e.clustering?.enabled;if(r_.isEmpty(_))throw sV;let l;return _===!0?l=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:vi,routes:n_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:vi}).required()}).required(),network:oe.object({port:vi}).required()}).required(),leafServer:oe.object({network:oe.object({port:vi,routes:n_}).required(),streams:oe.object({maxAge:Je.min(120).allow(null).optional(),maxBytes:Je.min(1).allow(null).optional(),maxMsgs:Je.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:Qt.optional().empty(null)}).required():l=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:Je.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:Je}),componentsRoot:s.optional(),clustering:l,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:be,logSuccessful:be}),file:be.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:be.optional(),compress:be.optional(),interval:Qt.custom(uV).optional().empty(null),maxSize:Qt.custom(cV).optional().empty(null),path:Qt.optional().empty(null).default(dc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:Ph.optional(),headersTimeout:Je.min(1).optional(),keepAliveTimeout:Je.min(1).optional(),port:Je.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(dc),securePort:Je.optional().empty(null),timeout:Je.min(1).optional()}).optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Qt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:vi,securePort:vi,mtls:oe.alternatives([be.optional(),oe.object({user:Qt.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:Je.optional(),cors:be.optional(),corsAccessList:Ph.optional(),headersTimeout:Je.min(1).optional(),port:Je.min(0).optional().empty(null),securePort:Je.min(0).optional().empty(null),maxHeaderSize:Je.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:Qt.optional(),certificateAuthority:i,required:be.optional()})])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:Je.min(1).optional(),host:Qt.optional(),waitForDebugger:be.optional()})),maxHeapMemory:Je.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:Qt.optional(),threshold:Je.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:u,prefetchWrites:be.optional(),maxFreeSpaceToLoad:Je.optional(),maxFreeSpaceToRetain:Je.optional()}).required(),ignoreScripts:be.optional(),tls:oe.object({certificate:i.optional(),certificateAuthority:i.optional(),privateKey:i.optional(),ciphers:Qt.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(iV,"configValidator");function oV(e){return zO||QO.existsSync(e)?null:`Specified path ${e} does not exist.`}a(oV,"doesPathExist");function aV(e,t){oe.assert(e,Qt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=oV(e);if(r)return t.message(r)}a(aV,"validatePath");function cV(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Zk);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(tV):e}a(cV,"validateRotationMaxSize");function uV(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(eV);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(rV):e}a(uV,"validateRotationInterval");function lV(e,t){let r=t.state.path.join("."),n=zk.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||YO();return i=Math.round(Math.min(i,YO())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Jk.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(lV,"setDefaultThreads");function dc(e,t){let r=t.state.path.join(".");if(!r_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(r_.isEmpty(Kn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Pi.join(Kn,Xk);case"logging.root":return Pi.join(Kn,WO);case"clustering.leafServer.streams.path":return Pi.join(Kn,"clustering","leaf");case"storage.path":let n=Pi.join(Kn,KO.LEGACY_DATABASES_DIR_NAME);return QO.existsSync(n)?n:Pi.join(Kn,KO.DATABASES_DIR_NAME);case"logging.rotation.path":return Pi.join(Kn,WO);case"operationsApi.network.domainSocket":return r==null?null:Pi.join(Kn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(dc,"setDefaultRoot");function _V(e){let t=oe.object({routes:n_});return jk.validateBySchema({routes:e},t)}a(_V,"routesValidator")});var Bi={};Fe(Bi,{server:()=>tt});var jO,tt,or=ge(()=>{jO=require("../../index"),tt={};(0,jO._assignPackageExport)("server",tt)});var cr=R((qoe,ob)=>{"use strict";var Lr=U(),Mt=Q(),bt=Y(),{configValidator:dV,routesValidator:XO}=vh(),ar=require("fs-extra"),fV=require("yaml"),bn=require("path"),EV=require("is-number"),eb=require("properties-reader"),hV=require("lodash"),{handleHDBError:mV}=ne(),{HTTP_STATUS_CODES:pV,HDB_ERROR_MSGS:s_}=Cr(),Foe=require("minimist"),{server:SV}=(or(),ie(Bi)),{DATABASES_PARAM_CONFIG:fc,CONFIG_PARAMS:Dr,CONFIG_PARAM_MAP:yn}=Lr,TV="Unable to get config value because config is uninitialized",gV="Config successfully initialized",RV="Error backing up config file",AV="Empty parameter sent to getConfigValue",tb=bn.join(Lr.PACKAGE_ROOT,"config","yaml",Lr.HDB_DEFAULT_CONFIG_FILE),OV="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",ZO={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_,yt,o_;ob.exports={createConfigFile:bV,getDefaultConfig:yV,getConfigValue:nb,initConfig:Hh,flattenConfig:qo,updateConfigValue:sb,updateConfigObject:IV,getConfiguration:DV,setConfiguration:LV,readConfigFile:Gh,getClusteringRoutes:MV,initOldConfig:ib,getConfigFromFile:UV,getConfigFilePath:Hi,addConfig:PV,deleteConfigFromFile:vV,getConfigObj:BV};function bV(e,t=!1){let r=js(tb);i_=qo(r.toJSON());let n;for(let c in e){let u=yn[c.toLowerCase()];if(u===Dr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=Bh(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){bt.error(d)}}}n&&rb(r,n),xh(r,t);let s=r.toJSON();yt=qo(s);let i=r.getIn(["rootPath"]),o=bn.join(i,Lr.HDB_CONFIG_FILE);ar.createFileSync(o),ar.writeFileSync(o,String(r)),bt.trace(`Config file written to ${o}`)}a(bV,"createConfigFile");function rb(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Mt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(fc.TABLES))for(let i in n[s][fc.TABLES])for(let o in n[s][fc.TABLES][i]){let c=n[s][fc.TABLES][i][o],u=[Dr.DATABASES,s,fc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Dr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){bt.error("Error parsing schemas CLI/env config arguments",n)}}a(rb,"setSchemasConfig");function yV(e){if(i_===void 0){let r=js(tb);i_=qo(r.toJSON())}let t=yn[e.toLowerCase()];if(t!==void 0)return i_[t.toLowerCase()]}a(yV,"getDefaultConfig");function nb(e){if(e==null){bt.error(AV);return}if(yt===void 0){bt.trace(TV);return}let t=yn[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(nb,"getConfigValue");function Hi(e=Mt.getPropsFilePath()){let t=Mt.getEnvCliRootPath();return t?bn.join(t,Lr.HDB_CONFIG_FILE):eb(e).get(Lr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Hi,"getConfigFilePath");function Hh(e=!1){if(yt===void 0||e){let t;if(!Mt.noBootFile()){t=Mt.getPropsFilePath();try{ar.accessSync(t,ar.constants.F_OK|ar.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Hi(t),n;if(r.includes("config/settings.js"))try{ib(r);return}catch(i){if(i.code!==Lr.NODE_ERROR_CODES.ENOENT)throw i}try{n=js(r)}catch(i){if(i.code===Lr.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}NV(n,r),xh(n);let s=n.toJSON();if(SV.config=s,yt=qo(s),yt.logging_rotation_rotate)for(let i in ZO)yt[i]&&bt.error(`Config ${ZO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(gV)}}a(Hh,"initConfig");function NV(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],bn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],bn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],bn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(bt.trace("Updating config file with missing config params"),ar.writeFileSync(t,String(e)))}a(NV,"checkForUpdatedConfig");function xh(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=dV(r,t);if(n.error)throw s_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(xh,"validateConfig");function IV(e,t){yt===void 0&&(yt={});let r=yn[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(IV,"updateConfigObject");function sb(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&Hh();let o=nb(yn.hdb_root),c=bn.join(o,Lr.HDB_CONFIG_FILE),u=js(c),_;if(r===void 0&&e.toLowerCase()===Dr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=yn[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Bh(f,t);u.setIn([...E],h)}else for(let f in r){let E=yn[f.toLowerCase()];if(E===Dr.HTTP_SECUREPORT&&r[f]===yt[Dr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Dr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===yt[Dr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Dr.DATABASES){_=r[f];continue}if(E?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!E&&(f.endsWith("_package")||f.endsWith("_port"))&&(E=f),E!==void 0){let h=E.split("_"),S=Lr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];S&&S.startsWith("customFunctions")&&u.hasIn(S.split("_"))&&(E=S,h=S.split("_"));let p=Bh(E,r[f]);E==="rootPath"&&p?.endsWith("/")&&(p=p.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],p)}catch(T){bt.error(T)}}}_&&rb(u,_),xh(u);let l=u.getIn(["rootPath"]),d=bn.join(l,Lr.HDB_CONFIG_FILE);n===!0&&wV(c,l),ar.writeFileSync(d,String(u)),s&&(yt=qo(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(sb,"updateConfigValue");function wV(e,t){try{let r=bn.join(t,"backup",`${Lr.HDB_CONFIG_FILE}.bak`);ar.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(RV),bt.error(r)}}a(wV,"backupConfigFile");var CV=["databases"];function qo(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)),o_=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!CV.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Dr[u.toUpperCase()]&&yn[u]&&(s[yn[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(qo,"flattenConfig");function Bh(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(EV(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Mt.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 Mt.autoCast(t)}a(Bh,"castConfigValue");function DV(){let e=Mt.getPropsFilePath(),t=Hi(e);return js(t).toJSON()}a(DV,"getConfiguration");async function LV(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return sb(void 0,void 0,s,!0),OV}catch(i){throw typeof i=="string"||i instanceof String?mV(i,i,pV.BAD_REQUEST,void 0,void 0,!0):i}}a(LV,"setConfiguration");function Gh(){let e=Mt.getPropsFilePath();try{ar.accessSync(e,ar.constants.F_OK|ar.constants.R_OK)}catch(n){if(!Mt.noBootFile())throw bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Hi(e);return js(t).toJSON()}a(Gh,"readConfigFile");function js(e){return fV.parseDocument(ar.readFileSync(e,"utf8"),{simpleKeys:!0})}a(js,"parseYamlDoc");function MV(){let e=Gh(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Mt.isEmptyOrZeroLength(t)?[]:t;let r=XO(t);if(r)throw s_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Mt.isEmptyOrZeroLength(n)?[]:n;let s=XO(n);if(s)throw s_.CONFIG_VALIDATION(s.message);if(!Mt.isEmptyOrZeroLength(n)&&!Mt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Mt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw s_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(MV,"getClusteringRoutes");function ib(e){let t=eb(e);yt={};for(let r in yn){let n=t.get(r.toUpperCase());if(Mt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=yn[r].toLowerCase();s===Dr.LOGGING_ROOT?yt[s]=bn.dirname(n):yt[s]=n}return yt}a(ib,"initOldConfig");function UV(e){let t=Gh();return hV.get(t,e.replaceAll("_","."))}a(UV,"getConfigFromFile");async function PV(e,t){let r=js(Hi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ar.writeFile(Hi(),String(r))}a(PV,"addConfig");function vV(e){let t=Hi(Mt.getPropsFilePath()),r=js(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=bn.join(n,Lr.HDB_CONFIG_FILE);ar.writeFileSync(s,String(r))}a(vV,"deleteConfigFromFile");function BV(){return o_||(Hh(),o_)}a(BV,"getConfigObj")});var re=R((Voe,_b)=>{"use strict";var Fh=require("fs-extra"),xi=require("path"),ab=require("os"),HV=require("properties-reader"),hc=Y(),Ec=Q(),ue=U(),a_=cr(),xV="Error initializing environment manager",c_="BOOT_PROPS_FILE_PATH",cb=!1,GV={[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},Ss={};_b.exports={BOOT_PROPS_FILE_PATH:c_,getHdbBasePath:FV,setHdbBasePath:qV,get:ub,initSync:VV,setProperty:Me,initTestEnvironment:YV,setCloneVar:$V};function FV(){return Ss[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(FV,"getHdbBasePath");function qV(e){Ss[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(qV,"setHdbBasePath");function ub(e){let t=a_.getConfigValue(e);return t===void 0?Ss[e]:t}a(ub,"get");function Me(e,t){GV[e]&&(Ss[e]=t),a_.updateConfigObject(e,t)}a(Me,"setProperty");function kV(){let e;try{e=Ec.getPropsFilePath(),Fh.accessSync(e,Fh.constants.F_OK|Fh.constants.R_OK),cb=!0;let t=HV(e);return Ss[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Ss[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ss[c_]=e,!0}catch{return hc.trace(`Environment manager found no properties file at ${e}`),!1}}a(kV,"doesPropFileExist");function VV(e=!1){try{(cb||kV()||Ec.noBootFile())&&!lb&&(a_.initConfig(e),Ss[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=a_.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){hc.error(xV),hc.error(t),console.error(t),process.exit(1)}}a(VV,"initSync");var lb=!1;function $V(e){lb=e}a($V,"setCloneVar");function YV(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=xi.join(__dirname,"../../","unitTests");Ss[c_]=xi.join(u,"hdb_boot_properties.file"),Me(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xi.join(u,"settings.test")),Me(ue.HDB_SETTINGS_NAMES.INSTALL_USER,ab.userInfo()?ab.userInfo().username:void 0),Me(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xi.join(u,"envDir","log")),Me(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xi.join(u,"envDir")),Me(ue.CONFIG_PARAMS.STORAGE_PATH,xi.join(u,"envDir")),s&&(Me(ue.CONFIG_PARAMS.HTTP_SECUREPORT,ub(ue.CONFIG_PARAMS.HTTP_PORT)),Me(ue.CONFIG_PARAMS.HTTP_PORT,null)),Me(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ec.isEmpty(i)?!1:i),Me(ue.CONFIG_PARAMS.HTTP_CORS,Ec.isEmpty(i)?!1:i),Me(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xi.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ec.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${c_}. Please check your boot props and settings files`;hc.fatal(r),hc.error(t)}}a(YV,"initTestEnvironment")});var Qe=R((Yoe,Sb)=>{"use strict";var gc=U(),KV=Q(),ur=re(),Rc=require("path"),WV=require("minimist"),db=require("fs-extra"),fb=require("lodash");ur.initSync();var{CONFIG_PARAMS:Xs,DATABASES_PARAM_CONFIG:mc,SYSTEM_SCHEMA_NAME:u_}=gc,pc,Sc,Tc;function Eb(){if(pc!==void 0)return pc;if(ur.getHdbBasePath()!==void 0)return pc=ur.get(Xs.STORAGE_PATH)||Rc.join(ur.getHdbBasePath(),gc.DATABASES_DIR_NAME),pc}a(Eb,"getBaseSchemaPath");function hb(){if(Sc!==void 0)return Sc;if(ur.getHdbBasePath()!==void 0)return Sc=pb(u_),Sc}a(hb,"getSystemSchemaPath");function mb(){if(Tc!==void 0)return Tc;if(ur.getHdbBasePath()!==void 0)return Tc=ur.get(gc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Rc.join(ur.getHdbBasePath(),gc.TRANSACTIONS_DIR_NAME),Tc}a(mb,"getTransactionAuditStoreBasePath");function QV(e,t){let r=ur.get(Xs.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Rc.join(mb(),e.toString())}a(QV,"getTransactionAuditStorePath");function pb(e,t){e=e.toString(),t=t&&t.toString();let r=ur.get(gc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Rc.join(Eb(),e)}a(pb,"getSchemaPath");function zV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,WV(process.argv));let n=r[Xs.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!KV.isObject(n))throw o;i=n}for(let o of i){let c=o[u_];if(!c)continue;let u=ur.get(Xs.DATABASES);u=u??{};let _=c?.tables?.[t]?.[mc.PATH];if(_)return fb.set(u,[u_,mc.TABLES,t,mc.PATH],_),ur.setProperty(Xs.DATABASES,u),_;let l=c?.[mc.PATH];if(l)return fb.set(u,[u_,mc.PATH],l),ur.setProperty(Xs.DATABASES,u),l}}let s=r[Xs.STORAGE_PATH.toUpperCase()];if(s){if(!db.pathExistsSync(s))throw new Error(s+" does not exist");let i=Rc.join(s,e);return db.mkdirsSync(i),ur.setProperty(Xs.STORAGE_PATH,s),i}return hb()}a(zV,"initSystemSchemaPaths");function JV(){pc=void 0,Sc=void 0,Tc=void 0}a(JV,"resetPaths");Sb.exports={getBaseSchemaPath:Eb,getSystemSchemaPath:hb,getTransactionAuditStorePath:QV,getTransactionAuditStoreBasePath:mb,getSchemaPath:pb,initSystemSchemaPaths:zV,resetPaths:JV}});var Mr=R((zoe,Ob)=>{"use strict";var jV=Cr().LMDB_ERRORS_ENUM,Woe=require("lmdb"),XV=ct(),Qoe=require("buffer").Buffer,{OVERFLOW_MARKER:Tb,MAX_SEARCH_KEY_LENGTH:l_}=XV,gb=["number","string","symbol","boolean","bigint"];function ZV(e){if(e=e?.primaryStore||e,!e)throw new Error(jV.ENV_REQUIRED)}a(ZV,"validateEnv");function e$(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(e$,"stringifyData");function t$(e){return e instanceof Date?e.valueOf():e}a(t$,"convertKeyValueToWrite");function r$(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(gb.includes(typeof e))return e.length>l_?[e.slice(0,l_)+Tb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(gb.includes(typeof i))i.length>l_?r.push(i.slice(0,l_)+Tb):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(r$,"getIndexedValues");var __=0,Rb=0;function Ab(){Rb=Date.now()-performance.now()}a(Ab,"adjustStartTime");Ab();var n$=6e4;setInterval(Ab,n$).unref();function s$(){let e=performance.now()+Rb;return e>__?(__=e,e):(__+=488e-6,__)}a(s$,"getNextMonotonicTime");Ob.exports={validateEnv:ZV,stringifyData:e$,convertKeyValueToWrite:t$,getNextMonotonicTime:s$,getIndexedValues:r$}});var bb,Nn,qh,Ac=ge(()=>{bb=require("events"),Nn=class extends bb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new qh;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)}},qh=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 $h={};Fe($h,{loadGQLSchema:()=>a$,start:()=>Vh,startOnMainThread:()=>o$});function Vh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let p of d.definitions)switch(p.kind){case u.OBJECT_TYPE_DEFINITION:let v=function(P){if(P.kind==="NonNullType"){let j=v(P.type);return j.nullable=!1,j}if(P.kind==="ListType")return{type:"array",elements:v(P.type)};let H={type:P.name?.value};return Object.defineProperty(H,"location",{value:P.loc.startToken}),H};a(v,"getProperty");let T=p.name.value,b=[],g={table:null,database:null,properties:b};f.set(T,g);for(let P of p.directives){if(P.name.value==="table"){for(let k of P.arguments)g[k.name.value]=k.value.value;g.schema&&(g.database=g.schema),g.table||(g.table=T),g.audit&&(g.audit=g.audit!=="false"),g.attributes=g.properties,E.push(g)}if(P.name.value==="sealed"&&(g.sealed=!0),P.name.value==="export"){g.export=!0;for(let k of P.arguments)k.name.value==="name"&&(g.export={name:k.value.value})}}let L=!1;for(let P of p.fields){let k=v(P.type);k.name=P.name.value,b.push(k);for(let H of P.directives)if(H.name.value==="primaryKey")L?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,L=!0);else if(H.name.value==="indexed")k.indexed=!0;else if(H.name.value==="relationship"){let j={};for(let z of H.arguments)j[z.name.value]=z.value.value;k.relationship=j}else if(H.name.value==="createdTime")k.assignCreatedTime=!0;else if(H.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(H.name.value==="expiresAt")k.expiresAt=!0;else if(H.name.value==="allow"){let j=k.authorizedRoles=[];for(let z of H.arguments)z.name.value==="role"&&j.push(z.value.value)}}g.type=T,T==="Query"&&(h=g)}function S(p){let T=f.get(p.type);T?(Object.defineProperty(p,"properties",{value:T.properties}),Object.defineProperty(p,"definition",{value:T})):p.type==="array"?S(p.elements):i$.includes(p.type)||(0,yb.getWorkerIndex)()===0&&console.error(`The type ${p.type} is unknown at line ${p.location.line}, column ${p.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let p of f.values())for(let T of p.properties)S(T);for(let p of E)p.tableClass=e(p),p.export&&(p.export.name===""?i.set((0,kh.dirname)(n),p.tableClass):i.set((0,kh.dirname)(n)+"/"+(p.export.name||p.type),p.tableClass))}}var kh,yb,i$,o$,a$,Nb=ge(()=>{kh=require("path");Re();yb=B(rt()),i$=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Vh,"start");o$=Vh,a$=Vh({ensureTable:ut}).handleFile});async function d_(e){return c$?(Oc||(Oc=u$(_$)),(await(await Oc).import(e)).namespace):import(e)}async function u$(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Oc=new Compartment({console,Math,Date,fetch:l$,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,wb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:qt,tables:Ur,databases:nt})}};let n=await(0,Ib.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Oc}function l$(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 _$(){return{Resource:qt,tables:Ur}}var Ib,wb,c$,Oc,Yh=ge(()=>{In();Re();Ib=require("fs/promises"),wb=require("path"),c$=!1;a(d_,"secureImport");a(u$,"getCompartment");a(l$,"secureOnlyFetch");a(_$,"getGlobalVars")});var Wh={};Fe(Wh,{handleFile:()=>d$});async function d$(e,t,r,n){let s=new Map,i=(0,Cb.pathToFileURL)(r).toString(),o=await d_(i);u(o.default)&&n.set((0,Kh.dirname)(t),o.default),c(o,(0,Kh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var Cb,Kh,Db=ge(()=>{Cb=require("url");Yh();Kh=require("path");a(d$,"handleFile")});var zh={};Fe(zh,{start:()=>f$});function f$({resources:e}){e.set("login",Qh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Qh,Lb=ge(()=>{In();a(f$,"start");Qh=class extends qt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var xb={};Fe(xb,{parse:()=>jh,streamAsJSON:()=>bc,stringify:()=>Gi});function bc(e){return new Jh({value:e})}function Mb(e){return console.error(e),JSON.stringify(e.toString())}function Ub(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Gi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Bb)return Hb(e);if(t.resolution)return t.resolution.then(()=>Gi(e));throw t}}function Hb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=Hb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Gi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function jh(e){return m$.test(e)?E$.parse(e):JSON.parse(e)}var Pb,vb,E$,h$,Bb,Jh,m$,Xh=ge(()=>{Pb=require("stream"),vb=B(require("json-bigint-fixes")),E$=(0,vb.default)({useNativeBigInt:!0}),h$=1e4,Bb={};BigInt.prototype.toJSON=function(){throw Bb};a(bc,"streamAsJSON");Jh=class extends Pb.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),Mb)}catch(s){yield Mb(s)}else yield Gi(t)}else yield Gi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Ub(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>h$?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 Ub(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(Mb,"handleError");a(Ub,"when");a(Gi,"stringify");a(Hb,"jsStringify");m$=/[[,:]\s*-?\d{16,}/;a(jh,"parse")});var jb=R((_ae,Jb)=>{"use strict";var Zh=require("recursive-iterator"),p$=require("alasql"),em=require("clone"),Gb=Q(),{handleHDBError:Fb,hdb_errors:S$}=ne(),{HDB_ERROR_MSGS:qb,HTTP_STATUS_CODES:kb}=S$,{getDatabases:T$}=(Re(),ie(qe)),g$=["DISTINCT_ARRAY"],Vb=Symbol("validateTables"),tm=Symbol("validateTable"),lae=Symbol("getAllColumns"),$b=Symbol("validateAllColumns"),f_=Symbol("findColumn"),Yb=Symbol("validateOrderBy"),yc=Symbol("validateSegment"),rm=Symbol("validateColumn"),Kb=Symbol("setColumnsForTable"),Wb=Symbol("checkColumnsForAsterisk"),Qb=Symbol("validateGroupBy"),zb=Symbol("hasColumns"),nm=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Vb](),this[Wb](),this[$b]()}[Vb](){if(this[zb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[tm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[tm](t.table)})}}[zb](){let t=!1,r=new Zh(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[tm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=T$();if(!r[t.databaseid])throw Fb(new Error,qb.SCHEMA_NOT_FOUND(t.databaseid),kb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Fb(new Error,qb.TABLE_NOT_FOUND(t.databaseid,t.tableid),kb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=em(s);i.table=em(t),this.attributes.push(i)})}[f_](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)}[Wb](){let t=new Zh(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Kb](r.tableid)}[Kb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new p$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[$b](){this[yc](this.statement.columns,!1),this[yc](this.statement.joins,!1),this[yc](this.statement.where,!1),this[Qb](this.statement.group,!1),this[yc](this.statement.order,!0)}[yc](t,r){if(!t)return;let n=new Zh(t),s=[];for(let{node:i,path:o}of n)!Gb.isEmpty(i)&&!Gb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Yb](i):s.push(this[rm](i)));return s}[Qb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&g$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=em(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[f_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[f_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[Yb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[rm](t)}[rm](t){let r=this[f_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Jb.exports=nm});var Zb=R((fae,Xb)=>{"use strict";var sm=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")}};Xb.exports=sm});var ty=R((hae,ey)=>{"use strict";var im=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};ey.exports=im});var iy={};Fe(iy,{HAS_EXPIRATION:()=>dm,LAST_TIMESTAMP_PLACEHOLDER:()=>wc,LOCAL_TIMESTAMP:()=>R$,METADATA:()=>Nc,NO_TIMESTAMP:()=>am,PENDING_LOCAL_TIME:()=>fm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>_m,RecordEncoder:()=>lm,TIMESTAMP_ASSIGN_LAST:()=>O$,TIMESTAMP_ASSIGN_NEW:()=>ny,TIMESTAMP_ASSIGN_PREVIOUS:()=>sy,TIMESTAMP_PLACEHOLDER:()=>E_,TIMESTAMP_RECORD_PREVIOUS:()=>cm,getUpdateRecord:()=>Em,handleLocalTimeForGets:()=>S_});function y$(){return Ic[0]=Ic[0]^64,A$.getFloat64(0)}function S_(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?.[Nc];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?.[Nc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[Nc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Fi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Fi.length;u++){let _=Fi[u].deref();(!_||_.isDone||_.isCommitted)&&Fi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Em(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?ko=i?.localTime?cm|sy:am:ko=u?i?.localTime?cm|16384:ny|16384:am,l>0&&(c|=dm),m_=c,um=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:ko>0},S;try{f&&(h.ifVersion=S=i?.version??null);let p=e.put(n,s,h);if(u){let T=_?.user?.username;if(E&&(h_=e.encoder.encode(E)),f&&i?.localTime){let b=i?.localTime,g=r.get(b);if(g){let L=Ut(g).previousLocalTime;return r.put(b,p_(o,t,n,L,T,d,h_),{ifVersion:S}),p}}r.put(wc,p_(o,t,n,i?.localTime?1:0,T,d,h_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:S})}return p}catch(p){throw p.message+=" id: "+n+" options: "+h,p}}}var ry,om,E_,wc,_m,R$,Nc,Ic,A$,am,ny,O$,sy,cm,dm,fm,b$,h_,ko,m_,um,lm,Fi,Cc=ge(()=>{ry=require("msgpackr");Zs();om=B(Y()),E_=new Uint8Array([1,1,1,1,4,64,0,0]),wc=new Uint8Array([1,1,1,1,1,0,0,0]),_m=new Uint8Array([1,1,1,1,3,64,0,0]),R$=Symbol("local-timestamp"),Nc=Symbol("metadata"),Ic=new Uint8Array(8),A$=new DataView(Ic.buffer,0,8),am=0,ny=0,O$=1,sy=3,cm=4,dm=16,fm=1,ko=0,m_=-1,um=0,lm=class extends ry.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(ko||m_>=0){let i=0,o=ko;o&&(i+=8,ko=0);let c=m_,u=um;c>=0&&(i+=2,m_=-1,u&&(i+=8,um=0));let _=b$=r.call(this,n,s|2048|i);h_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(E_[4]=o,E_[5]=o>>8,_.set(E_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(Ic,0,c),c+=8;else for(let d=0;d<8;d++)Ic[d]=t[c++];u=y$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&dm&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[Nc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(y$,"getTimestamp");a(S_,"handleLocalTimeForGets");Fi=[];setInterval(()=>{for(let e=0;e<Fi.length;e++){let t=Fi[e].deref();!t||t.isDone||t.isCommitted?Fi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(om.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):om.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(Em,"getUpdateRecord")});var Dc=R((gae,ay)=>{"use strict";var oy=re(),N$=U(),{RecordEncoder:I$}=(Cc(),ie(iy)),Tae=require("fs");oy.initSync();var w$=oy.get(N$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,hm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=w$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:I$})}};ay.exports=hm});var Lc=R((Aae,cy)=>{"use strict";var Pr=re(),sn=U();Pr.initSync();var 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.eventTurnBatching=!1,this.noSync=Pr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Pr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Pr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Pr.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Pr.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Pr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Pr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Pr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Pr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Pr.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Pr.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Pr.get(sn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};cy.exports=T_;T_.MAX_DBS=1e4});var Ye=R((bae,Sy)=>{"use strict";var pm=require("lmdb"),wn=require("fs-extra"),vr=require("path"),g_=Mr(),_y=Y(),lr=Cr().LMDB_ERRORS_ENUM,R_=ty(),Sm=Dc(),dy=Lc(),ei=ct(),uy=U(),{table:C$,resetDatabases:D$}=(Re(),ie(qe)),ly=re(),Cn=ei.INTERNAL_DBIS_NAME,fy=ei.DBI_DEFINITION_NAME,L$="data.mdb",M$="lock.mdb",Mc=".mdb",U$="-lock",mm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=on(t,r),this.key_type=this.dbi[ei.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ei.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new pm.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(lr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(lr.ENV_NAME_REQUIRED)}a(A_,"pathEnvNameValidation");async function Tm(e,t,r=!0){try{await wn.access(e)}catch(n){throw n.code==="ENOENT"?new Error(lr.INVALID_BASE_PATH):n}try{let n=vr.join(e,t+Mc);return await wn.access(n,wn.constants.R_OK|wn.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await wn.access(vr.join(e,t,L$),wn.constants.R_OK|wn.constants.F_OK),vr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(lr.INVALID_ENVIRONMENT)}else throw new Error(lr.INVALID_ENVIRONMENT);throw n}}a(Tm,"validateEnvironmentPath");function O_(e,t){if(g_.validateEnv(e),t===void 0)throw new Error(lr.DBI_NAME_REQUIRED)}a(O_,"validateEnvDBIName");async function P$(e,t,r=!1,n=!1){A_(e,t);let s=vr.basename(e);t=t.toString();let i=ly.get(uy.CONFIG_PARAMS.DATABASES);i||ly.setProperty(uy.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Tm(e,t,n),Ey(e,t,r)}catch(o){if(o.message===lr.INVALID_ENVIRONMENT){let c=vr.join(e,t);await wn.mkdirp(n?c:e);let u=new dy(n?c:c+Mc,!1),_=pm.open(u);_.dbis=Object.create(null);let l=new Sm(!1);_.openDB(Cn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=gm(e,t,r);return _[ei.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(P$,"createEnvironment");async function v$(e,t,r,n=!0){A_(e,t),t=t.toString();let s=vr.join(e,t);return C$({table:t,database:vr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(v$,"copyEnvironment");async function Ey(e,t,r=!1){A_(e,t),t=t.toString();let n=gm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await Tm(e,t),i=vr.join(e,t+Mc),o=s!=i,c=new dy(s,o),u=pm.open(c);u.dbis=Object.create(null);let _=my(u);for(let l=0;l<_.length;l++)on(u,_[l]);return u[ei.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(Ey,"openEnvironment");async function B$(e,t,r=!1){A_(e,t),t=t.toString();let n=vr.join(e,t+Mc),s=await Tm(e,t);if(global.lmdb_map!==void 0){let i=gm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await hy(o),delete global.lmdb_map[i]}}await wn.remove(s),await wn.remove(s===n?s+U$:vr.join(vr.dirname(s),M$))}a(B$,"deleteEnvironment");async function hy(e){g_.validateEnv(e);let t=e[ei.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(hy,"closeEnvironment");function gm(e,t,r=!1){let s=`${vr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(gm,"getCachedEnvironmentName");function H$(e){g_.validateEnv(e);let t=Object.create(null),r=on(e,Cn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==Cn)try{t[n]=Object.assign(new R_,s)}catch{_y.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(H$,"listDBIDefinitions");function my(e){g_.validateEnv(e);let t=[],r=on(e,Cn);for(let{key:n}of r.getRange({start:!1}))n!==Cn&&t.push(n);return t}a(my,"listDBIs");function x$(e,t){let n=on(e,Cn).getEntry(t),s=new R_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{_y.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(x$,"getDBIDefinition");function py(e,t,r,n=!r){if(O_(e,t),t=t.toString(),t===Cn)throw new Error(lr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return on(e,t)}catch(s){if(s.message===lr.DBI_DOES_NOT_EXIST){let i=new Sm(r,n===!0),o=e.openDB(t,i),c=new R_(r===!0,n);return o[fy]=c,on(e,Cn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(py,"createDBI");function on(e,t){if(O_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Cn?r=x$(e,t):r=new R_,r===void 0)throw new Error(lr.DBI_DOES_NOT_EXIST);let n;try{let s=new Sm(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(lr.DBI_DOES_NOT_EXIST):s}return n[fy]=r,e.dbis[t]=n,n}a(on,"openDBI");function G$(e,t){O_(e,t),t=t.toString();let r=on(e,t),n=r.getStats();return r[ei.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(G$,"statDBI");async function F$(e,t){try{let r=vr.join(e,t+Mc);return(await wn.stat(r)).size}catch{throw new Error(lr.INVALID_ENVIRONMENT)}}a(F$,"environmentDataSize");function q$(e,t){if(O_(e,t),t=t.toString(),t===Cn)throw new Error(lr.CANNOT_DROP_INTERNAL_DBIS_NAME);on(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],on(e,Cn).removeSync(t)}a(q$,"dropDBI");function k$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{on(e,i)}catch(o){if(o.message===lr.DBI_DOES_NOT_EXIST)py(e,i,i!==t,i===t),n=!0;else throw o}}n&&D$()}a(k$,"initializeDBIs");Sy.exports={openDBI:on,openEnvironment:Ey,createEnvironment:P$,listDBIs:my,listDBIDefinitions:H$,createDBI:py,dropDBI:q$,statDBI:G$,deleteEnvironment:B$,initializeDBIs:k$,TransactionCursor:mm,environmentDataSize:F$,copyEnvironment:v$,closeEnvironment:hy}});var gy=R((Nae,Ty)=>{"use strict";var Rm=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Ty.exports=Rm});var Ay=R((wae,Ry)=>{"use strict";var Am=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Ry.exports=Am});var by=R((Dae,Oy)=>{"use strict";var Om=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Oy.exports=Om});var Vo=R((vae,Iy)=>{"use strict";var V$=Ye(),$$=gy(),Y$=Ay(),K$=by(),Wn=Mr(),Uc=Cr().LMDB_ERRORS_ENUM,W$=ct(),Ts=U(),Q$=Q(),z$=require("uuid"),Mae=require("lmdb"),{handleHDBError:J$,hdb_errors:j$}=ne(),{OVERFLOW_MARKER:Uae,MAX_SEARCH_KEY_LENGTH:Pae}=W$,yy=re();yy.initSync();var b_=yy.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),bm=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function X$(e,t,r,n,s=Wn.getNextMonotonicTime()){wm(e,t,r,n),ym(e,t,r);let i=new $$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ny(_,!0,s);let l=Z$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Nm(o,c,n,i,s)}a(X$,"insertRecords");function Z$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ts.FUNC_VAL],n[o]=c)}let u=Wn.getIndexedValues(c),_=e.dbis[o];if(u){b_&&_.prefetch(u.map(l=>({key:l,value:s})),y_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}b_&&e.dbis[t].prefetch([s],y_),e.dbis[t].put(s,n,n[qi])})}a(Z$,"insertRecord");function e1(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(e1,"removeSkippedRecords");function Ny(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[bm]))&&(e[bm]=r||Wn.getNextMonotonicTime()):delete e[bm]}a(Ny,"setTimestamps");function ym(e,t,r){r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),V$.initializeDBIs(e,t,r)}a(ym,"initializeTransaction");async function t1(e,t,r,n,s=Wn.getNextMonotonicTime()){wm(e,t,r,n),ym(e,t,r);let i=new Y$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=Im(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return Nm(c,u,n,i,s,o)}a(t1,"updateRecords");async function r1(e,t,r,n,s=Wn.getNextMonotonicTime()){try{wm(e,t,r,n)}catch(u){throw J$(u,u.message,j$.HTTP_STATUS_CODES.BAD_REQUEST)}ym(e,t,r);let i=new K$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;Q$.isEmpty(_[t])?(l=z$.v4(),_[t]=l):l=_[t];let d=Im(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Nm(o,c,n,i,s)}a(r1,"upsertRecords");async function Nm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Wn.getNextMonotonicTime(),e1(r,i),n}a(Nm,"finalizeWrite");function Im(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Ny(r,!l,o),Number.isInteger(r[qi])&&_[qi]>r[qi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let S=r[h],p=e.dbis[h];if(p===void 0)continue;let T=_[h];if(typeof S=="function"){let g=S([[_]]);Array.isArray(g)&&(S=g[0][Ts.FUNC_VAL],r[h]=S)}if(S===T)continue;let b=Wn.getIndexedValues(T);if(b){b_&&p.prefetch(b.map(g=>({key:g,value:n})),y_);for(let g=0,L=b.length;g<L;g++)p.remove(b[g],n)}if(b=Wn.getIndexedValues(S),b){b_&&p.prefetch(b.map(g=>({key:g,value:n})),y_);for(let g=0,L=b.length;g<L;g++)p.put(b[g],n)}}let E=Object.assign({},_,r);c.put(n,E,E[qi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:Im(e,t,r,n,s,i,o))}a(Im,"updateUpsertRecord");function n1(e,t,r){if(Wn.validateEnv(e),t===void 0)throw new Error(Uc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Uc.WRITE_ATTRIBUTES_REQUIRED):new Error(Uc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(n1,"validateBasic");function wm(e,t,r,n){if(n1(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Uc.RECORDS_REQUIRED):new Error(Uc.RECORDS_MUST_BE_ARRAY)}a(wm,"validateWrite");function y_(){}a(y_,"noop");Iy.exports={insertRecords:X$,updateRecords:t1,upsertRecords:r1}});var ki=R((Hae,s1)=>{s1.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"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},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 zn=R((xae,Dy)=>{"use strict";var Cy=Q(),wy=U(),$o=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ti={schema_format:{pattern:$o,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},i1=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number(),Qn.array()).required(),o1=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number()),a1=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number()).required();function c1(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ti.schema_length.maximum?`'${e}' maximum of 250 characters`:$o.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(c1,"checkValidTable");function u1(e,t){return Cy.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(u1,"validateSchemaExists");function l1(e,t){let r=t.state.ancestors[0].schema;return Cy.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(l1,"validateTableExists");function _1(e,t){return e.toLowerCase()===wy.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${wy.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(_1,"validateSchemaName");Dy.exports={common_validators:ti,schema_regex:$o,hdb_schema_table:i1,validateSchemaExists:u1,validateTableExists:l1,validateSchemaName:_1,checkValidTable:c1,hdb_database:o1,hdb_table:a1}});var N_=R((Fae,Ly)=>{var{common_validators:Jn}=zn(),vc=et(),Pc="is required",mt={database:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},schema:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},table:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},hash_attribute:{presence:!0,format:Jn.schema_format,length:Jn.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 d1(e){return e=Bc(e),mt.table.presence=!1,mt.attribute.presence=!1,mt.hash_attribute.presence=!1,vc.validateObject(e,mt)}a(d1,"schema_object");function f1(e){return e=Bc(e),mt.table.presence={message:Pc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,vc.validateObject(e,mt)}a(f1,"table_object");function E1(e){return e=Bc(e),mt.table.presence={message:Pc},mt.attribute.presence=!1,vc.validateObject(e,mt)}a(E1,"create_table_object");function h1(e){return e=Bc(e),mt.table.presence={message:Pc},mt.attribute.presence={message:Pc},mt.hash_attribute.presence=!1,vc.validateObject(e,mt)}a(h1,"attribute_object");function m1(e){return e=Bc(e),mt.table.presence={message:Pc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,vc.validateObject(e,mt)}a(m1,"describe_table");function p1(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(p1,"validateTableResidence");Ly.exports={schema_object:d1,create_table_object:E1,table_object:f1,attribute_object:h1,describe_table:m1,validateTableResidence:p1}});var Uy=R((kae,My)=>{"use strict";var S1=require("uuid"),Cm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||S1.v4(),this.schema_table=`${this.schema}.${this.table}`}};My.exports=Cm});var I_=R(($ae,Py)=>{"use strict";var T1=Uy(),Dm=class extends T1{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};Py.exports=Dm});var By=R((Kae,vy)=>{"use strict";vy.exports=R1;var g1="inserted";function R1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===g1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(R1,"returnObject")});var w_=R((Qae,qy)=>{"use strict";var A1=U(),Lm=Ye(),O1=Vo(),{getSystemSchemaPath:b1,getSchemaPath:y1}=Qe(),N1=ki(),I1=N_(),w1=I_(),C1=By(),{handleHDBError:Hy,hdb_errors:Gy}=ne(),xy=Q(),{HTTP_STATUS_CODES:D1}=Gy,Mm=N1.hdb_attribute,Fy=[];for(let e=0;e<Mm.attributes.length;e++)Fy.push(Mm.attributes[e].attribute);var L1="inserted";qy.exports=M1;async function M1(e){let t=I1.attribute_object(e);if(t)throw Hy(new Error,t.message,Gy.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&xy.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Hy(new Error,r,D1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=xy.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new w1(e.schema,e.table,e.attribute,e.id);try{let i=await Lm.openEnvironment(y1(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}`);Lm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Lm.openEnvironment(b1(),A1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await O1.insertRecords(o,Mm.hash_attribute,Fy,[s]);return C1(L1,c,{records:[s]},u)}catch(i){throw i}}a(M1,"lmdbCreateAttribute")});var Pm=R((Jae,Vy)=>{var{hdb_table:U1,hdb_database:ky}=zn(),P1=et(),Um=require("joi"),v1={undefined:"undefined",null:"null"},B1=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||v1[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),H1=Um.object({database:ky,schema:ky,table:U1,records:Um.array().items(Um.object().custom(B1)).required()});Vy.exports=function(e){return P1.validateBySchema(e,H1)}});var Hc=R((Zae,Yy)=>{"use strict";var gs=Q(),$y=Y(),Xae=Pm(),{getDatabases:x1}=(Re(),ie(qe)),{ClientError:Vi}=ne();Yy.exports=G1;function G1(e){if(gs.isEmpty(e))throw new Vi("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new Vi("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new Vi("invalid table specified.");if(!Array.isArray(e.records))throw new Vi("records must be an array");let t=x1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new Vi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&gs.isEmptyOrZeroLength(o[r]))throw $y.error("a valid hash attribute must be provided with update record:",o),new Vi("a valid hash attribute must be provided with update record, check log for more info");if(!gs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw $y.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Vi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gs.isEmpty(o[r])&&o[r]!==""&&n.has(gs.autoCast(o[r]))&&(o.skip=!0),n.add(gs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(G1,"insertUpdateValidate")});var xc=R((tce,Ky)=>{"use strict";var F1=U().OPERATIONS_ENUM,vm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=F1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Ky.exports=vm});var Gc=R((sce,Qy)=>{"use strict";var nce=xc(),C_=U(),Bm=Q(),Wy=Y(),q1=require("uuid"),{handleHDBError:D_,hdb_errors:k1}=ne(),{HDB_ERROR_MSGS:L_,HTTP_STATUS_CODES:M_}=k1;Qy.exports=V1;function V1(e,t,r){for(let s=0;s<t.length;s++)$1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];Y1(i,r,e.operation)}}a(V1,"processRows");function $1(e){if(Buffer.byteLength(String(e))>C_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw D_(new Error,L_.ATTR_NAME_LENGTH_ERR(e),M_.BAD_REQUEST,void 0,void 0,!0);if(Bm.isEmptyOrZeroLength(e)||Bm.isEmpty(e.trim()))throw D_(new Error,L_.ATTR_NAME_NULLISH_ERR,M_.BAD_REQUEST,void 0,void 0,!0)}a($1,"validateAttribute");function Y1(e,t,r){if(!e.hasOwnProperty(t)||Bm.isEmptyOrZeroLength(e[t])){if(r===C_.OPERATIONS_ENUM.INSERT||r===C_.OPERATIONS_ENUM.UPSERT){e[t]=q1.v4();return}throw Wy.error("Update transaction aborted due to record with no hash value:",e),D_(new Error,L_.RECORD_MISSING_HASH_ERR,M_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>C_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Wy.error(e),D_(new Error,L_.HASH_VAL_LENGTH_ERR,M_.BAD_REQUEST,void 0,void 0,!0)}a(Y1,"validateHash")});var Jy=R((oce,zy)=>{"use strict";var Hm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};zy.exports=Hm});var Zy=R((cce,Xy)=>{"use strict";var xm=Ye(),K1=Y(),jy=Cr().LMDB_ERRORS_ENUM;Xy.exports=W1;async function W1(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 xm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==jy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await xm.closeEnvironment(global.lmdb_map[n]),await xm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==jy.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){K1.error(t)}}a(W1,"cleanLMDBMap")});var Rs=R((lce,nN)=>{"use strict";var Fc=require("crypto"),Q1=re(),{CONFIG_PARAMS:z1}=U(),tN="aes-256-cbc",J1=32,j1=16,Gm=64,rN=32,X1=Gm+rN,eN=new Map;nN.exports={encrypt:Z1,decrypt:eY,createNatsTableStreamName:tY};function Z1(e){let t=Fc.randomBytes(J1),r=Fc.randomBytes(j1),n=Fc.createCipheriv(tN,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(Z1,"encrypt");function eY(e){let t=e.substr(0,Gm),r=e.substr(Gm,rN),n=e.substr(X1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Fc.createDecipheriv(tN,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(eY,"decrypt");function tY(e,t){let r=Q1.get(z1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=eN.get(r);return n||(n=Fc.createHash("md5").update(r).digest("hex"),eN.set(r,n)),n}a(tY,"createNatsTableStreamName")});var ri=R((fce,iN)=>{"use strict";var dce=Br(),U_=Y(),sN=N_(),rY=Rs(),P_=Q(),{handleHDBError:v_,hdb_errors:nY}=ne(),{HDB_ERROR_MSGS:B_,HTTP_STATUS_CODES:Fm}=nY,sY=re();sY.initSync();var{getDatabases:qm}=(Re(),ie(qe));iN.exports={describeAll:iY,describeTable:H_,describeSchema:oY};async function iY(e){try{let t=P_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=qm(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await H_({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 H_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){U_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return U_.error("Got an error in describeAll"),U_.error(t),v_(new Error,B_.DESCRIBE_ALL_ERR)}}a(iY,"describeAll");async function H_(e,t){P_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=sN.describe_table(e);if(i)throw i;let c=qm()[r];if(!c)throw v_(new Error,B_.SCHEMA_NOT_FOUND(e.schema),Fm.NOT_FOUND);let u=c[n];if(!u)throw v_(new Error,B_.TABLE_NOT_FOUND(e.schema,e.table),Fm.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=rY.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){U_.warn(`unable to stat table dbi due to ${f}`)}return d}a(H_,"descTable");async function oY(e){P_.transformReq(e);let t=sN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=qm()[n];if(!i)throw v_(new Error,B_.SCHEMA_NOT_FOUND(e.schema),Fm.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),P_.isEmpty(u)||u.describe){let _=await H_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(oY,"describeSchema")});var As=R((pce,lN)=>{var aY=ki(),{callbackify:aN,promisify:cY}=require("util"),{getDatabases:cN}=(Re(),ie(qe));lN.exports={setSchemaDataToGlobal:oN,getTableSchema:uY,getSystemSchema:lY,setSchemaDataToGlobalAsync:cY(oN)};var uN=ri(),hce=aN(uN.describeAll),mce=aN(uN.describeTable);function oN(e){global.hdb_schema=cN(),e&&e()}a(oN,"setSchemaDataToGlobal");function uY(e,t,r){let n=cN()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(uY,"getTableSchema");function lY(){return aY}a(lY,"getSystemSchema")});var an=R((Tce,EN)=>{"use strict";var G_=Pm(),kt=Q(),_Y=require("util"),F_=Dn(),dY=As(),_N=Y(),{handleHDBError:$i,hdb_errors:fY}=ne(),{HTTP_STATUS_CODES:Yi}=fY,EY=_Y.promisify(dY.getTableSchema),hY="updated",dN="inserted",fN="upserted";EN.exports={insert:pY,update:SY,upsert:TY,validation:mY,flush:gY};async function mY(e){if(kt.isEmpty(e))throw new Error("invalid update parameters defined.");if(kt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(kt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await EY(e.schema,e.table),r=G_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&kt.isEmptyOrZeroLength(c[n]))throw _N.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(!kt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw _N.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!kt.isEmpty(c[n])&&c[n]!==""&&s.has(kt.autoCast(c[n]))&&(c.skip=!0),s.add(kt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(mY,"validation");async function pY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=G_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await F_.createRecords(e);return x_(dN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(pY,"insertData");async function SY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=G_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await F_.updateRecords(e);return kt.isEmpty(n.existing_rows)?x_(hY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):x_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(SY,"updateData");async function TY(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=G_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await F_.upsertRecords(e);return x_(fN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(TY,"upsertData");function x_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===dN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===fN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(x_,"returnObject");function gY(e){return kt.transformReq(e),F_.flush(e.schema,e.table)}a(gY,"flush")});var Vm=R((Rce,pN)=>{var RY=et(),km=require("joi"),{hdb_table:AY,hdb_database:hN}=zn(),mN={schema:hN,database:hN,table:AY},OY={date:km.date().iso().required()},bY={timestamp:km.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};pN.exports=function(e,t){let r=t==="timestamp"?{...mN,...bY}:{...mN,...OY},n=km.object(r);return RY.validateBySchema(e,n)}});var gN=R((Ace,TN)=>{var yY=et(),$m=require("joi"),{hdb_table:NY,hdb_database:SN}=zn(),IY=$m.object({schema:SN,database:SN,table:NY,hash_values:$m.array().required(),ids:$m.array()});TN.exports=function(e){return yY.validateBySchema(e,IY)}});var AN=R((Oce,RN)=>{"use strict";var Ym=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Km=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Wm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};RN.exports={InsertObject:Ym,NoSQLSeachObject:Km,DeleteResponseObject:Wm}});var Qi=R((yce,IN)=>{"use strict";var bN=Vm(),wY=gN(),Ki=Q(),ON=require("moment"),yN=Y(),{promisify:CY,callbackify:DY}=require("util"),Wi=U(),LY=As(),Qm=CY(LY.getTableSchema),zm=Dn(),{DeleteResponseObject:MY}=AN(),{handleHDBError:ni,hdb_errors:UY}=ne(),{HDB_ERROR_MSGS:q_,HTTP_STATUS_CODES:si}=UY,PY="records successfully deleted",vY=DY(NN);IN.exports={delete:vY,deleteRecord:NN,deleteFilesBefore:BY,deleteAuditLogsBefore:HY};async function BY(e){let t=bN(e,"date");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!ON(e.date,ON.ISO_8601).isValid())throw ni(new Error,q_.INVALID_DATE,si.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,q_.INVALID_DATE,!0);let n=Ki.checkSchemaTableExist(e.schema,e.table);if(n)throw ni(new Error,n,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,n,!0);let s=await zm.deleteRecordsBefore(e);if(await Qm(e.schema,e.table),yN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(BY,"deleteFilesBefore");async function HY(e){let t=bN(e,"timestamp");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw ni(new Error,q_.INVALID_VALUE("Timestamp"),si.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,q_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let n=await zm.deleteAuditLogsBefore(e);return await Qm(e.schema,e.table),yN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(HY,"deleteAuditLogsBefore");async function NN(e){e.ids&&(e.hash_values=e.ids);let t=wY(e);if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await Qm(e.schema,e.table);let n=await zm.deleteRecords(e);return Ki.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${PY}`),n}catch(n){if(n.message===Wi.SEARCH_NOT_FOUND_MESSAGE){let s=new MY;return s.message=Wi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(NN,"deleteRecord")});var k_=R((Ice,DN)=>{var xY=require("crypto"),wN=9;function GY(e){let t=qY(wN),r=CN(e+t);return t+r}a(GY,"createHash");function FY(e,t){let r=e?.substr(0,wN),n=r+CN(t+r);return e===n}a(FY,"validateHash");function qY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(qY,"generateSalt");function CN(e){return xY.createHash("md5").update(e).digest("hex")}a(CN,"md5");DN.exports={hash:GY,validate:FY}});var MN=R((Cce,LN)=>{var Jm=et(),zt={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 kY(e){return zt.password.presence=!0,zt.username.presence=!0,zt.role.presence=!0,zt.active.presence=!0,Jm.validateObject(e,zt)}a(kY,"addUserValidation");function VY(e){return zt.password.presence=!1,zt.username.presence=!0,zt.role.presence=!1,zt.active.presence=!1,Jm.validateObject(e,zt)}a(VY,"alterUserValidation");function $Y(e){return zt.password.presence=!1,zt.username.presence=!0,zt.role.presence=!1,zt.active.presence=!1,Jm.validateObject(e,zt)}a($Y,"dropUserValidation");LN.exports={addUserValidation:kY,alterUserValidation:VY,dropUserValidation:$Y}});var st=R((Mce,PN)=>{"use strict";var{platform:Lce}=require("os"),YY="nats-server.zip",jm="nats-server",KY=process.platform==="win32"?`${jm}.exe`:jm,WY=/^[^\s.,*>]+$/,UN="__request__",QY=a(e=>`${e}.${UN}`,"REQUEST_SUBJECT"),zY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},JY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},jY={HUB:"hub.pid",LEAF:"leaf.pid"},XY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},ZY={SUCCESS:"success",ERROR:"error"},eK={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},tK={TXN:"txn",MSGID:"msgid"},Yo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},rK={[Yo.ERR]:1,[Yo.WRN]:2,[Yo.INF]:3,[Yo.DBG]:4,[Yo.TRC]:5},nK={debug:"-D",trace:"-DVV"};PN.exports={NATS_SERVER_ZIP:YY,NATS_SERVER_NAME:jm,NATS_BINARY_NAME:KY,PID_FILES:jY,NATS_CONFIG_FILES:JY,SERVER_SUFFIX:XY,NATS_TERM_CONSTRAINTS_RX:WY,REQUEST_SUFFIX:UN,UPDATE_REMOTE_RESPONSE_STATUSES:ZY,CLUSTER_STATUS_STATUSES:eK,REQUEST_SUBJECT:QY,SUBJECT_PREFIXES:tK,MSG_HEADERS:zY,LOG_LEVELS:Yo,LOG_LEVEL_FLAGS:nK,LOG_LEVEL_HIERARCHY:rK}});var BN=R((Pce,vN)=>{"use strict";var V_=U(),$_=class{static{a(this,"BaseLicense")}constructor(t=0,r=V_.RAM_ALLOCATION_ENUM.DEFAULT,n=V_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},Xm=class extends $_{static{a(this,"ExtendedLicense")}constructor(t=0,r=V_.RAM_ALLOCATION_ENUM.DEFAULT,n=V_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};vN.exports={BaseLicense:$_,ExtendedLicense:Xm}});var zi=R((Bce,kN)=>{"use strict";var Wo=require("fs-extra"),xN=k_(),GN=require("crypto"),sK=require("moment"),iK=require("uuid").v4,Jt=Y(),ep=require("path"),oK=Q(),ii=U(),{totalmem:HN}=require("os"),aK=BN().ExtendedLicense,Ko="invalid license key format",cK="061183",uK="mofi25",lK="aes-256-cbc",_K=16,dK=32,FN=re();FN.initSync();var Zm;kN.exports={validateLicense:qN,generateFingerPrint:EK,licenseSearch:np,getLicense:pK,checkMemoryLimit:SK};function tp(){return ep.join(FN.getHdbBasePath(),ii.LICENSE_KEY_DIR_NAME,ii.LICENSE_FILE_NAME)}a(tp,"getLicenseDirPath");function fK(){let e=tp();return ep.join(e,ii.LICENSE_FILE_NAME)}a(fK,"getLicenseFilePath");function rp(){let e=tp();return ep.join(e,ii.REG_KEY_FILE_NAME)}a(rp,"getFingerPrintFilePath");async function EK(){let e=rp();try{return await Wo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await hK();throw Jt.error(`Error writing fingerprint file to ${e}`),Jt.error(t),new Error("There was an error generating the fingerprint")}}a(EK,"generateFingerPrint");async function hK(){let e=iK(),t=xN.hash(e),r=rp();try{await Wo.mkdirp(tp()),await Wo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Jt.error(`Error writing fingerprint file to ${r}`),Jt.error(n),new Error("There was an error generating the fingerprint")}return t}a(hK,"writeFingerprint");function qN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ii.RAM_ALLOCATION_ENUM.DEFAULT,version:ii.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Jt.error("empty license key passed to validate."),r;let n=rp(),s=!1;try{s=Wo.statSync(n)}catch(i){Jt.error(i)}if(s){let i;try{i=Wo.readFileSync(n,"utf8")}catch{Jt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(uK),c=o[1];c=Buffer.concat([Buffer.from(c)],_K);let u=Buffer.concat([Buffer.from(i)],dK),_=GN.createDecipheriv(lK,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=mK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Ko),Jt.error(Ko),new Error(Ko)}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(Ko),Jt.error(Ko),new Error(Ko)}else r.exp_date=l;r.exp_date<sK().valueOf()&&(r.valid_date=!1),xN.validate(o[1],`${cK}${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||Jt.error("Invalid licence"),r}a(qN,"validateLicense");function mK(e,t){try{let r=GN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Jt.warn("Check old license failed")}}a(mK,"checkOldLicense");function np(){let e=new aK,t=[];try{t=Wo.readFileSync(fK(),"utf-8").split(ii.NEW_LINE)}catch(r){r.code==="ENOENT"?Jt.info("no license file found"):Jt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(oK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=qN(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){Jt.error("There was an error parsing the license string."),Jt.error(s),e.ram_allocation=ii.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Zm=e,e}a(np,"licenseSearch");async function pK(){return Zm||await np(),Zm}a(pK,"getLicense");function SK(){let e=np().ram_allocation,t=process.constrainedMemory?.()||HN();if(t=Math.round(Math.min(t,HN())/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(SK,"checkMemoryLimit")});var xr=R((qce,sI)=>{"use strict";var KN="username is required",WN="nothing to update, must supply active, role or password to update",QN="password cannot be an empty string",zN="If role is specified, it cannot be empty.",JN="active must be true or false";sI.exports={addUser:IK,alterUser:wK,dropUser:DK,getSuperUser:PK,userInfo:LK,listUsers:K_,listUsersExternal:MK,setUsersToGlobal:zo,findAndValidateUser:rI,getClusterUser:vK,USERNAME_REQUIRED:KN,ALTERUSER_NOTHING_TO_UPDATE:WN,EMPTY_PASSWORD:QN,EMPTY_ROLE:zN,ACTIVE_BOOLEAN:JN};var jN=an(),TK=Qi(),op=k_(),XN=MN(),ZN=Br(),ap=Os(),Hr=Q(),eI=require("validate.js"),Ae=Y(),{promisify:gK}=require("util"),cp=Rs(),VN=U(),$N=st(),RK=cr(),xce=re(),Gce=zi(),AK=ki(),{table:Fce}=(Re(),ie(qe)),{handleHDBError:jn,hdb_errors:OK}=ne(),{HTTP_STATUS_CODES:Xn,AUTHENTICATION_ERROR_MSGS:sp,HDB_ERROR_MSGS:Qo}=OK,{UserEventMsg:up}=Ln(),ip=require("lodash"),{server:lp}=(or(),ie(Bi)),bK=Y();lp.getUser=(e,t)=>rI(e,t,t!=null);var tI={username:!0,active:!0,role:!0,password:!0},YN=new Map,Y_=ZN.searchByValue,yK=ZN.searchByHash,NK=gK(TK.delete);async function IK(e){let t=eI.cleanAttributes(e,tI),r=XN.addUserValidation(t);if(r)throw jn(new Error,r.message,Xn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await Y_(n),s=s&&Array.from(s)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!s||s.length<1)throw jn(new Error,Qo.ROLE_NAME_NOT_FOUND(t.role),Xn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw jn(new Error,Qo.DUP_ROLES_FOUND(t.role),Xn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=cp.encrypt(t.password)),t.password=op.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await jN.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await zo()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw jn(new Error,Qo.USER_ALREADY_EXISTS(t.username),Xn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],ap.signalUserChange(new up(process.pid)),`${c.username} successfully added`}a(IK,"addUser");async function wK(e){let t=eI.cleanAttributes(e,tI);if(Hr.isEmptyOrZeroLength(t.username))throw new Error(KN);if(Hr.isEmptyOrZeroLength(t.password)&&Hr.isEmptyOrZeroLength(t.role)&&Hr.isEmptyOrZeroLength(t.active))throw new Error(WN);if(!Hr.isEmpty(t.password)&&Hr.isEmptyOrZeroLength(t.password.trim()))throw new Error(QN);if(!Hr.isEmpty(t.active)&&!Hr.isBoolean(t.active))throw new Error(JN);let r=CK(t.username);if(!Hr.isEmpty(t.password)&&!Hr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=cp.encrypt(t.password)),t.password=op.hash(t.password)),t.role==="")throw new Error(zN);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 Y_(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=Qo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),jn(new Error,c,Xn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Qo.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),jn(new Error,c,Xn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await jN.update(n)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await zo()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return ap.signalUserChange(new up(process.pid)),s}a(wK,"alterUser");function CK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(CK,"isClusterUser");async function DK(e){try{let t=XN.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Hr.isEmpty(global.hdb_users.get(e.username)))throw jn(new Error,Qo.USER_NOT_EXIST(e.username),Xn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await NK(r)}catch(s){throw Ae.error("Got an error deleting a user."),Ae.error(s),s}Ae.debug(n);try{await zo()}catch(s){throw Ae.error("Got an error setting users to global."),Ae.error(s),s}return ap.signalUserChange(new up(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(DK,"dropUser");async function LK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=ip.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await yK(r)}catch(s){throw Ae.error("Got an error searching for a role."),Ae.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(LK,"userInfo");async function MK(){let e;try{e=await K_()}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(MK,"listUsersExternal");async function K_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await Y_(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]=ip.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await Y_(n)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of s)o=ip.cloneDeep(o),o.role=r[o.role],UK(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),Hr.errorizeMessage(e)}return null}a(K_,"listUsers");function UK(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(AK)){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(UK,"appendSystemTablesToRole");async function zo(){try{let e=await K_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(zo,"setUsersToGlobal");async function rI(e,t,r=!0){global.hdb_users||await zo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw jn(new Error,sp.GENERIC_AUTH_FAIL,Xn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw jn(new Error,sp.USER_INACTIVE,Xn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(YN.get(t)===n.password)return s;if(op.validate(n.password,t))YN.set(t,n.password);else throw jn(new Error,sp.GENERIC_AUTH_FAIL,Xn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(rI,"findAndValidateUser");async function PK(){global.hdb_users||await zo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(PK,"getSuperUser");async function vK(){let e=await K_(),t=RK.getConfigFromFile(VN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Hr.isEmpty(r)&&r?.role?.role===VN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=cp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+$N.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+$N.SERVER_SUFFIX.ADMIN,r}a(vK,"getClusterUser");var nI=[];lp.invalidateUser=function(e){for(let t of nI)try{t(e)}catch(r){bK.error("Error invalidating user",r)}};lp.onInvalidatedUser=function(e){nI.push(e)}});var kc=R((Yce,cI)=>{"use strict";var Ji=Y(),Gr=U(),BK=Zy(),Vce=As(),$ce=ri(),HK=xr(),{validateEvent:iI}=Ln(),qc=Dn(),xK=require("process"),{resetDatabases:GK}=(Re(),ie(qe)),FK={[Gr.ITC_EVENT_TYPES.SCHEMA]:qK,[Gr.ITC_EVENT_TYPES.USER]:aI};async function qK(e){let t=iI(e);if(t){Ji.error(t);return}Ji.trace("ITC schemaHandler received schema event:",e),await BK(e.message),await kK(e.message)}a(qK,"schemaHandler");async function kK(e){try{qc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),qc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),qc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=GK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Ji.error(t)}}a(kK,"syncSchemaMetadata");var oI=[];async function aI(e){try{try{qc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),qc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Ji.warn(r)}let t=iI(e);if(t){Ji.error(t);return}Ji.trace(`ITC userHandler ${Gr.HDB_ITC_CLIENT_PREFIX}${xK.pid} received user event:`,e),await HK.setUsersToGlobal();for(let r of oI)r()}catch(t){Ji.error(t)}}a(aI,"userHandler");aI.addListener=function(e){oI.push(e)};cI.exports=FK});var Ln=R((jce,lI)=>{"use strict";var Wce=Y(),_p=Q(),VK=U(),{ITC_ERRORS:Vc}=Cr(),{parentPort:Qce,threadId:$K,isMainThread:YK,workerData:zce}=require("worker_threads"),{onMessageFromWorkers:KK,broadcast:Jce,broadcastWithAcknowledgement:WK}=rt();lI.exports={sendItcEvent:QK,validateEvent:uI,SchemaEventMsg:zK,UserEventMsg:JK};var W_;KK(async(e,t)=>{W_=W_||kc(),uI(e),W_[e.type]&&await W_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function QK(e){return!YK&&e.message&&(e.message.originator=$K),WK(e)}a(QK,"sendItcEvent");function uI(e){if(typeof e!="object")return Vc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||_p.isEmpty(e.type))return Vc.MISSING_TYPE;if(!e.hasOwnProperty("message")||_p.isEmpty(e.message))return Vc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||_p.isEmpty(e.message.originator))return Vc.MISSING_ORIGIN;if(VK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Vc.INVALID_EVENT(e.type)}a(uI,"validateEvent");function zK(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(zK,"SchemaEventMsg");function JK(e){this.originator=e}a(JK,"UserEventMsg")});var Os=R((eue,EI)=>{"use strict";var _I=U(),Zce=Q(),Q_=Y(),dI=Jy(),Jo,{sendItcEvent:fI}=Ln();function jK(e){try{Q_.trace("signalSchemaChange called with message:",e),Jo=Jo||kc();let t=new dI(_I.ITC_EVENT_TYPES.SCHEMA,e);return Jo.schema(t),fI(t)}catch(t){Q_.error(t)}}a(jK,"signalSchemaChange");function XK(e){try{Q_.trace("signalUserChange called with message:",e),Jo=Jo||kc();let t=new dI(_I.ITC_EVENT_TYPES.USER,e);return Jo.user(t),fI(t)}catch(t){Q_.error(t)}}a(XK,"signalUserChange");EI.exports={signalSchemaChange:jK,signalUserChange:XK}});var z_=R((rue,mI)=>{"use strict";var hI=Q(),ZK=U(),eW=Y(),tW=w_(),rW=I_(),nW=Os(),{SchemaEventMsg:sW}=Ln(),iW="already exists in";mI.exports=oW;async function oW(e,t,r){if(hI.isEmptyOrZeroLength(r))return r;let n=[];hI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await aW(e,t.schema,t.name,i)})),s}a(oW,"lmdbCheckForNewAttributes");async function aW(e,t,r,n){let s=new rW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await cW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(iW))eW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(aW,"createNewAttribute");async function cW(e){let t;return t=await tW(e),nW.signalSchemaChange(new sW(process.pid,ZK.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(cW,"createAttribute")});var jo=R((sue,pI)=>{"use strict";var dp=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};pI.exports=dp});var TI=R((oue,SI)=>{"use strict";var uW=jo(),lW=U().OPERATIONS_ENUM,fp=class extends uW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(lW.INSERT,r,n,s,i),this.records=t}};SI.exports=fp});var RI=R((cue,gI)=>{"use strict";var _W=jo(),dW=U().OPERATIONS_ENUM,Ep=class extends _W{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(dW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};gI.exports=Ep});var OI=R((lue,AI)=>{"use strict";var fW=jo(),EW=U().OPERATIONS_ENUM,hp=class extends fW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(EW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};AI.exports=hp});var yI=R((due,bI)=>{"use strict";var hW=jo(),mW=U().OPERATIONS_ENUM,mp=class extends hW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(mW.DELETE,n,s,t,i),this.original_records=r}};bI.exports=mp});var $c=R((hue,CI)=>{"use strict";var Eue=require("path"),NI=Ye(),pW=TI(),SW=RI(),TW=OI(),gW=yI(),Xo=ct(),II=Q(),{CONFIG_PARAMS:RW}=U(),wI=re();wI.initSync();var J_=U().OPERATIONS_ENUM,{getTransactionAuditStorePath:AW}=Qe();CI.exports=OW;async function OW(e,t){if(wI.get(RW.LOGGING_AUDITLOG)===!1)return;let r=AW(e.schema,e.table),n=await NI.openEnvironment(r,e.table,!0),s=bW(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){NI.initializeDBIs(n,Xo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Xo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),II.isEmpty(s.user_name)||n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(OW,"writeTransaction");function bW(e,t){let r=II.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===J_.INSERT)return new pW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===J_.UPDATE)return new SW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===J_.UPSERT)return new TW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===J_.DELETE)return new gW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(bW,"createTransactionObject")});var pp=R((Sue,DI)=>{"use strict";var yW=Hc(),pue=xc(),Yc=U(),NW=Gc(),IW=Vo().insertRecords,wW=Ye(),CW=Y(),DW=z_(),{getSchemaPath:LW}=Qe(),MW=$c();DI.exports=UW;async function UW(e){try{let{schema_table:t,attributes:r}=yW(e);NW(e,r,t.hash_attribute),e.schema!==Yc.SYSTEM_SCHEMA_NAME&&(r.includes(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await DW(e.hdb_auth_header,t,r),s=LW(e.schema,e.table),i=await wW.openEnvironment(s,e.table),o=await IW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await MW(e,o)}catch(c){CW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(UW,"lmdbCreateRecords")});var UI=R((gue,MI)=>{"use strict";var LI=U(),PW=pp(),vW=xc(),BW=require("fs-extra"),{getSchemaPath:HW}=Qe();MI.exports=xW;async function xW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new vW(LI.SYSTEM_SCHEMA_NAME,LI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await PW(r),await BW.mkdirp(HW(e.schema))}a(xW,"lmdbCreateSchema")});var vI=R((Aue,PI)=>{"use strict";var Sp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};PI.exports=Sp});var GI=R((Iue,xI)=>{"use strict";var BI=Ye(),Tp=Mr(),gp=Cr().LMDB_ERRORS_ENUM,GW=ct(),HI=Y(),bue=Q(),FW=require("lmdb"),qW=vI(),kW=U(),{OVERFLOW_MARKER:yue,MAX_SEARCH_KEY_LENGTH:Nue}=GW,VW=kW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function $W(e,t,r,n){if(Tp.validateEnv(e),t===void 0)throw new Error(gp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(gp.IDS_REQUIRED):new Error(gp.IDS_MUST_BE_ITERABLE);try{let s=BI.listDBIs(e);BI.initializeDBIs(e,t,s);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||n&&h[VW]>n){i.skipped.push(o);continue}let S=e.dbis[t].ifVersion(o,FW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let p=0;p<s.length;p++){let T=s[p];if(!h.hasOwnProperty(T)||T===t)continue;let b=e.dbis[T],g=h[T];if(g!=null)try{let L=Tp.getIndexedValues(g);if(L)for(let v=0,P=L.length;v<P;v++)b.remove(L[v],o)}catch{HI.warn(`cannot delete from attribute: ${T}, ${g}:${o}`)}}});c.push(S),u.push(o),i.original_records.push(h)}catch(h){HI.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=Tp.getNextMonotonicTime(),i}catch(s){throw s}}a($W,"deleteRecords");xI.exports={deleteRecords:$W}});var Kc=R((Cue,qI)=>{"use strict";var Zo=Q(),YW=GI(),KW=Ye(),{getSchemaPath:WW}=Qe(),QW=$c(),zW=Y();qI.exports=JW;async function JW(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(Zo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Zo.isEmptyOrZeroLength(e.hash_values)&&!Zo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];Zo.isEmpty(u)||e.hash_values.push(u)}}if(Zo.isEmptyOrZeroLength(e.hash_values))return FI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Zo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=WW(e.schema,e.table),i=await KW.openEnvironment(s,e.table),o=await YW.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await QW(e,o)}catch(c){zW.error(`unable to write transaction due to ${c.message}`)}return FI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(JW,"lmdbDeleteRecords");function FI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(FI,"createDeleteResponse")});var Ap=R((Mue,kI)=>{"use strict";var jW=U(),Lue=Mr();function Rp(e,t){let r=Object.create(null);if(t.length===1&&jW.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(Rp,"parseRow");function XW(e,t,r,n){let s=Rp(r,e);n.push(s)}a(XW,"searchAll");function ZW(e,t,r,n){let s=Rp(r,e);n[t]=s}a(ZW,"searchAllToMap");function eQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(eQ,"iterateDBI");function ji(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(ji,"pushResults");function tQ(e,t,r,n,s,i){t.toString().endsWith(e)&&ji(t,r,n,s,i)}a(tQ,"endsWith");function rQ(e,t,r,n,s,i){t.toString().includes(e)&&ji(t,r,n,s,i)}a(rQ,"contains");function nQ(e,t,r,n,s,i){t>e&&ji(t,r,n,s,i)}a(nQ,"greaterThanCompare");function sQ(e,t,r,n,s,i){t>=e&&ji(t,r,n,s,i)}a(sQ,"greaterThanEqualCompare");function iQ(e,t,r,n,s,i){t<e&&ji(t,r,n,s,i)}a(iQ,"lessThanCompare");function oQ(e,t,r,n,s,i){t<=e&&ji(t,r,n,s,i)}a(oQ,"lessThanEqualCompare");kI.exports={parseRow:Rp,searchAll:XW,searchAllToMap:ZW,iterateDBI:eQ,endsWith:tQ,contains:rQ,greaterThanCompare:nQ,greaterThanEqualCompare:sQ,lessThanCompare:iQ,lessThanEqualCompare:oQ,pushResults:ji}});var ea=R((Hue,zI)=>{"use strict";var oi=Ye(),Pue=Y(),Fr=Mr(),j_=ct(),lt=Cr().LMDB_ERRORS_ENUM,vue=Q(),aQ=U(),X_=Ap(),{parseRow:cQ}=X_,Bue=require("lmdb"),{OVERFLOW_MARKER:VI,MAX_SEARCH_KEY_LENGTH:uQ}=j_;function $I(e,t,r,n=!1,s=void 0,i=void 0){return Xi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a($I,"iterateFullIndex");function Wc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Xi(e,t,r,(l,d,f,E)=>{let b={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(b.values=!1,d.getRange(b).map(g=>({value:g}))):d.getRange(b)})}a(Wc,"iterateRangeBetween");function Xi(e,t,r,n){let s=e.database||e,i=oi.openDBI(s,r);i[j_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&oi.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Xi,"setupTransaction");function YI(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(VI)){if(!s)if(r)s=oi.openDBI(e,r);else{let u=oi.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=oi.openDBI(e,u[_]),!s[j_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(YI,"getOverflowCheck");function lQ(e,t,r,n=!1,s=void 0,i=void 0){if(Fr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return Xi(e,t,t,(o,c,u)=>(Z_(r),r=Qc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>cQ(_.value,r))))}a(lQ,"searchAll");function _Q(e,t,r,n=!1,s=void 0,i=void 0){if(Fr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);Z_(r),r=Qc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of $I(e,t,t,n,s,i))o.set(c,X_.parseRow(u,r));return o}a(_Q,"searchAllToMap");function dQ(e,t,r=!1,n=void 0,s=void 0){if(Fr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=$I(e,void 0,t,r,n,s),c=o.transaction,u=YI(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(dQ,"iterateDBI");function fQ(e,t){if(Fr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return oi.statDBI(e,t).entryCount}a(fQ,"countAll");function EQ(e,t,r,n,s=!1,i=void 0,o=void 0){return ai(e,r,n),Xi(e,t,r,(c,u,_,l)=>(n=Fr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(EQ,"equals");function hQ(e,t,r){return ai(e,t,r),oi.openDBI(e,t).getValuesCount(r)}a(hQ,"count");function mQ(e,t,r,n,s=!1,i=void 0,o=void 0){return ai(e,r,n),Xi(e,null,r,(c,u)=>{n=Fr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(mQ,"startsWith");function pQ(e,t,r,n,s=!1,i=void 0,o=void 0){return KI(e,t,r,n,s,i,o,!0)}a(pQ,"endsWith");function KI(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ai(e,r,n),Xi(e,null,r,(u,_,l,d)=>{let f=YI(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(VI)?_.getValues(E,{transaction:u}).map(S=>{let p=f(E,S);if(c?p.endsWith(n):p.includes(n))return{key:p,value:S}}).filter(S=>S):(c?h.endsWith(n):h.includes(n))?_[j_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(S=>({key:E,value:S})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(KI,"contains");function SQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Wc(e,t,r,n,u,s,i,o,!0,!1)}a(SQ,"greaterThan");function TQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Wc(e,t,r,n,u,s,i,o,!1,!1)}a(TQ,"greaterThanEqual");function gQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Wc(e,t,r,u,n,s,i,o,!1,!0)}a(gQ,"lessThan");function RQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Wc(e,t,r,u,n,s,i,o,!1,!1)}a(RQ,"lessThanEqual");function AQ(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Fr.validateEnv(e),r===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(lt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(lt.END_VALUE_REQUIRED);if(n=Fr.convertKeyValueToWrite(n),s=Fr.convertKeyValueToWrite(s),n>s)throw new Error(lt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Wc(e,t,r,n,s,i,o,c)}a(AQ,"between");function OQ(e,t,r,n){Fr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(Z_(r),r=Qc(s,r),n===void 0)throw new Error(lt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=X_.parseRow(c,r)),o}a(OQ,"searchByHash");function bQ(e,t,r){Fr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(bQ,"checkHashExists");function yQ(e,t,r,n,s=[]){return QI(e,t,r,n,s),WI(e,t,r,n,s).map(i=>i[1])}a(yQ,"batchSearchByHash");function NQ(e,t,r,n,s=[]){QI(e,t,r,n,s);let i=new Map;for(let[o,c]of WI(e,t,r,n,s))i.set(o,c);return i}a(NQ,"batchSearchByHashToMap");function WI(e,t,r,n,s=[]){return Xi(e,t,t,(i,o,c)=>{r=Qc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,X_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(WI,"batchHashSearch");function QI(e,t,r,n,s){if(Fr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(Z_(r),n==null)throw new Error(lt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(lt.IDS_MUST_BE_ITERABLE)}a(QI,"initializeBatchSearchByHash");function Z_(e){if(!Array.isArray(e))throw e===void 0?new Error(lt.FETCH_ATTRIBUTES_REQUIRED):new Error(lt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(Z_,"validateFetchAttributes");function ai(e,t,r){if(Fr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.SEARCH_VALUE_REQUIRED);if(r?.length>uQ)throw new Error(lt.SEARCH_VALUE_TOO_LARGE)}a(ai,"validateComparisonFunctions");function Qc(e,t){return t.length===1&&aQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=oi.listDBIs(e)),t}a(Qc,"setGetWholeRowAttributes");zI.exports={searchAll:lQ,searchAllToMap:_Q,count:hQ,countAll:fQ,equals:EQ,startsWith:mQ,endsWith:pQ,contains:KI,searchByHash:OQ,setGetWholeRowAttributes:Qc,batchSearchByHash:yQ,batchSearchByHashToMap:NQ,checkHashExists:bQ,iterateDBI:dQ,greaterThan:SQ,greaterThanEqual:TQ,lessThan:gQ,lessThanEqual:RQ,between:AQ}});var ta=R((Gue,ew)=>{var JI=require("lodash"),jI=et(),fe=require("joi"),IQ=Q(),{hdb_schema_table:zc,checkValidTable:XI,hdb_table:ZI,hdb_database:ed}=zn(),{handleHDBError:wQ,hdb_errors:CQ}=ne(),{getDatabases:DQ}=(Re(),ie(qe)),{HTTP_STATUS_CODES:LQ}=CQ,MQ=fe.object({database:ed,schema:ed,table:ZI,search_attribute:zc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(zc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),UQ=fe.object({database:ed,schema:ed,table:ZI,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(zc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(zc,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(zc,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()});ew.exports=function(e,t){let r=null;switch(t){case"value":r=jI.validateBySchema(e,MQ);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(XI("database",e.schema)),i(XI("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=jI.validateBySchema(e,UQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=IQ.checkGlobalSchemaTable(e.schema,e.table);if(s)return wQ(new Error,s,LQ.NOT_FOUND);let o=DQ()[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 _=JI.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!JI.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 Op=R((que,tw)=>{"use strict";var PQ=Ye(),vQ=ta(),{getSchemaPath:BQ}=Qe();tw.exports=HQ;function HQ(e){let t=vQ(e,"hashes");if(t)throw t;let r=BQ(e.schema,e.table);return PQ.openEnvironment(r,e.table)}a(HQ,"initialize")});var bp=R((Vue,rw)=>{"use strict";var xQ=ea(),GQ=Op();rw.exports=FQ;async function FQ(e){let t=await GQ(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return xQ.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(FQ,"lmdbGetDataByHash")});var ra=R((Yue,nw)=>{"use strict";var yp=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};nw.exports=yp});var iw=R((Que,sw)=>{"use strict";var Wue=ra(),qQ=ea(),kQ=Op();sw.exports=VQ;async function VQ(e){let t=await kQ(e),r=global.hdb_schema[e.schema][e.table];return qQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(VQ,"lmdbSearchByHash")});var Zn=R((Jue,ow)=>{"use strict";var Np=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};ow.exports=Np});var td=R((Xue,dw)=>{"use strict";var jt=ea(),$Q=Ye(),YQ=Q(),Ee=ct(),Zi=U(),KQ=ki(),aw=Cr().LMDB_ERRORS_ENUM,{getSchemaPath:WQ}=Qe(),bs=Zi.SEARCH_WILDCARDS;async function QQ(e,t,r){let n;e.schema===Zi.SYSTEM_SCHEMA_NAME?n=KQ[e.table]:n=global.hdb_schema[e.schema][e.table];let s=_w(e,n.hash_attribute,r,t);return uw(e,s,n.hash_attribute,r)}a(QQ,"prepSearch");async function uw(e,t,r,n){let s=WQ(e.schema,e.table),i=await $Q.openEnvironment(s,e.table),o=lw(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(zQ(e,r)===!1){let l=e.search_attribute;if(l===r)return n?cw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?cw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?jt.batchSearchByHashToMap(c,r,e.get_attributes,_):jt.batchSearchByHash(c,r,e.get_attributes,_)}a(uw,"executeSearch");function lw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=jt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=jt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=jt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=jt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return jt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return jt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return jt.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return jt.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=jt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=jt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=jt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=jt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=jt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(lw,"searchByType");function cw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(cw,"createMapFromIterable");function zQ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(zQ,"checkToFetchMore");function _w(e,t,r,n){if(YQ.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),bs.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(bs[0])<0&&s.indexOf(bs[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(bs.indexOf(i)>=0&&bs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(bs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(bs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(bs[0])||s.includes(bs[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(aw.UNKNOWN_SEARCH_TYPE)}else switch(n){case Zi.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case Zi.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case Zi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(aw.UNKNOWN_SEARCH_TYPE)}}a(_w,"createSearchTypeFromSearchObject");dw.exports={executeSearch:uw,createSearchTypeFromSearchObject:_w,prepSearch:QQ,searchByType:lw}});var Ew=R((tle,fw)=>{"use strict";var ele=Zn(),JQ=ta(),jQ=Q(),XQ=U(),ZQ=td();fw.exports=ez;function ez(e,t){if(!jQ.isEmpty(t)&&XQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=JQ(e,"value");if(n)throw n;return ZQ.prepSearch(e,t,!0)}a(ez,"lmdbGetDataByValue")});var Jc=R((sle,hw)=>{"use strict";var nle=Zn(),tz=ta(),rz=Q(),nz=U(),sz=td();hw.exports=iz;async function iz(e,t){if(!rz.isEmpty(t)&&nz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=tz(e,"value");if(n)throw n;return sz.prepSearch(e,t,!1)}a(iz,"lmdbSearchByValue")});var pw=R((ale,mw)=>{"use strict";var ole=ct(),Ip=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},wp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Cp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};mw.exports={SearchByConditionsObject:Ip,SearchCondition:wp,SortAttribute:Cp}});var Aw=R((_le,Rw)=>{"use strict";var ule=pw().SearchByConditionsObject,oz=Zn(),az=ta(),Dp=ea(),rd=ct(),{Resource:lle}=(In(),ie(Lp)),gw=td(),cz=Ap(),uz=require("lodash"),{getSchemaPath:lz}=Qe(),Sw=Ye(),{handleHDBError:_z,hdb_errors:dz}=ne(),{HTTP_STATUS_CODES:fz}=dz,Ez=1e8;Rw.exports=hz;async function hz(e){let t=az(e,"conditions");if(t)throw _z(t,t.message,fz.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=lz(e.schema,e.table),n=await Sw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Sw.openDBI(n,_.search_attribute);let i=uz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===rd.SEARCH_TYPES.EQUALS?_.estimated_count=Dp.count(n,_.search_attribute,_.search_value):l===rd.SEARCH_TYPES.CONTAINS||l===rd.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Ez}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Tw(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(gw.filterByType),d=l.length,f=Dp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>cz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Tw(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Dp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(hz,"lmdbSearchByConditions");async function Tw(e,t,r,n){let s=new oz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===rd.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,gw.searchByType(e,s,i,n).map(o=>o.value)}a(Tw,"executeConditionSearch")});var jc=R((fle,Ow)=>{"use strict";var mz=U().OPERATIONS_ENUM,Mp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=mz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Ow.exports=Mp});var Up=R((hle,Lw)=>{"use strict";var Iw=Zn(),ww=jc(),Cw=Jc(),Dw=Kc(),_r=U(),bw=Q(),yw=Ye(),{getTransactionAuditStorePath:pz,getSchemaPath:Sz}=Qe(),Nw=Y();Lw.exports=Tz;async function Tz(e){try{if(bw.isEmpty(global.hdb_schema[e.schema])||bw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await gz(e),await Rz(e);let t=Sz(e.schema,e.table);try{await yw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Nw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=pz(e.schema,e.table);await yw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Nw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Tz,"lmdbDropTable");async function gz(e){let t=new Iw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Cw(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new ww(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Dw(s)}a(gz,"deleteAttributesFromSystem");async function Rz(e){let t=new Iw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Cw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new ww(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Dw(s)}catch(i){throw i}}a(Rz,"dropTableFromSystem")});var Uw=R((ple,Mw)=>{"use strict";var Az=require("fs-extra"),Oz=Zn(),bz=ra(),yz=jc(),Nz=Up(),Iz=Kc(),wz=bp(),Cz=Jc(),ys=U(),{getSchemaPath:Dz}=Qe(),{handleHDBError:Lz,hdb_errors:Mz}=ne(),{HDB_ERROR_MSGS:Uz,HTTP_STATUS_CODES:Pz}=Mz;Mw.exports=vz;async function vz(e){let t;try{t=await Bz(e.schema);let r=new Oz(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await Cz(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await Nz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new yz(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Iz(s);let i=Dz(t);await Az.remove(i)}catch(r){throw r}}a(vz,"lmdbDropSchema");async function Bz(e){let t=new bz(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await wz(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw Lz(new Error,Uz.SCHEMA_NOT_FOUND(e),Pz.NOT_FOUND,void 0,void 0,!0);return n}a(Bz,"validateDropSchema")});var vp=R((Tle,Pw)=>{"use strict";var Pp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Pw.exports=Pp});var Bw=R((Ale,vw)=>{"use strict";var Hz=require("fs-extra"),nd=Ye(),{getTransactionAuditStorePath:xz}=Qe(),Bp=ct(),Rle=vp();vw.exports=Gz;async function Gz(e){let t;try{let r=xz(e.schema,e.table);await Hz.mkdirp(r),t=await nd.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{nd.createDBI(t,Bp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),nd.createDBI(t,Bp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),nd.createDBI(t,Bp.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(Gz,"createTransactionsAuditEnvironment")});var Fw=R((ble,Gw)=>{"use strict";var Hp=U(),Hw=Ye(),Fz=Vo(),{getSystemSchemaPath:qz,getSchemaPath:kz}=Qe(),Vz=ki(),$z=w_(),xp=I_(),Yz=Y(),Kz=Bw(),Fp=Vz.hdb_table,xw=[];for(let e=0;e<Fp.attributes.length;e++)xw.push(Fp.attributes[e].attribute);Gw.exports=Wz;async function Wz(e,t){let r=kz(t.schema,t.table),n=new xp(t.schema,t.table,Hp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new xp(t.schema,t.table,Hp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new xp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Hw.createEnvironment(r,t.table),e!==void 0){let o=await Hw.openEnvironment(qz(),Hp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Fz.insertRecords(o,Fp.hash_attribute,xw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Gp(n),await Gp(s),await Gp(i)}await Kz(t)}catch(o){throw o}}a(Wz,"lmdbCreateTable");async function Gp(e){try{await $z(e)}catch(t){Yz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Gp,"createAttribute")});var kw=R((Nle,qw)=>{"use strict";var Qz=Hc(),zz=Gc(),Jz=z_(),Xc=U(),jz=Vo().updateRecords,Xz=Ye(),{getSchemaPath:Zz}=Qe(),e2=$c(),t2=Y();qw.exports=r2;async function r2(e){try{let{schema_table:t,attributes:r}=Qz(e);zz(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 n=await Jz(e.hdb_auth_header,t,r),s=Zz(e.schema,e.table),i=await Xz.openEnvironment(s,e.table),o=await jz(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await e2(e,o)}catch(c){t2.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(r2,"lmdbUpdateRecords")});var $w=R((wle,Vw)=>{"use strict";var n2=U().OPERATIONS_ENUM,qp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=n2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Vw.exports=qp});var Kw=R((Lle,Yw)=>{"use strict";var Dle=$w(),s2=Hc(),i2=Gc(),o2=z_(),Zc=U(),a2=Vo().upsertRecords,c2=Ye(),{getSchemaPath:u2}=Qe(),l2=$c(),_2=Y(),{handleHDBError:d2,hdb_errors:f2}=ne();Yw.exports=E2;async function E2(e){let t;try{t=s2(e)}catch(u){throw d2(u,u.message,f2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;i2(e,n,r.hash_attribute),e.schema!==Zc.SYSTEM_SCHEMA_NAME&&(n.includes(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await o2(e.hdb_auth_header,r,n),i=u2(e.schema,e.table),o=await c2.openEnvironment(i,e.table),c=await a2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await l2(e,c)}catch(u){_2.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(E2,"lmdbUpsertRecords")});var Qw=R((Ule,Ww)=>{"use strict";var kp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};Ww.exports=kp});var Jw=R((vle,zw)=>{"use strict";var Vp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};zw.exports=Vp});var Zw=R((xle,Xw)=>{"use strict";var $p=Ye(),{getTransactionAuditStorePath:h2}=Qe(),Hle=Qw(),eu=ct(),m2=Q(),jw=Jw(),p2=require("util").promisify,S2=p2(setTimeout),T2=1e4,g2=100;Xw.exports=R2;async function R2(e){let t=h2(e.schema,e.table),r=await $p.openEnvironment(t,e.table,!0),n=$p.listDBIs(r);$p.initializeDBIs(r,eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new jw;do s=await A2(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await S2(g2);while(s.transactions_deleted>0);return i}a(R2,"deleteAuditLogsBefore");async function A2(e,t){let r=new jw;try{let n=e.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[eu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];m2.isEmpty(c)||(s=e.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>T2)break}return await s,r}catch(n){throw n}}a(A2,"deleteTransactions")});var tC=R((Fle,eC)=>{"use strict";var Yp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};eC.exports=Yp});var nC=R((Vle,rC)=>{"use strict";var O2=Zn(),b2=jc(),kle=tC(),es=U(),y2=Q(),Kp=Ye(),N2=ki(),I2=Jc(),w2=Kc(),{getSchemaPath:C2}=Qe();rC.exports=D2;async function D2(e,t=!0){let r;e.schema===es.SYSTEM_SCHEMA_NAME?r=N2[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await M2(e),s=C2(e.schema,e.table),i=await Kp.openEnvironment(s,e.table);return t===!0&&await L2(e,i,r.hash_attribute),Kp.dropDBI(i,e.attribute),n}a(D2,"lmdbDropAttribute");async function L2(e,t,r){let n=Kp.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(L2,"removeAttributeFromAllObjects");async function M2(e){let t=new O2(es.SYSTEM_SCHEMA_NAME,es.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await I2(t)).filter(o=>o[es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(y2.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new b2(es.SYSTEM_SCHEMA_NAME,es.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return w2(i)}a(M2,"dropAttributeFromSystem")});var uC=R((Kle,cC)=>{"use strict";var Wp=Ye(),na=ct(),Yle=Mr(),Qp=U(),sC=Q(),{getTransactionAuditStorePath:U2}=Qe(),P2=ea(),sd=jo(),v2=Y();cC.exports=B2;async function B2(e){let t=U2(e.schema,e.table),r=await Wp.openEnvironment(t,e.table,!0),n=Wp.listDBIs(r);Wp.initializeDBIs(r,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case Qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return iC(r,e.search_values);case Qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,x2(r,e.search_values,s);case Qp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return H2(r,e.search_values);default:return iC(r)}}a(B2,"readAuditLog");function iC(e,t=[0,Date.now()]){sC.isEmpty(t[0])&&(t[0]=0),sC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new sd,s))}a(iC,"searchTransactionsByTimestamp");function H2(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,aC(e,i))}return Object.fromEntries(r)}a(H2,"searchTransactionsByUsername");function x2(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=P2.equals(e,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,na.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=aC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);oC(u,"records",r,l,o),oC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(x2,"searchTransactionsByHashValues");function oC(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new sd(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new sd(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(oC,"loopRecords");function aC(e,t){let r=[];try{let n=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new sd,i);r.push(o)}}catch(i){v2.warn(i)}return r}catch(n){throw n}}a(aC,"batchSearchTransactions")});var _C=R((Jle,lC)=>{"use strict";var{getSchemaPath:Qle}=Qe(),zle=Ye(),{database:G2}=(Re(),ie(qe));lC.exports={writeTransaction:F2};async function F2(e,t,r){return G2({database:e,table:t}).transaction(r)}a(F2,"writeTransaction")});var hC=R((Xle,EC)=>{"use strict";var{getSchemaPath:dC}=Qe(),fC=Ye();EC.exports={flush:q2,resetReadTxn:k2};async function q2(e,t){return(await fC.openEnvironment(dC(e,t),t.toString())).flushed}a(q2,"flush");async function k2(e,t){try{(await fC.openEnvironment(dC(e,t),t.toString())).resetReadTxn()}catch{}}a(k2,"resetReadTxn")});var TC=R((e_e,SC)=>{"use strict";var{Readable:V2}=require("stream"),{getDatabases:$2}=(Re(),ie(qe)),{readSync:Y2,openSync:K2,createReadStream:mC}=require("fs"),{open:W2}=require("lmdb"),pC=Dc(),Q2=Lc(),{AUDIT_STORE_OPTIONS:z2}=(Zs(),ie(gC)),{INTERNAL_DBIS_NAME:J2,AUDIT_STORE_NAME:j2}=ct();SC.exports=Z2;var zp=32768,X2=100;async function Z2(e){let t=e.database||e.schema||"data",r=$2()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=W2({noSync:!0,maxDbs:Q2.MAX_DBS}),f,E=d.openDB(J2,new pC(!1)),h=l.useReadTransaction(),S=0,p=a(async function(b,g){g.encoding="binary",g.encoder=void 0;let L=d.openDB(b,g),v=l.openDB(b,g);for(let{key:P,version:k,value:H}of v.getRange({start:null,transaction:h,versions:v.useVersions}))f=L.put(P,H,k),S++%X2===0&&(await new Promise(j=>setTimeout(j,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:b,value:g}of l.getRange({transaction:h,start:!1}))if(s.some(L=>b.startsWith?.(L+"/"))){E.put(b,g);let[,L]=b.split("/"),v=!L,P=new pC(!v,v);await p(b,P)}e.include_audit&&await p(j2,Object.assign({},z2)),await f;let T=mC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=K2(o.path);return o.transaction(()=>{let _=Buffer.alloc(zp);Y2(c,_,0,zp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=mC(null,{fd:c,start:zp}),f=new V2.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(Z2,"getBackup")});var OC=R((r_e,AC)=>{"use strict";var eJ=Y(),{handleHDBError:tJ}=ne(),rJ=Zb(),nJ=w_(),sJ=pp(),iJ=UI(),oJ=Kc(),aJ=bp(),cJ=iw(),uJ=Ew(),lJ=Jc(),_J=Aw(),dJ=Uw(),fJ=Fw(),EJ=kw(),hJ=Kw(),mJ=Zw(),pJ=Up(),SJ=nC(),TJ=uC(),gJ=_C(),RC=hC(),RJ=TC(),Jp=class extends rJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return _J(t)}async getDataByHash(t){return await aJ(t)}async searchByHash(t){return await cJ(t)}async getDataByValue(t,r){return await uJ(t,r)}async searchByValue(t){return await lJ(t)}async createSchema(t){return await iJ(t)}async dropSchema(t){return await dJ(t)}async createTable(t,r){return await fJ(t,r)}async dropTable(t){return await pJ(t)}async createAttribute(t){return await nJ(t)}async createRecords(t){return await sJ(t)}async updateRecords(t){return await EJ(t)}async upsertRecords(t){try{return await hJ(t)}catch(r){throw tJ(r,null,null,eJ.ERR,r)}}async deleteRecords(t){return await oJ(t)}async dropAttribute(t){return await SJ(t)}async deleteAuditLogsBefore(t){return await mJ(t)}async readAuditLog(t){return await TJ(t)}writeTransaction(t,r,n){return gJ.writeTransaction(t,r,n)}flush(t,r){return RC.flush(t,r)}resetReadTxn(t,r){return RC.resetReadTxn(t,r)}getBackup(t){return RJ(t)}};AC.exports=Jp});function NJ(){yJ=setInterval(function(){for(let e of jp)if(e.stale){let t=e[ye]?.url;NC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},bJ).unref()}var Xp,yC,NC,AJ,jp,OJ,tu,bC,eo,id,bJ,yJ,Zp=ge(()=>{Xp=B(Mr()),yC=B(ne()),NC=B(Y());In();AJ=100,jp=new Set,OJ=25e3,eo=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),jp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(jp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(tu&&performance.now()-bC>OJ)throw new yC.ServerError("Outstanding write transactions have too long of queue, please try again later",503)}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,Xp.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let S=this.writes[h];if(!S)continue;let p=S[f===0?"before":"beforeIntermediate"];if(p){let T=p();E?E.push?E.push(T):E=[E,T]:E=T}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<AJ>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return tu||(tu=s,bC=performance.now(),tu.then(()=>{tu=null})),s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},id=class extends eo{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Xp.getNextMonotonicTime)())}getReadTxn(){}},bJ=3e4;a(NJ,"startMonitoringTxns");NJ()});function ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new eo;e.timestamp&&(n.timestamp=e.timestamp),n[ye]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var IC,to=ge(()=>{IC=require("../../index");In();Zp();a(ze,"transaction");(0,IC._assignPackageExport)("transaction",ze);ze.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};ze.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var BC={};Fe(BC,{ResourceBridge:()=>rS});function nS({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 CC(e,t){let r=ts(e),n=nS(e,r);if(!r)throw new Mn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&ad(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 ts(e){let t=e.database||e.schema||wJ,r=dr()[t];if(!r)throw(0,Mn.handleHDBError)(new Error,IJ.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function DC(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*LC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var MC,od,Mn,UC,PC,Un,eS,tS,vC,IJ,wJ,CJ,DJ,wC,rS,HC=ge(()=>{"use strict";MC=B(OC()),od=B(ta()),Mn=B(ne());Re();UC=B(Hc()),PC=B(Gc()),Un=B(U()),eS=B(Os()),tS=B(Ln()),vC=B(Q());to();cd();({HDB_ERROR_MSGS:IJ}=Mn.hdb_errors),wJ="data",CJ=1e4,DJ=10,rS=class extends MC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),wC=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,od.default)(t,"conditions");if(r)throw(0,Mn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=ts(t);if(!n)throw new Mn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:nS(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Mn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ut({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await ts(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=ts(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){ts(t).dropTable()}createSchema(t){return ru({database:t.schema,table:null}),eS.signalSchemaChange(new tS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await sS(t.schema),eS.signalSchemaChange(new tS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,wC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,UC.default)(t);(0,PC.default)(t,n,r.primaryKey);let s,i=dr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=ad(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=dr()[t.schema][t.table],n={user:t.hdb_user};return ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return DC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=dr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Mn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,vC.async_set_timeout)(DJ),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%CJ===0&&await _();return u.length>0&&await _(),s?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,od.default)(t,"hashes");if(r)throw r;return CC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of CC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,od.default)(t,"value");if(n)throw n;let s=ts(t);if(!s)throw new Mn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Un.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:nS(t,s)})}async getDataByValue(t,r){let n=new Map,s=ts(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){ts({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return ts(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=ts(t),n={};switch(t.search_type){case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of LC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return LC(r,t.search_values?.[0],t.search_values?.[1])}}};a(nS,"getSelect");a(CC,"getRecords");a(ts,"getTable");a(DC,"createDeleteResponse");a(LC,"groupRecordsInHistory")});var Dn=R((p_e,xC)=>{"use strict";var{ResourceBridge:LJ}=(HC(),ie(BC)),MJ=re();MJ.initSync();var ud;function UJ(){return ud||(ud=new LJ,ud)}a(UJ,"getBridge");xC.exports=UJ()});var kC=R((T_e,qC)=>{"use strict";var GC=require("lodash"),nu=require("mathjs"),PJ=require("jsonata"),FC=Q();qC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?GC.uniqWith(e,GC.isEqual):e,searchJSON:vJ,mad:su.bind(null,nu.mad),mean:su.bind(null,nu.mean),mode:su.bind(null,nu.mode),prod:su.bind(null,nu.prod),median:su.bind(null,nu.median)};function su(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(su,"aggregateFunction");function vJ(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(FC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),FC.isEmpty(this.__ala__.res[r])){let n=PJ(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(vJ,"searchJSON")});var $C=R((R_e,VC)=>{"use strict";var pt=require("moment"),iS="YYYY-MM-DDTHH:mm:ss.SSSZZ";pt.suppressDeprecationWarnings=!0;VC.exports={current_date:()=>pt().utc().format("YYYY-MM-DD"),current_time:()=>pt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return pt(e).utc().format("YYYY");case"month":return pt(e).utc().format("MM");case"day":return pt(e).utc().format("DD");case"hour":return pt(e).utc().format("HH");case"minute":return pt(e).utc().format("mm");case"second":return pt(e).utc().format("ss");case"millisecond":return pt(e).utc().format("SSS");default:break}},date:e=>pt(e).utc().format(iS),date_format:(e,t)=>pt(e).utc().format(t),date_add:(e,t,r)=>pt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>pt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=pt(e).utc(),s=pt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>pt().utc().valueOf(),get_server_time:()=>pt().format(iS),offset_utc:(e,t)=>pt(e).utc().utcOffset(t).format(iS)}});var QC=R((A_e,WC)=>{"use strict";var BJ=require("@turf/area"),HJ=require("@turf/length"),xJ=require("@turf/circle"),GJ=require("@turf/difference"),FJ=require("@turf/distance"),qJ=require("@turf/boolean-contains"),kJ=require("@turf/boolean-equal"),VJ=require("@turf/boolean-disjoint"),$J=require("@turf/helpers"),YC=U(),Se=Q(),Ns=Y();WC.exports={geoArea:YJ,geoLength:KJ,geoCircle:WJ,geoDifference:QJ,geoDistance:KC,geoNear:zJ,geoContains:JJ,geoEqual:jJ,geoCrosses:XJ,geoConvert:ZJ};function YJ(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return BJ.default(e)}catch(t){return Ns.trace(t,e),NaN}}a(YJ,"geoArea");function KJ(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return HJ.default(e,{units:t||"kilometers"})}catch(r){return Ns.trace(r,e),NaN}}a(KJ,"geoLength");function WJ(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return xJ.default(e,t,{units:r||"kilometers"})}catch(n){return Ns.trace(n,e,t),NaN}}a(WJ,"geoCircle");function QJ(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return GJ(e,t)}catch(r){return Ns.trace(r,e,t),NaN}}a(QJ,"geoDifference");function KC(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return FJ.default(e,t,{units:r||"kilometers"})}catch(n){return Ns.trace(n,e,t),NaN}}a(KC,"geoDistance");function zJ(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return KC(e,t,n)<=r}catch(s){return Ns.trace(s,e,t),!1}}a(zJ,"geoNear");function JJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return qJ.default(e,t)}catch(r){return Ns.trace(r,e,t),!1}}a(JJ,"geoContains");function jJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return kJ.default(e,t)}catch(r){return Ns.trace(r,e,t),!1}}a(jJ,"geoEqual");function XJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!VJ.default(e,t)}catch(r){return Ns.trace(r,e,t),!1}}a(XJ,"geoCrosses");function ZJ(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(YC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(YC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),$J[t](e,r)}a(ZJ,"geoConvert")});var ld=R((b_e,zC)=>{var ro=kC(),qr=$C(),rs=QC();zC.exports=e=>{e.aggr.mad=e.aggr.MAD=ro.mad,e.aggr.mean=e.aggr.MEAN=ro.mean,e.aggr.mode=e.aggr.MODE=ro.mode,e.aggr.prod=e.aggr.PROD=ro.prod,e.aggr.median=e.aggr.MEDIAN=ro.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ro.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ro.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=qr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=qr.current_time,e.fn.extract=e.fn.EXTRACT=qr.extract,e.fn.date=e.fn.DATE=qr.date,e.fn.date_format=e.fn.DATE_FORMAT=qr.date_format,e.fn.date_add=e.fn.DATE_ADD=qr.date_add,e.fn.date_sub=e.fn.DATE_SUB=qr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=qr.date_diff,e.fn.now=e.fn.NOW=qr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=qr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=qr.get_server_time,e.fn.getdate=e.fn.GETDATE=qr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=qr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=rs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=rs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=rs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=rs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=rs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=rs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=rs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=rs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=rs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=rs.geoNear}});var ZC=R((y_e,XC)=>{"use strict";var iu=require("lodash"),fr=require("alasql");fr.options.cache=!1;var e4=ld(),JC=require("clone"),_d=require("recursive-iterator"),le=Y(),De=Q(),sa=Dn(),t4=U(),{hdb_errors:r4}=ne(),{getDatabases:jC}=(Re(),ie(qe)),n4="IS NULL",Pn="There was a problem performing this search. Please check the logs and try again.";e4(fr);var oS=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.isEmpty(t))throw le.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.isEmptyOrZeroLength(n))return le.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(n),new Error(Pn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(n),new Error(Pn)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(n),new Error(Pn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(n),new Error(Pn)}try{return t=await this._finalSQL(),t}catch(n){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(n),new Error(Pn)}}_getColumns(){let t=new _d(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(JC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=iu.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=jC()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new _d(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new fr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new fr.yy.LogicValue({value:i}):n instanceof fr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new fr.yy.NumValue({value:i}))});if(t){le.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new _d(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!De.isEmpty(t4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.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(De.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"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&iu.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await fr.promise(r)}catch(r){throw le.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),le.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(JC(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(De.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(n4)>-1&&this.tables.forEach(s=>{let i={columnid:jC()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=iu.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await sa.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Pn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await sa.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Pn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.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 sa.getDataByValue(c,E.operation);if(u)for(let[S]of h)this.data[i].__merged_data[S]||(this.data[i].__merged_data[S]=[...n[i]],this._setMergedHashAttribute(i,S));else for(let[S,p]of h)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]):(this.data[i].__merged_data[S]=[...n[i]],this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]),this._setMergedHashAttribute(i,S))}}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(Pn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await sa.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(Pn)}}}_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 fr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new fr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new fr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new fr.yy.FuncValue:new fr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,S=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${S}.${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 "${S}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await fr.promise(h,t),t=null}catch(E){throw le.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),le.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let S=f[E];o.forEach(p=>{S[p.key]!==null&&S[p.key]!==void 0&&p.keys.add(S[p.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),S=iu.difference(h,[...E.keys].map(p=>p.toString()));for(let p=0,T=S.length;p<T;p++){let b=S[p];delete this.data[`${E.schema}_${E.table}`].__merged_data[b]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new _d(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=iu.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(Pn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await sa.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let S=s.columns[h],p=E[S]===void 0?null:E[S];this.data[n].__merged_data[f].push(p)}}}}catch(r){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getData."),le.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();le.trace(`Final SQL: ${s}`),n=await fr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),le.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return le.error(r4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),le.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await sa.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(Pn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};XC.exports=oS});var Br=R((I_e,eD)=>{"use strict";var s4=jb();eD.exports={searchByConditions:o4,searchByHash:a4,searchByValue:c4,search:u4};var aS=Dn(),{transformReq:cS}=Q(),i4=ZC();async function o4(e){return cS(e),aS.searchByConditions(e)}a(o4,"searchByConditions");async function a4(e){cS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of aS.searchByHash(e))r&&t.push(r);return t}a(a4,"searchByHash");async function c4(e){cS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of aS.searchByValue(e))t.push(r);return t}a(c4,"searchByValue");function u4(e,t){try{let r=new s4(e);r.validate(),new i4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(u4,"search")});var dd=R((C_e,tD)=>{"use strict";var l4=Dn();tD.exports={writeTransaction:_4};function _4(e,t,r){return l4.writeTransaction(e,t,r)}a(_4,"writeTransaction")});var iD=R((M_e,sD)=>{"use strict";var d4=Br(),f4=As(),rD=Y(),E4=an(),L_e=dd(),h4=require("clone"),lS=require("alasql"),m4=ld(),nD=require("util"),p4=nD.promisify(f4.getTableSchema),S4=nD.promisify(d4.search),T4=U(),uS=Q();m4(lS);sD.exports={update:R4};var g4="There was a problem performing this update. Please check the logs and try again.";async function R4({statement:e,hdb_user:t}){let r=await p4(e.table.databaseid,e.table.tableid),n=A4(e.columns);uS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=h4(s),c=uS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=lS.parse(u).statements[0],l=await S4(_),d=O4(n,l);return b4(o,d,t)}a(R4,"update");function A4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=lS.compile(`SELECT ${r.expression.toString()} AS [${T4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw rD.error(t),new Error(g4)}}a(A4,"createUpdateRecord");function O4(e,t){return uS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(O4,"buildUpdateRecords");async function b4(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await E4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){rD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(b4,"updateRecords")});var aD=R((B_e,oD)=>{var y4=require("alasql"),N4=Br(),I4=Y(),w4=Dn(),dS=require("util"),_S=Q(),C4=U(),D4=As(),P_e=dd(),v_e=an(),L4="record",M4="successfully deleted",U4=dS.callbackify(H4),P4=dS.promisify(N4.search),v4=dS.promisify(D4.getTableSchema);oD.exports={convertDelete:U4};function B4(e){return`${e.deleted_hashes.length} ${L4}${e.deleted_hashes.length===1?"":"s"} ${M4}`}a(B4,"generateReturnMessage");async function H4({statement:e,hdb_user:t}){let r=await v4(e.table.databaseid,e.table.tableid);_S.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=_S.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=y4.parse(o).statements[0],u={operation:C4.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await P4(c);let _=await w4.deleteRecords(u);return _S.isEmptyOrZeroLength(_.message)&&(_.message=B4(_)),delete _.txn_time,_}catch(_){throw I4.error(_),_.hdb_code?_.message:_}}a(H4,"convertDelete")});var dD=R((x_e,_D)=>{"use strict";var x4=ri(),{hdb_errors:cD}=ne(),{getDatabases:uD}=(Re(),ie(qe));_D.exports={checkSchemaExists:lD,checkSchemaTableExists:G4,schema_describe:x4};async function lD(e){if(!uD()[e])return cD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(lD,"checkSchemaExists");async function G4(e,t){let r=await lD(e);if(r)return r;if(!uD()[e][t])return cD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(G4,"checkSchemaTableExists")});var ou=R((F_e,F4)=>{F4.exports={name:"harperdb",version:"4.3.2",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},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/client-s3":"3.535.0","@aws-sdk/lib-storage":"3.535.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@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.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","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.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.3",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","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.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.3","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.16.0",yaml:"2.4.1"},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.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",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.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",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.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var _u={};Fe(_u,{addAnalyticsListener:()=>lu,recordAction:()=>kr,recordActionBinary:()=>cn,setAnalyticsEnabled:()=>q4});function q4(e){RD=e}function kr(e,t,r,n,s){if(!RD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=hd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},hd.set(i,o)}fd||k4()}function cn(e,t,r,n,s){kr(!!e,t,r,n,s)}function lu(e){bD.push(e)}function k4(){fd=performance.now(),setTimeout(async()=>{let e=performance.now()-fd;fd=0;let t=[],r={time:Date.now(),period:e,threadId:no.threadId,metrics:t};for(let[s,i]of hd){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 yD){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let S=_[_.length-1];typeof S=="number"?_[_.length-1]={value:S,count:1+h}:S.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 ND()}let n=process.memoryUsage();t.push({metric:"memory",threadId:no.threadId,byThread:!0,...n});for(let s of bD)s(t);hd=new Map,no.parentPort?no.parentPort.postMessage({type:OD,report:r}):CD({report:r})},AD).unref()}async function V4(e,t=6e4){let r=hS(),n=ID(),s=new Promise(S=>{let p=performance.now();setImmediate(()=>{let T=performance.now();T-p>5e3&&(0,au.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-p)+"ms"),p=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-p>5e3&&(0,au.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-p)+"ms"),S(T-p)})}),i;for(let S of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(S.value?.time){i=S.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:S,value:p}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(o){if(S>o+t)break}else o=S;l=S;let{metrics:T,threadId:b}=p;for(let g of T||[]){let{path:L,method:v,type:P,metric:k,count:H,total:j,distribution:z,threads:J,...me}=g;H||(H=1);let ce=k+(L?"-"+L:"");v!==void 0&&(ce+="-"+v),P!==void 0&&(ce+="-"+P);let de=c.get(ce);if(de){if(de.threads){let Be=de.threads[b];if(Be)de=Be;else{de.threads[b]=Object.assign({},me);continue}}de.count||(de.count=1);let Le=de.count;for(let Be in me){let Lt=me[Be];typeof Lt=="number"&&(de[Be]=(de[Be]*Le+Lt*H)/(Le+H))}de.count+=H,j>=0&&(de.total+=j,de.ratio=de.total/de.count)}else de=Object.assign({period:t},g),delete de.distribution,c.set(ce,de),de.byThread&&(de.threads=[],de.threads[b]=Object.assign({},me),_.push(de));if(z){z=z.map(Be=>typeof Be=="number"?{value:Be,count:1}:Be);let Le=u.get(ce);Le?Le.push(...z):u.set(ce,z)}}await ND()}for(let S of _){let{path:p,method:T,type:b,metric:g,count:L,total:v,distribution:P,threads:k,...H}=S;k=k.filter(j=>j);for(let j in H){if(typeof S[j]!="number")continue;let z=0;for(let J of k){let me=J[j];typeof me=="number"&&(z+=me)}S[j]=z}S.count=k.length,delete S.threads,delete S.byThread}for(let[S,p]of u){let T=c.get(S);p.sort((Be,Lt)=>Be.value>Lt.value?1:-1);let b=T.count-1,g=[],L=0,v=0,P;for(let Be of yD){let Lt=b*Be;for(;L<Lt;)P=p[v++],L+=P.count,v===1&&L--;let Vl=p[v>1?v-2:0];P||(P=p[0]),g.push(P.value-(P.value-Vl.value)*(L-Lt)/P.count)}let[k,H,j,z,J,me,ce,de,Le]=g;Object.assign(T,{p1:k,p10:H,p25:j,median:z,p75:J,p90:me,p95:ce,p99:de,p999:Le})}let d;for(let[S,p]of c)p.id=(0,Ed.getNextMonotonicTime)(),p.time=l,n.primaryStore.put(p.id,p,{append:!0}).then(T=>{T||n.primaryStore.put(p.id,p)}),d=!0;let f=Date.now(),{idle:E,active:h}=performance.eventLoopUtilization();if(d||h*10>E){let S=(0,Ed.getNextMonotonicTime)(),p={id:S,metric:"main-thread-utilization",idle:E-fD,active:h-ED,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(S,p,{append:!0}).then(T=>{T||n.primaryStore.put(S,p)})}fD=E,ED=h}async function hD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function hS(){return mD||(mD=ut({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function ID(){return pD||(pD=ut({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function K4(){wD=!0;let e=(0,uu.get)(ES.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await V4(AD,e),await hD(hS(),$4),await hD(ID(),Y4)},Math.min(e/2,2147483647)).unref()}function CD(e,t){let r=e.report;r.threadId=t?.threadId||no.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(SD+=n.mean*n.count);r.totalBytesProcessed=SD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(TD.get(t))}),TD.set(t,t.performance.eventLoopUtilization())),r.id=(0,Ed.getNextMonotonicTime)(),hS().primaryStore.put(r.id,r),wD||K4(),W4&&(DD=z4(r))}async function z4(e){if(await DD,!ci){let r=(0,cu.dirname)((0,au.getLogFilePath)());try{ci=await(0,fS.open)((0,cu.join)(r,"analytics.log"),"r+")}catch{ci=await(0,fS.open)((0,cu.join)(r,"analytics.log"),"w+")}}let t=(await ci.stat()).size;if(t>Q4){let r=Buffer.alloc(t);await ci.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ci.write(r,{position:0}),await ci.truncate(r.length),t=r.length}await ci.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var no,gD,
|
|
6
|
+
`)},Vk="certificate.pem",$k="privateKey.pem",Yk="ca.pem";kO.exports={CERTIFICATE_VALUES:kk,CERTIFICATE_PEM_NAME:Vk,PRIVATEKEY_PEM_NAME:$k,CA_PEM_NAME:Yk}});var et=R((voe,$O)=>{"use strict";var ar=require("validate.js");ar.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||ar.validators.type.checks[t](e)?null:` must be a '${t}' value`};ar.validators.type.checks={Object:function(e){return ar.isObject(e)&&!ar.isArray(e)},Array:ar.isArray,Integer:ar.isInteger,Number:ar.isNumber,String:ar.isString,Date:ar.isDate,Boolean:function(e){return typeof e=="boolean"}};ar.validators.hasValidFileExt=function(e,t){return ar.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};$O.exports={validateObject:Kk,validateObjectAsync:Wk,validateBySchema:Qk};function Kk(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=ar(e,t,{format:"flat"});return r?new Error(r):null}a(Kk,"validateObject");async function Wk(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ar.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(Wk,"validateObjectAsync");function Qk(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(Qk,"validateBySchema")});var Bh=R((xoe,JO)=>{"use strict";var QO=require("fs-extra"),oe=require("joi"),zk=require("os"),{boolean:be,string:zt,number:Je,array:vh}=oe.types(),{totalmem:YO}=require("os"),Pi=require("path"),Jk=Y(),r_=Q(),Hoe=VO(),KO=U(),jk=et(),WO="log",Xk="components",Zk="Invalid logging.rotation.maxSize unit. Available units are G, M or K",eV="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",tV="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",rV="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",nV="rootPath config parameter is undefined",sV="clustering.enabled config parameter is undefined",vi=Je.min(0).required(),n_=vh.items({host:zt.required(),port:vi}).empty(null),Kn,zO=!1;JO.exports={configValidator:iV,routesValidator:_V,route_constraints:n_};function iV(e,t=!1){if(zO=t,Kn=e.rootPath,r_.isEmpty(Kn))throw nV;let r=be.required(),n=Je.min(0).max(1e3).empty(null).default(lV),s=zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(fc),i=zt.optional().empty(null),o=zt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(fc),u=oe.custom(aV).empty(null).default(fc),_=e.clustering?.enabled;if(r_.isEmpty(_))throw sV;let l;return _===!0?l=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:vi,routes:n_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:vi}).required()}).required(),network:oe.object({port:vi}).required()}).required(),leafServer:oe.object({network:oe.object({port:vi,routes:n_}).required(),streams:oe.object({maxAge:Je.min(120).allow(null).optional(),maxBytes:Je.min(1).allow(null).optional(),maxMsgs:Je.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:zt.optional().empty(null)}).required():l=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:Je.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:Je}),componentsRoot:s.optional(),clustering:l,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:be,logSuccessful:be}),file:be.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:be.optional(),compress:be.optional(),interval:zt.custom(uV).optional().empty(null),maxSize:zt.custom(cV).optional().empty(null),path:zt.optional().empty(null).default(fc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:vh.optional(),headersTimeout:Je.min(1).optional(),keepAliveTimeout:Je.min(1).optional(),port:Je.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(fc),securePort:Je.optional().empty(null),timeout:Je.min(1).optional()}).optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:vi,securePort:vi,mtls:oe.alternatives([be.optional(),oe.object({user:zt.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:Je.optional(),cors:be.optional(),corsAccessList:vh.optional(),headersTimeout:Je.min(1).optional(),port:Je.min(0).optional().empty(null),securePort:Je.min(0).optional().empty(null),maxHeaderSize:Je.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:zt.optional(),certificateAuthority:i,required:be.optional()})])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:Je.min(1).optional(),host:zt.optional(),waitForDebugger:be.optional()})),maxHeapMemory:Je.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:zt.optional(),threshold:Je.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:u,prefetchWrites:be.optional(),maxFreeSpaceToLoad:Je.optional(),maxFreeSpaceToRetain:Je.optional()}).required(),ignoreScripts:be.optional(),tls:oe.object({certificate:i.optional(),certificateAuthority:i.optional(),privateKey:i.optional(),ciphers:zt.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(iV,"configValidator");function oV(e){return zO||QO.existsSync(e)?null:`Specified path ${e} does not exist.`}a(oV,"doesPathExist");function aV(e,t){oe.assert(e,zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=oV(e);if(r)return t.message(r)}a(aV,"validatePath");function cV(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Zk);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(tV):e}a(cV,"validateRotationMaxSize");function uV(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(eV);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(rV):e}a(uV,"validateRotationInterval");function lV(e,t){let r=t.state.path.join("."),n=zk.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||YO();return i=Math.round(Math.min(i,YO())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Jk.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(lV,"setDefaultThreads");function fc(e,t){let r=t.state.path.join(".");if(!r_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(r_.isEmpty(Kn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Pi.join(Kn,Xk);case"logging.root":return Pi.join(Kn,WO);case"clustering.leafServer.streams.path":return Pi.join(Kn,"clustering","leaf");case"storage.path":let n=Pi.join(Kn,KO.LEGACY_DATABASES_DIR_NAME);return QO.existsSync(n)?n:Pi.join(Kn,KO.DATABASES_DIR_NAME);case"logging.rotation.path":return Pi.join(Kn,WO);case"operationsApi.network.domainSocket":return r==null?null:Pi.join(Kn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(fc,"setDefaultRoot");function _V(e){let t=oe.object({routes:n_});return jk.validateBySchema({routes:e},t)}a(_V,"routesValidator")});var Bi={};Fe(Bi,{server:()=>tt});var jO,tt,cr=ge(()=>{jO=require("../../index"),tt={};(0,jO._assignPackageExport)("server",tt)});var lr=R((qoe,ob)=>{"use strict";var Ur=U(),Mt=Q(),bt=Y(),{configValidator:dV,routesValidator:XO}=Bh(),ur=require("fs-extra"),fV=require("yaml"),bn=require("path"),EV=require("is-number"),eb=require("properties-reader"),hV=require("lodash"),{handleHDBError:mV}=ne(),{HTTP_STATUS_CODES:pV,HDB_ERROR_MSGS:s_}=Lr(),Foe=require("minimist"),{server:SV}=(cr(),ie(Bi)),{DATABASES_PARAM_CONFIG:Ec,CONFIG_PARAMS:Mr,CONFIG_PARAM_MAP:yn}=Ur,TV="Unable to get config value because config is uninitialized",gV="Config successfully initialized",RV="Error backing up config file",AV="Empty parameter sent to getConfigValue",tb=bn.join(Ur.PACKAGE_ROOT,"config","yaml",Ur.HDB_DEFAULT_CONFIG_FILE),OV="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",ZO={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_,yt,o_;ob.exports={createConfigFile:bV,getDefaultConfig:yV,getConfigValue:nb,initConfig:xh,flattenConfig:qo,updateConfigValue:sb,updateConfigObject:IV,getConfiguration:DV,setConfiguration:LV,readConfigFile:Fh,getClusteringRoutes:MV,initOldConfig:ib,getConfigFromFile:UV,getConfigFilePath:Hi,addConfig:PV,deleteConfigFromFile:vV,getConfigObj:BV};function bV(e,t=!1){let r=js(tb);i_=qo(r.toJSON());let n;for(let c in e){let u=yn[c.toLowerCase()];if(u===Mr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=Hh(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){bt.error(d)}}}n&&rb(r,n),Gh(r,t);let s=r.toJSON();yt=qo(s);let i=r.getIn(["rootPath"]),o=bn.join(i,Ur.HDB_CONFIG_FILE);ur.createFileSync(o),ur.writeFileSync(o,String(r)),bt.trace(`Config file written to ${o}`)}a(bV,"createConfigFile");function rb(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Mt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Ec.TABLES))for(let i in n[s][Ec.TABLES])for(let o in n[s][Ec.TABLES][i]){let c=n[s][Ec.TABLES][i][o],u=[Mr.DATABASES,s,Ec.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Mr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){bt.error("Error parsing schemas CLI/env config arguments",n)}}a(rb,"setSchemasConfig");function yV(e){if(i_===void 0){let r=js(tb);i_=qo(r.toJSON())}let t=yn[e.toLowerCase()];if(t!==void 0)return i_[t.toLowerCase()]}a(yV,"getDefaultConfig");function nb(e){if(e==null){bt.error(AV);return}if(yt===void 0){bt.trace(TV);return}let t=yn[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(nb,"getConfigValue");function Hi(e=Mt.getPropsFilePath()){let t=Mt.getEnvCliRootPath();return t?bn.join(t,Ur.HDB_CONFIG_FILE):eb(e).get(Ur.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Hi,"getConfigFilePath");function xh(e=!1){if(yt===void 0||e){let t;if(!Mt.noBootFile()){t=Mt.getPropsFilePath();try{ur.accessSync(t,ur.constants.F_OK|ur.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Hi(t),n;if(r.includes("config/settings.js"))try{ib(r);return}catch(i){if(i.code!==Ur.NODE_ERROR_CODES.ENOENT)throw i}try{n=js(r)}catch(i){if(i.code===Ur.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}NV(n,r),Gh(n);let s=n.toJSON();if(SV.config=s,yt=qo(s),yt.logging_rotation_rotate)for(let i in ZO)yt[i]&&bt.error(`Config ${ZO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(gV)}}a(xh,"initConfig");function NV(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],bn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],bn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],bn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(bt.trace("Updating config file with missing config params"),ur.writeFileSync(t,String(e)))}a(NV,"checkForUpdatedConfig");function Gh(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=dV(r,t);if(n.error)throw s_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(Gh,"validateConfig");function IV(e,t){yt===void 0&&(yt={});let r=yn[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(IV,"updateConfigObject");function sb(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&xh();let o=nb(yn.hdb_root),c=bn.join(o,Ur.HDB_CONFIG_FILE),u=js(c),_;if(r===void 0&&e.toLowerCase()===Mr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=yn[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Hh(f,t);u.setIn([...E],h)}else for(let f in r){let E=yn[f.toLowerCase()];if(E===Mr.HTTP_SECUREPORT&&r[f]===yt[Mr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Mr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===yt[Mr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Mr.DATABASES){_=r[f];continue}if(E?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!E&&(f.endsWith("_package")||f.endsWith("_port"))&&(E=f),E!==void 0){let h=E.split("_"),S=Ur.LEGACY_CONFIG_PARAMS[f.toUpperCase()];S&&S.startsWith("customFunctions")&&u.hasIn(S.split("_"))&&(E=S,h=S.split("_"));let p=Hh(E,r[f]);E==="rootPath"&&p?.endsWith("/")&&(p=p.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],p)}catch(T){bt.error(T)}}}_&&rb(u,_),Gh(u);let l=u.getIn(["rootPath"]),d=bn.join(l,Ur.HDB_CONFIG_FILE);n===!0&&wV(c,l),ur.writeFileSync(d,String(u)),s&&(yt=qo(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(sb,"updateConfigValue");function wV(e,t){try{let r=bn.join(t,"backup",`${Ur.HDB_CONFIG_FILE}.bak`);ur.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(RV),bt.error(r)}}a(wV,"backupConfigFile");var CV=["databases"];function qo(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)),o_=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!CV.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Mr[u.toUpperCase()]&&yn[u]&&(s[yn[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(qo,"flattenConfig");function Hh(e,t){if(e===Mr.CLUSTERING_NODENAME||e===Mr.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(EV(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Mt.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 Mt.autoCast(t)}a(Hh,"castConfigValue");function DV(){let e=Mt.getPropsFilePath(),t=Hi(e);return js(t).toJSON()}a(DV,"getConfiguration");async function LV(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return sb(void 0,void 0,s,!0),OV}catch(i){throw typeof i=="string"||i instanceof String?mV(i,i,pV.BAD_REQUEST,void 0,void 0,!0):i}}a(LV,"setConfiguration");function Fh(){let e=Mt.getPropsFilePath();try{ur.accessSync(e,ur.constants.F_OK|ur.constants.R_OK)}catch(n){if(!Mt.noBootFile())throw bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Hi(e);return js(t).toJSON()}a(Fh,"readConfigFile");function js(e){return fV.parseDocument(ur.readFileSync(e,"utf8"),{simpleKeys:!0})}a(js,"parseYamlDoc");function MV(){let e=Fh(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Mt.isEmptyOrZeroLength(t)?[]:t;let r=XO(t);if(r)throw s_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Mt.isEmptyOrZeroLength(n)?[]:n;let s=XO(n);if(s)throw s_.CONFIG_VALIDATION(s.message);if(!Mt.isEmptyOrZeroLength(n)&&!Mt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Mt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw s_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(MV,"getClusteringRoutes");function ib(e){let t=eb(e);yt={};for(let r in yn){let n=t.get(r.toUpperCase());if(Mt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=yn[r].toLowerCase();s===Mr.LOGGING_ROOT?yt[s]=bn.dirname(n):yt[s]=n}return yt}a(ib,"initOldConfig");function UV(e){let t=Fh();return hV.get(t,e.replaceAll("_","."))}a(UV,"getConfigFromFile");async function PV(e,t){let r=js(Hi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ur.writeFile(Hi(),String(r))}a(PV,"addConfig");function vV(e){let t=Hi(Mt.getPropsFilePath()),r=js(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=bn.join(n,Ur.HDB_CONFIG_FILE);ur.writeFileSync(s,String(r))}a(vV,"deleteConfigFromFile");function BV(){return o_||(xh(),o_)}a(BV,"getConfigObj")});var re=R((Voe,_b)=>{"use strict";var qh=require("fs-extra"),xi=require("path"),ab=require("os"),HV=require("properties-reader"),mc=Y(),hc=Q(),ue=U(),a_=lr(),xV="Error initializing environment manager",c_="BOOT_PROPS_FILE_PATH",cb=!1,GV={[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},Ss={};_b.exports={BOOT_PROPS_FILE_PATH:c_,getHdbBasePath:FV,setHdbBasePath:qV,get:ub,initSync:VV,setProperty:Me,initTestEnvironment:YV,setCloneVar:$V};function FV(){return Ss[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(FV,"getHdbBasePath");function qV(e){Ss[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(qV,"setHdbBasePath");function ub(e){let t=a_.getConfigValue(e);return t===void 0?Ss[e]:t}a(ub,"get");function Me(e,t){GV[e]&&(Ss[e]=t),a_.updateConfigObject(e,t)}a(Me,"setProperty");function kV(){let e;try{e=hc.getPropsFilePath(),qh.accessSync(e,qh.constants.F_OK|qh.constants.R_OK),cb=!0;let t=HV(e);return Ss[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Ss[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ss[c_]=e,!0}catch{return mc.trace(`Environment manager found no properties file at ${e}`),!1}}a(kV,"doesPropFileExist");function VV(e=!1){try{(cb||kV()||hc.noBootFile())&&!lb&&(a_.initConfig(e),Ss[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=a_.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){mc.error(xV),mc.error(t),console.error(t),process.exit(1)}}a(VV,"initSync");var lb=!1;function $V(e){lb=e}a($V,"setCloneVar");function YV(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=xi.join(__dirname,"../../","unitTests");Ss[c_]=xi.join(u,"hdb_boot_properties.file"),Me(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xi.join(u,"settings.test")),Me(ue.HDB_SETTINGS_NAMES.INSTALL_USER,ab.userInfo()?ab.userInfo().username:void 0),Me(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xi.join(u,"envDir","log")),Me(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xi.join(u,"envDir")),Me(ue.CONFIG_PARAMS.STORAGE_PATH,xi.join(u,"envDir")),s&&(Me(ue.CONFIG_PARAMS.HTTP_SECUREPORT,ub(ue.CONFIG_PARAMS.HTTP_PORT)),Me(ue.CONFIG_PARAMS.HTTP_PORT,null)),Me(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,hc.isEmpty(i)?!1:i),Me(ue.CONFIG_PARAMS.HTTP_CORS,hc.isEmpty(i)?!1:i),Me(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xi.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,hc.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${c_}. Please check your boot props and settings files`;mc.fatal(r),mc.error(t)}}a(YV,"initTestEnvironment")});var Qe=R((Yoe,Sb)=>{"use strict";var Rc=U(),KV=Q(),_r=re(),Ac=require("path"),WV=require("minimist"),db=require("fs-extra"),fb=require("lodash");_r.initSync();var{CONFIG_PARAMS:Xs,DATABASES_PARAM_CONFIG:pc,SYSTEM_SCHEMA_NAME:u_}=Rc,Sc,Tc,gc;function Eb(){if(Sc!==void 0)return Sc;if(_r.getHdbBasePath()!==void 0)return Sc=_r.get(Xs.STORAGE_PATH)||Ac.join(_r.getHdbBasePath(),Rc.DATABASES_DIR_NAME),Sc}a(Eb,"getBaseSchemaPath");function hb(){if(Tc!==void 0)return Tc;if(_r.getHdbBasePath()!==void 0)return Tc=pb(u_),Tc}a(hb,"getSystemSchemaPath");function mb(){if(gc!==void 0)return gc;if(_r.getHdbBasePath()!==void 0)return gc=_r.get(Rc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Ac.join(_r.getHdbBasePath(),Rc.TRANSACTIONS_DIR_NAME),gc}a(mb,"getTransactionAuditStoreBasePath");function QV(e,t){let r=_r.get(Xs.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Ac.join(mb(),e.toString())}a(QV,"getTransactionAuditStorePath");function pb(e,t){e=e.toString(),t=t&&t.toString();let r=_r.get(Rc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Ac.join(Eb(),e)}a(pb,"getSchemaPath");function zV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,WV(process.argv));let n=r[Xs.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!KV.isObject(n))throw o;i=n}for(let o of i){let c=o[u_];if(!c)continue;let u=_r.get(Xs.DATABASES);u=u??{};let _=c?.tables?.[t]?.[pc.PATH];if(_)return fb.set(u,[u_,pc.TABLES,t,pc.PATH],_),_r.setProperty(Xs.DATABASES,u),_;let l=c?.[pc.PATH];if(l)return fb.set(u,[u_,pc.PATH],l),_r.setProperty(Xs.DATABASES,u),l}}let s=r[Xs.STORAGE_PATH.toUpperCase()];if(s){if(!db.pathExistsSync(s))throw new Error(s+" does not exist");let i=Ac.join(s,e);return db.mkdirsSync(i),_r.setProperty(Xs.STORAGE_PATH,s),i}return hb()}a(zV,"initSystemSchemaPaths");function JV(){Sc=void 0,Tc=void 0,gc=void 0}a(JV,"resetPaths");Sb.exports={getBaseSchemaPath:Eb,getSystemSchemaPath:hb,getTransactionAuditStorePath:QV,getTransactionAuditStoreBasePath:mb,getSchemaPath:pb,initSystemSchemaPaths:zV,resetPaths:JV}});var Pr=R((zoe,Ob)=>{"use strict";var jV=Lr().LMDB_ERRORS_ENUM,Woe=require("lmdb"),XV=ct(),Qoe=require("buffer").Buffer,{OVERFLOW_MARKER:Tb,MAX_SEARCH_KEY_LENGTH:l_}=XV,gb=["number","string","symbol","boolean","bigint"];function ZV(e){if(e=e?.primaryStore||e,!e)throw new Error(jV.ENV_REQUIRED)}a(ZV,"validateEnv");function e$(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(e$,"stringifyData");function t$(e){return e instanceof Date?e.valueOf():e}a(t$,"convertKeyValueToWrite");function r$(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(gb.includes(typeof e))return e.length>l_?[e.slice(0,l_)+Tb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(gb.includes(typeof i))i.length>l_?r.push(i.slice(0,l_)+Tb):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(r$,"getIndexedValues");var __=0,Rb=0;function Ab(){Rb=Date.now()-performance.now()}a(Ab,"adjustStartTime");Ab();var n$=6e4;setInterval(Ab,n$).unref();function s$(){let e=performance.now()+Rb;return e>__?(__=e,e):(__+=488e-6,__)}a(s$,"getNextMonotonicTime");Ob.exports={validateEnv:ZV,stringifyData:e$,convertKeyValueToWrite:t$,getNextMonotonicTime:s$,getIndexedValues:r$}});var bb,Nn,kh,Oc=ge(()=>{bb=require("events"),Nn=class extends bb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new kh;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)}},kh=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 Yh={};Fe(Yh,{loadGQLSchema:()=>a$,start:()=>$h,startOnMainThread:()=>o$});function $h({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let p of d.definitions)switch(p.kind){case u.OBJECT_TYPE_DEFINITION:let v=function(P){if(P.kind==="NonNullType"){let j=v(P.type);return j.nullable=!1,j}if(P.kind==="ListType")return{type:"array",elements:v(P.type)};let H={type:P.name?.value};return Object.defineProperty(H,"location",{value:P.loc.startToken}),H};a(v,"getProperty");let T=p.name.value,b=[],g={table:null,database:null,properties:b};f.set(T,g);for(let P of p.directives){if(P.name.value==="table"){for(let k of P.arguments)g[k.name.value]=k.value.value;g.schema&&(g.database=g.schema),g.table||(g.table=T),g.audit&&(g.audit=g.audit!=="false"),g.attributes=g.properties,E.push(g)}if(P.name.value==="sealed"&&(g.sealed=!0),P.name.value==="export"){g.export=!0;for(let k of P.arguments)k.name.value==="name"&&(g.export={name:k.value.value})}}let L=!1;for(let P of p.fields){let k=v(P.type);k.name=P.name.value,b.push(k);for(let H of P.directives)if(H.name.value==="primaryKey")L?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,L=!0);else if(H.name.value==="indexed")k.indexed=!0;else if(H.name.value==="relationship"){let j={};for(let z of H.arguments)j[z.name.value]=z.value.value;k.relationship=j}else if(H.name.value==="createdTime")k.assignCreatedTime=!0;else if(H.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(H.name.value==="expiresAt")k.expiresAt=!0;else if(H.name.value==="allow"){let j=k.authorizedRoles=[];for(let z of H.arguments)z.name.value==="role"&&j.push(z.value.value)}}g.type=T,T==="Query"&&(h=g)}function S(p){let T=f.get(p.type);T?(Object.defineProperty(p,"properties",{value:T.properties}),Object.defineProperty(p,"definition",{value:T})):p.type==="array"?S(p.elements):i$.includes(p.type)||(0,yb.getWorkerIndex)()===0&&console.error(`The type ${p.type} is unknown at line ${p.location.line}, column ${p.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let p of f.values())for(let T of p.properties)S(T);for(let p of E)p.tableClass=e(p),p.export&&(p.export.name===""?i.set((0,Vh.dirname)(n),p.tableClass):i.set((0,Vh.dirname)(n)+"/"+(p.export.name||p.type),p.tableClass))}}var Vh,yb,i$,o$,a$,Nb=ge(()=>{Vh=require("path");Re();yb=B(rt()),i$=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a($h,"start");o$=$h,a$=$h({ensureTable:ut}).handleFile});async function d_(e){return c$?(bc||(bc=u$(_$)),(await(await bc).import(e)).namespace):import(e)}async function u$(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),bc=new Compartment({console,Math,Date,fetch:l$,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,wb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:qt,tables:vr,databases:nt})}};let n=await(0,Ib.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),bc}function l$(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 _$(){return{Resource:qt,tables:vr}}var Ib,wb,c$,bc,Kh=ge(()=>{In();Re();Ib=require("fs/promises"),wb=require("path"),c$=!1;a(d_,"secureImport");a(u$,"getCompartment");a(l$,"secureOnlyFetch");a(_$,"getGlobalVars")});var Qh={};Fe(Qh,{handleFile:()=>d$});async function d$(e,t,r,n){let s=new Map,i=(0,Cb.pathToFileURL)(r).toString(),o=await d_(i);u(o.default)&&n.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)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var Cb,Wh,Db=ge(()=>{Cb=require("url");Kh();Wh=require("path");a(d$,"handleFile")});var Jh={};Fe(Jh,{start:()=>f$});function f$({resources:e}){e.set("login",zh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var zh,Lb=ge(()=>{In();a(f$,"start");zh=class extends qt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var xb={};Fe(xb,{parse:()=>Xh,streamAsJSON:()=>yc,stringify:()=>Gi});function yc(e){return new jh({value:e})}function Mb(e){return console.error(e),JSON.stringify(e.toString())}function Ub(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Gi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Bb)return Hb(e);if(t.resolution)return t.resolution.then(()=>Gi(e));throw t}}function Hb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=Hb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Gi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Xh(e){return m$.test(e)?E$.parse(e):JSON.parse(e)}var Pb,vb,E$,h$,Bb,jh,m$,Zh=ge(()=>{Pb=require("stream"),vb=B(require("json-bigint-fixes")),E$=(0,vb.default)({useNativeBigInt:!0}),h$=1e4,Bb={};BigInt.prototype.toJSON=function(){throw Bb};a(yc,"streamAsJSON");jh=class extends Pb.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),Mb)}catch(s){yield Mb(s)}else yield Gi(t)}else yield Gi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Ub(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>h$?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 Ub(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(Mb,"handleError");a(Ub,"when");a(Gi,"stringify");a(Hb,"jsStringify");m$=/[[,:]\s*-?\d{16,}/;a(Xh,"parse")});var jb=R((_ae,Jb)=>{"use strict";var em=require("recursive-iterator"),p$=require("alasql"),tm=require("clone"),Gb=Q(),{handleHDBError:Fb,hdb_errors:S$}=ne(),{HDB_ERROR_MSGS:qb,HTTP_STATUS_CODES:kb}=S$,{getDatabases:T$}=(Re(),ie(qe)),g$=["DISTINCT_ARRAY"],Vb=Symbol("validateTables"),rm=Symbol("validateTable"),lae=Symbol("getAllColumns"),$b=Symbol("validateAllColumns"),f_=Symbol("findColumn"),Yb=Symbol("validateOrderBy"),Nc=Symbol("validateSegment"),nm=Symbol("validateColumn"),Kb=Symbol("setColumnsForTable"),Wb=Symbol("checkColumnsForAsterisk"),Qb=Symbol("validateGroupBy"),zb=Symbol("hasColumns"),sm=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Vb](),this[Wb](),this[$b]()}[Vb](){if(this[zb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[rm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[rm](t.table)})}}[zb](){let t=!1,r=new em(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[rm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=T$();if(!r[t.databaseid])throw Fb(new Error,qb.SCHEMA_NOT_FOUND(t.databaseid),kb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Fb(new Error,qb.TABLE_NOT_FOUND(t.databaseid,t.tableid),kb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=tm(s);i.table=tm(t),this.attributes.push(i)})}[f_](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)}[Wb](){let t=new em(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Kb](r.tableid)}[Kb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new p$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[$b](){this[Nc](this.statement.columns,!1),this[Nc](this.statement.joins,!1),this[Nc](this.statement.where,!1),this[Qb](this.statement.group,!1),this[Nc](this.statement.order,!0)}[Nc](t,r){if(!t)return;let n=new em(t),s=[];for(let{node:i,path:o}of n)!Gb.isEmpty(i)&&!Gb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Yb](i):s.push(this[nm](i)));return s}[Qb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&g$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=tm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[f_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[f_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[Yb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[nm](t)}[nm](t){let r=this[f_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Jb.exports=sm});var Zb=R((fae,Xb)=>{"use strict";var im=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")}};Xb.exports=im});var ty=R((hae,ey)=>{"use strict";var om=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};ey.exports=om});var iy={};Fe(iy,{HAS_EXPIRATION:()=>fm,LAST_TIMESTAMP_PLACEHOLDER:()=>Cc,LOCAL_TIMESTAMP:()=>R$,METADATA:()=>Ic,NO_TIMESTAMP:()=>cm,PENDING_LOCAL_TIME:()=>Em,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>dm,RecordEncoder:()=>_m,TIMESTAMP_ASSIGN_LAST:()=>O$,TIMESTAMP_ASSIGN_NEW:()=>ny,TIMESTAMP_ASSIGN_PREVIOUS:()=>sy,TIMESTAMP_PLACEHOLDER:()=>E_,TIMESTAMP_RECORD_PREVIOUS:()=>um,getUpdateRecord:()=>hm,handleLocalTimeForGets:()=>S_});function y$(){return wc[0]=wc[0]^64,A$.getFloat64(0)}function S_(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?.[Ic];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?.[Ic]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[Ic];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Fi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Fi.length;u++){let _=Fi[u].deref();(!_||_.isDone||_.isCommitted)&&Fi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function hm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?ko=i?.localTime?um|sy:cm:ko=u?i?.localTime?um|16384:ny|16384:cm,l>0&&(c|=fm),m_=c,lm=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:ko>0},S;try{f&&(h.ifVersion=S=i?.version??null);let p=e.put(n,s,h);if(u){let T=_?.user?.username;if(E&&(h_=e.encoder.encode(E)),f&&i?.localTime){let b=i?.localTime,g=r.get(b);if(g){let L=Ut(g).previousLocalTime;return r.put(b,p_(o,t,n,L,T,d,h_),{ifVersion:S}),p}}r.put(Cc,p_(o,t,n,i?.localTime?1:0,T,d,h_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:S})}return p}catch(p){throw p.message+=" id: "+n+" options: "+h,p}}}var ry,am,E_,Cc,dm,R$,Ic,wc,A$,cm,ny,O$,sy,um,fm,Em,b$,h_,ko,m_,lm,_m,Fi,Dc=ge(()=>{ry=require("msgpackr");Zs();am=B(Y()),E_=new Uint8Array([1,1,1,1,4,64,0,0]),Cc=new Uint8Array([1,1,1,1,1,0,0,0]),dm=new Uint8Array([1,1,1,1,3,64,0,0]),R$=Symbol("local-timestamp"),Ic=Symbol("metadata"),wc=new Uint8Array(8),A$=new DataView(wc.buffer,0,8),cm=0,ny=0,O$=1,sy=3,um=4,fm=16,Em=1,ko=0,m_=-1,lm=0,_m=class extends ry.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(ko||m_>=0){let i=0,o=ko;o&&(i+=8,ko=0);let c=m_,u=lm;c>=0&&(i+=2,m_=-1,u&&(i+=8,lm=0));let _=b$=r.call(this,n,s|2048|i);h_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(E_[4]=o,E_[5]=o>>8,_.set(E_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(wc,0,c),c+=8;else for(let d=0;d<8;d++)wc[d]=t[c++];u=y$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&fm&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[Ic]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(y$,"getTimestamp");a(S_,"handleLocalTimeForGets");Fi=[];setInterval(()=>{for(let e=0;e<Fi.length;e++){let t=Fi[e].deref();!t||t.isDone||t.isCommitted?Fi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(am.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):am.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(hm,"getUpdateRecord")});var Lc=R((gae,ay)=>{"use strict";var oy=re(),N$=U(),{RecordEncoder:I$}=(Dc(),ie(iy)),Tae=require("fs");oy.initSync();var w$=oy.get(N$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,mm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=w$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:I$})}};ay.exports=mm});var Mc=R((Aae,cy)=>{"use strict";var Br=re(),sn=U();Br.initSync();var 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.eventTurnBatching=!1,this.noSync=Br.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Br.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Br.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Br.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Br.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Br.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Br.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Br.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Br.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Br.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Br.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Br.get(sn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};cy.exports=T_;T_.MAX_DBS=1e4});var Ye=R((bae,Sy)=>{"use strict";var Sm=require("lmdb"),wn=require("fs-extra"),Hr=require("path"),g_=Pr(),_y=Y(),dr=Lr().LMDB_ERRORS_ENUM,R_=ty(),Tm=Lc(),dy=Mc(),ei=ct(),uy=U(),{table:C$,resetDatabases:D$}=(Re(),ie(qe)),ly=re(),Cn=ei.INTERNAL_DBIS_NAME,fy=ei.DBI_DEFINITION_NAME,L$="data.mdb",M$="lock.mdb",Uc=".mdb",U$="-lock",pm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=on(t,r),this.key_type=this.dbi[ei.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ei.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Sm.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(dr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(dr.ENV_NAME_REQUIRED)}a(A_,"pathEnvNameValidation");async function gm(e,t,r=!0){try{await wn.access(e)}catch(n){throw n.code==="ENOENT"?new Error(dr.INVALID_BASE_PATH):n}try{let n=Hr.join(e,t+Uc);return await wn.access(n,wn.constants.R_OK|wn.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await wn.access(Hr.join(e,t,L$),wn.constants.R_OK|wn.constants.F_OK),Hr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(dr.INVALID_ENVIRONMENT)}else throw new Error(dr.INVALID_ENVIRONMENT);throw n}}a(gm,"validateEnvironmentPath");function O_(e,t){if(g_.validateEnv(e),t===void 0)throw new Error(dr.DBI_NAME_REQUIRED)}a(O_,"validateEnvDBIName");async function P$(e,t,r=!1,n=!1){A_(e,t);let s=Hr.basename(e);t=t.toString();let i=ly.get(uy.CONFIG_PARAMS.DATABASES);i||ly.setProperty(uy.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await gm(e,t,n),Ey(e,t,r)}catch(o){if(o.message===dr.INVALID_ENVIRONMENT){let c=Hr.join(e,t);await wn.mkdirp(n?c:e);let u=new dy(n?c:c+Uc,!1),_=Sm.open(u);_.dbis=Object.create(null);let l=new Tm(!1);_.openDB(Cn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Rm(e,t,r);return _[ei.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(P$,"createEnvironment");async function v$(e,t,r,n=!0){A_(e,t),t=t.toString();let s=Hr.join(e,t);return C$({table:t,database:Hr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(v$,"copyEnvironment");async function Ey(e,t,r=!1){A_(e,t),t=t.toString();let n=Rm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await gm(e,t),i=Hr.join(e,t+Uc),o=s!=i,c=new dy(s,o),u=Sm.open(c);u.dbis=Object.create(null);let _=my(u);for(let l=0;l<_.length;l++)on(u,_[l]);return u[ei.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(Ey,"openEnvironment");async function B$(e,t,r=!1){A_(e,t),t=t.toString();let n=Hr.join(e,t+Uc),s=await gm(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 hy(o),delete global.lmdb_map[i]}}await wn.remove(s),await wn.remove(s===n?s+U$:Hr.join(Hr.dirname(s),M$))}a(B$,"deleteEnvironment");async function hy(e){g_.validateEnv(e);let t=e[ei.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(hy,"closeEnvironment");function Rm(e,t,r=!1){let s=`${Hr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(Rm,"getCachedEnvironmentName");function H$(e){g_.validateEnv(e);let t=Object.create(null),r=on(e,Cn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==Cn)try{t[n]=Object.assign(new R_,s)}catch{_y.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(H$,"listDBIDefinitions");function my(e){g_.validateEnv(e);let t=[],r=on(e,Cn);for(let{key:n}of r.getRange({start:!1}))n!==Cn&&t.push(n);return t}a(my,"listDBIs");function x$(e,t){let n=on(e,Cn).getEntry(t),s=new R_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{_y.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(x$,"getDBIDefinition");function py(e,t,r,n=!r){if(O_(e,t),t=t.toString(),t===Cn)throw new Error(dr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return on(e,t)}catch(s){if(s.message===dr.DBI_DOES_NOT_EXIST){let i=new Tm(r,n===!0),o=e.openDB(t,i),c=new R_(r===!0,n);return o[fy]=c,on(e,Cn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(py,"createDBI");function on(e,t){if(O_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Cn?r=x$(e,t):r=new R_,r===void 0)throw new Error(dr.DBI_DOES_NOT_EXIST);let n;try{let s=new Tm(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(dr.DBI_DOES_NOT_EXIST):s}return n[fy]=r,e.dbis[t]=n,n}a(on,"openDBI");function G$(e,t){O_(e,t),t=t.toString();let r=on(e,t),n=r.getStats();return r[ei.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(G$,"statDBI");async function F$(e,t){try{let r=Hr.join(e,t+Uc);return(await wn.stat(r)).size}catch{throw new Error(dr.INVALID_ENVIRONMENT)}}a(F$,"environmentDataSize");function q$(e,t){if(O_(e,t),t=t.toString(),t===Cn)throw new Error(dr.CANNOT_DROP_INTERNAL_DBIS_NAME);on(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],on(e,Cn).removeSync(t)}a(q$,"dropDBI");function k$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{on(e,i)}catch(o){if(o.message===dr.DBI_DOES_NOT_EXIST)py(e,i,i!==t,i===t),n=!0;else throw o}}n&&D$()}a(k$,"initializeDBIs");Sy.exports={openDBI:on,openEnvironment:Ey,createEnvironment:P$,listDBIs:my,listDBIDefinitions:H$,createDBI:py,dropDBI:q$,statDBI:G$,deleteEnvironment:B$,initializeDBIs:k$,TransactionCursor:pm,environmentDataSize:F$,copyEnvironment:v$,closeEnvironment:hy}});var gy=R((Nae,Ty)=>{"use strict";var Am=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Ty.exports=Am});var Ay=R((wae,Ry)=>{"use strict";var Om=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Ry.exports=Om});var by=R((Dae,Oy)=>{"use strict";var bm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Oy.exports=bm});var Vo=R((vae,Iy)=>{"use strict";var V$=Ye(),$$=gy(),Y$=Ay(),K$=by(),Wn=Pr(),Pc=Lr().LMDB_ERRORS_ENUM,W$=ct(),Ts=U(),Q$=Q(),z$=require("uuid"),Mae=require("lmdb"),{handleHDBError:J$,hdb_errors:j$}=ne(),{OVERFLOW_MARKER:Uae,MAX_SEARCH_KEY_LENGTH:Pae}=W$,yy=re();yy.initSync();var b_=yy.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),ym=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function X$(e,t,r,n,s=Wn.getNextMonotonicTime()){Cm(e,t,r,n),Nm(e,t,r);let i=new $$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ny(_,!0,s);let l=Z$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Im(o,c,n,i,s)}a(X$,"insertRecords");function Z$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ts.FUNC_VAL],n[o]=c)}let u=Wn.getIndexedValues(c),_=e.dbis[o];if(u){b_&&_.prefetch(u.map(l=>({key:l,value:s})),y_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}b_&&e.dbis[t].prefetch([s],y_),e.dbis[t].put(s,n,n[qi])})}a(Z$,"insertRecord");function e1(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(e1,"removeSkippedRecords");function Ny(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[ym]))&&(e[ym]=r||Wn.getNextMonotonicTime()):delete e[ym]}a(Ny,"setTimestamps");function Nm(e,t,r){r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),V$.initializeDBIs(e,t,r)}a(Nm,"initializeTransaction");async function t1(e,t,r,n,s=Wn.getNextMonotonicTime()){Cm(e,t,r,n),Nm(e,t,r);let i=new Y$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=wm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return Im(c,u,n,i,s,o)}a(t1,"updateRecords");async function r1(e,t,r,n,s=Wn.getNextMonotonicTime()){try{Cm(e,t,r,n)}catch(u){throw J$(u,u.message,j$.HTTP_STATUS_CODES.BAD_REQUEST)}Nm(e,t,r);let i=new K$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;Q$.isEmpty(_[t])?(l=z$.v4(),_[t]=l):l=_[t];let d=wm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Im(o,c,n,i,s)}a(r1,"upsertRecords");async function Im(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Wn.getNextMonotonicTime(),e1(r,i),n}a(Im,"finalizeWrite");function wm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Ny(r,!l,o),Number.isInteger(r[qi])&&_[qi]>r[qi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let S=r[h],p=e.dbis[h];if(p===void 0)continue;let T=_[h];if(typeof S=="function"){let g=S([[_]]);Array.isArray(g)&&(S=g[0][Ts.FUNC_VAL],r[h]=S)}if(S===T)continue;let b=Wn.getIndexedValues(T);if(b){b_&&p.prefetch(b.map(g=>({key:g,value:n})),y_);for(let g=0,L=b.length;g<L;g++)p.remove(b[g],n)}if(b=Wn.getIndexedValues(S),b){b_&&p.prefetch(b.map(g=>({key:g,value:n})),y_);for(let g=0,L=b.length;g<L;g++)p.put(b[g],n)}}let E=Object.assign({},_,r);c.put(n,E,E[qi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:wm(e,t,r,n,s,i,o))}a(wm,"updateUpsertRecord");function n1(e,t,r){if(Wn.validateEnv(e),t===void 0)throw new Error(Pc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Pc.WRITE_ATTRIBUTES_REQUIRED):new Error(Pc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(n1,"validateBasic");function Cm(e,t,r,n){if(n1(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Pc.RECORDS_REQUIRED):new Error(Pc.RECORDS_MUST_BE_ARRAY)}a(Cm,"validateWrite");function y_(){}a(y_,"noop");Iy.exports={insertRecords:X$,updateRecords:t1,upsertRecords:r1}});var ki=R((Hae,s1)=>{s1.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"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},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 zn=R((xae,Dy)=>{"use strict";var Cy=Q(),wy=U(),$o=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ti={schema_format:{pattern:$o,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},i1=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number(),Qn.array()).required(),o1=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number()),a1=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern($o).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number()).required();function c1(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ti.schema_length.maximum?`'${e}' maximum of 250 characters`:$o.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(c1,"checkValidTable");function u1(e,t){return Cy.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(u1,"validateSchemaExists");function l1(e,t){let r=t.state.ancestors[0].schema;return Cy.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(l1,"validateTableExists");function _1(e,t){return e.toLowerCase()===wy.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${wy.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(_1,"validateSchemaName");Dy.exports={common_validators:ti,schema_regex:$o,hdb_schema_table:i1,validateSchemaExists:u1,validateTableExists:l1,validateSchemaName:_1,checkValidTable:c1,hdb_database:o1,hdb_table:a1}});var N_=R((Fae,Ly)=>{var{common_validators:Jn}=zn(),Bc=et(),vc="is required",mt={database:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},schema:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},table:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},hash_attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length}};function Hc(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(Hc,"makeAttributesStrings");function d1(e){return e=Hc(e),mt.table.presence=!1,mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Bc.validateObject(e,mt)}a(d1,"schema_object");function f1(e){return e=Hc(e),mt.table.presence={message:vc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Bc.validateObject(e,mt)}a(f1,"table_object");function E1(e){return e=Hc(e),mt.table.presence={message:vc},mt.attribute.presence=!1,Bc.validateObject(e,mt)}a(E1,"create_table_object");function h1(e){return e=Hc(e),mt.table.presence={message:vc},mt.attribute.presence={message:vc},mt.hash_attribute.presence=!1,Bc.validateObject(e,mt)}a(h1,"attribute_object");function m1(e){return e=Hc(e),mt.table.presence={message:vc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Bc.validateObject(e,mt)}a(m1,"describe_table");function p1(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(p1,"validateTableResidence");Ly.exports={schema_object:d1,create_table_object:E1,table_object:f1,attribute_object:h1,describe_table:m1,validateTableResidence:p1}});var Uy=R((kae,My)=>{"use strict";var S1=require("uuid"),Dm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||S1.v4(),this.schema_table=`${this.schema}.${this.table}`}};My.exports=Dm});var I_=R(($ae,Py)=>{"use strict";var T1=Uy(),Lm=class extends T1{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};Py.exports=Lm});var By=R((Kae,vy)=>{"use strict";vy.exports=R1;var g1="inserted";function R1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===g1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(R1,"returnObject")});var w_=R((Qae,qy)=>{"use strict";var A1=U(),Mm=Ye(),O1=Vo(),{getSystemSchemaPath:b1,getSchemaPath:y1}=Qe(),N1=ki(),I1=N_(),w1=I_(),C1=By(),{handleHDBError:Hy,hdb_errors:Gy}=ne(),xy=Q(),{HTTP_STATUS_CODES:D1}=Gy,Um=N1.hdb_attribute,Fy=[];for(let e=0;e<Um.attributes.length;e++)Fy.push(Um.attributes[e].attribute);var L1="inserted";qy.exports=M1;async function M1(e){let t=I1.attribute_object(e);if(t)throw Hy(new Error,t.message,Gy.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&xy.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Hy(new Error,r,D1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=xy.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new w1(e.schema,e.table,e.attribute,e.id);try{let i=await Mm.openEnvironment(y1(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}`);Mm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Mm.openEnvironment(b1(),A1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await O1.insertRecords(o,Um.hash_attribute,Fy,[s]);return C1(L1,c,{records:[s]},u)}catch(i){throw i}}a(M1,"lmdbCreateAttribute")});var vm=R((Jae,Vy)=>{var{hdb_table:U1,hdb_database:ky}=zn(),P1=et(),Pm=require("joi"),v1={undefined:"undefined",null:"null"},B1=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||v1[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),H1=Pm.object({database:ky,schema:ky,table:U1,records:Pm.array().items(Pm.object().custom(B1)).required()});Vy.exports=function(e){return P1.validateBySchema(e,H1)}});var xc=R((Zae,Yy)=>{"use strict";var gs=Q(),$y=Y(),Xae=vm(),{getDatabases:x1}=(Re(),ie(qe)),{ClientError:Vi}=ne();Yy.exports=G1;function G1(e){if(gs.isEmpty(e))throw new Vi("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new Vi("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new Vi("invalid table specified.");if(!Array.isArray(e.records))throw new Vi("records must be an array");let t=x1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new Vi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&gs.isEmptyOrZeroLength(o[r]))throw $y.error("a valid hash attribute must be provided with update record:",o),new Vi("a valid hash attribute must be provided with update record, check log for more info");if(!gs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw $y.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Vi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gs.isEmpty(o[r])&&o[r]!==""&&n.has(gs.autoCast(o[r]))&&(o.skip=!0),n.add(gs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(G1,"insertUpdateValidate")});var Gc=R((tce,Ky)=>{"use strict";var F1=U().OPERATIONS_ENUM,Bm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=F1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Ky.exports=Bm});var Fc=R((sce,Qy)=>{"use strict";var nce=Gc(),C_=U(),Hm=Q(),Wy=Y(),q1=require("uuid"),{handleHDBError:D_,hdb_errors:k1}=ne(),{HDB_ERROR_MSGS:L_,HTTP_STATUS_CODES:M_}=k1;Qy.exports=V1;function V1(e,t,r){for(let s=0;s<t.length;s++)$1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];Y1(i,r,e.operation)}}a(V1,"processRows");function $1(e){if(Buffer.byteLength(String(e))>C_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw D_(new Error,L_.ATTR_NAME_LENGTH_ERR(e),M_.BAD_REQUEST,void 0,void 0,!0);if(Hm.isEmptyOrZeroLength(e)||Hm.isEmpty(e.trim()))throw D_(new Error,L_.ATTR_NAME_NULLISH_ERR,M_.BAD_REQUEST,void 0,void 0,!0)}a($1,"validateAttribute");function Y1(e,t,r){if(!e.hasOwnProperty(t)||Hm.isEmptyOrZeroLength(e[t])){if(r===C_.OPERATIONS_ENUM.INSERT||r===C_.OPERATIONS_ENUM.UPSERT){e[t]=q1.v4();return}throw Wy.error("Update transaction aborted due to record with no hash value:",e),D_(new Error,L_.RECORD_MISSING_HASH_ERR,M_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>C_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Wy.error(e),D_(new Error,L_.HASH_VAL_LENGTH_ERR,M_.BAD_REQUEST,void 0,void 0,!0)}a(Y1,"validateHash")});var Jy=R((oce,zy)=>{"use strict";var xm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};zy.exports=xm});var Zy=R((cce,Xy)=>{"use strict";var Gm=Ye(),K1=Y(),jy=Lr().LMDB_ERRORS_ENUM;Xy.exports=W1;async function W1(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 Gm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==jy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await Gm.closeEnvironment(global.lmdb_map[n]),await Gm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==jy.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){K1.error(t)}}a(W1,"cleanLMDBMap")});var Rs=R((lce,nN)=>{"use strict";var qc=require("crypto"),Q1=re(),{CONFIG_PARAMS:z1}=U(),tN="aes-256-cbc",J1=32,j1=16,Fm=64,rN=32,X1=Fm+rN,eN=new Map;nN.exports={encrypt:Z1,decrypt:eY,createNatsTableStreamName:tY};function Z1(e){let t=qc.randomBytes(J1),r=qc.randomBytes(j1),n=qc.createCipheriv(tN,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(Z1,"encrypt");function eY(e){let t=e.substr(0,Fm),r=e.substr(Fm,rN),n=e.substr(X1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=qc.createDecipheriv(tN,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(eY,"decrypt");function tY(e,t){let r=Q1.get(z1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=eN.get(r);return n||(n=qc.createHash("md5").update(r).digest("hex"),eN.set(r,n)),n}a(tY,"createNatsTableStreamName")});var ri=R((fce,iN)=>{"use strict";var dce=xr(),U_=Y(),sN=N_(),rY=Rs(),P_=Q(),{handleHDBError:v_,hdb_errors:nY}=ne(),{HDB_ERROR_MSGS:B_,HTTP_STATUS_CODES:qm}=nY,sY=re();sY.initSync();var{getDatabases:km}=(Re(),ie(qe));iN.exports={describeAll:iY,describeTable:H_,describeSchema:oY};async function iY(e){try{let t=P_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=km(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await H_({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 H_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){U_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return U_.error("Got an error in describeAll"),U_.error(t),v_(new Error,B_.DESCRIBE_ALL_ERR)}}a(iY,"describeAll");async function H_(e,t){P_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=sN.describe_table(e);if(i)throw i;let c=km()[r];if(!c)throw v_(new Error,B_.SCHEMA_NOT_FOUND(e.schema),qm.NOT_FOUND);let u=c[n];if(!u)throw v_(new Error,B_.TABLE_NOT_FOUND(e.schema,e.table),qm.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=rY.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){U_.warn(`unable to stat table dbi due to ${f}`)}return d}a(H_,"descTable");async function oY(e){P_.transformReq(e);let t=sN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=km()[n];if(!i)throw v_(new Error,B_.SCHEMA_NOT_FOUND(e.schema),qm.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),P_.isEmpty(u)||u.describe){let _=await H_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(oY,"describeSchema")});var As=R((pce,lN)=>{var aY=ki(),{callbackify:aN,promisify:cY}=require("util"),{getDatabases:cN}=(Re(),ie(qe));lN.exports={setSchemaDataToGlobal:oN,getTableSchema:uY,getSystemSchema:lY,setSchemaDataToGlobalAsync:cY(oN)};var uN=ri(),hce=aN(uN.describeAll),mce=aN(uN.describeTable);function oN(e){global.hdb_schema=cN(),e&&e()}a(oN,"setSchemaDataToGlobal");function uY(e,t,r){let n=cN()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(uY,"getTableSchema");function lY(){return aY}a(lY,"getSystemSchema")});var an=R((Tce,EN)=>{"use strict";var G_=vm(),kt=Q(),_Y=require("util"),F_=Dn(),dY=As(),_N=Y(),{handleHDBError:$i,hdb_errors:fY}=ne(),{HTTP_STATUS_CODES:Yi}=fY,EY=_Y.promisify(dY.getTableSchema),hY="updated",dN="inserted",fN="upserted";EN.exports={insert:pY,update:SY,upsert:TY,validation:mY,flush:gY};async function mY(e){if(kt.isEmpty(e))throw new Error("invalid update parameters defined.");if(kt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(kt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await EY(e.schema,e.table),r=G_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&kt.isEmptyOrZeroLength(c[n]))throw _N.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(!kt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw _N.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!kt.isEmpty(c[n])&&c[n]!==""&&s.has(kt.autoCast(c[n]))&&(c.skip=!0),s.add(kt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(mY,"validation");async function pY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=G_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await F_.createRecords(e);return x_(dN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(pY,"insertData");async function SY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=G_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await F_.updateRecords(e);return kt.isEmpty(n.existing_rows)?x_(hY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):x_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(SY,"updateData");async function TY(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=G_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await F_.upsertRecords(e);return x_(fN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(TY,"upsertData");function x_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===dN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===fN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(x_,"returnObject");function gY(e){return kt.transformReq(e),F_.flush(e.schema,e.table)}a(gY,"flush")});var $m=R((Rce,pN)=>{var RY=et(),Vm=require("joi"),{hdb_table:AY,hdb_database:hN}=zn(),mN={schema:hN,database:hN,table:AY},OY={date:Vm.date().iso().required()},bY={timestamp:Vm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};pN.exports=function(e,t){let r=t==="timestamp"?{...mN,...bY}:{...mN,...OY},n=Vm.object(r);return RY.validateBySchema(e,n)}});var gN=R((Ace,TN)=>{var yY=et(),Ym=require("joi"),{hdb_table:NY,hdb_database:SN}=zn(),IY=Ym.object({schema:SN,database:SN,table:NY,hash_values:Ym.array().required(),ids:Ym.array()});TN.exports=function(e){return yY.validateBySchema(e,IY)}});var AN=R((Oce,RN)=>{"use strict";var Km=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Wm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Qm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};RN.exports={InsertObject:Km,NoSQLSeachObject:Wm,DeleteResponseObject:Qm}});var Qi=R((yce,IN)=>{"use strict";var bN=$m(),wY=gN(),Ki=Q(),ON=require("moment"),yN=Y(),{promisify:CY,callbackify:DY}=require("util"),Wi=U(),LY=As(),zm=CY(LY.getTableSchema),Jm=Dn(),{DeleteResponseObject:MY}=AN(),{handleHDBError:ni,hdb_errors:UY}=ne(),{HDB_ERROR_MSGS:q_,HTTP_STATUS_CODES:si}=UY,PY="records successfully deleted",vY=DY(NN);IN.exports={delete:vY,deleteRecord:NN,deleteFilesBefore:BY,deleteAuditLogsBefore:HY};async function BY(e){let t=bN(e,"date");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!ON(e.date,ON.ISO_8601).isValid())throw ni(new Error,q_.INVALID_DATE,si.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,q_.INVALID_DATE,!0);let n=Ki.checkSchemaTableExist(e.schema,e.table);if(n)throw ni(new Error,n,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,n,!0);let s=await Jm.deleteRecordsBefore(e);if(await zm(e.schema,e.table),yN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(BY,"deleteFilesBefore");async function HY(e){let t=bN(e,"timestamp");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw ni(new Error,q_.INVALID_VALUE("Timestamp"),si.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,q_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let n=await Jm.deleteAuditLogsBefore(e);return await zm(e.schema,e.table),yN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(HY,"deleteAuditLogsBefore");async function NN(e){e.ids&&(e.hash_values=e.ids);let t=wY(e);if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await zm(e.schema,e.table);let n=await Jm.deleteRecords(e);return Ki.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${PY}`),n}catch(n){if(n.message===Wi.SEARCH_NOT_FOUND_MESSAGE){let s=new MY;return s.message=Wi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(NN,"deleteRecord")});var k_=R((Ice,DN)=>{var xY=require("crypto"),wN=9;function GY(e){let t=qY(wN),r=CN(e+t);return t+r}a(GY,"createHash");function FY(e,t){let r=e?.substr(0,wN),n=r+CN(t+r);return e===n}a(FY,"validateHash");function qY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(qY,"generateSalt");function CN(e){return xY.createHash("md5").update(e).digest("hex")}a(CN,"md5");DN.exports={hash:GY,validate:FY}});var MN=R((Cce,LN)=>{var jm=et(),Jt={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 kY(e){return Jt.password.presence=!0,Jt.username.presence=!0,Jt.role.presence=!0,Jt.active.presence=!0,jm.validateObject(e,Jt)}a(kY,"addUserValidation");function VY(e){return Jt.password.presence=!1,Jt.username.presence=!0,Jt.role.presence=!1,Jt.active.presence=!1,jm.validateObject(e,Jt)}a(VY,"alterUserValidation");function $Y(e){return Jt.password.presence=!1,Jt.username.presence=!0,Jt.role.presence=!1,Jt.active.presence=!1,jm.validateObject(e,Jt)}a($Y,"dropUserValidation");LN.exports={addUserValidation:kY,alterUserValidation:VY,dropUserValidation:$Y}});var st=R((Mce,PN)=>{"use strict";var{platform:Lce}=require("os"),YY="nats-server.zip",Xm="nats-server",KY=process.platform==="win32"?`${Xm}.exe`:Xm,WY=/^[^\s.,*>]+$/,UN="__request__",QY=a(e=>`${e}.${UN}`,"REQUEST_SUBJECT"),zY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},JY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},jY={HUB:"hub.pid",LEAF:"leaf.pid"},XY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},ZY={SUCCESS:"success",ERROR:"error"},eK={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},tK={TXN:"txn",MSGID:"msgid"},Yo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},rK={[Yo.ERR]:1,[Yo.WRN]:2,[Yo.INF]:3,[Yo.DBG]:4,[Yo.TRC]:5},nK={debug:"-D",trace:"-DVV"};PN.exports={NATS_SERVER_ZIP:YY,NATS_SERVER_NAME:Xm,NATS_BINARY_NAME:KY,PID_FILES:jY,NATS_CONFIG_FILES:JY,SERVER_SUFFIX:XY,NATS_TERM_CONSTRAINTS_RX:WY,REQUEST_SUFFIX:UN,UPDATE_REMOTE_RESPONSE_STATUSES:ZY,CLUSTER_STATUS_STATUSES:eK,REQUEST_SUBJECT:QY,SUBJECT_PREFIXES:tK,MSG_HEADERS:zY,LOG_LEVELS:Yo,LOG_LEVEL_FLAGS:nK,LOG_LEVEL_HIERARCHY:rK}});var BN=R((Pce,vN)=>{"use strict";var V_=U(),$_=class{static{a(this,"BaseLicense")}constructor(t=0,r=V_.RAM_ALLOCATION_ENUM.DEFAULT,n=V_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},Zm=class extends $_{static{a(this,"ExtendedLicense")}constructor(t=0,r=V_.RAM_ALLOCATION_ENUM.DEFAULT,n=V_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};vN.exports={BaseLicense:$_,ExtendedLicense:Zm}});var zi=R((Bce,kN)=>{"use strict";var Wo=require("fs-extra"),xN=k_(),GN=require("crypto"),sK=require("moment"),iK=require("uuid").v4,jt=Y(),tp=require("path"),oK=Q(),ii=U(),{totalmem:HN}=require("os"),aK=BN().ExtendedLicense,Ko="invalid license key format",cK="061183",uK="mofi25",lK="aes-256-cbc",_K=16,dK=32,FN=re();FN.initSync();var ep;kN.exports={validateLicense:qN,generateFingerPrint:EK,licenseSearch:sp,getLicense:pK,checkMemoryLimit:SK};function rp(){return tp.join(FN.getHdbBasePath(),ii.LICENSE_KEY_DIR_NAME,ii.LICENSE_FILE_NAME)}a(rp,"getLicenseDirPath");function fK(){let e=rp();return tp.join(e,ii.LICENSE_FILE_NAME)}a(fK,"getLicenseFilePath");function np(){let e=rp();return tp.join(e,ii.REG_KEY_FILE_NAME)}a(np,"getFingerPrintFilePath");async function EK(){let e=np();try{return await Wo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await hK();throw jt.error(`Error writing fingerprint file to ${e}`),jt.error(t),new Error("There was an error generating the fingerprint")}}a(EK,"generateFingerPrint");async function hK(){let e=iK(),t=xN.hash(e),r=np();try{await Wo.mkdirp(rp()),await Wo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw jt.error(`Error writing fingerprint file to ${r}`),jt.error(n),new Error("There was an error generating the fingerprint")}return t}a(hK,"writeFingerprint");function qN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ii.RAM_ALLOCATION_ENUM.DEFAULT,version:ii.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return jt.error("empty license key passed to validate."),r;let n=np(),s=!1;try{s=Wo.statSync(n)}catch(i){jt.error(i)}if(s){let i;try{i=Wo.readFileSync(n,"utf8")}catch{jt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(uK),c=o[1];c=Buffer.concat([Buffer.from(c)],_K);let u=Buffer.concat([Buffer.from(i)],dK),_=GN.createDecipheriv(lK,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=mK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Ko),jt.error(Ko),new Error(Ko)}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(Ko),jt.error(Ko),new Error(Ko)}else r.exp_date=l;r.exp_date<sK().valueOf()&&(r.valid_date=!1),xN.validate(o[1],`${cK}${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||jt.error("Invalid licence"),r}a(qN,"validateLicense");function mK(e,t){try{let r=GN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{jt.warn("Check old license failed")}}a(mK,"checkOldLicense");function sp(){let e=new aK,t=[];try{t=Wo.readFileSync(fK(),"utf-8").split(ii.NEW_LINE)}catch(r){r.code==="ENOENT"?jt.info("no license file found"):jt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(oK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=qN(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){jt.error("There was an error parsing the license string."),jt.error(s),e.ram_allocation=ii.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return ep=e,e}a(sp,"licenseSearch");async function pK(){return ep||await sp(),ep}a(pK,"getLicense");function SK(){let e=sp().ram_allocation,t=process.constrainedMemory?.()||HN();if(t=Math.round(Math.min(t,HN())/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(SK,"checkMemoryLimit")});var Fr=R((qce,sI)=>{"use strict";var KN="username is required",WN="nothing to update, must supply active, role or password to update",QN="password cannot be an empty string",zN="If role is specified, it cannot be empty.",JN="active must be true or false";sI.exports={addUser:IK,alterUser:wK,dropUser:DK,getSuperUser:PK,userInfo:LK,listUsers:K_,listUsersExternal:MK,setUsersToGlobal:zo,findAndValidateUser:rI,getClusterUser:vK,USERNAME_REQUIRED:KN,ALTERUSER_NOTHING_TO_UPDATE:WN,EMPTY_PASSWORD:QN,EMPTY_ROLE:zN,ACTIVE_BOOLEAN:JN};var jN=an(),TK=Qi(),ap=k_(),XN=MN(),ZN=xr(),cp=Os(),Gr=Q(),eI=require("validate.js"),Ae=Y(),{promisify:gK}=require("util"),up=Rs(),VN=U(),$N=st(),RK=lr(),xce=re(),Gce=zi(),AK=ki(),{table:Fce}=(Re(),ie(qe)),{handleHDBError:jn,hdb_errors:OK}=ne(),{HTTP_STATUS_CODES:Xn,AUTHENTICATION_ERROR_MSGS:ip,HDB_ERROR_MSGS:Qo}=OK,{UserEventMsg:lp}=Ln(),op=require("lodash"),{server:_p}=(cr(),ie(Bi)),bK=Y();_p.getUser=(e,t)=>rI(e,t,t!=null);var tI={username:!0,active:!0,role:!0,password:!0},YN=new Map,Y_=ZN.searchByValue,yK=ZN.searchByHash,NK=gK(TK.delete);async function IK(e){let t=eI.cleanAttributes(e,tI),r=XN.addUserValidation(t);if(r)throw jn(new Error,r.message,Xn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await Y_(n),s=s&&Array.from(s)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!s||s.length<1)throw jn(new Error,Qo.ROLE_NAME_NOT_FOUND(t.role),Xn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw jn(new Error,Qo.DUP_ROLES_FOUND(t.role),Xn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=up.encrypt(t.password)),t.password=ap.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await jN.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await zo()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw jn(new Error,Qo.USER_ALREADY_EXISTS(t.username),Xn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],cp.signalUserChange(new lp(process.pid)),`${c.username} successfully added`}a(IK,"addUser");async function wK(e){let t=eI.cleanAttributes(e,tI);if(Gr.isEmptyOrZeroLength(t.username))throw new Error(KN);if(Gr.isEmptyOrZeroLength(t.password)&&Gr.isEmptyOrZeroLength(t.role)&&Gr.isEmptyOrZeroLength(t.active))throw new Error(WN);if(!Gr.isEmpty(t.password)&&Gr.isEmptyOrZeroLength(t.password.trim()))throw new Error(QN);if(!Gr.isEmpty(t.active)&&!Gr.isBoolean(t.active))throw new Error(JN);let r=CK(t.username);if(!Gr.isEmpty(t.password)&&!Gr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=up.encrypt(t.password)),t.password=ap.hash(t.password)),t.role==="")throw new Error(zN);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 Y_(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=Qo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),jn(new Error,c,Xn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Qo.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),jn(new Error,c,Xn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await jN.update(n)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await zo()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return cp.signalUserChange(new lp(process.pid)),s}a(wK,"alterUser");function CK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(CK,"isClusterUser");async function DK(e){try{let t=XN.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Gr.isEmpty(global.hdb_users.get(e.username)))throw jn(new Error,Qo.USER_NOT_EXIST(e.username),Xn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await NK(r)}catch(s){throw Ae.error("Got an error deleting a user."),Ae.error(s),s}Ae.debug(n);try{await zo()}catch(s){throw Ae.error("Got an error setting users to global."),Ae.error(s),s}return cp.signalUserChange(new lp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(DK,"dropUser");async function LK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=op.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await yK(r)}catch(s){throw Ae.error("Got an error searching for a role."),Ae.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(LK,"userInfo");async function MK(){let e;try{e=await K_()}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(MK,"listUsersExternal");async function K_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await Y_(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]=op.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await Y_(n)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of s)o=op.cloneDeep(o),o.role=r[o.role],UK(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),Gr.errorizeMessage(e)}return null}a(K_,"listUsers");function UK(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(AK)){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(UK,"appendSystemTablesToRole");async function zo(){try{let e=await K_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(zo,"setUsersToGlobal");async function rI(e,t,r=!0){global.hdb_users||await zo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw jn(new Error,ip.GENERIC_AUTH_FAIL,Xn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw jn(new Error,ip.USER_INACTIVE,Xn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(YN.get(t)===n.password)return s;if(ap.validate(n.password,t))YN.set(t,n.password);else throw jn(new Error,ip.GENERIC_AUTH_FAIL,Xn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(rI,"findAndValidateUser");async function PK(){global.hdb_users||await zo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(PK,"getSuperUser");async function vK(){let e=await K_(),t=RK.getConfigFromFile(VN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Gr.isEmpty(r)&&r?.role?.role===VN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=up.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+$N.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+$N.SERVER_SUFFIX.ADMIN,r}a(vK,"getClusterUser");var nI=[];_p.invalidateUser=function(e){for(let t of nI)try{t(e)}catch(r){bK.error("Error invalidating user",r)}};_p.onInvalidatedUser=function(e){nI.push(e)}});var Vc=R((Yce,cI)=>{"use strict";var Ji=Y(),qr=U(),BK=Zy(),Vce=As(),$ce=ri(),HK=Fr(),{validateEvent:iI}=Ln(),kc=Dn(),xK=require("process"),{resetDatabases:GK}=(Re(),ie(qe)),FK={[qr.ITC_EVENT_TYPES.SCHEMA]:qK,[qr.ITC_EVENT_TYPES.USER]:aI};async function qK(e){let t=iI(e);if(t){Ji.error(t);return}Ji.trace("ITC schemaHandler received schema event:",e),await BK(e.message),await kK(e.message)}a(qK,"schemaHandler");async function kK(e){try{kc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),kc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),kc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=GK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Ji.error(t)}}a(kK,"syncSchemaMetadata");var oI=[];async function aI(e){try{try{kc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),kc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Ji.warn(r)}let t=iI(e);if(t){Ji.error(t);return}Ji.trace(`ITC userHandler ${qr.HDB_ITC_CLIENT_PREFIX}${xK.pid} received user event:`,e),await HK.setUsersToGlobal();for(let r of oI)r()}catch(t){Ji.error(t)}}a(aI,"userHandler");aI.addListener=function(e){oI.push(e)};cI.exports=FK});var Ln=R((jce,lI)=>{"use strict";var Wce=Y(),dp=Q(),VK=U(),{ITC_ERRORS:$c}=Lr(),{parentPort:Qce,threadId:$K,isMainThread:YK,workerData:zce}=require("worker_threads"),{onMessageFromWorkers:KK,broadcast:Jce,broadcastWithAcknowledgement:WK}=rt();lI.exports={sendItcEvent:QK,validateEvent:uI,SchemaEventMsg:zK,UserEventMsg:JK};var W_;KK(async(e,t)=>{W_=W_||Vc(),uI(e),W_[e.type]&&await W_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function QK(e){return!YK&&e.message&&(e.message.originator=$K),WK(e)}a(QK,"sendItcEvent");function uI(e){if(typeof e!="object")return $c.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||dp.isEmpty(e.type))return $c.MISSING_TYPE;if(!e.hasOwnProperty("message")||dp.isEmpty(e.message))return $c.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||dp.isEmpty(e.message.originator))return $c.MISSING_ORIGIN;if(VK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return $c.INVALID_EVENT(e.type)}a(uI,"validateEvent");function zK(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(zK,"SchemaEventMsg");function JK(e){this.originator=e}a(JK,"UserEventMsg")});var Os=R((eue,EI)=>{"use strict";var _I=U(),Zce=Q(),Q_=Y(),dI=Jy(),Jo,{sendItcEvent:fI}=Ln();function jK(e){try{Q_.trace("signalSchemaChange called with message:",e),Jo=Jo||Vc();let t=new dI(_I.ITC_EVENT_TYPES.SCHEMA,e);return Jo.schema(t),fI(t)}catch(t){Q_.error(t)}}a(jK,"signalSchemaChange");function XK(e){try{Q_.trace("signalUserChange called with message:",e),Jo=Jo||Vc();let t=new dI(_I.ITC_EVENT_TYPES.USER,e);return Jo.user(t),fI(t)}catch(t){Q_.error(t)}}a(XK,"signalUserChange");EI.exports={signalSchemaChange:jK,signalUserChange:XK}});var z_=R((rue,mI)=>{"use strict";var hI=Q(),ZK=U(),eW=Y(),tW=w_(),rW=I_(),nW=Os(),{SchemaEventMsg:sW}=Ln(),iW="already exists in";mI.exports=oW;async function oW(e,t,r){if(hI.isEmptyOrZeroLength(r))return r;let n=[];hI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await aW(e,t.schema,t.name,i)})),s}a(oW,"lmdbCheckForNewAttributes");async function aW(e,t,r,n){let s=new rW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await cW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(iW))eW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(aW,"createNewAttribute");async function cW(e){let t;return t=await tW(e),nW.signalSchemaChange(new sW(process.pid,ZK.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(cW,"createAttribute")});var jo=R((sue,pI)=>{"use strict";var fp=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};pI.exports=fp});var TI=R((oue,SI)=>{"use strict";var uW=jo(),lW=U().OPERATIONS_ENUM,Ep=class extends uW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(lW.INSERT,r,n,s,i),this.records=t}};SI.exports=Ep});var RI=R((cue,gI)=>{"use strict";var _W=jo(),dW=U().OPERATIONS_ENUM,hp=class extends _W{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(dW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};gI.exports=hp});var OI=R((lue,AI)=>{"use strict";var fW=jo(),EW=U().OPERATIONS_ENUM,mp=class extends fW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(EW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};AI.exports=mp});var yI=R((due,bI)=>{"use strict";var hW=jo(),mW=U().OPERATIONS_ENUM,pp=class extends hW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(mW.DELETE,n,s,t,i),this.original_records=r}};bI.exports=pp});var Yc=R((hue,CI)=>{"use strict";var Eue=require("path"),NI=Ye(),pW=TI(),SW=RI(),TW=OI(),gW=yI(),Xo=ct(),II=Q(),{CONFIG_PARAMS:RW}=U(),wI=re();wI.initSync();var J_=U().OPERATIONS_ENUM,{getTransactionAuditStorePath:AW}=Qe();CI.exports=OW;async function OW(e,t){if(wI.get(RW.LOGGING_AUDITLOG)===!1)return;let r=AW(e.schema,e.table),n=await NI.openEnvironment(r,e.table,!0),s=bW(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){NI.initializeDBIs(n,Xo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Xo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),II.isEmpty(s.user_name)||n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Xo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(OW,"writeTransaction");function bW(e,t){let r=II.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===J_.INSERT)return new pW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===J_.UPDATE)return new SW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===J_.UPSERT)return new TW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===J_.DELETE)return new gW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(bW,"createTransactionObject")});var Sp=R((Sue,DI)=>{"use strict";var yW=xc(),pue=Gc(),Kc=U(),NW=Fc(),IW=Vo().insertRecords,wW=Ye(),CW=Y(),DW=z_(),{getSchemaPath:LW}=Qe(),MW=Yc();DI.exports=UW;async function UW(e){try{let{schema_table:t,attributes:r}=yW(e);NW(e,r,t.hash_attribute),e.schema!==Kc.SYSTEM_SCHEMA_NAME&&(r.includes(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await DW(e.hdb_auth_header,t,r),s=LW(e.schema,e.table),i=await wW.openEnvironment(s,e.table),o=await IW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await MW(e,o)}catch(c){CW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(UW,"lmdbCreateRecords")});var UI=R((gue,MI)=>{"use strict";var LI=U(),PW=Sp(),vW=Gc(),BW=require("fs-extra"),{getSchemaPath:HW}=Qe();MI.exports=xW;async function xW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new vW(LI.SYSTEM_SCHEMA_NAME,LI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await PW(r),await BW.mkdirp(HW(e.schema))}a(xW,"lmdbCreateSchema")});var vI=R((Aue,PI)=>{"use strict";var Tp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};PI.exports=Tp});var GI=R((Iue,xI)=>{"use strict";var BI=Ye(),gp=Pr(),Rp=Lr().LMDB_ERRORS_ENUM,GW=ct(),HI=Y(),bue=Q(),FW=require("lmdb"),qW=vI(),kW=U(),{OVERFLOW_MARKER:yue,MAX_SEARCH_KEY_LENGTH:Nue}=GW,VW=kW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function $W(e,t,r,n){if(gp.validateEnv(e),t===void 0)throw new Error(Rp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Rp.IDS_REQUIRED):new Error(Rp.IDS_MUST_BE_ITERABLE);try{let s=BI.listDBIs(e);BI.initializeDBIs(e,t,s);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||n&&h[VW]>n){i.skipped.push(o);continue}let S=e.dbis[t].ifVersion(o,FW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let p=0;p<s.length;p++){let T=s[p];if(!h.hasOwnProperty(T)||T===t)continue;let b=e.dbis[T],g=h[T];if(g!=null)try{let L=gp.getIndexedValues(g);if(L)for(let v=0,P=L.length;v<P;v++)b.remove(L[v],o)}catch{HI.warn(`cannot delete from attribute: ${T}, ${g}:${o}`)}}});c.push(S),u.push(o),i.original_records.push(h)}catch(h){HI.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=gp.getNextMonotonicTime(),i}catch(s){throw s}}a($W,"deleteRecords");xI.exports={deleteRecords:$W}});var Wc=R((Cue,qI)=>{"use strict";var Zo=Q(),YW=GI(),KW=Ye(),{getSchemaPath:WW}=Qe(),QW=Yc(),zW=Y();qI.exports=JW;async function JW(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(Zo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Zo.isEmptyOrZeroLength(e.hash_values)&&!Zo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];Zo.isEmpty(u)||e.hash_values.push(u)}}if(Zo.isEmptyOrZeroLength(e.hash_values))return FI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Zo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=WW(e.schema,e.table),i=await KW.openEnvironment(s,e.table),o=await YW.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await QW(e,o)}catch(c){zW.error(`unable to write transaction due to ${c.message}`)}return FI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(JW,"lmdbDeleteRecords");function FI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(FI,"createDeleteResponse")});var Op=R((Mue,kI)=>{"use strict";var jW=U(),Lue=Pr();function Ap(e,t){let r=Object.create(null);if(t.length===1&&jW.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(Ap,"parseRow");function XW(e,t,r,n){let s=Ap(r,e);n.push(s)}a(XW,"searchAll");function ZW(e,t,r,n){let s=Ap(r,e);n[t]=s}a(ZW,"searchAllToMap");function eQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(eQ,"iterateDBI");function ji(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(ji,"pushResults");function tQ(e,t,r,n,s,i){t.toString().endsWith(e)&&ji(t,r,n,s,i)}a(tQ,"endsWith");function rQ(e,t,r,n,s,i){t.toString().includes(e)&&ji(t,r,n,s,i)}a(rQ,"contains");function nQ(e,t,r,n,s,i){t>e&&ji(t,r,n,s,i)}a(nQ,"greaterThanCompare");function sQ(e,t,r,n,s,i){t>=e&&ji(t,r,n,s,i)}a(sQ,"greaterThanEqualCompare");function iQ(e,t,r,n,s,i){t<e&&ji(t,r,n,s,i)}a(iQ,"lessThanCompare");function oQ(e,t,r,n,s,i){t<=e&&ji(t,r,n,s,i)}a(oQ,"lessThanEqualCompare");kI.exports={parseRow:Ap,searchAll:XW,searchAllToMap:ZW,iterateDBI:eQ,endsWith:tQ,contains:rQ,greaterThanCompare:nQ,greaterThanEqualCompare:sQ,lessThanCompare:iQ,lessThanEqualCompare:oQ,pushResults:ji}});var ea=R((Hue,zI)=>{"use strict";var oi=Ye(),Pue=Y(),kr=Pr(),j_=ct(),lt=Lr().LMDB_ERRORS_ENUM,vue=Q(),aQ=U(),X_=Op(),{parseRow:cQ}=X_,Bue=require("lmdb"),{OVERFLOW_MARKER:VI,MAX_SEARCH_KEY_LENGTH:uQ}=j_;function $I(e,t,r,n=!1,s=void 0,i=void 0){return Xi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a($I,"iterateFullIndex");function Qc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Xi(e,t,r,(l,d,f,E)=>{let b={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(b.values=!1,d.getRange(b).map(g=>({value:g}))):d.getRange(b)})}a(Qc,"iterateRangeBetween");function Xi(e,t,r,n){let s=e.database||e,i=oi.openDBI(s,r);i[j_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&oi.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Xi,"setupTransaction");function YI(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(VI)){if(!s)if(r)s=oi.openDBI(e,r);else{let u=oi.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=oi.openDBI(e,u[_]),!s[j_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(YI,"getOverflowCheck");function lQ(e,t,r,n=!1,s=void 0,i=void 0){if(kr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return Xi(e,t,t,(o,c,u)=>(Z_(r),r=zc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>cQ(_.value,r))))}a(lQ,"searchAll");function _Q(e,t,r,n=!1,s=void 0,i=void 0){if(kr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);Z_(r),r=zc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of $I(e,t,t,n,s,i))o.set(c,X_.parseRow(u,r));return o}a(_Q,"searchAllToMap");function dQ(e,t,r=!1,n=void 0,s=void 0){if(kr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=$I(e,void 0,t,r,n,s),c=o.transaction,u=YI(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(dQ,"iterateDBI");function fQ(e,t){if(kr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return oi.statDBI(e,t).entryCount}a(fQ,"countAll");function EQ(e,t,r,n,s=!1,i=void 0,o=void 0){return ai(e,r,n),Xi(e,t,r,(c,u,_,l)=>(n=kr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(EQ,"equals");function hQ(e,t,r){return ai(e,t,r),oi.openDBI(e,t).getValuesCount(r)}a(hQ,"count");function mQ(e,t,r,n,s=!1,i=void 0,o=void 0){return ai(e,r,n),Xi(e,null,r,(c,u)=>{n=kr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(mQ,"startsWith");function pQ(e,t,r,n,s=!1,i=void 0,o=void 0){return KI(e,t,r,n,s,i,o,!0)}a(pQ,"endsWith");function KI(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ai(e,r,n),Xi(e,null,r,(u,_,l,d)=>{let f=YI(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(VI)?_.getValues(E,{transaction:u}).map(S=>{let p=f(E,S);if(c?p.endsWith(n):p.includes(n))return{key:p,value:S}}).filter(S=>S):(c?h.endsWith(n):h.includes(n))?_[j_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(S=>({key:E,value:S})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(KI,"contains");function SQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Qc(e,t,r,n,u,s,i,o,!0,!1)}a(SQ,"greaterThan");function TQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Qc(e,t,r,n,u,s,i,o,!1,!1)}a(TQ,"greaterThanEqual");function gQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Qc(e,t,r,u,n,s,i,o,!1,!0)}a(gQ,"lessThan");function RQ(e,t,r,n,s=!1,i=void 0,o=void 0){ai(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Qc(e,t,r,u,n,s,i,o,!1,!1)}a(RQ,"lessThanEqual");function AQ(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(kr.validateEnv(e),r===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(lt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(lt.END_VALUE_REQUIRED);if(n=kr.convertKeyValueToWrite(n),s=kr.convertKeyValueToWrite(s),n>s)throw new Error(lt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Qc(e,t,r,n,s,i,o,c)}a(AQ,"between");function OQ(e,t,r,n){kr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(Z_(r),r=zc(s,r),n===void 0)throw new Error(lt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=X_.parseRow(c,r)),o}a(OQ,"searchByHash");function bQ(e,t,r){kr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(bQ,"checkHashExists");function yQ(e,t,r,n,s=[]){return QI(e,t,r,n,s),WI(e,t,r,n,s).map(i=>i[1])}a(yQ,"batchSearchByHash");function NQ(e,t,r,n,s=[]){QI(e,t,r,n,s);let i=new Map;for(let[o,c]of WI(e,t,r,n,s))i.set(o,c);return i}a(NQ,"batchSearchByHashToMap");function WI(e,t,r,n,s=[]){return Xi(e,t,t,(i,o,c)=>{r=zc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,X_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(WI,"batchHashSearch");function QI(e,t,r,n,s){if(kr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(Z_(r),n==null)throw new Error(lt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(lt.IDS_MUST_BE_ITERABLE)}a(QI,"initializeBatchSearchByHash");function Z_(e){if(!Array.isArray(e))throw e===void 0?new Error(lt.FETCH_ATTRIBUTES_REQUIRED):new Error(lt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(Z_,"validateFetchAttributes");function ai(e,t,r){if(kr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.SEARCH_VALUE_REQUIRED);if(r?.length>uQ)throw new Error(lt.SEARCH_VALUE_TOO_LARGE)}a(ai,"validateComparisonFunctions");function zc(e,t){return t.length===1&&aQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=oi.listDBIs(e)),t}a(zc,"setGetWholeRowAttributes");zI.exports={searchAll:lQ,searchAllToMap:_Q,count:hQ,countAll:fQ,equals:EQ,startsWith:mQ,endsWith:pQ,contains:KI,searchByHash:OQ,setGetWholeRowAttributes:zc,batchSearchByHash:yQ,batchSearchByHashToMap:NQ,checkHashExists:bQ,iterateDBI:dQ,greaterThan:SQ,greaterThanEqual:TQ,lessThan:gQ,lessThanEqual:RQ,between:AQ}});var ta=R((Gue,ew)=>{var JI=require("lodash"),jI=et(),fe=require("joi"),IQ=Q(),{hdb_schema_table:Jc,checkValidTable:XI,hdb_table:ZI,hdb_database:ed}=zn(),{handleHDBError:wQ,hdb_errors:CQ}=ne(),{getDatabases:DQ}=(Re(),ie(qe)),{HTTP_STATUS_CODES:LQ}=CQ,MQ=fe.object({database:ed,schema:ed,table:ZI,search_attribute:Jc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(Jc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),UQ=fe.object({database:ed,schema:ed,table:ZI,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(Jc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(Jc,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(Jc,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()});ew.exports=function(e,t){let r=null;switch(t){case"value":r=jI.validateBySchema(e,MQ);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(XI("database",e.schema)),i(XI("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=jI.validateBySchema(e,UQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=IQ.checkGlobalSchemaTable(e.schema,e.table);if(s)return wQ(new Error,s,LQ.NOT_FOUND);let o=DQ()[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 _=JI.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!JI.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 bp=R((que,tw)=>{"use strict";var PQ=Ye(),vQ=ta(),{getSchemaPath:BQ}=Qe();tw.exports=HQ;function HQ(e){let t=vQ(e,"hashes");if(t)throw t;let r=BQ(e.schema,e.table);return PQ.openEnvironment(r,e.table)}a(HQ,"initialize")});var yp=R((Vue,rw)=>{"use strict";var xQ=ea(),GQ=bp();rw.exports=FQ;async function FQ(e){let t=await GQ(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return xQ.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(FQ,"lmdbGetDataByHash")});var ra=R((Yue,nw)=>{"use strict";var Np=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};nw.exports=Np});var iw=R((Que,sw)=>{"use strict";var Wue=ra(),qQ=ea(),kQ=bp();sw.exports=VQ;async function VQ(e){let t=await kQ(e),r=global.hdb_schema[e.schema][e.table];return qQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(VQ,"lmdbSearchByHash")});var Zn=R((Jue,ow)=>{"use strict";var Ip=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};ow.exports=Ip});var td=R((Xue,dw)=>{"use strict";var Xt=ea(),$Q=Ye(),YQ=Q(),Ee=ct(),Zi=U(),KQ=ki(),aw=Lr().LMDB_ERRORS_ENUM,{getSchemaPath:WQ}=Qe(),bs=Zi.SEARCH_WILDCARDS;async function QQ(e,t,r){let n;e.schema===Zi.SYSTEM_SCHEMA_NAME?n=KQ[e.table]:n=global.hdb_schema[e.schema][e.table];let s=_w(e,n.hash_attribute,r,t);return uw(e,s,n.hash_attribute,r)}a(QQ,"prepSearch");async function uw(e,t,r,n){let s=WQ(e.schema,e.table),i=await $Q.openEnvironment(s,e.table),o=lw(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(zQ(e,r)===!1){let l=e.search_attribute;if(l===r)return n?cw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?cw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Xt.batchSearchByHashToMap(c,r,e.get_attributes,_):Xt.batchSearchByHash(c,r,e.get_attributes,_)}a(uw,"executeSearch");function lw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=Xt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=Xt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=Xt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=Xt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Xt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Xt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Xt.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Xt.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=Xt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=Xt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Xt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=Xt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=Xt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(lw,"searchByType");function cw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(cw,"createMapFromIterable");function zQ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(zQ,"checkToFetchMore");function _w(e,t,r,n){if(YQ.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),bs.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(bs[0])<0&&s.indexOf(bs[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(bs.indexOf(i)>=0&&bs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(bs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(bs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(bs[0])||s.includes(bs[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(aw.UNKNOWN_SEARCH_TYPE)}else switch(n){case Zi.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case Zi.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case Zi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(aw.UNKNOWN_SEARCH_TYPE)}}a(_w,"createSearchTypeFromSearchObject");dw.exports={executeSearch:uw,createSearchTypeFromSearchObject:_w,prepSearch:QQ,searchByType:lw}});var Ew=R((tle,fw)=>{"use strict";var ele=Zn(),JQ=ta(),jQ=Q(),XQ=U(),ZQ=td();fw.exports=ez;function ez(e,t){if(!jQ.isEmpty(t)&&XQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=JQ(e,"value");if(n)throw n;return ZQ.prepSearch(e,t,!0)}a(ez,"lmdbGetDataByValue")});var jc=R((sle,hw)=>{"use strict";var nle=Zn(),tz=ta(),rz=Q(),nz=U(),sz=td();hw.exports=iz;async function iz(e,t){if(!rz.isEmpty(t)&&nz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=tz(e,"value");if(n)throw n;return sz.prepSearch(e,t,!1)}a(iz,"lmdbSearchByValue")});var pw=R((ale,mw)=>{"use strict";var ole=ct(),wp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},Cp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Dp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};mw.exports={SearchByConditionsObject:wp,SearchCondition:Cp,SortAttribute:Dp}});var Aw=R((_le,Rw)=>{"use strict";var ule=pw().SearchByConditionsObject,oz=Zn(),az=ta(),Lp=ea(),rd=ct(),{Resource:lle}=(In(),ie(Mp)),gw=td(),cz=Op(),uz=require("lodash"),{getSchemaPath:lz}=Qe(),Sw=Ye(),{handleHDBError:_z,hdb_errors:dz}=ne(),{HTTP_STATUS_CODES:fz}=dz,Ez=1e8;Rw.exports=hz;async function hz(e){let t=az(e,"conditions");if(t)throw _z(t,t.message,fz.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=lz(e.schema,e.table),n=await Sw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Sw.openDBI(n,_.search_attribute);let i=uz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===rd.SEARCH_TYPES.EQUALS?_.estimated_count=Lp.count(n,_.search_attribute,_.search_value):l===rd.SEARCH_TYPES.CONTAINS||l===rd.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Ez}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Tw(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(gw.filterByType),d=l.length,f=Lp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>cz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Tw(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Lp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(hz,"lmdbSearchByConditions");async function Tw(e,t,r,n){let s=new oz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===rd.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,gw.searchByType(e,s,i,n).map(o=>o.value)}a(Tw,"executeConditionSearch")});var Xc=R((fle,Ow)=>{"use strict";var mz=U().OPERATIONS_ENUM,Up=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=mz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Ow.exports=Up});var Pp=R((hle,Lw)=>{"use strict";var Iw=Zn(),ww=Xc(),Cw=jc(),Dw=Wc(),fr=U(),bw=Q(),yw=Ye(),{getTransactionAuditStorePath:pz,getSchemaPath:Sz}=Qe(),Nw=Y();Lw.exports=Tz;async function Tz(e){try{if(bw.isEmpty(global.hdb_schema[e.schema])||bw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await gz(e),await Rz(e);let t=Sz(e.schema,e.table);try{await yw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Nw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=pz(e.schema,e.table);await yw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Nw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Tz,"lmdbDropTable");async function gz(e){let t=new Iw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Cw(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new ww(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Dw(s)}a(gz,"deleteAttributesFromSystem");async function Rz(e){let t=new Iw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Cw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new ww(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Dw(s)}catch(i){throw i}}a(Rz,"dropTableFromSystem")});var Uw=R((ple,Mw)=>{"use strict";var Az=require("fs-extra"),Oz=Zn(),bz=ra(),yz=Xc(),Nz=Pp(),Iz=Wc(),wz=yp(),Cz=jc(),ys=U(),{getSchemaPath:Dz}=Qe(),{handleHDBError:Lz,hdb_errors:Mz}=ne(),{HDB_ERROR_MSGS:Uz,HTTP_STATUS_CODES:Pz}=Mz;Mw.exports=vz;async function vz(e){let t;try{t=await Bz(e.schema);let r=new Oz(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await Cz(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await Nz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new yz(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Iz(s);let i=Dz(t);await Az.remove(i)}catch(r){throw r}}a(vz,"lmdbDropSchema");async function Bz(e){let t=new bz(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await wz(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw Lz(new Error,Uz.SCHEMA_NOT_FOUND(e),Pz.NOT_FOUND,void 0,void 0,!0);return n}a(Bz,"validateDropSchema")});var Bp=R((Tle,Pw)=>{"use strict";var vp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Pw.exports=vp});var Bw=R((Ale,vw)=>{"use strict";var Hz=require("fs-extra"),nd=Ye(),{getTransactionAuditStorePath:xz}=Qe(),Hp=ct(),Rle=Bp();vw.exports=Gz;async function Gz(e){let t;try{let r=xz(e.schema,e.table);await Hz.mkdirp(r),t=await nd.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{nd.createDBI(t,Hp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),nd.createDBI(t,Hp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),nd.createDBI(t,Hp.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(Gz,"createTransactionsAuditEnvironment")});var Fw=R((ble,Gw)=>{"use strict";var xp=U(),Hw=Ye(),Fz=Vo(),{getSystemSchemaPath:qz,getSchemaPath:kz}=Qe(),Vz=ki(),$z=w_(),Gp=I_(),Yz=Y(),Kz=Bw(),qp=Vz.hdb_table,xw=[];for(let e=0;e<qp.attributes.length;e++)xw.push(qp.attributes[e].attribute);Gw.exports=Wz;async function Wz(e,t){let r=kz(t.schema,t.table),n=new Gp(t.schema,t.table,xp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Gp(t.schema,t.table,xp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Gp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Hw.createEnvironment(r,t.table),e!==void 0){let o=await Hw.openEnvironment(qz(),xp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Fz.insertRecords(o,qp.hash_attribute,xw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Fp(n),await Fp(s),await Fp(i)}await Kz(t)}catch(o){throw o}}a(Wz,"lmdbCreateTable");async function Fp(e){try{await $z(e)}catch(t){Yz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Fp,"createAttribute")});var kw=R((Nle,qw)=>{"use strict";var Qz=xc(),zz=Fc(),Jz=z_(),Zc=U(),jz=Vo().updateRecords,Xz=Ye(),{getSchemaPath:Zz}=Qe(),e2=Yc(),t2=Y();qw.exports=r2;async function r2(e){try{let{schema_table:t,attributes:r}=Qz(e);zz(e,r,t.hash_attribute),e.schema!==Zc.SYSTEM_SCHEMA_NAME&&(r.includes(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Jz(e.hdb_auth_header,t,r),s=Zz(e.schema,e.table),i=await Xz.openEnvironment(s,e.table),o=await jz(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await e2(e,o)}catch(c){t2.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(r2,"lmdbUpdateRecords")});var $w=R((wle,Vw)=>{"use strict";var n2=U().OPERATIONS_ENUM,kp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=n2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Vw.exports=kp});var Kw=R((Lle,Yw)=>{"use strict";var Dle=$w(),s2=xc(),i2=Fc(),o2=z_(),eu=U(),a2=Vo().upsertRecords,c2=Ye(),{getSchemaPath:u2}=Qe(),l2=Yc(),_2=Y(),{handleHDBError:d2,hdb_errors:f2}=ne();Yw.exports=E2;async function E2(e){let t;try{t=s2(e)}catch(u){throw d2(u,u.message,f2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;i2(e,n,r.hash_attribute),e.schema!==eu.SYSTEM_SCHEMA_NAME&&(n.includes(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await o2(e.hdb_auth_header,r,n),i=u2(e.schema,e.table),o=await c2.openEnvironment(i,e.table),c=await a2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await l2(e,c)}catch(u){_2.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(E2,"lmdbUpsertRecords")});var Qw=R((Ule,Ww)=>{"use strict";var Vp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};Ww.exports=Vp});var Jw=R((vle,zw)=>{"use strict";var $p=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};zw.exports=$p});var Zw=R((xle,Xw)=>{"use strict";var Yp=Ye(),{getTransactionAuditStorePath:h2}=Qe(),Hle=Qw(),tu=ct(),m2=Q(),jw=Jw(),p2=require("util").promisify,S2=p2(setTimeout),T2=1e4,g2=100;Xw.exports=R2;async function R2(e){let t=h2(e.schema,e.table),r=await Yp.openEnvironment(t,e.table,!0),n=Yp.listDBIs(r);Yp.initializeDBIs(r,tu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new jw;do s=await A2(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await S2(g2);while(s.transactions_deleted>0);return i}a(R2,"deleteAuditLogsBefore");async function A2(e,t){let r=new jw;try{let n=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];m2.isEmpty(c)||(s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>T2)break}return await s,r}catch(n){throw n}}a(A2,"deleteTransactions")});var tC=R((Fle,eC)=>{"use strict";var Kp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};eC.exports=Kp});var nC=R((Vle,rC)=>{"use strict";var O2=Zn(),b2=Xc(),kle=tC(),es=U(),y2=Q(),Wp=Ye(),N2=ki(),I2=jc(),w2=Wc(),{getSchemaPath:C2}=Qe();rC.exports=D2;async function D2(e,t=!0){let r;e.schema===es.SYSTEM_SCHEMA_NAME?r=N2[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await M2(e),s=C2(e.schema,e.table),i=await Wp.openEnvironment(s,e.table);return t===!0&&await L2(e,i,r.hash_attribute),Wp.dropDBI(i,e.attribute),n}a(D2,"lmdbDropAttribute");async function L2(e,t,r){let n=Wp.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(L2,"removeAttributeFromAllObjects");async function M2(e){let t=new O2(es.SYSTEM_SCHEMA_NAME,es.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await I2(t)).filter(o=>o[es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(y2.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[es.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new b2(es.SYSTEM_SCHEMA_NAME,es.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return w2(i)}a(M2,"dropAttributeFromSystem")});var uC=R((Kle,cC)=>{"use strict";var Qp=Ye(),na=ct(),Yle=Pr(),zp=U(),sC=Q(),{getTransactionAuditStorePath:U2}=Qe(),P2=ea(),sd=jo(),v2=Y();cC.exports=B2;async function B2(e){let t=U2(e.schema,e.table),r=await Qp.openEnvironment(t,e.table,!0),n=Qp.listDBIs(r);Qp.initializeDBIs(r,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case zp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return iC(r,e.search_values);case zp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,x2(r,e.search_values,s);case zp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return H2(r,e.search_values);default:return iC(r)}}a(B2,"readAuditLog");function iC(e,t=[0,Date.now()]){sC.isEmpty(t[0])&&(t[0]=0),sC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new sd,s))}a(iC,"searchTransactionsByTimestamp");function H2(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,aC(e,i))}return Object.fromEntries(r)}a(H2,"searchTransactionsByUsername");function x2(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=P2.equals(e,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,na.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=aC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);oC(u,"records",r,l,o),oC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(x2,"searchTransactionsByHashValues");function oC(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new sd(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new sd(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(oC,"loopRecords");function aC(e,t){let r=[];try{let n=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new sd,i);r.push(o)}}catch(i){v2.warn(i)}return r}catch(n){throw n}}a(aC,"batchSearchTransactions")});var _C=R((Jle,lC)=>{"use strict";var{getSchemaPath:Qle}=Qe(),zle=Ye(),{database:G2}=(Re(),ie(qe));lC.exports={writeTransaction:F2};async function F2(e,t,r){return G2({database:e,table:t}).transaction(r)}a(F2,"writeTransaction")});var hC=R((Xle,EC)=>{"use strict";var{getSchemaPath:dC}=Qe(),fC=Ye();EC.exports={flush:q2,resetReadTxn:k2};async function q2(e,t){return(await fC.openEnvironment(dC(e,t),t.toString())).flushed}a(q2,"flush");async function k2(e,t){try{(await fC.openEnvironment(dC(e,t),t.toString())).resetReadTxn()}catch{}}a(k2,"resetReadTxn")});var TC=R((e_e,SC)=>{"use strict";var{Readable:V2}=require("stream"),{getDatabases:$2}=(Re(),ie(qe)),{readSync:Y2,openSync:K2,createReadStream:mC}=require("fs"),{open:W2}=require("lmdb"),pC=Lc(),Q2=Mc(),{AUDIT_STORE_OPTIONS:z2}=(Zs(),ie(gC)),{INTERNAL_DBIS_NAME:J2,AUDIT_STORE_NAME:j2}=ct();SC.exports=Z2;var Jp=32768,X2=100;async function Z2(e){let t=e.database||e.schema||"data",r=$2()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=W2({noSync:!0,maxDbs:Q2.MAX_DBS}),f,E=d.openDB(J2,new pC(!1)),h=l.useReadTransaction(),S=0,p=a(async function(b,g){g.encoding="binary",g.encoder=void 0;let L=d.openDB(b,g),v=l.openDB(b,g);for(let{key:P,version:k,value:H}of v.getRange({start:null,transaction:h,versions:v.useVersions}))f=L.put(P,H,k),S++%X2===0&&(await new Promise(j=>setTimeout(j,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:b,value:g}of l.getRange({transaction:h,start:!1}))if(s.some(L=>b.startsWith?.(L+"/"))){E.put(b,g);let[,L]=b.split("/"),v=!L,P=new pC(!v,v);await p(b,P)}e.include_audit&&await p(j2,Object.assign({},z2)),await f;let T=mC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=K2(o.path);return o.transaction(()=>{let _=Buffer.alloc(Jp);Y2(c,_,0,Jp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=mC(null,{fd:c,start:Jp}),f=new V2.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(Z2,"getBackup")});var OC=R((r_e,AC)=>{"use strict";var eJ=Y(),{handleHDBError:tJ}=ne(),rJ=Zb(),nJ=w_(),sJ=Sp(),iJ=UI(),oJ=Wc(),aJ=yp(),cJ=iw(),uJ=Ew(),lJ=jc(),_J=Aw(),dJ=Uw(),fJ=Fw(),EJ=kw(),hJ=Kw(),mJ=Zw(),pJ=Pp(),SJ=nC(),TJ=uC(),gJ=_C(),RC=hC(),RJ=TC(),jp=class extends rJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return _J(t)}async getDataByHash(t){return await aJ(t)}async searchByHash(t){return await cJ(t)}async getDataByValue(t,r){return await uJ(t,r)}async searchByValue(t){return await lJ(t)}async createSchema(t){return await iJ(t)}async dropSchema(t){return await dJ(t)}async createTable(t,r){return await fJ(t,r)}async dropTable(t){return await pJ(t)}async createAttribute(t){return await nJ(t)}async createRecords(t){return await sJ(t)}async updateRecords(t){return await EJ(t)}async upsertRecords(t){try{return await hJ(t)}catch(r){throw tJ(r,null,null,eJ.ERR,r)}}async deleteRecords(t){return await oJ(t)}async dropAttribute(t){return await SJ(t)}async deleteAuditLogsBefore(t){return await mJ(t)}async readAuditLog(t){return await TJ(t)}writeTransaction(t,r,n){return gJ.writeTransaction(t,r,n)}flush(t,r){return RC.flush(t,r)}resetReadTxn(t,r){return RC.resetReadTxn(t,r)}getBackup(t){return RJ(t)}};AC.exports=jp});function NJ(){yJ=setInterval(function(){for(let e of Xp)if(e.stale){let t=e[ye]?.url;NC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},bJ).unref()}var Zp,yC,NC,AJ,Xp,OJ,ru,bC,eo,id,bJ,yJ,eS=ge(()=>{Zp=B(Pr()),yC=B(ne()),NC=B(Y());In();AJ=100,Xp=new Set,OJ=25e3,eo=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),Xp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Xp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(ru&&performance.now()-bC>OJ)throw new yC.ServerError("Outstanding write transactions have too long of queue, please try again later",503)}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,Zp.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let S=this.writes[h];if(!S)continue;let p=S[f===0?"before":"beforeIntermediate"];if(p){let T=p();E?E.push?E.push(T):E=[E,T]:E=T}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<AJ>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return ru||(ru=s,bC=performance.now(),ru.then(()=>{ru=null})),s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},id=class extends eo{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Zp.getNextMonotonicTime)())}getReadTxn(){}},bJ=3e4;a(NJ,"startMonitoringTxns");NJ()});function ze(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new eo;e.timestamp&&(n.timestamp=e.timestamp),n[ye]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var IC,to=ge(()=>{IC=require("../../index");In();eS();a(ze,"transaction");(0,IC._assignPackageExport)("transaction",ze);ze.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};ze.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var BC={};Fe(BC,{ResourceBridge:()=>nS});function sS({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 CC(e,t){let r=ts(e),n=sS(e,r);if(!r)throw new Mn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&ad(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 ts(e){let t=e.database||e.schema||wJ,r=Er()[t];if(!r)throw(0,Mn.handleHDBError)(new Error,IJ.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function DC(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*LC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var MC,od,Mn,UC,PC,Un,tS,rS,vC,IJ,wJ,CJ,DJ,wC,nS,HC=ge(()=>{"use strict";MC=B(OC()),od=B(ta()),Mn=B(ne());Re();UC=B(xc()),PC=B(Fc()),Un=B(U()),tS=B(Os()),rS=B(Ln()),vC=B(Q());to();cd();({HDB_ERROR_MSGS:IJ}=Mn.hdb_errors),wJ="data",CJ=1e4,DJ=10,nS=class extends MC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),wC=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,od.default)(t,"conditions");if(r)throw(0,Mn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=ts(t);if(!n)throw new Mn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:sS(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Mn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ut({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await ts(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=ts(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){ts(t).dropTable()}createSchema(t){return nu({database:t.schema,table:null}),tS.signalSchemaChange(new rS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await iS(t.schema),tS.signalSchemaChange(new rS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,wC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,UC.default)(t);(0,PC.default)(t,n,r.primaryKey);let s,i=Er()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=ad(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=Er()[t.schema][t.table],n={user:t.hdb_user};return ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return DC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=Er()[t.schema][t.table];if(!r.createdTimeProperty)throw new Mn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,vC.async_set_timeout)(DJ),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%CJ===0&&await _();return u.length>0&&await _(),s?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,od.default)(t,"hashes");if(r)throw r;return CC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of CC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,od.default)(t,"value");if(n)throw n;let s=ts(t);if(!s)throw new Mn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Un.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:sS(t,s)})}async getDataByValue(t,r){let n=new Map,s=ts(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){ts({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return ts(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=ts(t),n={};switch(t.search_type){case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of LC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return LC(r,t.search_values?.[0],t.search_values?.[1])}}};a(sS,"getSelect");a(CC,"getRecords");a(ts,"getTable");a(DC,"createDeleteResponse");a(LC,"groupRecordsInHistory")});var Dn=R((p_e,xC)=>{"use strict";var{ResourceBridge:LJ}=(HC(),ie(BC)),MJ=re();MJ.initSync();var ud;function UJ(){return ud||(ud=new LJ,ud)}a(UJ,"getBridge");xC.exports=UJ()});var kC=R((T_e,qC)=>{"use strict";var GC=require("lodash"),su=require("mathjs"),PJ=require("jsonata"),FC=Q();qC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?GC.uniqWith(e,GC.isEqual):e,searchJSON:vJ,mad:iu.bind(null,su.mad),mean:iu.bind(null,su.mean),mode:iu.bind(null,su.mode),prod:iu.bind(null,su.prod),median:iu.bind(null,su.median)};function iu(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(iu,"aggregateFunction");function vJ(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(FC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),FC.isEmpty(this.__ala__.res[r])){let n=PJ(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(vJ,"searchJSON")});var $C=R((R_e,VC)=>{"use strict";var pt=require("moment"),oS="YYYY-MM-DDTHH:mm:ss.SSSZZ";pt.suppressDeprecationWarnings=!0;VC.exports={current_date:()=>pt().utc().format("YYYY-MM-DD"),current_time:()=>pt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return pt(e).utc().format("YYYY");case"month":return pt(e).utc().format("MM");case"day":return pt(e).utc().format("DD");case"hour":return pt(e).utc().format("HH");case"minute":return pt(e).utc().format("mm");case"second":return pt(e).utc().format("ss");case"millisecond":return pt(e).utc().format("SSS");default:break}},date:e=>pt(e).utc().format(oS),date_format:(e,t)=>pt(e).utc().format(t),date_add:(e,t,r)=>pt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>pt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=pt(e).utc(),s=pt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>pt().utc().valueOf(),get_server_time:()=>pt().format(oS),offset_utc:(e,t)=>pt(e).utc().utcOffset(t).format(oS)}});var QC=R((A_e,WC)=>{"use strict";var BJ=require("@turf/area"),HJ=require("@turf/length"),xJ=require("@turf/circle"),GJ=require("@turf/difference"),FJ=require("@turf/distance"),qJ=require("@turf/boolean-contains"),kJ=require("@turf/boolean-equal"),VJ=require("@turf/boolean-disjoint"),$J=require("@turf/helpers"),YC=U(),Se=Q(),Ns=Y();WC.exports={geoArea:YJ,geoLength:KJ,geoCircle:WJ,geoDifference:QJ,geoDistance:KC,geoNear:zJ,geoContains:JJ,geoEqual:jJ,geoCrosses:XJ,geoConvert:ZJ};function YJ(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return BJ.default(e)}catch(t){return Ns.trace(t,e),NaN}}a(YJ,"geoArea");function KJ(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return HJ.default(e,{units:t||"kilometers"})}catch(r){return Ns.trace(r,e),NaN}}a(KJ,"geoLength");function WJ(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return xJ.default(e,t,{units:r||"kilometers"})}catch(n){return Ns.trace(n,e,t),NaN}}a(WJ,"geoCircle");function QJ(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return GJ(e,t)}catch(r){return Ns.trace(r,e,t),NaN}}a(QJ,"geoDifference");function KC(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return FJ.default(e,t,{units:r||"kilometers"})}catch(n){return Ns.trace(n,e,t),NaN}}a(KC,"geoDistance");function zJ(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return KC(e,t,n)<=r}catch(s){return Ns.trace(s,e,t),!1}}a(zJ,"geoNear");function JJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return qJ.default(e,t)}catch(r){return Ns.trace(r,e,t),!1}}a(JJ,"geoContains");function jJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return kJ.default(e,t)}catch(r){return Ns.trace(r,e,t),!1}}a(jJ,"geoEqual");function XJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!VJ.default(e,t)}catch(r){return Ns.trace(r,e,t),!1}}a(XJ,"geoCrosses");function ZJ(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(YC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(YC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),$J[t](e,r)}a(ZJ,"geoConvert")});var ld=R((b_e,zC)=>{var ro=kC(),Vr=$C(),rs=QC();zC.exports=e=>{e.aggr.mad=e.aggr.MAD=ro.mad,e.aggr.mean=e.aggr.MEAN=ro.mean,e.aggr.mode=e.aggr.MODE=ro.mode,e.aggr.prod=e.aggr.PROD=ro.prod,e.aggr.median=e.aggr.MEDIAN=ro.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ro.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ro.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Vr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Vr.current_time,e.fn.extract=e.fn.EXTRACT=Vr.extract,e.fn.date=e.fn.DATE=Vr.date,e.fn.date_format=e.fn.DATE_FORMAT=Vr.date_format,e.fn.date_add=e.fn.DATE_ADD=Vr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Vr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Vr.date_diff,e.fn.now=e.fn.NOW=Vr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Vr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Vr.get_server_time,e.fn.getdate=e.fn.GETDATE=Vr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Vr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=rs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=rs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=rs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=rs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=rs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=rs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=rs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=rs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=rs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=rs.geoNear}});var ZC=R((y_e,XC)=>{"use strict";var ou=require("lodash"),hr=require("alasql");hr.options.cache=!1;var e4=ld(),JC=require("clone"),_d=require("recursive-iterator"),le=Y(),De=Q(),sa=Dn(),t4=U(),{hdb_errors:r4}=ne(),{getDatabases:jC}=(Re(),ie(qe)),n4="IS NULL",Pn="There was a problem performing this search. Please check the logs and try again.";e4(hr);var aS=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.isEmpty(t))throw le.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.isEmptyOrZeroLength(n))return le.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(n),new Error(Pn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(n),new Error(Pn)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(n),new Error(Pn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(n),new Error(Pn)}try{return t=await this._finalSQL(),t}catch(n){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(n),new Error(Pn)}}_getColumns(){let t=new _d(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(JC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=ou.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=jC()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new _d(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new hr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new hr.yy.LogicValue({value:i}):n instanceof hr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new hr.yy.NumValue({value:i}))});if(t){le.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new _d(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!De.isEmpty(t4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.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(De.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"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&ou.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await hr.promise(r)}catch(r){throw le.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),le.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(JC(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(De.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(n4)>-1&&this.tables.forEach(s=>{let i={columnid:jC()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=ou.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await sa.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Pn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await sa.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Pn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.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 sa.getDataByValue(c,E.operation);if(u)for(let[S]of h)this.data[i].__merged_data[S]||(this.data[i].__merged_data[S]=[...n[i]],this._setMergedHashAttribute(i,S));else for(let[S,p]of h)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]):(this.data[i].__merged_data[S]=[...n[i]],this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]),this._setMergedHashAttribute(i,S))}}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(Pn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await sa.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(Pn)}}}_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 hr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new hr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new hr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new hr.yy.FuncValue:new hr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,S=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${S}.${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 "${S}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await hr.promise(h,t),t=null}catch(E){throw le.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),le.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let S=f[E];o.forEach(p=>{S[p.key]!==null&&S[p.key]!==void 0&&p.keys.add(S[p.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),S=ou.difference(h,[...E.keys].map(p=>p.toString()));for(let p=0,T=S.length;p<T;p++){let b=S[p];delete this.data[`${E.schema}_${E.table}`].__merged_data[b]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new _d(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=ou.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(Pn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await sa.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let S=s.columns[h],p=E[S]===void 0?null:E[S];this.data[n].__merged_data[f].push(p)}}}}catch(r){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getData."),le.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();le.trace(`Final SQL: ${s}`),n=await hr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),le.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return le.error(r4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),le.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await sa.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(Pn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};XC.exports=aS});var xr=R((I_e,eD)=>{"use strict";var s4=jb();eD.exports={searchByConditions:o4,searchByHash:a4,searchByValue:c4,search:u4};var cS=Dn(),{transformReq:uS}=Q(),i4=ZC();async function o4(e){return uS(e),cS.searchByConditions(e)}a(o4,"searchByConditions");async function a4(e){uS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of cS.searchByHash(e))r&&t.push(r);return t}a(a4,"searchByHash");async function c4(e){uS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of cS.searchByValue(e))t.push(r);return t}a(c4,"searchByValue");function u4(e,t){try{let r=new s4(e);r.validate(),new i4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(u4,"search")});var dd=R((C_e,tD)=>{"use strict";var l4=Dn();tD.exports={writeTransaction:_4};function _4(e,t,r){return l4.writeTransaction(e,t,r)}a(_4,"writeTransaction")});var iD=R((M_e,sD)=>{"use strict";var d4=xr(),f4=As(),rD=Y(),E4=an(),L_e=dd(),h4=require("clone"),_S=require("alasql"),m4=ld(),nD=require("util"),p4=nD.promisify(f4.getTableSchema),S4=nD.promisify(d4.search),T4=U(),lS=Q();m4(_S);sD.exports={update:R4};var g4="There was a problem performing this update. Please check the logs and try again.";async function R4({statement:e,hdb_user:t}){let r=await p4(e.table.databaseid,e.table.tableid),n=A4(e.columns);lS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=h4(s),c=lS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=_S.parse(u).statements[0],l=await S4(_),d=O4(n,l);return b4(o,d,t)}a(R4,"update");function A4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=_S.compile(`SELECT ${r.expression.toString()} AS [${T4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw rD.error(t),new Error(g4)}}a(A4,"createUpdateRecord");function O4(e,t){return lS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(O4,"buildUpdateRecords");async function b4(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await E4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){rD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(b4,"updateRecords")});var aD=R((B_e,oD)=>{var y4=require("alasql"),N4=xr(),I4=Y(),w4=Dn(),fS=require("util"),dS=Q(),C4=U(),D4=As(),P_e=dd(),v_e=an(),L4="record",M4="successfully deleted",U4=fS.callbackify(H4),P4=fS.promisify(N4.search),v4=fS.promisify(D4.getTableSchema);oD.exports={convertDelete:U4};function B4(e){return`${e.deleted_hashes.length} ${L4}${e.deleted_hashes.length===1?"":"s"} ${M4}`}a(B4,"generateReturnMessage");async function H4({statement:e,hdb_user:t}){let r=await v4(e.table.databaseid,e.table.tableid);dS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=dS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=y4.parse(o).statements[0],u={operation:C4.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await P4(c);let _=await w4.deleteRecords(u);return dS.isEmptyOrZeroLength(_.message)&&(_.message=B4(_)),delete _.txn_time,_}catch(_){throw I4.error(_),_.hdb_code?_.message:_}}a(H4,"convertDelete")});var dD=R((x_e,_D)=>{"use strict";var x4=ri(),{hdb_errors:cD}=ne(),{getDatabases:uD}=(Re(),ie(qe));_D.exports={checkSchemaExists:lD,checkSchemaTableExists:G4,schema_describe:x4};async function lD(e){if(!uD()[e])return cD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(lD,"checkSchemaExists");async function G4(e,t){let r=await lD(e);if(r)return r;if(!uD()[e][t])return cD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(G4,"checkSchemaTableExists")});var au=R((F_e,F4)=>{F4.exports={name:"harperdb",version:"4.3.4",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},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/client-s3":"3.535.0","@aws-sdk/lib-storage":"3.535.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@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.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","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.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.4",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","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.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.3","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.16.0",yaml:"2.4.1"},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.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",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.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",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.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var du={};Fe(du,{addAnalyticsListener:()=>_u,recordAction:()=>$r,recordActionBinary:()=>cn,setAnalyticsEnabled:()=>q4});function q4(e){RD=e}function $r(e,t,r,n,s){if(!RD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=hd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},hd.set(i,o)}fd||k4()}function cn(e,t,r,n,s){$r(!!e,t,r,n,s)}function _u(e){bD.push(e)}function k4(){fd=performance.now(),setTimeout(async()=>{let e=performance.now()-fd;fd=0;let t=[],r={time:Date.now(),period:e,threadId:no.threadId,metrics:t};for(let[s,i]of hd){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 yD){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let S=_[_.length-1];typeof S=="number"?_[_.length-1]={value:S,count:1+h}:S.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 ND()}let n=process.memoryUsage();t.push({metric:"memory",threadId:no.threadId,byThread:!0,...n});for(let s of bD)s(t);hd=new Map,no.parentPort?no.parentPort.postMessage({type:OD,report:r}):CD({report:r})},AD).unref()}async function V4(e,t=6e4){let r=mS(),n=ID(),s=new Promise(S=>{let p=performance.now();setImmediate(()=>{let T=performance.now();T-p>5e3&&(0,cu.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-p)+"ms"),p=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-p>5e3&&(0,cu.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-p)+"ms"),S(T-p)})}),i;for(let S of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(S.value?.time){i=S.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:S,value:p}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(o){if(S>o+t)break}else o=S;l=S;let{metrics:T,threadId:b}=p;for(let g of T||[]){let{path:L,method:v,type:P,metric:k,count:H,total:j,distribution:z,threads:J,...me}=g;H||(H=1);let ce=k+(L?"-"+L:"");v!==void 0&&(ce+="-"+v),P!==void 0&&(ce+="-"+P);let de=c.get(ce);if(de){if(de.threads){let Be=de.threads[b];if(Be)de=Be;else{de.threads[b]=Object.assign({},me);continue}}de.count||(de.count=1);let Le=de.count;for(let Be in me){let Lt=me[Be];typeof Lt=="number"&&(de[Be]=(de[Be]*Le+Lt*H)/(Le+H))}de.count+=H,j>=0&&(de.total+=j,de.ratio=de.total/de.count)}else de=Object.assign({period:t},g),delete de.distribution,c.set(ce,de),de.byThread&&(de.threads=[],de.threads[b]=Object.assign({},me),_.push(de));if(z){z=z.map(Be=>typeof Be=="number"?{value:Be,count:1}:Be);let Le=u.get(ce);Le?Le.push(...z):u.set(ce,z)}}await ND()}for(let S of _){let{path:p,method:T,type:b,metric:g,count:L,total:v,distribution:P,threads:k,...H}=S;k=k.filter(j=>j);for(let j in H){if(typeof S[j]!="number")continue;let z=0;for(let J of k){let me=J[j];typeof me=="number"&&(z+=me)}S[j]=z}S.count=k.length,delete S.threads,delete S.byThread}for(let[S,p]of u){let T=c.get(S);p.sort((Be,Lt)=>Be.value>Lt.value?1:-1);let b=T.count-1,g=[],L=0,v=0,P;for(let Be of yD){let Lt=b*Be;for(;L<Lt;)P=p[v++],L+=P.count,v===1&&L--;let Vl=p[v>1?v-2:0];P||(P=p[0]),g.push(P.value-(P.value-Vl.value)*(L-Lt)/P.count)}let[k,H,j,z,J,me,ce,de,Le]=g;Object.assign(T,{p1:k,p10:H,p25:j,median:z,p75:J,p90:me,p95:ce,p99:de,p999:Le})}let d;for(let[S,p]of c)p.id=(0,Ed.getNextMonotonicTime)(),p.time=l,n.primaryStore.put(p.id,p,{append:!0}).then(T=>{T||n.primaryStore.put(p.id,p)}),d=!0;let f=Date.now(),{idle:E,active:h}=performance.eventLoopUtilization();if(d||h*10>E){let S=(0,Ed.getNextMonotonicTime)(),p={id:S,metric:"main-thread-utilization",idle:E-fD,active:h-ED,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(S,p,{append:!0}).then(T=>{T||n.primaryStore.put(S,p)})}fD=E,ED=h}async function hD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function mS(){return mD||(mD=ut({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function ID(){return pD||(pD=ut({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function K4(){wD=!0;let e=(0,lu.get)(hS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await V4(AD,e),await hD(mS(),$4),await hD(ID(),Y4)},Math.min(e/2,2147483647)).unref()}function CD(e,t){let r=e.report;r.threadId=t?.threadId||no.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(SD+=n.mean*n.count);r.totalBytesProcessed=SD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(TD.get(t))}),TD.set(t,t.performance.eventLoopUtilization())),r.id=(0,Ed.getNextMonotonicTime)(),mS().primaryStore.put(r.id,r),wD||K4(),W4&&(DD=z4(r))}async function z4(e){if(await DD,!ci){let r=(0,uu.dirname)((0,cu.getLogFilePath)());try{ci=await(0,ES.open)((0,uu.join)(r,"analytics.log"),"r+")}catch{ci=await(0,ES.open)((0,uu.join)(r,"analytics.log"),"w+")}}let t=(await ci.stat()).size;if(t>Q4){let r=Buffer.alloc(t);await ci.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ci.write(r,{position:0}),await ci.truncate(r.length),t=r.length}await ci.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var no,gD,cu,uu,ES,Ed,lu,hS,hd,RD,fd,AD,OD,bD,yD,fD,ED,ND,$4,Y4,mD,pD,wD,SD,TD,W4,DD,ci,Q4,Is=ge(()=>{no=require("worker_threads"),gD=B(rt());Re();cu=B(Y()),uu=require("path"),ES=require("fs/promises"),Ed=B(Pr()),lu=B(re()),hS=B(U());cr();(0,lu.initSync)();hd=new Map,RD=(0,lu.get)(hS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(q4,"setAnalyticsEnabled");a($r,"recordAction");tt.recordAnalytics=$r;a(cn,"recordActionBinary");fd=0,AD=1e3,OD="analytics-report",bD=[];a(_u,"addAnalyticsListener");yD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(k4,"sendAnalytics");a(V4,"aggregation");fD=0,ED=0,ND=a(()=>new Promise(setImmediate),"rest");a(hD,"cleanup");$4=36e5,Y4=31536e6;a(mS,"getRawAnalyticsTable");a(ID,"getAnalyticsTable");(0,gD.setChildListenerByType)(OD,CD);a(K4,"startScheduledTasks");SD=0,TD=new Map,W4=!1;a(CD,"recordAnalytics");Q4=1e6;a(z4,"logAnalytics")});var AS=R((Z_e,FD)=>{"use strict";var{decode:J4}=require("msgpackr"),{isMainThread:J_e,parentPort:j_e,threadId:X_e}=require("worker_threads"),fu=St(),ia=st(),TS=U(),Zt=Y(),SS=re(),j4=U(),{onMessageByType:X4}=rt(),UD=Rs(),{recordAction:Z4,recordActionBinary:e3}=(Is(),ie(du)),{publishToStream:t3}=fu,{ConsumerEvents:LD}=require("nats"),r3=xr(),{promisify:n3}=require("util"),PD=n3(setTimeout),Sd=1e4,Td,pd,s3,i3,vD,Eu=new Map,oa=new Map;FD.exports={initialize:gS,ingestConsumer:RS,setSubscription:o3,setIgnoreOrigin:u3,getDatabaseSubscriptions:c3,updateConsumer:BD};async function gS(){X4(TS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await BD(n)}),vD=!0,Zt.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await fu.getNATSReferences();Td=e,pd=e.info.server_name,s3=t,i3=r}a(gS,"initialize");async function BD(e){if(e.status==="start"){let{js:t,jsm:r}=await HD(e.node_domain_name);RS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=Eu.get(e.stream_name+e.node_domain_name);t&&(Zt.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),Eu.set(e.stream_name+e.node_domain_name,"close")),oa.get(e.node_domain_name)==="failed"&&oa.set(e.node_domain_name,"close")}}a(BD,"updateConsumer");var gd=new Map;function o3(e,t,r){let n=gd.get(e);n||gd.set(e,n=new Map),n.set(t,r),vD||gS().then(a3)}a(o3,"setSubscription");async function a3(){let e=await r3.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+ia.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await HD(r),!n))break;let{schema:o,table:c}=i,u=UD.createNatsTableStreamName(o,c);RS(u,n,s,r)}}}a(a3,"accessConsumers");async function HD(e){let t,r,n=1;for(;!r;)try{t=await Td.jetstream({domain:e}),r=await Td.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(oa.get(e)==="close")break;oa.set(e,"failed"),n%10===1&&Zt.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<Sd?n++*100:Sd;await PD(i)}return{js:t,jsm:r}}a(HD,"connectToRemoteJS");function c3(){return gd}a(c3,"getDatabaseSubscriptions");var xD;function u3(e){xD=e}a(u3,"setIgnoreOrigin");var GD=100,MD=new Array(GD),md=0;async function RS(e,t,r,n){let{connection:s}=await fu.getNATSReferences();Td=s,pd=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,pd),Zt.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(oa.get(n)==="close")break;o%10===1&&Zt.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(Zt.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await fu.createConsumer(r,e,pd,new Date(Date.now()).toISOString()));let l=o++*100<Sd?o++*100:Sd;await PD(l)}let c=!1,u;for(;!c;){if(Eu.get(e+n)==="close"||oa.get(n)==="close"){Eu.delete(e+n),c=!0;continue}u=await i.consume({max_messages:SS.get(TS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100}),Eu.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===LD.ConsumerDeleted&&(await u.close(),c=!0),l.type===LD.HeartbeatsMissed){let d=l.data;Zt.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===2&&(Zt.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await MD[md],MD[md]=l3(l).catch(d=>{Zt.error(d)}),++md>=GD&&(md=0)}catch(l){l.message==="consumer deleted"?(Zt.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):Zt.error("Error consuming clustering ingest, restarting consumer",l)}fu.clearClientCache(),!c&&_&&await gS()}}a(RS,"ingestConsumer");async function l3(e){let t=J4(e.data);Z4(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),Zt.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=SS.get(TS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(ia.MSG_HEADERS.TRANSACTED_NODES)&&r.values(ia.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(ia.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!xD),e3(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(ia.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Zt.trace("processing message:",o,c,_,(l?"records: "+l.map(L=>L?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Zt.trace(`messageProcessor nats msg id: ${e.headers.get(ia.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let S=new Promise(L=>h=L),{timestamp:p,user:T,node_name:b}=f||{},g=gd.get(c)?.get(_);if(!g)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,g.send(t);else if(l.length===1&&!u)g.send({type:pS(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:T,nodeName:b});else{let L=l.map((v,P)=>({type:pS(o),value:v,expiresAt:E,id:d?.[P],table:_}));for(;u;)L.push({type:pS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;g.send({type:"transaction",writes:L,table:_,timestamp:p,onCommit:h,user:T,nodeName:b})}SS.get(j4.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&t3(e.subject.split(".").slice(0,-1).join("."),UD.createNatsTableStreamName(c,_),e.headers,e.data),await S}catch(o){Zt.error(o)}e.ack()}a(l3,"messageProcessor");function pS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(pS,"convertOperation")});var St=R((ode,nL)=>{"use strict";var Pt=re();Pt.initSync();var _3=require("fs-extra"),d3=require("semver"),pu=require("path"),{monotonicFactory:f3}=require("ulidx"),kD=f3(),E3=require("util"),VD=require("child_process"),h3=E3.promisify(VD.exec),m3=VD.spawn,Vt=st(),Ne=U(),Rd=Q(),vn=Y(),Ad=Rs(),p3=dd(),hu=lr(),{broadcast:S3,onMessageByType:T3,getWorkerIndex:g3}=rt(),{isMainThread:$D}=require("worker_threads"),{Encoder:R3,decode:NS}=require("msgpackr"),YD=new R3,{isEmpty:ao}=Rd,KD=Fr(),tde=48*36e11;$D&&T3(Ne.ITC_EVENT_TYPES.RESTART,()=>{mr=void 0,oo=void 0});var{connect:A3,StorageType:O3,RetentionPolicy:b3,AckPolicy:IS,DeliverPolicy:wS,DiscardPolicy:y3,NatsConnection:rde,JetStreamManager:nde,JetStreamClient:sde,StringCodec:ide,JSONCodec:N3,createInbox:CS,headers:I3,ErrorCode:qD}=require("nats"),{PACKAGE_ROOT:w3}=U(),C3=au(),{recordAction:D3}=(Is(),ie(du)),WD=N3(),L3="clustering",M3=C3.engines[Vt.NATS_SERVER_NAME],U3=pu.join(w3,"dependencies"),yS=pu.join(U3,`${process.platform}-${process.arch}`,Vt.NATS_BINARY_NAME),OS,bS,mu,so,io;nL.exports={runCommand:QD,checkNATSServerInstalled:P3,createConnection:DS,getConnection:Su,getJetStreamManager:Tu,getJetStream:JD,getNATSReferences:ns,getServerList:B3,createLocalStream:LS,listStreams:jD,deleteLocalStream:H3,getServerConfig:aa,listRemoteStreams:x3,viewStream:G3,viewStreamIterator:F3,publishToStream:q3,request:$3,reloadNATS:MS,reloadNATSHub:Y3,reloadNATSLeaf:K3,extractServerName:V3,requestErrorHandler:W3,createLocalTableStream:tL,createTableStreams:J3,purgeTableStream:rL,purgeSchemaTableStreams:j3,getStreamInfo:X3,updateLocalStreams:ej,closeConnection:v3,getJsmServerName:Od,addNatsMsgHeader:XD,clearClientCache:zD,updateRemoteConsumer:Q3,createConsumer:ZD,updateConsumerIterator:z3};async function QD(e,t=void 0){let{stdout:r,stderr:n}=await h3(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(QD,"runCommand");async function P3(){try{await _3.access(bS)}catch{return!1}let e=await QD(`${bS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return d3.eq(t,M3)}a(P3,"checkNATSServerInstalled");async function CS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await KD.getClusterUser();if(ao(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}vn.trace("create nats connection called");let i=await A3({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),vn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&vn.error("Error with Nats client connection, connection closed",o),zD()}),i}a(CS,"createConnection");function zD(){Er=void 0,so=void 0,io=void 0,oo=void 0}a(zD,"clearClientCache");async function v3(){Er&&(await Er.drain(),Er=void 0,so=void 0,io=void 0,oo=void 0)}a(v3,"closeConnection");var Er,oo;async function pu(){return oo||(oo=CS(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Er=await oo),Er||oo}a(pu,"getConnection");async function Su(){if(so)return so;ao(Er)&&await pu();let{domain:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ao(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return so=await Er.jetstreamManager({domain:e,timeout:6e4}),so}a(Su,"getJetStreamManager");async function JD(){if(io)return io;ao(Er)&&await pu();let{domain:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ao(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=Er.jetstream({domain:e,timeout:6e4}),io}a(JD,"getJetStream");async function ns(){let e=Er||await pu(),t=so||await Su(),r=io||await JD();return{connection:e,jsm:t,js:r}}a(ns,"getNATSReferences");async function B3(e){let t=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await KD.getClusterUser(),s=await CS(t,r,n),i=wS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=WD.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await Rd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(B3,"getServerList");async function DS(e,t){let{jsm:r}=await ns(),n=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:O3.File,retention:b3.Limits,subjects:t,discard:y3.Old,max_msgs:s,max_bytes:i,max_age:n})}a(DS,"createLocalStream");async function jD(){let{jsm:e}=await ns(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(jD,"listStreams");async function H3(e){let{jsm:t}=await ns();await t.streams.delete(e)}a(H3,"deleteLocalStream");async function x3(e){let{connection:t}=await ns(),r=[],n=wS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(WD.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(x3,"listRemoteStreams");async function G3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ns(),i=kD(),o={durable_name:i,ack_policy:NS.Explicit};t&&(o.deliver_policy=IS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=yS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Vt.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(G3,"viewStream");async function*F3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ns(),i=kD(),o={durable_name:i,ack_policy:NS.Explicit};t&&(o.deliver_policy=IS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=yS(_.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(Vt.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(F3,"viewStreamIterator");async function q3(e,t,r,n){vn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=XD(n,r);let{js:s}=await ns(),i=await Od(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:YD.encode(n);try{vn.trace(`publishToStream publishing to subject: ${o}`),D3(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return eL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){vn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await DS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(q3,"publishToStream");function XD(e,t){t===void 0&&(t=I3());let r=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Vt.MSG_HEADERS.ORIGIN)&&r&&t.append(Vt.MSG_HEADERS.ORIGIN,r),t}a(XD,"addNatsMsgHeader");function aa(e){e=e.toLowerCase();let t=mu.join(Pt.get(Ne.CONFIG_PARAMS.ROOTPATH),L3);if(e===Ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ao(OS)&&(OS={port:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.HUB,config_file:Vt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:mu.join(t,Vt.PID_FILES.HUB),hdb_nats_path:t}),OS;if(e===Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ao(AS)&&(AS={port:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,config_file:Vt.NATS_CONFIG_FILES.LEAF_SERVER,domain:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,pid_file_path:mu.join(t,Vt.PID_FILES.LEAF),hdb_nats_path:t}),AS;vn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(aa,"getServerConfig");async function ZD(e,t,r,n){try{await e.consumers.add(t,{ack_policy:NS.Explicit,durable_name:r,deliver_policy:IS.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(ZD,"createConsumer");async function k3(e,t,r){await e.consumers.delete(t,r)}a(k3,"removeConsumer");function V3(e){return e.split(".")[1]}a(V3,"extractServerName");async function $3(e,t,r=6e4,n=wS()){if(!Rd.isObject(t))throw new Error("data param must be an object");let s=YD.encode(t),{connection:i}=await ns(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return yS(c.data)}a($3,"request");function LS(e){return new Promise(async(t,r)=>{let n=m3(bS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(LS,"reloadNATS");async function Y3(){let{pid_file_path:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await LS(e)}a(Y3,"reloadNATSHub");async function K3(){let{pid_file_path:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await LS(e)}a(K3,"reloadNATSLeaf");function W3(e,t,r){let n;switch(e.code){case qD.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case qD.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(W3,"requestErrorHandler");async function Q3(e,t){let r=t+Vt.SERVER_SUFFIX.LEAF,{connection:n}=await ns(),{jsm:s}=await rj(r),{schema:i,table:o}=e,c=Ad.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await eL(async()=>{if(e.subscribe===!0)await ZD(s,c,n.info.server_name,u);else try{await k3(s,c,n.info.server_name)}catch(_){vn.trace(_)}})}a(Q3,"updateRemoteConsumer");async function z3(e,t,r,n){let s=Ad.createNatsTableStreamName(e,t),i=r+Vt.SERVER_SUFFIX.LEAF,o={type:Ne.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!$D&&g3()<Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=RS();await c(o)}await S3(o),n==="stop"&&await Rd.async_set_timeout(1e3)}a(z3,"updateConsumerIterator");function eL(e){return p3.writeTransaction(Ne.SYSTEM_SCHEMA_NAME,Ne.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(eL,"exclusiveLock");async function tL(e,t){let r=Ad.createNatsTableStreamName(e,t),n=await Od(),s=Z3(e,t,n);await DS(r,[s])}a(tL,"createLocalTableStream");async function J3(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await tL(n,s)}}a(J3,"createTableStreams");async function rL(e,t,r=void 0){if(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Ad.createNatsTableStreamName(e,t),{domain:s}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await pu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")vn.warn(n);else throw n}}a(rL,"purgeTableStream");async function j3(e,t){if(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await rL(e,t[r])}a(j3,"purgeSchemaTableStreams");async function X3(e){return(await Su()).streams.info(e)}a(X3,"getStreamInfo");function Z3(e,t,r){return`${Vt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Z3,"createSubjectName");async function Od(){if(hu)return hu;if(hu=(await Su())?.nc?.info?.server_name,hu===void 0)throw new Error("Unable to get jetstream manager server name");return hu}a(Od,"getJsmServerName");async function ej(){let e=await Su(),t=await Od(),r=await jD();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=tj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");vn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(ej,"updateLocalStreams");function tj(e){let{config:t}=e,r=!1,n=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(tj,"updateStreamLimits");async function rj(e){let t,r;try{t=await Er.jetstream({domain:e}),r=await Er.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw vn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(rj,"connectToRemoteJS")});var Id=R((ude,aL)=>{"use strict";var ca=N_(),ua=dD(),nj=Y(),sj=require("uuid").v4,cde=require("clone"),yd=Os(),la=U(),ij=require("util"),ui=Dn(),{handleHDBError:hr,hdb_errors:oj}=ne(),{HDB_ERROR_MSGS:bd,HTTP_STATUS_CODES:mr}=oj,{SchemaEventMsg:Nd}=Ln(),sL=St(),{getDatabases:aj}=(Re(),ie(qe)),{transformReq:_a}=Q();aL.exports={createSchema:cj,createSchemaStructure:iL,createTable:uj,createTableStructure:oL,createAttribute:Ej,dropSchema:lj,dropTable:_j,dropAttribute:dj,getBackup:hj};async function cj(e){let t=await iL(e);return yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema)),t}a(cj,"createSchema");async function iL(e){let t=ca.schema_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(_a(e),!await ua.checkSchemaExists(e.schema))throw hr(new Error,bd.SCHEMA_EXISTS_ERR(e.schema),mr.BAD_REQUEST,la.LOG_LEVELS.ERROR,bd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ui.createSchema(e),`database '${e.schema}' successfully created`}a(iL,"createSchemaStructure");async function uj(e){return _a(e),e.hash_attribute=e.primary_key??e.hash_attribute,await oL(e)}a(uj,"createTable");async function oL(e){let t=ca.create_table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(ca.validateTableResidence(e.residence),!await ua.checkSchemaTableExists(e.schema,e.table))throw hr(new Error,bd.TABLE_EXISTS_ERR(e.schema,e.table),mr.BAD_REQUEST,la.LOG_LEVELS.ERROR,bd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:sj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ui.createTable(n,e);else throw hr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",mr.BAD_REQUEST);else await ui.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(oL,"createTableStructure");async function lj(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ca.schema_object(e),n=t??r;if(n)throw hr(n,n.message,mr.BAD_REQUEST,void 0,void 0,!0);_a(e);let s=await ua.checkSchemaExists(e.schema);if(s)throw hr(new Error,s,mr.NOT_FOUND,la.LOG_LEVELS.ERROR,s,!0);let i=await ua.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ui.dropSchema(e),yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema)),await sL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(lj,"dropSchema");async function _j(e){let t=ca.table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);_a(e);let r=await ua.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,la.LOG_LEVELS.ERROR,r,!0);return await ui.dropTable(e),await sL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(_j,"dropTable");async function dj(e){let t=ca.attribute_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);_a(e);let r=await ua.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,la.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw hr(new Error,"You cannot drop a hash attribute",mr.BAD_REQUEST,void 0,void 0,!0);if(la.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw hr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,mr.BAD_REQUEST,void 0,void 0,!0);try{return await ui.dropAttribute(e),fj(e),yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw nj.error(`Got an error deleting attribute ${ij.inspect(e)}.`),n}}a(dj,"dropAttribute");function fj(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(fj,"dropAttributeFromGlobal");async function Ej(e){_a(e);let t=aj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw hr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,mr.BAD_REQUEST,void 0,void 0,!0);return await ui.createAttribute(e),yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Ej,"createAttribute");function hj(e){return ui.getBackup(e)}a(hj,"getBackup")});var uL=R((_de,cL)=>{"use strict";var{OPERATIONS_ENUM:mj}=U(),MS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=mj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};cL.exports=MS});var US=R((Ede,EL)=>{"use strict";var pj=Dn(),fde=uL(),wd=Q(),Cd=U(),Sj=re(),{handleHDBError:lL,hdb_errors:Tj}=ne(),{HDB_ERROR_MSGS:_L,HTTP_STATUS_CODES:dL}=Tj,gj=Object.values(Cd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),fL="To use this operation audit log must be enabled in harperdb-config.yaml";EL.exports=Rj;async function Rj(e){if(wd.isEmpty(e.schema))throw new Error(_L.SCHEMA_REQUIRED_ERR);if(wd.isEmpty(e.table))throw new Error(_L.TABLE_REQUIRED_ERR);if(!Sj.get(Cd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw lL(new Error,fL,dL.BAD_REQUEST,Cd.LOG_LEVELS.ERROR,fL,!0);let t=wd.checkSchemaTableExist(e.schema,e.table);if(t)throw lL(new Error,t,dL.NOT_FOUND,Cd.LOG_LEVELS.ERROR,t,!0);if(!wd.isEmpty(e.search_type)&&gj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await pj.readAuditLog(e)}a(Rj,"readAuditLog")});var mL=R((mde,hL)=>{"use strict";var{OPERATIONS_ENUM:Aj}=U(),PS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Aj.GET_BACKUP,this.schema=t,this.table=r}};hL.exports=PS});var TL=R((gde,SL)=>{"use strict";var Oj=Dn(),Sde=mL(),vS=Q(),bj=U(),Tde=re(),{handleHDBError:yj,hdb_errors:Nj}=ne(),{HDB_ERROR_MSGS:pL,HTTP_STATUS_CODES:Ij}=Nj;SL.exports=wj;async function wj(e){if(vS.isEmpty(e.schema))throw new Error(pL.SCHEMA_REQUIRED_ERR);if(vS.isEmpty(e.table))throw new Error(pL.TABLE_REQUIRED_ERR);let t=vS.checkSchemaTableExist(e.schema,e.table);if(t)throw yj(new Error,t,Ij.NOT_FOUND,bj.LOG_LEVELS.ERROR,t,!0);return await Oj.getBackup(read_audit_log_object)}a(wj,"getBackup")});var yL=R((Ade,bL)=>{var li=require("validate.js"),RL=et(),da=U(),{handleHDBError:Cj,hdb_errors:Dj}=ne(),{HDB_ERROR_MSGS:_t,HTTP_STATUS_CODES:Lj}=Dj,BS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),Mj={STRUCTURE_USER:"structure_user"},gL=Object.values(da.ROLE_TYPES_ENUM),Uj="attribute_permissions",Pj="attribute_name",{PERMS_CRUD_ENUM:fa}=da,vj=[Uj,...Object.values(fa)],AL=[fa.READ,fa.INSERT,fa.UPDATE],Bj=[Pj,...AL];function Hj(e){let t=BS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,OL(e,t)}a(Hj,"addRoleValidation");function xj(e){let t=BS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,OL(e,t)}a(xj,"alterRoleValidation");function Gj(e){let t=BS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,RL.validateObject(e,t)}a(Gj,"dropRoleValidation");var Fj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function OL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Fj.includes(n[o])||s.push(n[o]);s.length>0&&Tt(_t.INVALID_ROLE_JSON_KEYS(s),r);let i=RL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Tt(o,r)}),e.permission){let o=qj(e);o&&Tt(o,r),gL.forEach(c=>{e.permission[c]&&!li.isBoolean(e.permission[c])&&Tt(_t.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(gL.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]||Tt(_t.SCHEMA_NOT_FOUND(d),r)}continue}Tt(_t.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Tt(_t.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){Tt(_t.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{vj.includes(l)||Tt(_t.INVALID_PERM_KEY(l),r,o,u)}),Object.values(fa).forEach(l=>{li.isDefined(_[l])?li.isBoolean(_[l])||Tt(_t.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Tt(_t.TABLE_PERM_MISSING(l),r,o,u)}),li.isDefined(_.attribute_permissions)){if(!li.isArray(_.attribute_permissions)){Tt(_t.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Tt(_t.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(S=>{!Bj.includes(S)&&S!==fa.DELETE&&Tt(_t.INVALID_ATTR_PERM_KEY(S),r,o,u)}),!li.isDefined(E.attribute_name)){Tt(_t.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){Tt(_t.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}AL.forEach(S=>{li.isDefined(E[S])?li.isBoolean(E[S])||Tt(_t.ATTR_PERM_NOT_BOOLEAN(S,h),r,o,u):Tt(_t.ATTR_PERM_MISSING(S,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}`;Tt(_t.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return kj(r)}a(OL,"customValidate");bL.exports={addRoleValidation:Hj,alterRoleValidation:xj,dropRoleValidation:Gj};function qj(e){let{operation:t,permission:r}=e;if(t===da.OPERATIONS_ENUM.ADD_ROLE||t===da.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return _t.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?da.ROLE_TYPES_ENUM.SUPER_USER:da.ROLE_TYPES_ENUM.CLUSTER_USER;return _t.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(qj,"validateNoSUPerms");function kj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:_t.ROLE_PERMS_ERROR,...e};return Cj(new Error,n,Lj.BAD_REQUEST)}else return null}a(kj,"generateRolePermResponse");function Tt(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Tt,"addPermError")});var kS=R((bde,CL)=>{"use strict";var NL=an(),IL=Br(),Vj=Qi(),xS=yL(),GS=Os(),$j=require("uuid").v4,Yj=require("util"),Dd=U(),Kj=Q(),FS=IL.searchByValue,Wj=IL.searchByHash,Qj=Yj.promisify(Vj.delete),zj=Zn(),Jj=ra(),{hdb_errors:jj,handleHDBError:co}=ne(),{HDB_ERROR_MSGS:wL,HTTP_STATUS_CODES:Tu}=jj,{UserEventMsg:qS}=Ln();CL.exports={addRole:Xj,alterRole:Zj,dropRole:eX,listRoles:tX};function HS(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(HS,"scrubRoleDetails");async function Xj(e){let t=xS.addRoleValidation(e);if(t)throw t;e=HS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await FS(r)||[])}catch(i){throw co(i)}if(n&&n.length>0)throw co(new Error,wL.ROLE_ALREADY_EXISTS(e.role),Tu.CONFLICT,void 0,void 0,!0);e.id||(e.id=$j());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await NL.insert(s),GS.signalUserChange(new qS(process.pid)),e=HS(e),e}a(Xj,"addRole");async function Zj(e){let t=xS.alterRoleValidation(e);if(t)throw t;e=HS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await NL.update(r)}catch(s){throw co(s)}if(n&&n?.message==="updated 0 of 1 records")throw co(new Error,"Invalid role id",Tu.BAD_REQUEST,void 0,void 0,!0);return await GS.signalUserChange(new qS(process.pid)),e}a(Zj,"alterRole");async function eX(e){let t=xS.dropRoleValidation(e);if(t)throw co(new Error,t,Tu.BAD_REQUEST,void 0,void 0,!0);let r=new Jj(Dd.SYSTEM_SCHEMA_NAME,Dd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Wj(r));if(n.length===0)throw co(new Error,wL.ROLE_NOT_FOUND,Tu.NOT_FOUND,void 0,void 0,!0);let s=new zj(Dd.SYSTEM_SCHEMA_NAME,Dd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await FS(s)),o=!1;if(Kj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw co(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Tu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Qj(c),GS.signalUserChange(new qS(process.pid)),`${n[0].role} successfully deleted`}a(eX,"dropRole");async function tX(){return FS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(tX,"listRoles")});var UL=R((Nde,ML)=>{"use strict";var rX=re(),_i=require("joi"),nX=et(),DL=require("moment"),sX=require("fs-extra"),VS=require("path"),iX=require("lodash"),gu=U(),{LOG_LEVELS:uo}=U(),oX="YYYY-MM-DD hh:mm:ss",aX=VS.resolve(__dirname,"../logs");ML.exports=function(e){return nX.validateBySchema(e,cX)};var cX=_i.object({from:_i.custom(LL),until:_i.custom(LL),level:_i.valid(uo.NOTIFY,uo.FATAL,uo.ERROR,uo.WARN,uo.INFO,uo.DEBUG,uo.TRACE),order:_i.valid("asc","desc"),limit:_i.number().min(1),start:_i.number().min(0),log_name:_i.custom(uX)});function LL(e,t){if(DL(e,DL.ISO_8601).format(oX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(LL,"validateDatetime");function uX(e,t){if(iX.invert(gu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=rX.get(gu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?gu.LOG_NAMES.HDB:e,i=s===gu.LOG_NAMES.INSTALL?VS.join(aX,gu.LOG_NAMES.INSTALL):VS.join(n,s);return sX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(uX,"validateReadLogPath")});var YS=R((wde,vL)=>{"use strict";var Ld=U(),lX=Y(),_X=re(),dX=UL(),$S=require("path"),PL=require("fs-extra"),{once:fX}=require("events"),{handleHDBError:EX,hdb_errors:hX}=ne(),{PACKAGE_ROOT:mX}=U(),pX=$S.join(mX,"logs"),SX=1e3,TX=200;vL.exports=gX;async function gX(e){let t=dX(e);if(t)throw EX(t,t.message,hX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=_X.get(Ld.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Ld.LOG_NAMES.HDB:e.log_name,s=n===Ld.LOG_NAMES.INSTALL?$S.join(pX,Ld.LOG_NAMES.INSTALL):$S.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?SX:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,S=0;f==="desc"&&!u&&!l&&(S=Math.max(PL.statSync(s).size-(h+5)*TX,0));let p=PL.createReadStream(s,{start:S});p.on("error",P=>{lX.error(P)});let T=0,b=[],g="",L;p.on("data",P=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=g+P;let H=0,j;for(;(j=k.exec(P))&&!p.destroyed;){L&&(L.message=P.slice(H,j.index),v(L));let[z,J,me]=j,ce=me.split("] ["),de=ce[0],Le=ce[1];ce.splice(0,2),L={timestamp:J,thread:de,level:Le,tags:ce,message:""},H=j.index+z.length}g=P.slice(H)}),p.on("end",P=>{p.destroyed||L&&(L.message=g.trim(),v(L))}),p.resume();function v(P){let k,H,j;switch(!0){case(i&&c&&_):k=new Date(P.timestamp),H=new Date(u),j=new Date(l),P.level===o&&k>=H&&k<=j&&T<E?T++:P.level===o&&k>=H&&k<=j&&(di(P,f,b),T++,T===h&&p.destroy());break;case(i&&c):k=new Date(P.timestamp),H=new Date(u),P.level===o&&k>=H&&T<E?T++:P.level===o&&k>=H&&(di(P,f,b),T++,T===h&&p.destroy());break;case(i&&_):k=new Date(P.timestamp),j=new Date(l),P.level===o&&k<=j&&T<E?T++:P.level===o&&k<=j&&(di(P,f,b),T++,T===h&&p.destroy());break;case(c&&_):k=new Date(P.timestamp),H=new Date(u),j=new Date(l),k>=H&&k<=j&&T<E?T++:k>=H&&k<=j&&(di(P,f,b),T++,T===h&&p.destroy());break;case i:P.level===o&&T<E?T++:P.level===o&&(di(P,f,b),T++,T===h&&p.destroy());break;case c:k=new Date(P.timestamp),H=new Date(u),k>=H&&T<E?T++:k>=H&&T>=E&&(di(P,f,b),T++,T===h&&p.destroy());break;case _:k=new Date(P.timestamp),j=new Date(l),k<=j&&T<E?T++:k<=j&&T>=E&&(di(P,f,b),T++,T===h&&p.destroy());break;default:T<E?T++:(di(P,f,b),T++,T===h&&p.destroy())}}return a(v,"onLogMessage"),await fX(p,"close"),b}a(gX,"readLog");function di(e,t,r){t==="desc"?RX(e,r):t==="asc"?AX(e,r):r.push(e)}a(di,"pushLineToResult");function RX(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(RX,"insertDescending");function AX(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(AX,"insertAscending")});var Md=R((Ude,GL)=>{"use strict";var KS=require("joi"),{string:Ru,boolean:BL,date:OX}=KS.types(),bX=et(),{validateSchemaExists:Dde,validateTableExists:Lde,validateSchemaName:Mde}=zn(),yX=U(),NX=st(),HL=re();HL.initSync();var IX=Ru.invalid(HL.get(yX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(NX.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(),xL={operation:Ru.valid("add_node","update_node","set_node_replication"),node_name:IX,subscriptions:KS.array().items({table:Ru.optional(),schema:Ru.optional(),database:Ru.optional(),subscribe:BL.required(),publish:BL.required().custom(CX),start_time:OX.iso()}).min(1).required()};function wX(e){return bX.validateBySchema(e,KS.object(xL))}a(wX,"addUpdateNodeValidator");function CX(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(CX,"checkForFalsy");GL.exports={addUpdateNodeValidator:wX,validation_schema:xL}});var qL=R((vde,FL)=>{var DX=et(),LX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};FL.exports=function(e){return DX.validateObject(e,LX)}});var QS=R((Bde,kL)=>{"use strict";var MX=U().OPERATIONS_ENUM,WS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=MX.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};kL.exports=WS});var $L=R((xde,VL)=>{"use strict";var UX={OPERATION:"operation",REFRESH:"refresh"},zS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},JS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};VL.exports={JWTTokens:zS,TOKEN_TYPE_ENUM:UX,JWTRSAKeys:JS}});var bu=R((Fde,QL)=>{"use strict";var Ou=require("jsonwebtoken"),jS=require("fs-extra"),XS=Q(),un=U(),{handleHDBError:pr,hdb_errors:PX}=ne(),{HTTP_STATUS_CODES:Sr,AUTHENTICATION_ERROR_MSGS:Tr}=PX,Au=Y(),YL=k_(),tT=xr(),vX=an().update,BX=QS(),HX=Os(),{UserEventMsg:xX}=Ln(),fi=re();fi.initSync();var ZS=require("path"),{JWTTokens:GX,JWTRSAKeys:FX,TOKEN_TYPE_ENUM:Ud}=$L(),qX=fi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?fi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",kX=fi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?fi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Pd="RS256",eT;QL.exports={createTokens:VX,validateOperationToken:YX,refreshOperationToken:$X,validateRefreshToken:WL};async function VX(e){if(XS.isEmpty(e)||typeof e!="object")throw pr(new Error,Tr.INVALID_AUTH_OBJECT,Sr.BAD_REQUEST,void 0,void 0,!0);if(XS.isEmpty(e.username))throw pr(new Error,Tr.USERNAME_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);if(XS.isEmpty(e.password))throw pr(new Error,Tr.PASSWORD_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await tT.findAndValidateUser(e.username,e.password),!t)throw pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Au.error(f),pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}let r=await vd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await KL(i,r.private_key,r.passphrase),c=await Ou.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:kX,algorithm:Pd,subject:Ud.REFRESH}),u=YL.hash(c),_=new BX(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await vX(_)}catch(f){Au.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw pr(new Error,Tr.REFRESH_TOKEN_SAVE_FAILED,Sr.INTERNAL_SERVER_ERROR);return HX.signalUserChange(new xX(process.pid)),new GX(o,c)}a(VX,"createTokens");async function KL(e,t,r){return await Ou.sign(e,{key:t,passphrase:r},{expiresIn:qX,algorithm:Pd,subject:Ud.OPERATION})}a(KL,"signOperationToken");async function vd(){if(eT===void 0)try{let e=ZS.join(fi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PASSPHRASE_NAME),t=ZS.join(fi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=ZS.join(fi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await jS.readFile(e)).toString(),s=(await jS.readFile(t)).toString(),i=(await jS.readFile(r)).toString();eT=new FX(i,s,n)}catch(e){throw Au.error(e),pr(new Error,Tr.NO_ENCRYPTION_KEYS,Sr.INTERNAL_SERVER_ERROR)}return eT}a(vd,"getJWTRSAKeys");async function $X(e){if(!e)throw pr(new Error,Tr.INVALID_BODY,Sr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw pr(new Error,Tr.REFRESH_TOKEN_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);await WL(e.refresh_token);let t=await vd(),r=await Ou.decode(e.refresh_token);return{operation_token:await KL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a($X,"refreshOperationToken");async function YX(e){try{let t=await vd(),r=await Ou.verify(e,t.public_key,{algorithms:Pd,subject:Ud.OPERATION});return await tT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Au.warn(t),t.name&&t.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}}a(YX,"validateOperationToken");async function WL(e){let t;try{let r=await vd(),n=await Ou.verify(e,r.public_key,{algorithms:Pd,subject:Ud.REFRESH});t=await tT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Au.warn(r),r.name&&r.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}if(!YL.validate(t.refresh_token,e))throw pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED);return t}a(WL,"validateRefreshToken")});var rT=R((Vde,jL)=>{"use strict";var KX=qL(),Ea=require("passport"),WX=require("passport-local").Strategy,QX=require("passport-http").BasicStrategy,zX=require("util"),JX=xr(),JL=zX.callbackify(JX.findAndValidateUser),kde=Cr(),jX=U(),zL=bu();Ea.use(new WX(function(e,t,r){JL(e,t,r)}));Ea.use(new QX(function(e,t,r){JL(e,t,r)}));Ea.serializeUser(function(e,t){t(null,e)});Ea.deserializeUser(function(e,t){t(null,e)});function XX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Ea.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===jX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?zL.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):zL.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Ea.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(XX,"authorize");function ZX(e,t){let r=KX(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(ZX,"checkPermissions");jL.exports={authorize:XX,checkPermissions:ZX}});var ha=R((Yde,XL)=>{"use strict";var nT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},sT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};XL.exports={Node:nT,NodeSubscription:sT}});var eM=R((Wde,ZL)=>{"use strict";var eZ=U().OPERATIONS_ENUM,iT=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=eZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};ZL.exports=iT});var yu=R((zde,tM)=>{"use strict";var oT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},aT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};tM.exports={RemotePayloadObject:oT,RemotePayloadSubscription:aT}});var nM=R((jde,rM)=>{"use strict";var cT=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};rM.exports=cT});var oM=R((rfe,iM)=>{"use strict";var tZ=nM(),Zde=ct(),sM=Ye(),rZ=Y(),{getSchemaPath:efe,getTransactionAuditStorePath:tfe}=Qe(),{getDatabases:nZ}=(Re(),ie(qe));iM.exports=sZ;async function sZ(e){let t=new tZ;try{let r=nZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await sM.environmentDataSize(schema_path,e.name),o=await sM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){rZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(sZ,"lmdbGetTableSize")});var cM=R((sfe,aM)=>{"use strict";var uT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};aM.exports=uT});var ma=R((ufe,fM)=>{"use strict";var iZ=require("fs-extra"),oZ=require("path"),Zt=require("systeminformation"),Ei=Y(),uM=St(),ofe=st(),Hd=U(),aZ=oM(),cZ=ri(),{getThreadInfo:lM}=rt(),TT=re();TT.initSync();var uZ=cM(),{openEnvironment:afe}=Ye(),{getSchemaPath:cfe}=Qe(),{database:lZ,databases:_M}=(Re(),ie(qe)),Bd;fM.exports={getHDBProcessInfo:fT,getNetworkInfo:hT,getDiskInfo:ET,getMemoryInfo:dT,getCPUInfo:_T,getTimeInfo:lT,getSystemInformation:mT,systemInformation:_Z,getTableSize:pT,getMetrics:ST};function lT(){return Zt.time()}a(lT,"getTimeInfo");async function _T(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Zt.cpu();l.cpu_speed=await Zt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:S,raw_currentload_user:p,cpus:T,...b}=await Zt.currentLoad();return b.cpus=[],T.forEach(g=>{let{raw_load:L,raw_load_idle:v,raw_load_irq:P,raw_load_nice:k,raw_load_system:H,raw_load_user:j,...z}=g;b.cpus.push(z)}),l.current_load=b,l}catch(e){return Ei.error(`error in getCPUInfo: ${e}`),{}}}a(_T,"getCPUInfo");async function dT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Zt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ei.error(`error in getMemoryInfo: ${e}`),{}}}a(dT,"getMemoryInfo");async function fT(){let e={core:[],clustering:[]};try{let t=await Zt.processes(),r;try{r=Number.parseInt(await iZ.readFile(oZ.join(TT.get(Hd.CONFIG_PARAMS.ROOTPATH),Hd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Hd.NODE_ERROR_CODES.ENOENT)Ei.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Ei.error(`error in getHDBProcessInfo: ${t}`),e}}a(fT,"getHDBProcessInfo");async function ET(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Zt.fsStats();return e.read_write=_,e.size=await Zt.fsSize(),e}catch(t){return Ei.error(`error in getDiskInfo: ${t}`),e}}a(ET,"getDiskInfo");async function hT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Zt.networkInterfaceDefault(),e.latency=await Zt.inetChecksite("google.com"),(await Zt.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await Zt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ei.error(`error in getNetworkInfo: ${t}`),e}}a(hT,"getNetworkInfo");async function mT(){if(Bd!==void 0)return Bd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Zt.osInfo();e=c;let u=await Zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Bd=e,Bd}catch(t){return Ei.error(`error in getSystemInformation: ${t}`),e}}a(mT,"getSystemInformation");async function pT(){let e=[],t=await cZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await aZ(n));return e}a(pT,"getTableSize");async function ST(){let e={};for(let t in _M){let r=e[t]={};for(let n in _M[t])try{let s=lZ({database:t,table:n}),i=s.getStats();i.readers=s.readerList().split(/\n\s+/).slice(1).map(o=>{let[c,u,_]=o.trim().split(" ");return{pid:c,thread:u,txnid:_}}),r[n]=i}catch(s){Ei.notify(`Error getting stats for table ${n}: ${s}`)}}return e}a(ST,"getMetrics");async function dM(){if(TT.get(Hd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await uM.getNATSReferences(),t=await uM.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(dM,"getNatsStreamInfo");async function _Z(e){let t=new uZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await mT(),t.time=lT(),t.cpu=await _T(),t.memory=await dT(),t.disk=await ET(),t.network=await hT(),t.harperdb_processes=await fT(),t.table_size=await pT(),t.metrics=await ST(),t.threads=await lM(),t.replication=await dM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await mT();break;case"time":t.time=lT();break;case"cpu":t.cpu=await _T();break;case"memory":t.memory=await dT();break;case"disk":t.disk=await ET();break;case"network":t.network=await hT();break;case"harperdb_processes":t.harperdb_processes=await fT();break;case"table_size":t.table_size=await pT();break;case"database_metrics":case"metrics":t.metrics=await ST();break;case"threads":t.threads=await lM();break;case"replication":t.replication=await dM();break;default:break}return t}a(_Z,"systemInformation")});var Gd=R((_fe,EM)=>{"use strict";EM.exports={version:dZ,printVersion:fZ};var xd=ou();function dZ(){if(xd)return xd.version}a(dZ,"version");function fZ(){xd&&console.log(`HarperDB Version ${xd.version}`)}a(fZ,"printVersion")});var ws=R((hfe,SM)=>{"use strict";var EZ=an(),gT=Q(),hZ=require("util"),lo=U(),hM=re();hM.initSync();var mZ=rT(),mM=Br(),{Node:ffe,NodeSubscription:Efe}=ha(),pZ=ra(),SZ=eM(),{RemotePayloadObject:TZ,RemotePayloadSubscription:gZ}=yu(),{handleHDBError:RZ,hdb_errors:AZ}=ne(),{HTTP_STATUS_CODES:OZ,HDB_ERROR_MSGS:bZ}=AZ,yZ=Zn(),NZ=ma(),IZ=Gd(),{getDatabases:wZ}=(Re(),ie(qe)),CZ=hZ.promisify(mZ.authorize),DZ=mM.searchByHash,LZ=mM.searchByValue;SM.exports={authHeaderToUser:MZ,isEmpty:UZ,getNodeRecord:PZ,upsertNodeRecord:vZ,buildNodePayloads:BZ,checkClusteringEnabled:HZ,getAllNodeRecords:xZ,getSystemInfo:GZ,reverseSubscription:pM};async function MZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await CZ(t,null),e}a(MZ,"authHeaderToUser");function UZ(e){return e==null}a(UZ,"isEmpty");async function PZ(e){let t=new pZ(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return DZ(t)}a(PZ,"getNodeRecord");async function vZ(e){let t=new SZ(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return EZ.upsert(t)}a(vZ,"upsertNodeRecord");function pM(e){if(gT.isEmpty(e.subscribe)||gT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(pM,"reverseSubscription");function BZ(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=gT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=pM(c),E=wZ()[u]?.[_],h=new gZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new TZ(r,t,s,n)}a(BZ,"buildNodePayloads");function HZ(){if(!hM.get(lo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw RZ(new Error,bZ.CLUSTERING_NOT_ENABLED,OZ.BAD_REQUEST,void 0,void 0,!0)}a(HZ,"checkClusteringEnabled");async function xZ(){let e=new yZ(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await LZ(e))}a(xZ,"getAllNodeRecords");async function GZ(){let e=await NZ.getSystemInformation();return{hdb_version:IZ.version(),node_version:e.node_version,platform:e.platform}}a(GZ,"getSystemInfo")});var RT=R((pfe,NM)=>{"use strict";var Fd=St(),TM=Q(),gM=st(),RM=U(),qd=Y(),AM=Id(),FZ=vp(),{RemotePayloadObject:qZ}=yu(),{handleHDBError:OM,hdb_errors:kZ}=ne(),{HTTP_STATUS_CODES:bM}=kZ,{NodeSubscription:yM}=ha();NM.exports=VZ;async function VZ(e,t){let r;try{r=await Fd.request(`${t}.${gM.REQUEST_SUFFIX}`,new qZ(RM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),qd.trace("Response from remote describe all request:",r)}catch(o){qd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Fd.requestErrorHandler(o,"add_node",t);throw OM(new Error,c,bM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===gM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw OM(new Error,o,bM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===RM.SYSTEM_SCHEMA_NAME){await Fd.createLocalTableStream(u,c);let h=new yM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=TM.doesSchemaExist(u),l=n[u]!==void 0,d=c?TM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(qd.trace(`addNode creating schema: ${u}`),await AM.createSchema({operation:"create_schema",schema:u})),!d&&f){qd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new FZ(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await AM.createTable(h)}await Fd.createLocalTableStream(u,c);let E=new yM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(VZ,"reviewSubscriptions")});var Yd=R((Tfe,CM)=>{"use strict";var{handleHDBError:kd,hdb_errors:$Z}=ne(),{HTTP_STATUS_CODES:Vd}=$Z,{addUpdateNodeValidator:YZ}=Md(),$d=Y(),wM=U(),IM=st(),KZ=Q(),Nu=St(),Iu=ws(),WZ=re(),QZ=RT(),{Node:zZ,NodeSubscription:JZ}=ha(),{broadcast:jZ}=rt(),XZ="Unable to create 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=WZ.get(wM.CONFIG_PARAMS.CLUSTERING_NODENAME);CM.exports=t5;async function t5(e,t=!1){$d.trace("addNode called with:",e),Iu.checkClusteringEnabled();let r=YZ(e);if(r)throw kd(r,r.message,Vd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Iu.getNodeRecord(n);if(!KZ.isEmptyOrZeroLength(d))throw kd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Vd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await QZ(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=XZ,o;let c=Iu.buildNodePayloads(s,e5,wM.OPERATIONS_ENUM.ADD_NODE,await Iu.getSystemInfo()),u=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new JZ(E.schema,E.table,E.publish,E.subscribe))}$d.trace("addNode sending remote payload:",c);let _;try{_=await Nu.request(`${n}.${IM.REQUEST_SUFFIX}`,c)}catch(d){$d.error(`addNode received error from request: ${d}`);for(let E=0,h=s.length;E<h;E++){let S=s[E];S.publish=!1,S.subscribe=!1,await Nu.updateRemoteConsumer(S,n)}let f=Nu.requestErrorHandler(d,"add_node",n);throw kd(new Error,f,Vd.INTERNAL_SERVER_ERROR,"error",f)}if(_.status===IM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw kd(new Error,d,Vd.INTERNAL_SERVER_ERROR,"error",d)}$d.trace(_);for(let d=0,f=s.length;d<f;d++){let E=s[d];await Nu.updateRemoteConsumer(E,n),E.subscribe===!0&&await Nu.updateConsumerIterator(E.schema,E.table,n,"start")}let l=new zZ(n,u,_.system_info);return await Iu.upsertNodeRecord(l),jZ({type:"nats_update"}),i.length>0?o.message=ZZ:o.message=`Successfully added '${n}' to manifest`,o}a(t5,"addNode")});var bT=R((Afe,MM)=>{"use strict";var{handleHDBError:AT,hdb_errors:r5}=ne(),{HTTP_STATUS_CODES:OT}=r5,{addUpdateNodeValidator:n5}=Md(),wu=Y(),LM=U(),DM=st(),Rfe=Q(),Cu=St(),Du=ws(),s5=re(),{cloneDeep:i5}=require("lodash"),o5=RT(),{Node:a5,NodeSubscription:c5}=ha(),{broadcast:u5}=rt(),l5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",_5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",d5=s5.get(LM.CONFIG_PARAMS.CLUSTERING_NODENAME);MM.exports=f5;async function f5(e){wu.trace("updateNode called with:",e),Du.checkClusteringEnabled();let t=n5(e);if(t)throw AT(t,t.message,OT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Du.getNodeRecord(r);s.length>0&&(n=i5(s));let{added:i,skipped:o}=await o5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=l5,c;let u=Du.buildNodePayloads(i,d5,LM.OPERATIONS_ENUM.UPDATE_NODE,await Du.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let f=i[l];wu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),i[l].start_time===void 0&&delete i[l].start_time}wu.trace("updateNode sending remote payload:",u);let _;try{_=await Cu.request(`${r}.${DM.REQUEST_SUFFIX}`,u)}catch(l){wu.error(`updateNode received error from request: ${l}`);let d=Cu.requestErrorHandler(l,"update_node",r);throw AT(new Error,d,OT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===DM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw AT(new Error,l,OT.INTERNAL_SERVER_ERROR,"error",l)}wu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];await Cu.updateRemoteConsumer(f,r),f.subscribe===!0?await Cu.updateConsumerIterator(f.schema,f.table,r,"start"):await Cu.updateConsumerIterator(f.schema,f.table,r,"stop")}return n||(n=[new a5(r,[],_.system_info)]),await E5(n[0],i,_.system_info),o.length>0?c.message=_5:c.message=`Successfully updated '${r}'`,c}a(f5,"updateNode");async function E5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new c5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Du.upsertNodeRecord(n),u5({type:"nats_update"})}a(E5,"updateNodeTable")});var HM=R((bfe,BM)=>{"use strict";var vM=require("joi"),{string:UM}=vM.types(),h5=et(),PM=U(),m5=re(),p5=st();BM.exports=S5;function S5(e){let t=UM.invalid(m5.get(PM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(p5.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=vM.object({operation:UM.valid(PM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return h5.validateBySchema(e,r)}a(S5,"removeNodeValidator")});var Wd=R((Nfe,kM)=>{"use strict";var{handleHDBError:xM,hdb_errors:T5}=ne(),{HTTP_STATUS_CODES:GM}=T5,g5=HM(),Lu=Y(),FM=ws(),R5=Q(),Kd=U(),qM=st(),yT=St(),A5=re(),{RemotePayloadObject:O5}=yu(),{NodeSubscription:b5}=ha(),y5=jc(),N5=Qi(),{broadcast:I5}=rt(),w5=A5.get(Kd.CONFIG_PARAMS.CLUSTERING_NODENAME);kM.exports=C5;async function C5(e){Lu.trace("removeNode called with:",e),FM.checkClusteringEnabled();let t=g5(e);if(t)throw xM(t,t.message,GM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await FM.getNodeRecord(r);if(R5.isEmptyOrZeroLength(n))throw xM(new Error,`Node '${r}' was not found.`,GM.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new O5(Kd.OPERATIONS_ENUM.REMOVE_NODE,w5,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await yT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await yT.updateRemoteConsumer(new b5(l.schema,l.table,!1,!1),r)}catch(d){Lu.error(d)}}try{i=await yT.request(`${r}.${qM.REQUEST_SUFFIX}`,s),Lu.trace("Remove node reply from remote node:",r,i)}catch(u){Lu.error("removeNode received error from request:",u),o=!0}let c=new y5(Kd.SYSTEM_SCHEMA_NAME,Kd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await N5.deleteRecord(c),I5({type:"nats_update"}),i?.status===qM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Lu.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(C5,"removeNode")});var YM=R((wfe,$M)=>{"use strict";var VM=require("joi"),{string:D5,array:L5}=VM.types(),M5=et(),U5=Md();$M.exports=P5;function P5(e){let t=VM.object({operation:D5.valid("configure_cluster").required(),connections:L5.items(U5.validation_schema).required()});return M5.validateBySchema(e,t)}a(P5,"configureClusterValidator")});var NT=R((Dfe,JM)=>{"use strict";var v5=U(),Qd=Y(),B5=Q(),H5=Wd(),x5=Yd(),KM=ws(),G5=YM(),{handleHDBError:WM,hdb_errors:F5}=ne(),{HTTP_STATUS_CODES:QM}=F5,q5="Configure cluster complete.",k5="Failed to configure the cluster. Check the logs for more details.",V5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";JM.exports=$5;async function $5(e){Qd.trace("configure cluster called with:",e),KM.checkClusteringEnabled();let t=G5(e);if(t)throw WM(t,t.message,QM.BAD_REQUEST,void 0,void 0,!0);let r=await KM.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let f=await zM(H5,{operation:v5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(f)}Qd.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],f=await zM(x5,d,d.node_name);s.push(f)}Qd.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let f=_[l];f.status==="rejected"&&(Qd.error(f),o.includes(f.node_name)||o.push(f.node_name)),(f?.result?.message?.includes?.("Successfully")||f?.result?.includes?.("Successfully"))&&(u=!0),!(typeof f.result=="string"&&f.result.includes("Successfully removed")||f.status==="rejected")&&c.push({node_name:f?.node_name,subscriptions:f?.result})}if(B5.isEmptyOrZeroLength(o))return{message:q5,connections:c};if(u)return{message:V5,failed_nodes:o,connections:c};throw WM(new Error,k5,QM.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a($5,"configureCluster");async function zM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(zM,"functionWrapper")});var eU=R((Mfe,ZM)=>{"use strict";var Mu=require("joi"),Y5=et(),{validateSchemaExists:jM,validateTableExists:K5,validateSchemaName:XM}=zn(),W5=Mu.object({operation:Mu.string().valid("purge_stream"),schema:Mu.string().custom(jM).custom(XM).optional(),database:Mu.string().custom(jM).custom(XM).optional(),table:Mu.string().custom(K5).required()});function Q5(e){return Y5.validateBySchema(e,W5)}a(Q5,"purgeStreamValidator");ZM.exports=Q5});var IT=R((Pfe,tU)=>{"use strict";var{handleHDBError:z5,hdb_errors:J5}=ne(),{HTTP_STATUS_CODES:j5}=J5,X5=eU(),Z5=St(),e8=ws();tU.exports=t8;async function t8(e){e.schema=e.schema??e.database;let t=X5(e);if(t)throw z5(t,t.message,j5.BAD_REQUEST,void 0,void 0,!0);e8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await Z5.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(t8,"purgeStream")});var DT=R((Bfe,aU)=>{"use strict";var CT=ws(),r8=St(),sU=re(),zd=U(),_o=st(),n8=Q(),wT=Y(),{RemotePayloadObject:s8}=yu(),{ErrorCode:rU}=require("nats"),nU=sU.get(zd.CONFIG_PARAMS.CLUSTERING_ENABLED),iU=sU.get(zd.CONFIG_PARAMS.CLUSTERING_NODENAME);aU.exports={clusterStatus:i8,buildNodeStatus:oU};async function i8(){let e={node_name:iU,is_enabled:nU,connections:[]};if(!nU)return e;let t=await CT.getAllNodeRecords();if(n8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(oU(t[n],e.connections));return await Promise.allSettled(r),e}a(i8,"clusterStatus");async function oU(e,t){let r=e.name,n=new s8(zd.OPERATIONS_ENUM.CLUSTER_STATUS,iU,void 0,await CT.getSystemInfo()),s,i,o=_o.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await r8.request(_o.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===_o.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=_o.CLUSTER_STATUS_STATUSES.CLOSED,wT.error(`Error getting node status from ${r} `,s))}catch(u){wT.warn(`Error getting node status from ${r}`,u),u.code===rU.NoResponders?o=_o.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===rU.Timeout?o=_o.CLUSTER_STATUS_STATUSES.TIMEOUT:o=_o.CLUSTER_STATUS_STATUSES.CLOSED}let c=new o8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==zd.PRE_4_0_0_VERSION&&await CT.upsertNodeRecord(u)}catch(u){wT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(oU,"buildNodeStatus");function o8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(o8,"NodeStatusObject")});var MT=R((xfe,cU)=>{"use strict";var{handleHDBError:a8,hdb_errors:c8}=ne(),{HTTP_STATUS_CODES:u8}=c8,l8=St(),_8=ws(),LT=Q(),Jd=require("joi"),d8=et(),f8=2e3,E8=Jd.object({timeout:Jd.number().min(1),connected_nodes:Jd.boolean(),routes:Jd.boolean()});cU.exports=h8;async function h8(e){_8.checkClusteringEnabled();let t=d8.validateBySchema(e,E8);if(t)throw a8(t,t.message,u8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||LT.autoCastBoolean(n),o=s===void 0||LT.autoCastBoolean(s),c={nodes:[]},u=await l8.getServerList(r??f8),_={};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(S=>{h.connected_nodes.includes(S.name.slice(0,-4))||h.connected_nodes.push(S.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(S=>({host:S.split(":")[0],port:LT.autoCast(S.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(h8,"clusterNetwork")});var dU=R((Ffe,_U)=>{"use strict";var UT=require("joi"),uU=et(),{route_constraints:lU}=vh();_U.exports={setRoutesValidator:m8,deleteRoutesValidator:p8};function m8(e){let t=UT.object({server:UT.valid("hub","leaf").required(),routes:lU.required()});return uU.validateBySchema(e,t)}a(m8,"setRoutesValidator");function p8(e){let t=UT.object({routes:lU.required()});return uU.validateBySchema(e,t)}a(p8,"deleteRoutesValidator")});var vT=R((kfe,mU)=>{"use strict";var fo=cr(),PT=Q(),jd=U(),fU=dU(),{handleHDBError:EU,hdb_errors:S8}=ne(),{HTTP_STATUS_CODES:hU}=S8,T8="cluster routes successfully set",g8="cluster routes successfully deleted";mU.exports={setRoutes:R8,getRoutes:A8,deleteRoutes:O8};function R8(e){let t=fU.setRoutesValidator(e);if(t)throw EU(t,t.message,hU.BAD_REQUEST,void 0,void 0,!0);let r=fo.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=PT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:T8,set:o,skipped:i}}a(R8,"setRoutes");function A8(){let e=fo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(A8,"getRoutes");function O8(e){let t=fU.deleteRoutesValidator(e);if(t)throw EU(t,t.message,hU.BAD_REQUEST,void 0,void 0,!0);let r=fo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let S=n[E];if(d.host===S.host&&d.port===S.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,S=s.length;h<S;h++){let p=s[h];if(d.host===p.host&&d.port===p.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=PT.isEmptyOrZeroLength(n)?null:n,fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=PT.isEmptyOrZeroLength(s)?null:s,fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:g8,deleted:i,skipped:o}}a(O8,"deleteRoutes")});var SU=R(($fe,pU)=>{"use strict";var Uu=require("alasql"),Eo=require("recursive-iterator"),Bn=Y(),b8=Q(),Pu=U(),BT=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,N8(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Pu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Pu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Pu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=y8(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(_=>!Pu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Uu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function y8(e){return e.filter(t=>t[Pu.PERMS_CRUD_ENUM.READ])}a(y8,"filterReadRestrictedAttrs");function N8(e,t,r,n,s){I8(e,t,r,n,s)}a(N8,"interpretAST");function vu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(vu,"addSchemaTableToMap");function I8(e,t,r,n,s){if(!e){Bn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?L8(e,t,r):e instanceof Uu.yy.Select?w8(e,t,r,n,s):e instanceof Uu.yy.Update?C8(e,t,r):e instanceof Uu.yy.Delete?D8(e,t,r):Bn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(I8,"getRecordAttributesAST");function w8(e,t,r,n,s){if(!e){Bn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(b8.isEmptyOrZeroLength(i)){Bn.error("No schema specified");return}e.from.forEach(c=>{vu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),vu(c.table,t,r,n,s)});let o=new Eo(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Bn.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 Eo(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{Bn.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 Eo(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Bn.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 Eo(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Bn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(w8,"getSelectAttributes");function C8(e,t,r){if(!e){Bn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new Eo(e.columns),s=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&HT(e.table.tableid,s,i.columnid,t,r)}a(C8,"getUpdateAttributes");function D8(e,t,r){if(!e){Bn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new Eo(e.where),s=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&HT(e.table.tableid,s,i.columnid,t,r)}a(D8,"getDeleteAttributes");function L8(e,t,r){if(!e){Bn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new Eo(e.columns),s=e.into.databaseid;vu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&HT(e.into.tableid,s,i.columnid,t,r)}a(L8,"getInsertAttributes");function HT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(HT,"pushAttribute");pU.exports=BT});var FT=R((Kfe,AU)=>{var Xd=zi(),TU=require("chalk"),Vr=Y(),gU=require("prompt"),{promisify:M8}=require("util"),xT=U(),U8=require("fs-extra"),P8=require("path"),v8=Q(),B8=Gd(),RU=re();RU.initSync();var H8=require("moment"),x8=M8(gU.get),G8=P8.join(RU.getHdbBasePath(),xT.LICENSE_KEY_DIR_NAME,xT.LICENSE_FILE_NAME,xT.LICENSE_FILE_NAME);AU.exports={getFingerprint:q8,setLicense:F8,parseLicense:GT,register:k8,getRegistrationInfo:$8};async function F8(e){if(e&&e.key&&e.company){try{Vr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await GT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Vr.error(r),Vr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(F8,"setLicense");async function q8(){let e={};try{e=await Xd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Vr.error(r),Vr.error(t),new Error(r)}return e}a(q8,"getFingerprint");async function GT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Vr.info("Validating license input...");let r=Xd.validateLicense(e,t);if(Vr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Vr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Vr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Vr.info("writing license to disk"),await U8.writeFile(G8,JSON.stringify({license_key:e,company:t}))}catch(n){throw Vr.error("Failed to write License"),n}return"Registration successful."}a(GT,"parseLicense");async function k8(){let e=await V8();return GT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(k8,"register");async function V8(){let e=await Xd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:TU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:TU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{gU.start()}catch(n){Vr.error(n)}let r;try{r=await x8(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(V8,"promptForRegistration");async function $8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Xd.getLicense()}catch(r){throw Vr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(v8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=B8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=H8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a($8,"getRegistrationInfo")});var bU=R((Qfe,OU)=>{"use strict";var Y8=st(),qT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+Y8.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};OU.exports=qT});var IU=R((Jfe,NU)=>{"use strict";var yU=st(),kT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+yU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+yU.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"}};NU.exports=kT});var CU=R((Xfe,wU)=>{"use strict";var VT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};wU.exports=VT});var LU=R((eEe,DU)=>{"use strict";var K8=st(),$T=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+K8.SERVER_SUFFIX.ADMIN,this.password=r}};DU.exports=$T});var WT=R((rEe,PU)=>{"use strict";var pa=require("path"),tf=require("fs-extra"),W8=bU(),Q8=IU(),z8=CU(),J8=LU(),YT=xr(),Ta=Q(),gr=cr(),ef=U(),Bu=st(),{CONFIG_PARAMS:dt}=ef,ga=Y(),Hu=re(),MU=Rs(),KT=St(),Sa="clustering",j8=1e4,UU=50;PU.exports={generateNatsConfig:Z8,removeNatsConfig:e6,getHubConfigPath:X8};function X8(){let e=Hu.get(dt.ROOTPATH);return pa.join(e,Sa,Bu.NATS_CONFIG_FILES.HUB_SERVER)}a(X8,"getHubConfigPath");async function Z8(e=!1,t=void 0){Hu.initSync();let r=Hu.get(dt.ROOTPATH),n=pa.join(r,Sa,Bu.PID_FILES.HUB),s=pa.join(r,Sa,Bu.PID_FILES.LEAF),i=gr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=pa.join(r,Sa,Bu.NATS_CONFIG_FILES.HUB_SERVER),c=pa.join(r,Sa,Bu.NATS_CONFIG_FILES.LEAF_SERVER),u=gr.getConfigFromFile(dt.CLUSTERING_TLS_CERTIFICATE),_=gr.getConfigFromFile(dt.CLUSTERING_TLS_PRIVATEKEY),l=gr.getConfigFromFile(dt.CLUSTERING_TLS_CERT_AUTH),d=gr.getConfigFromFile(dt.CLUSTERING_TLS_INSECURE),f=gr.getConfigFromFile(dt.CLUSTERING_TLS_VERIFY),E=gr.getConfigFromFile(dt.CLUSTERING_NODENAME),h=gr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await KT.checkNATSServerInstalled()||rf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let S=await YT.listUsers(),p=gr.getConfigFromFile(dt.CLUSTERING_USER),T=await YT.getClusterUser();(Ta.isEmpty(T)||T.active!==!0)&&rf(`Invalid cluster user '${p}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Zd(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Zd(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Zd(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),await Zd(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let b=[],g=[];for(let[z,J]of S.entries())J.role.role===ef.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(b.push(new J8(J.username,MU.decrypt(J.hash))),g.push(new z8(J.username,MU.decrypt(J.hash))));let L=[],{hub_routes:v}=gr.getClusteringRoutes();if(!Ta.isEmptyOrZeroLength(v))for(let z of v)L.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${z.host}:${z.port}`);let P=new W8(gr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,gr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NAME),gr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),L,b,g);l==null&&(delete P.tls.ca_file,delete P.leafnodes.tls.ca_file),t=Ta.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===ef.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await tf.writeJson(o,P),ga.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,H=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,j=new Q8(gr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[k],[H],b,g,u,_,l,d);l==null&&delete j.tls.ca_file,(t===void 0||t===ef.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await tf.writeJson(c,j),ga.trace(`Leaf server config written to ${c}`))}a(Z8,"generateNatsConfig");async function Zd(e){let t=Hu.get(e);return Ta.isEmpty(t)&&rf(`port undefined for '${e}'`),await Ta.isPortTaken(t)&&rf(`'${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(Zd,"isPortAvailable");function rf(e){let t=`Error generating clustering config: ${e}`;ga.error(t),console.error(t),process.exit(1)}a(rf,"generateNatsConfigError");async function e6(e){let{port:t,config_file:r}=KT.getServerConfig(e),{username:n,decrypt_hash:s}=await YT.getClusterUser(),i=0,o=2e3;for(;i<UU;){try{let l=await KT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){ga.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=UU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&ga.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Ta.async_set_timeout(_)}let c="0".repeat(j8),u=pa.join(Hu.get(dt.ROOTPATH),Sa,r);await tf.writeFile(u,c),await tf.remove(u),ga.notify(e,"started.")}a(e6,"removeNatsConfig")});var FU=R((sEe,GU)=>{"use strict";var $r=re(),t6=zi(),he=U(),xu=st(),Cs=require("path"),{PACKAGE_ROOT:sf}=U(),vU=re(),nf=Q(),Ra="/dev/null",r6=Cs.join(sf,"launchServiceScripts"),BU=Cs.join(sf,"utility/scripts"),n6=Cs.join(BU,he.HDB_RESTART_SCRIPT),HU=Cs.resolve(sf,"dependencies",`${process.platform}-${process.arch}`,xu.NATS_BINARY_NAME);function xU(){let t=t6.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return nf.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=nf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:sf}}a(xU,"generateMainServerConfig");var s6=9930;function i6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",xu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=vU.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=xu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==s6?"-"+n:""),script:HU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ra,i.error_file=Ra),i}a(i6,"generateNatsHubServerConfig");var o6=9940;function a6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",xu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=vU.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=xu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==o6?"-"+n:""),script:HU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ra,i.error_file=Ra),i}a(a6,"generateNatsLeafServerConfig");function c6(){$r.initSync();let e=Cs.join($r.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:r6,autorestart:!1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Ra,t.error_file=Ra),t}a(c6,"generateClusteringUpgradeV4ServiceConfig");function u6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return nf.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=nf.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:BU},script:n6}}a(u6,"generateRestart");function l6(){return{apps:[xU()]}}a(l6,"generateAllServiceConfigs");GU.exports={generateAllServiceConfigs:l6,generateMainServerConfig:xU,generateRestart:u6,generateNatsHubServerConfig:i6,generateNatsLeafServerConfig:a6,generateClusteringUpgradeV4ServiceConfig:c6}});var eP=R((aEe,ZU)=>{"use strict";var ve=U(),_6=Q(),Ls=WT(),of=St(),Ds=st(),hi=FU(),af=re(),mi=Y(),d6=ws(),{startWorker:qU,onMessageFromWorkers:f6}=rt(),E6=ma(),oEe=require("util"),h6=require("child_process"),m6=require("fs"),{execFile:p6}=h6,Ie;ZU.exports={enterPM2Mode:S6,start:pi,stop:QT,reload:VU,restart:$U,list:zT,describe:KU,connect:Ms,kill:O6,startAllServices:b6,startService:JT,getUniqueServicesList:WU,restartAllServices:y6,isServiceRegistered:QU,reloadStopStart:zU,restartHdb:YU,deleteProcess:R6,startClusteringProcesses:jU,startClusteringThreads:XU,isHdbRestartRunning:A6,isClusteringRunning:I6,stopClustering:N6,reloadClustering:w6};var Gu=!1;f6(e=>{e.type==="restart"&&af.initSync(!0)});function S6(){Gu=!0}a(S6,"enterPM2Mode");function Ms(){return Ie||(Ie=require("pm2")),new Promise((e,t)=>{Ie.connect((r,n)=>{mi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var Rr,T6=10,kU;function pi(e,t=!1){if(Gu)return g6(e);let r=p6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Rr.indexOf(r);o>-1&&Rr.splice(o,1),!kU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<T6&&(m6.existsSync(Ls.getHubConfigPath())?pi(e):(await Ls.generateNatsConfig(!0),pi(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=af.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Ds.LOG_LEVELS[f]}if(Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Rr=[],!Rr&&!t){let i=a(()=>{kU=!0,Rr&&(Rr.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)}Rr.push(r)}a(pi,"start");function g6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.start(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(g6,"startWithPM2");function QT(e){if(!Gu){for(let t of Rr||[])t.name===e&&(Rr.splice(Rr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.stop(e,async(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.delete(e,(i,o)=>{i&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(o)})})})}a(QT,"stop");function VU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.reload(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(VU,"reload");function $U(e){if(!Gu)for(let t of Rr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.restart(e,(n,s)=>{Ie.disconnect(),t(s)})})}a($U,"restart");function R6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.delete(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(R6,"deleteProcess");async function YU(){await pi(hi.generateRestart())}a(YU,"restartHdb");async function A6(){let e=await zT();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(A6,"isHdbRestartRunning");function zT(){return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ie.list((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(zT,"list");function KU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.describe(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(KU,"describe");function O6(){if(!Gu){for(let e of Rr||[])e.kill();Rr=[];return}return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ie.killDaemon((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(O6,"kill");async function b6(){try{await jU(),await XU(),await pi(hi.generateAllServiceConfigs())}catch(e){throw Ie?.disconnect(),e}}a(b6,"startAllServices");async function JT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=hi.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=hi.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=hi.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=hi.generateNatsHubServerConfig(),await pi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=hi.generateNatsLeafServerConfig(),await pi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=hi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await pi(r)}catch(r){throw Ie?.disconnect(),r}}a(JT,"startService");async function WU(){try{let e=await zT(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw Ie?.disconnect(),e}}a(WU,"getUniqueServicesList");async function y6(e=[]){try{let t=!1,r=await WU();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await $U(o))}t&&await zU(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ie?.disconnect(),t}}a(y6,"restartAllServices");async function QU(e){if(Rr?.find(r=>r.name===e))return!0;let t=await E6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(QU,"isServiceRegistered");async function zU(e){let t=af.get(ve.CONFIG_PARAMS.THREADS_COUNT)??af.get(ve.CONFIG_PARAMS.THREADS),r=await KU(e),n=_6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await QT(e),await JT(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await YU():await VU(e)}a(zU,"reloadStopStart");var JU;async function jU(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await JT(r,e)}}a(jU,"startClusteringProcesses");async function XU(){JU=qU(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await of.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await of.updateLocalStreams();let e=await d6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){mi.info("Starting clustering upgrade 4.0.0 process"),qU(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(XU,"startClusteringThreads");async function N6(){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 JU.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await QT(t)}}a(N6,"stopClustering");async function I6(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await QU(t)===!1)return!1}return!0}a(I6,"isClusteringRunning");async function w6(){await Ls.generateNatsConfig(!0),await of.reloadNATSHub(),await of.reloadNATSLeaf(),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(w6,"reloadClustering")});var aP={};Fe(aP,{compactOnStart:()=>C6,copyDb:()=>oP});async function C6(){qu.notify("Running compact on start"),console.log("Running compact on start");let e=(0,jT.get)(Si.CONFIG_PARAMS.ROOTPATH),t=new Map,r=dr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}let i=(0,cf.join)(e,"backup",n+".mdb"),o=(0,cf.join)(e,Si.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await tP(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await oP(n,o),console.log("Backing up",n,"to",i),await(0,ho.move)(s,i,{overwrite:!0})}Fu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,ho.move)(i,s,{overwrite:!0}),await(0,ho.remove)((0,cf.join)(e,Si.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Fu()}catch(n){qu.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,XT.updateConfigValue)(Si.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,ho.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Fu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await tP(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
|
|
10
|
+
`,"")}a(QD,"runCommand");async function P3(){try{await _3.access(yS)}catch{return!1}let e=await QD(`${yS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return d3.eq(t,M3)}a(P3,"checkNATSServerInstalled");async function DS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await KD.getClusterUser();if(ao(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}vn.trace("create nats connection called");let i=await A3({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),vn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&vn.error("Error with Nats client connection, connection closed",o),zD()}),i}a(DS,"createConnection");function zD(){mr=void 0,so=void 0,io=void 0,oo=void 0}a(zD,"clearClientCache");async function v3(){mr&&(await mr.drain(),mr=void 0,so=void 0,io=void 0,oo=void 0)}a(v3,"closeConnection");var mr,oo;async function Su(){return oo||(oo=DS(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),mr=await oo),mr||oo}a(Su,"getConnection");async function Tu(){if(so)return so;ao(mr)&&await Su();let{domain:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ao(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return so=await mr.jetstreamManager({domain:e,timeout:6e4}),so}a(Tu,"getJetStreamManager");async function JD(){if(io)return io;ao(mr)&&await Su();let{domain:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ao(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=mr.jetstream({domain:e,timeout:6e4}),io}a(JD,"getJetStream");async function ns(){let e=mr||await Su(),t=so||await Tu(),r=io||await JD();return{connection:e,jsm:t,js:r}}a(ns,"getNATSReferences");async function B3(e){let t=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await KD.getClusterUser(),s=await DS(t,r,n),i=CS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=WD.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await Rd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(B3,"getServerList");async function LS(e,t){let{jsm:r}=await ns(),n=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:O3.File,retention:b3.Limits,subjects:t,discard:y3.Old,max_msgs:s,max_bytes:i,max_age:n})}a(LS,"createLocalStream");async function jD(){let{jsm:e}=await ns(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(jD,"listStreams");async function H3(e){let{jsm:t}=await ns();await t.streams.delete(e)}a(H3,"deleteLocalStream");async function x3(e){let{connection:t}=await ns(),r=[],n=CS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(WD.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(x3,"listRemoteStreams");async function G3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ns(),i=kD(),o={durable_name:i,ack_policy:IS.Explicit};t&&(o.deliver_policy=wS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=NS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Vt.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(G3,"viewStream");async function*F3(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ns(),i=kD(),o={durable_name:i,ack_policy:IS.Explicit};t&&(o.deliver_policy=wS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=NS(_.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(Vt.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(F3,"viewStreamIterator");async function q3(e,t,r,n){vn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=XD(n,r);let{js:s}=await ns(),i=await Od(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:YD.encode(n);try{vn.trace(`publishToStream publishing to subject: ${o}`),D3(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return eL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){vn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await LS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(q3,"publishToStream");function XD(e,t){t===void 0&&(t=I3());let r=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Vt.MSG_HEADERS.ORIGIN)&&r&&t.append(Vt.MSG_HEADERS.ORIGIN,r),t}a(XD,"addNatsMsgHeader");function aa(e){e=e.toLowerCase();let t=pu.join(Pt.get(Ne.CONFIG_PARAMS.ROOTPATH),L3);if(e===Ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ao(bS)&&(bS={port:hu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:hu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.HUB,config_file:Vt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:pu.join(t,Vt.PID_FILES.HUB),hdb_nats_path:t}),bS;if(e===Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ao(OS)&&(OS={port:hu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:hu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,config_file:Vt.NATS_CONFIG_FILES.LEAF_SERVER,domain:hu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,pid_file_path:pu.join(t,Vt.PID_FILES.LEAF),hdb_nats_path:t}),OS;vn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(aa,"getServerConfig");async function ZD(e,t,r,n){try{await e.consumers.add(t,{ack_policy:IS.Explicit,durable_name:r,deliver_policy:wS.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(ZD,"createConsumer");async function k3(e,t,r){await e.consumers.delete(t,r)}a(k3,"removeConsumer");function V3(e){return e.split(".")[1]}a(V3,"extractServerName");async function $3(e,t,r=6e4,n=CS()){if(!Rd.isObject(t))throw new Error("data param must be an object");let s=YD.encode(t),{connection:i}=await ns(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return NS(c.data)}a($3,"request");function MS(e){return new Promise(async(t,r)=>{let n=m3(yS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(MS,"reloadNATS");async function Y3(){let{pid_file_path:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await MS(e)}a(Y3,"reloadNATSHub");async function K3(){let{pid_file_path:e}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await MS(e)}a(K3,"reloadNATSLeaf");function W3(e,t,r){let n;switch(e.code){case qD.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case qD.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(W3,"requestErrorHandler");async function Q3(e,t){let r=t+Vt.SERVER_SUFFIX.LEAF,{connection:n}=await ns(),{jsm:s}=await rj(r),{schema:i,table:o}=e,c=Ad.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await eL(async()=>{if(e.subscribe===!0)await ZD(s,c,n.info.server_name,u);else try{await k3(s,c,n.info.server_name)}catch(_){vn.trace(_)}})}a(Q3,"updateRemoteConsumer");async function z3(e,t,r,n){let s=Ad.createNatsTableStreamName(e,t),i=r+Vt.SERVER_SUFFIX.LEAF,o={type:Ne.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!$D&&g3()<Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=AS();await c(o)}await S3(o),n==="stop"&&await Rd.async_set_timeout(1e3)}a(z3,"updateConsumerIterator");function eL(e){return p3.writeTransaction(Ne.SYSTEM_SCHEMA_NAME,Ne.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(eL,"exclusiveLock");async function tL(e,t){let r=Ad.createNatsTableStreamName(e,t),n=await Od(),s=Z3(e,t,n);await LS(r,[s])}a(tL,"createLocalTableStream");async function J3(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await tL(n,s)}}a(J3,"createTableStreams");async function rL(e,t,r=void 0){if(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Ad.createNatsTableStreamName(e,t),{domain:s}=aa(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Su()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")vn.warn(n);else throw n}}a(rL,"purgeTableStream");async function j3(e,t){if(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await rL(e,t[r])}a(j3,"purgeSchemaTableStreams");async function X3(e){return(await Tu()).streams.info(e)}a(X3,"getStreamInfo");function Z3(e,t,r){return`${Vt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Z3,"createSubjectName");async function Od(){if(mu)return mu;if(mu=(await Tu())?.nc?.info?.server_name,mu===void 0)throw new Error("Unable to get jetstream manager server name");return mu}a(Od,"getJsmServerName");async function ej(){let e=await Tu(),t=await Od(),r=await jD();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=tj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");vn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(ej,"updateLocalStreams");function tj(e){let{config:t}=e,r=!1,n=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(tj,"updateStreamLimits");async function rj(e){let t,r;try{t=await mr.jetstream({domain:e}),r=await mr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw vn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(rj,"connectToRemoteJS")});var Id=R((ude,aL)=>{"use strict";var ca=N_(),ua=dD(),nj=Y(),sj=require("uuid").v4,cde=require("clone"),yd=Os(),la=U(),ij=require("util"),ui=Dn(),{handleHDBError:pr,hdb_errors:oj}=ne(),{HDB_ERROR_MSGS:bd,HTTP_STATUS_CODES:Sr}=oj,{SchemaEventMsg:Nd}=Ln(),sL=St(),{getDatabases:aj}=(Re(),ie(qe)),{transformReq:_a}=Q();aL.exports={createSchema:cj,createSchemaStructure:iL,createTable:uj,createTableStructure:oL,createAttribute:Ej,dropSchema:lj,dropTable:_j,dropAttribute:dj,getBackup:hj};async function cj(e){let t=await iL(e);return yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema)),t}a(cj,"createSchema");async function iL(e){let t=ca.schema_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);if(_a(e),!await ua.checkSchemaExists(e.schema))throw pr(new Error,bd.SCHEMA_EXISTS_ERR(e.schema),Sr.BAD_REQUEST,la.LOG_LEVELS.ERROR,bd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ui.createSchema(e),`database '${e.schema}' successfully created`}a(iL,"createSchemaStructure");async function uj(e){return _a(e),e.hash_attribute=e.primary_key??e.hash_attribute,await oL(e)}a(uj,"createTable");async function oL(e){let t=ca.create_table_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);if(ca.validateTableResidence(e.residence),!await ua.checkSchemaTableExists(e.schema,e.table))throw pr(new Error,bd.TABLE_EXISTS_ERR(e.schema,e.table),Sr.BAD_REQUEST,la.LOG_LEVELS.ERROR,bd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:sj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ui.createTable(n,e);else throw pr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Sr.BAD_REQUEST);else await ui.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(oL,"createTableStructure");async function lj(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ca.schema_object(e),n=t??r;if(n)throw pr(n,n.message,Sr.BAD_REQUEST,void 0,void 0,!0);_a(e);let s=await ua.checkSchemaExists(e.schema);if(s)throw pr(new Error,s,Sr.NOT_FOUND,la.LOG_LEVELS.ERROR,s,!0);let i=await ua.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ui.dropSchema(e),yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema)),await sL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(lj,"dropSchema");async function _j(e){let t=ca.table_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);_a(e);let r=await ua.checkSchemaTableExists(e.schema,e.table);if(r)throw pr(new Error,r,Sr.NOT_FOUND,la.LOG_LEVELS.ERROR,r,!0);return await ui.dropTable(e),await sL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(_j,"dropTable");async function dj(e){let t=ca.attribute_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);_a(e);let r=await ua.checkSchemaTableExists(e.schema,e.table);if(r)throw pr(new Error,r,Sr.NOT_FOUND,la.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw pr(new Error,"You cannot drop a hash attribute",Sr.BAD_REQUEST,void 0,void 0,!0);if(la.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw pr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Sr.BAD_REQUEST,void 0,void 0,!0);try{return await ui.dropAttribute(e),fj(e),yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw nj.error(`Got an error deleting attribute ${ij.inspect(e)}.`),n}}a(dj,"dropAttribute");function fj(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(fj,"dropAttributeFromGlobal");async function Ej(e){_a(e);let t=aj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw pr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Sr.BAD_REQUEST,void 0,void 0,!0);return await ui.createAttribute(e),yd.signalSchemaChange(new Nd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Ej,"createAttribute");function hj(e){return ui.getBackup(e)}a(hj,"getBackup")});var uL=R((_de,cL)=>{"use strict";var{OPERATIONS_ENUM:mj}=U(),US=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=mj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};cL.exports=US});var PS=R((Ede,EL)=>{"use strict";var pj=Dn(),fde=uL(),wd=Q(),Cd=U(),Sj=re(),{handleHDBError:lL,hdb_errors:Tj}=ne(),{HDB_ERROR_MSGS:_L,HTTP_STATUS_CODES:dL}=Tj,gj=Object.values(Cd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),fL="To use this operation audit log must be enabled in harperdb-config.yaml";EL.exports=Rj;async function Rj(e){if(wd.isEmpty(e.schema))throw new Error(_L.SCHEMA_REQUIRED_ERR);if(wd.isEmpty(e.table))throw new Error(_L.TABLE_REQUIRED_ERR);if(!Sj.get(Cd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw lL(new Error,fL,dL.BAD_REQUEST,Cd.LOG_LEVELS.ERROR,fL,!0);let t=wd.checkSchemaTableExist(e.schema,e.table);if(t)throw lL(new Error,t,dL.NOT_FOUND,Cd.LOG_LEVELS.ERROR,t,!0);if(!wd.isEmpty(e.search_type)&&gj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await pj.readAuditLog(e)}a(Rj,"readAuditLog")});var mL=R((mde,hL)=>{"use strict";var{OPERATIONS_ENUM:Aj}=U(),vS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Aj.GET_BACKUP,this.schema=t,this.table=r}};hL.exports=vS});var TL=R((gde,SL)=>{"use strict";var Oj=Dn(),Sde=mL(),BS=Q(),bj=U(),Tde=re(),{handleHDBError:yj,hdb_errors:Nj}=ne(),{HDB_ERROR_MSGS:pL,HTTP_STATUS_CODES:Ij}=Nj;SL.exports=wj;async function wj(e){if(BS.isEmpty(e.schema))throw new Error(pL.SCHEMA_REQUIRED_ERR);if(BS.isEmpty(e.table))throw new Error(pL.TABLE_REQUIRED_ERR);let t=BS.checkSchemaTableExist(e.schema,e.table);if(t)throw yj(new Error,t,Ij.NOT_FOUND,bj.LOG_LEVELS.ERROR,t,!0);return await Oj.getBackup(read_audit_log_object)}a(wj,"getBackup")});var yL=R((Ade,bL)=>{var li=require("validate.js"),RL=et(),da=U(),{handleHDBError:Cj,hdb_errors:Dj}=ne(),{HDB_ERROR_MSGS:_t,HTTP_STATUS_CODES:Lj}=Dj,HS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),Mj={STRUCTURE_USER:"structure_user"},gL=Object.values(da.ROLE_TYPES_ENUM),Uj="attribute_permissions",Pj="attribute_name",{PERMS_CRUD_ENUM:fa}=da,vj=[Uj,...Object.values(fa)],AL=[fa.READ,fa.INSERT,fa.UPDATE],Bj=[Pj,...AL];function Hj(e){let t=HS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,OL(e,t)}a(Hj,"addRoleValidation");function xj(e){let t=HS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,OL(e,t)}a(xj,"alterRoleValidation");function Gj(e){let t=HS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,RL.validateObject(e,t)}a(Gj,"dropRoleValidation");var Fj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function OL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Fj.includes(n[o])||s.push(n[o]);s.length>0&&Tt(_t.INVALID_ROLE_JSON_KEYS(s),r);let i=RL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Tt(o,r)}),e.permission){let o=qj(e);o&&Tt(o,r),gL.forEach(c=>{e.permission[c]&&!li.isBoolean(e.permission[c])&&Tt(_t.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(gL.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]||Tt(_t.SCHEMA_NOT_FOUND(d),r)}continue}Tt(_t.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Tt(_t.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){Tt(_t.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{vj.includes(l)||Tt(_t.INVALID_PERM_KEY(l),r,o,u)}),Object.values(fa).forEach(l=>{li.isDefined(_[l])?li.isBoolean(_[l])||Tt(_t.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Tt(_t.TABLE_PERM_MISSING(l),r,o,u)}),li.isDefined(_.attribute_permissions)){if(!li.isArray(_.attribute_permissions)){Tt(_t.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Tt(_t.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(S=>{!Bj.includes(S)&&S!==fa.DELETE&&Tt(_t.INVALID_ATTR_PERM_KEY(S),r,o,u)}),!li.isDefined(E.attribute_name)){Tt(_t.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){Tt(_t.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}AL.forEach(S=>{li.isDefined(E[S])?li.isBoolean(E[S])||Tt(_t.ATTR_PERM_NOT_BOOLEAN(S,h),r,o,u):Tt(_t.ATTR_PERM_MISSING(S,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}`;Tt(_t.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return kj(r)}a(OL,"customValidate");bL.exports={addRoleValidation:Hj,alterRoleValidation:xj,dropRoleValidation:Gj};function qj(e){let{operation:t,permission:r}=e;if(t===da.OPERATIONS_ENUM.ADD_ROLE||t===da.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return _t.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?da.ROLE_TYPES_ENUM.SUPER_USER:da.ROLE_TYPES_ENUM.CLUSTER_USER;return _t.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(qj,"validateNoSUPerms");function kj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:_t.ROLE_PERMS_ERROR,...e};return Cj(new Error,n,Lj.BAD_REQUEST)}else return null}a(kj,"generateRolePermResponse");function Tt(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Tt,"addPermError")});var VS=R((bde,CL)=>{"use strict";var NL=an(),IL=xr(),Vj=Qi(),GS=yL(),FS=Os(),$j=require("uuid").v4,Yj=require("util"),Dd=U(),Kj=Q(),qS=IL.searchByValue,Wj=IL.searchByHash,Qj=Yj.promisify(Vj.delete),zj=Zn(),Jj=ra(),{hdb_errors:jj,handleHDBError:co}=ne(),{HDB_ERROR_MSGS:wL,HTTP_STATUS_CODES:gu}=jj,{UserEventMsg:kS}=Ln();CL.exports={addRole:Xj,alterRole:Zj,dropRole:eX,listRoles:tX};function xS(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(xS,"scrubRoleDetails");async function Xj(e){let t=GS.addRoleValidation(e);if(t)throw t;e=xS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await qS(r)||[])}catch(i){throw co(i)}if(n&&n.length>0)throw co(new Error,wL.ROLE_ALREADY_EXISTS(e.role),gu.CONFLICT,void 0,void 0,!0);e.id||(e.id=$j());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await NL.insert(s),FS.signalUserChange(new kS(process.pid)),e=xS(e),e}a(Xj,"addRole");async function Zj(e){let t=GS.alterRoleValidation(e);if(t)throw t;e=xS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await NL.update(r)}catch(s){throw co(s)}if(n&&n?.message==="updated 0 of 1 records")throw co(new Error,"Invalid role id",gu.BAD_REQUEST,void 0,void 0,!0);return await FS.signalUserChange(new kS(process.pid)),e}a(Zj,"alterRole");async function eX(e){let t=GS.dropRoleValidation(e);if(t)throw co(new Error,t,gu.BAD_REQUEST,void 0,void 0,!0);let r=new Jj(Dd.SYSTEM_SCHEMA_NAME,Dd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Wj(r));if(n.length===0)throw co(new Error,wL.ROLE_NOT_FOUND,gu.NOT_FOUND,void 0,void 0,!0);let s=new zj(Dd.SYSTEM_SCHEMA_NAME,Dd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await qS(s)),o=!1;if(Kj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw co(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,gu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Qj(c),FS.signalUserChange(new kS(process.pid)),`${n[0].role} successfully deleted`}a(eX,"dropRole");async function tX(){return qS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(tX,"listRoles")});var UL=R((Nde,ML)=>{"use strict";var rX=re(),_i=require("joi"),nX=et(),DL=require("moment"),sX=require("fs-extra"),$S=require("path"),iX=require("lodash"),Ru=U(),{LOG_LEVELS:uo}=U(),oX="YYYY-MM-DD hh:mm:ss",aX=$S.resolve(__dirname,"../logs");ML.exports=function(e){return nX.validateBySchema(e,cX)};var cX=_i.object({from:_i.custom(LL),until:_i.custom(LL),level:_i.valid(uo.NOTIFY,uo.FATAL,uo.ERROR,uo.WARN,uo.INFO,uo.DEBUG,uo.TRACE),order:_i.valid("asc","desc"),limit:_i.number().min(1),start:_i.number().min(0),log_name:_i.custom(uX)});function LL(e,t){if(DL(e,DL.ISO_8601).format(oX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(LL,"validateDatetime");function uX(e,t){if(iX.invert(Ru.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=rX.get(Ru.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Ru.LOG_NAMES.HDB:e,i=s===Ru.LOG_NAMES.INSTALL?$S.join(aX,Ru.LOG_NAMES.INSTALL):$S.join(n,s);return sX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(uX,"validateReadLogPath")});var KS=R((wde,vL)=>{"use strict";var Ld=U(),lX=Y(),_X=re(),dX=UL(),YS=require("path"),PL=require("fs-extra"),{once:fX}=require("events"),{handleHDBError:EX,hdb_errors:hX}=ne(),{PACKAGE_ROOT:mX}=U(),pX=YS.join(mX,"logs"),SX=1e3,TX=200;vL.exports=gX;async function gX(e){let t=dX(e);if(t)throw EX(t,t.message,hX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=_X.get(Ld.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Ld.LOG_NAMES.HDB:e.log_name,s=n===Ld.LOG_NAMES.INSTALL?YS.join(pX,Ld.LOG_NAMES.INSTALL):YS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?SX:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,S=0;f==="desc"&&!u&&!l&&(S=Math.max(PL.statSync(s).size-(h+5)*TX,0));let p=PL.createReadStream(s,{start:S});p.on("error",P=>{lX.error(P)});let T=0,b=[],g="",L;p.on("data",P=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=g+P;let H=0,j;for(;(j=k.exec(P))&&!p.destroyed;){L&&(L.message=P.slice(H,j.index),v(L));let[z,J,me]=j,ce=me.split("] ["),de=ce[0],Le=ce[1];ce.splice(0,2),L={timestamp:J,thread:de,level:Le,tags:ce,message:""},H=j.index+z.length}g=P.slice(H)}),p.on("end",P=>{p.destroyed||L&&(L.message=g.trim(),v(L))}),p.resume();function v(P){let k,H,j;switch(!0){case(i&&c&&_):k=new Date(P.timestamp),H=new Date(u),j=new Date(l),P.level===o&&k>=H&&k<=j&&T<E?T++:P.level===o&&k>=H&&k<=j&&(di(P,f,b),T++,T===h&&p.destroy());break;case(i&&c):k=new Date(P.timestamp),H=new Date(u),P.level===o&&k>=H&&T<E?T++:P.level===o&&k>=H&&(di(P,f,b),T++,T===h&&p.destroy());break;case(i&&_):k=new Date(P.timestamp),j=new Date(l),P.level===o&&k<=j&&T<E?T++:P.level===o&&k<=j&&(di(P,f,b),T++,T===h&&p.destroy());break;case(c&&_):k=new Date(P.timestamp),H=new Date(u),j=new Date(l),k>=H&&k<=j&&T<E?T++:k>=H&&k<=j&&(di(P,f,b),T++,T===h&&p.destroy());break;case i:P.level===o&&T<E?T++:P.level===o&&(di(P,f,b),T++,T===h&&p.destroy());break;case c:k=new Date(P.timestamp),H=new Date(u),k>=H&&T<E?T++:k>=H&&T>=E&&(di(P,f,b),T++,T===h&&p.destroy());break;case _:k=new Date(P.timestamp),j=new Date(l),k<=j&&T<E?T++:k<=j&&T>=E&&(di(P,f,b),T++,T===h&&p.destroy());break;default:T<E?T++:(di(P,f,b),T++,T===h&&p.destroy())}}return a(v,"onLogMessage"),await fX(p,"close"),b}a(gX,"readLog");function di(e,t,r){t==="desc"?RX(e,r):t==="asc"?AX(e,r):r.push(e)}a(di,"pushLineToResult");function RX(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(RX,"insertDescending");function AX(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(AX,"insertAscending")});var Md=R((Ude,GL)=>{"use strict";var WS=require("joi"),{string:Au,boolean:BL,date:OX}=WS.types(),bX=et(),{validateSchemaExists:Dde,validateTableExists:Lde,validateSchemaName:Mde}=zn(),yX=U(),NX=st(),HL=re();HL.initSync();var IX=Au.invalid(HL.get(yX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(NX.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(),xL={operation:Au.valid("add_node","update_node","set_node_replication"),node_name:IX,subscriptions:WS.array().items({table:Au.optional(),schema:Au.optional(),database:Au.optional(),subscribe:BL.required(),publish:BL.required().custom(CX),start_time:OX.iso()}).min(1).required()};function wX(e){return bX.validateBySchema(e,WS.object(xL))}a(wX,"addUpdateNodeValidator");function CX(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(CX,"checkForFalsy");GL.exports={addUpdateNodeValidator:wX,validation_schema:xL}});var qL=R((vde,FL)=>{var DX=et(),LX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};FL.exports=function(e){return DX.validateObject(e,LX)}});var zS=R((Bde,kL)=>{"use strict";var MX=U().OPERATIONS_ENUM,QS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=MX.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};kL.exports=QS});var $L=R((xde,VL)=>{"use strict";var UX={OPERATION:"operation",REFRESH:"refresh"},JS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},jS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};VL.exports={JWTTokens:JS,TOKEN_TYPE_ENUM:UX,JWTRSAKeys:jS}});var yu=R((Fde,QL)=>{"use strict";var bu=require("jsonwebtoken"),XS=require("fs-extra"),ZS=Q(),un=U(),{handleHDBError:Tr,hdb_errors:PX}=ne(),{HTTP_STATUS_CODES:gr,AUTHENTICATION_ERROR_MSGS:Rr}=PX,Ou=Y(),YL=k_(),rT=Fr(),vX=an().update,BX=zS(),HX=Os(),{UserEventMsg:xX}=Ln(),fi=re();fi.initSync();var eT=require("path"),{JWTTokens:GX,JWTRSAKeys:FX,TOKEN_TYPE_ENUM:Ud}=$L(),qX=fi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?fi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",kX=fi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?fi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Pd="RS256",tT;QL.exports={createTokens:VX,validateOperationToken:YX,refreshOperationToken:$X,validateRefreshToken:WL};async function VX(e){if(ZS.isEmpty(e)||typeof e!="object")throw Tr(new Error,Rr.INVALID_AUTH_OBJECT,gr.BAD_REQUEST,void 0,void 0,!0);if(ZS.isEmpty(e.username))throw Tr(new Error,Rr.USERNAME_REQUIRED,gr.BAD_REQUEST,void 0,void 0,!0);if(ZS.isEmpty(e.password))throw Tr(new Error,Rr.PASSWORD_REQUIRED,gr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await rT.findAndValidateUser(e.username,e.password),!t)throw Tr(new Error,Rr.INVALID_CREDENTIALS,gr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Ou.error(f),Tr(new Error,Rr.INVALID_CREDENTIALS,gr.UNAUTHORIZED,void 0,void 0,!0)}let r=await vd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await KL(i,r.private_key,r.passphrase),c=await bu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:kX,algorithm:Pd,subject:Ud.REFRESH}),u=YL.hash(c),_=new BX(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await vX(_)}catch(f){Ou.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw Tr(new Error,Rr.REFRESH_TOKEN_SAVE_FAILED,gr.INTERNAL_SERVER_ERROR);return HX.signalUserChange(new xX(process.pid)),new GX(o,c)}a(VX,"createTokens");async function KL(e,t,r){return await bu.sign(e,{key:t,passphrase:r},{expiresIn:qX,algorithm:Pd,subject:Ud.OPERATION})}a(KL,"signOperationToken");async function vd(){if(tT===void 0)try{let e=eT.join(fi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PASSPHRASE_NAME),t=eT.join(fi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=eT.join(fi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await XS.readFile(e)).toString(),s=(await XS.readFile(t)).toString(),i=(await XS.readFile(r)).toString();tT=new FX(i,s,n)}catch(e){throw Ou.error(e),Tr(new Error,Rr.NO_ENCRYPTION_KEYS,gr.INTERNAL_SERVER_ERROR)}return tT}a(vd,"getJWTRSAKeys");async function $X(e){if(!e)throw Tr(new Error,Rr.INVALID_BODY,gr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Tr(new Error,Rr.REFRESH_TOKEN_REQUIRED,gr.BAD_REQUEST,void 0,void 0,!0);await WL(e.refresh_token);let t=await vd(),r=await bu.decode(e.refresh_token);return{operation_token:await KL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a($X,"refreshOperationToken");async function YX(e){try{let t=await vd(),r=await bu.verify(e,t.public_key,{algorithms:Pd,subject:Ud.OPERATION});return await rT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Ou.warn(t),t.name&&t.name==="TokenExpiredError"?Tr(new Error,Rr.TOKEN_EXPIRED,gr.FORBIDDEN):Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED)}}a(YX,"validateOperationToken");async function WL(e){let t;try{let r=await vd(),n=await bu.verify(e,r.public_key,{algorithms:Pd,subject:Ud.REFRESH});t=await rT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Ou.warn(r),r.name&&r.name==="TokenExpiredError"?Tr(new Error,Rr.TOKEN_EXPIRED,gr.FORBIDDEN):Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED)}if(!YL.validate(t.refresh_token,e))throw Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED);return t}a(WL,"validateRefreshToken")});var nT=R((Vde,jL)=>{"use strict";var KX=qL(),Ea=require("passport"),WX=require("passport-local").Strategy,QX=require("passport-http").BasicStrategy,zX=require("util"),JX=Fr(),JL=zX.callbackify(JX.findAndValidateUser),kde=Lr(),jX=U(),zL=yu();Ea.use(new WX(function(e,t,r){JL(e,t,r)}));Ea.use(new QX(function(e,t,r){JL(e,t,r)}));Ea.serializeUser(function(e,t){t(null,e)});Ea.deserializeUser(function(e,t){t(null,e)});function XX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Ea.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===jX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?zL.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):zL.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Ea.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(XX,"authorize");function ZX(e,t){let r=KX(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(ZX,"checkPermissions");jL.exports={authorize:XX,checkPermissions:ZX}});var ha=R((Yde,XL)=>{"use strict";var sT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},iT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};XL.exports={Node:sT,NodeSubscription:iT}});var eM=R((Wde,ZL)=>{"use strict";var eZ=U().OPERATIONS_ENUM,oT=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=eZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};ZL.exports=oT});var Nu=R((zde,tM)=>{"use strict";var aT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},cT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};tM.exports={RemotePayloadObject:aT,RemotePayloadSubscription:cT}});var nM=R((jde,rM)=>{"use strict";var uT=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};rM.exports=uT});var oM=R((rfe,iM)=>{"use strict";var tZ=nM(),Zde=ct(),sM=Ye(),rZ=Y(),{getSchemaPath:efe,getTransactionAuditStorePath:tfe}=Qe(),{getDatabases:nZ}=(Re(),ie(qe));iM.exports=sZ;async function sZ(e){let t=new tZ;try{let r=nZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await sM.environmentDataSize(schema_path,e.name),o=await sM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){rZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(sZ,"lmdbGetTableSize")});var cM=R((sfe,aM)=>{"use strict";var lT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};aM.exports=lT});var ma=R((ufe,fM)=>{"use strict";var iZ=require("fs-extra"),oZ=require("path"),er=require("systeminformation"),Ei=Y(),uM=St(),ofe=st(),Hd=U(),aZ=oM(),cZ=ri(),{getThreadInfo:lM}=rt(),gT=re();gT.initSync();var uZ=cM(),{openEnvironment:afe}=Ye(),{getSchemaPath:cfe}=Qe(),{database:lZ,databases:_M}=(Re(),ie(qe)),Bd;fM.exports={getHDBProcessInfo:ET,getNetworkInfo:mT,getDiskInfo:hT,getMemoryInfo:fT,getCPUInfo:dT,getTimeInfo:_T,getSystemInformation:pT,systemInformation:_Z,getTableSize:ST,getMetrics:TT};function _T(){return er.time()}a(_T,"getTimeInfo");async function dT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await er.cpu();l.cpu_speed=await er.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:S,raw_currentload_user:p,cpus:T,...b}=await er.currentLoad();return b.cpus=[],T.forEach(g=>{let{raw_load:L,raw_load_idle:v,raw_load_irq:P,raw_load_nice:k,raw_load_system:H,raw_load_user:j,...z}=g;b.cpus.push(z)}),l.current_load=b,l}catch(e){return Ei.error(`error in getCPUInfo: ${e}`),{}}}a(dT,"getCPUInfo");async function fT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await er.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ei.error(`error in getMemoryInfo: ${e}`),{}}}a(fT,"getMemoryInfo");async function ET(){let e={core:[],clustering:[]};try{let t=await er.processes(),r;try{r=Number.parseInt(await iZ.readFile(oZ.join(gT.get(Hd.CONFIG_PARAMS.ROOTPATH),Hd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Hd.NODE_ERROR_CODES.ENOENT)Ei.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Ei.error(`error in getHDBProcessInfo: ${t}`),e}}a(ET,"getHDBProcessInfo");async function hT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await er.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await er.fsStats();return e.read_write=_,e.size=await er.fsSize(),e}catch(t){return Ei.error(`error in getDiskInfo: ${t}`),e}}a(hT,"getDiskInfo");async function mT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await er.networkInterfaceDefault(),e.latency=await er.inetChecksite("google.com"),(await er.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await er.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ei.error(`error in getNetworkInfo: ${t}`),e}}a(mT,"getNetworkInfo");async function pT(){if(Bd!==void 0)return Bd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await er.osInfo();e=c;let u=await er.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Bd=e,Bd}catch(t){return Ei.error(`error in getSystemInformation: ${t}`),e}}a(pT,"getSystemInformation");async function ST(){let e=[],t=await cZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await aZ(n));return e}a(ST,"getTableSize");async function TT(){let e={};for(let t in _M){let r=e[t]={};for(let n in _M[t])try{let s=lZ({database:t,table:n}),i=s.getStats();i.readers=s.readerList().split(/\n\s+/).slice(1).map(o=>{let[c,u,_]=o.trim().split(" ");return{pid:c,thread:u,txnid:_}}),r[n]=i}catch(s){Ei.notify(`Error getting stats for table ${n}: ${s}`)}}return e}a(TT,"getMetrics");async function dM(){if(gT.get(Hd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await uM.getNATSReferences(),t=await uM.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(dM,"getNatsStreamInfo");async function _Z(e){let t=new uZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await pT(),t.time=_T(),t.cpu=await dT(),t.memory=await fT(),t.disk=await hT(),t.network=await mT(),t.harperdb_processes=await ET(),t.table_size=await ST(),t.metrics=await TT(),t.threads=await lM(),t.replication=await dM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await pT();break;case"time":t.time=_T();break;case"cpu":t.cpu=await dT();break;case"memory":t.memory=await fT();break;case"disk":t.disk=await hT();break;case"network":t.network=await mT();break;case"harperdb_processes":t.harperdb_processes=await ET();break;case"table_size":t.table_size=await ST();break;case"database_metrics":case"metrics":t.metrics=await TT();break;case"threads":t.threads=await lM();break;case"replication":t.replication=await dM();break;default:break}return t}a(_Z,"systemInformation")});var Gd=R((_fe,EM)=>{"use strict";EM.exports={version:dZ,printVersion:fZ};var xd=au();function dZ(){if(xd)return xd.version}a(dZ,"version");function fZ(){xd&&console.log(`HarperDB Version ${xd.version}`)}a(fZ,"printVersion")});var ws=R((hfe,SM)=>{"use strict";var EZ=an(),RT=Q(),hZ=require("util"),lo=U(),hM=re();hM.initSync();var mZ=nT(),mM=xr(),{Node:ffe,NodeSubscription:Efe}=ha(),pZ=ra(),SZ=eM(),{RemotePayloadObject:TZ,RemotePayloadSubscription:gZ}=Nu(),{handleHDBError:RZ,hdb_errors:AZ}=ne(),{HTTP_STATUS_CODES:OZ,HDB_ERROR_MSGS:bZ}=AZ,yZ=Zn(),NZ=ma(),IZ=Gd(),{getDatabases:wZ}=(Re(),ie(qe)),CZ=hZ.promisify(mZ.authorize),DZ=mM.searchByHash,LZ=mM.searchByValue;SM.exports={authHeaderToUser:MZ,isEmpty:UZ,getNodeRecord:PZ,upsertNodeRecord:vZ,buildNodePayloads:BZ,checkClusteringEnabled:HZ,getAllNodeRecords:xZ,getSystemInfo:GZ,reverseSubscription:pM};async function MZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await CZ(t,null),e}a(MZ,"authHeaderToUser");function UZ(e){return e==null}a(UZ,"isEmpty");async function PZ(e){let t=new pZ(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return DZ(t)}a(PZ,"getNodeRecord");async function vZ(e){let t=new SZ(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return EZ.upsert(t)}a(vZ,"upsertNodeRecord");function pM(e){if(RT.isEmpty(e.subscribe)||RT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(pM,"reverseSubscription");function BZ(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=RT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=pM(c),E=wZ()[u]?.[_],h=new gZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new TZ(r,t,s,n)}a(BZ,"buildNodePayloads");function HZ(){if(!hM.get(lo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw RZ(new Error,bZ.CLUSTERING_NOT_ENABLED,OZ.BAD_REQUEST,void 0,void 0,!0)}a(HZ,"checkClusteringEnabled");async function xZ(){let e=new yZ(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await LZ(e))}a(xZ,"getAllNodeRecords");async function GZ(){let e=await NZ.getSystemInformation();return{hdb_version:IZ.version(),node_version:e.node_version,platform:e.platform}}a(GZ,"getSystemInfo")});var AT=R((pfe,NM)=>{"use strict";var Fd=St(),TM=Q(),gM=st(),RM=U(),qd=Y(),AM=Id(),FZ=Bp(),{RemotePayloadObject:qZ}=Nu(),{handleHDBError:OM,hdb_errors:kZ}=ne(),{HTTP_STATUS_CODES:bM}=kZ,{NodeSubscription:yM}=ha();NM.exports=VZ;async function VZ(e,t){let r;try{r=await Fd.request(`${t}.${gM.REQUEST_SUFFIX}`,new qZ(RM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),qd.trace("Response from remote describe all request:",r)}catch(o){qd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Fd.requestErrorHandler(o,"add_node",t);throw OM(new Error,c,bM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===gM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw OM(new Error,o,bM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===RM.SYSTEM_SCHEMA_NAME){await Fd.createLocalTableStream(u,c);let h=new yM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=TM.doesSchemaExist(u),l=n[u]!==void 0,d=c?TM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(qd.trace(`addNode creating schema: ${u}`),await AM.createSchema({operation:"create_schema",schema:u})),!d&&f){qd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new FZ(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await AM.createTable(h)}await Fd.createLocalTableStream(u,c);let E=new yM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(VZ,"reviewSubscriptions")});var Yd=R((Tfe,CM)=>{"use strict";var{handleHDBError:kd,hdb_errors:$Z}=ne(),{HTTP_STATUS_CODES:Vd}=$Z,{addUpdateNodeValidator:YZ}=Md(),$d=Y(),wM=U(),IM=st(),KZ=Q(),Iu=St(),wu=ws(),WZ=re(),QZ=AT(),{Node:zZ,NodeSubscription:JZ}=ha(),{broadcast:jZ}=rt(),XZ="Unable to create 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=WZ.get(wM.CONFIG_PARAMS.CLUSTERING_NODENAME);CM.exports=t5;async function t5(e,t=!1){$d.trace("addNode called with:",e),wu.checkClusteringEnabled();let r=YZ(e);if(r)throw kd(r,r.message,Vd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await wu.getNodeRecord(n);if(!KZ.isEmptyOrZeroLength(d))throw kd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Vd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await QZ(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=XZ,o;let c=wu.buildNodePayloads(s,e5,wM.OPERATIONS_ENUM.ADD_NODE,await wu.getSystemInfo()),u=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new JZ(E.schema,E.table,E.publish,E.subscribe))}$d.trace("addNode sending remote payload:",c);let _;try{_=await Iu.request(`${n}.${IM.REQUEST_SUFFIX}`,c)}catch(d){$d.error(`addNode received error from request: ${d}`);for(let E=0,h=s.length;E<h;E++){let S=s[E];S.publish=!1,S.subscribe=!1,await Iu.updateRemoteConsumer(S,n)}let f=Iu.requestErrorHandler(d,"add_node",n);throw kd(new Error,f,Vd.INTERNAL_SERVER_ERROR,"error",f)}if(_.status===IM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw kd(new Error,d,Vd.INTERNAL_SERVER_ERROR,"error",d)}$d.trace(_);for(let d=0,f=s.length;d<f;d++){let E=s[d];await Iu.updateRemoteConsumer(E,n),E.subscribe===!0&&await Iu.updateConsumerIterator(E.schema,E.table,n,"start")}let l=new zZ(n,u,_.system_info);return await wu.upsertNodeRecord(l),jZ({type:"nats_update"}),i.length>0?o.message=ZZ:o.message=`Successfully added '${n}' to manifest`,o}a(t5,"addNode")});var yT=R((Afe,MM)=>{"use strict";var{handleHDBError:OT,hdb_errors:r5}=ne(),{HTTP_STATUS_CODES:bT}=r5,{addUpdateNodeValidator:n5}=Md(),Cu=Y(),LM=U(),DM=st(),Rfe=Q(),Du=St(),Lu=ws(),s5=re(),{cloneDeep:i5}=require("lodash"),o5=AT(),{Node:a5,NodeSubscription:c5}=ha(),{broadcast:u5}=rt(),l5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",_5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",d5=s5.get(LM.CONFIG_PARAMS.CLUSTERING_NODENAME);MM.exports=f5;async function f5(e){Cu.trace("updateNode called with:",e),Lu.checkClusteringEnabled();let t=n5(e);if(t)throw OT(t,t.message,bT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Lu.getNodeRecord(r);s.length>0&&(n=i5(s));let{added:i,skipped:o}=await o5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=l5,c;let u=Lu.buildNodePayloads(i,d5,LM.OPERATIONS_ENUM.UPDATE_NODE,await Lu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let f=i[l];Cu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),i[l].start_time===void 0&&delete i[l].start_time}Cu.trace("updateNode sending remote payload:",u);let _;try{_=await Du.request(`${r}.${DM.REQUEST_SUFFIX}`,u)}catch(l){Cu.error(`updateNode received error from request: ${l}`);let d=Du.requestErrorHandler(l,"update_node",r);throw OT(new Error,d,bT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===DM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw OT(new Error,l,bT.INTERNAL_SERVER_ERROR,"error",l)}Cu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];await Du.updateRemoteConsumer(f,r),f.subscribe===!0?await Du.updateConsumerIterator(f.schema,f.table,r,"start"):await Du.updateConsumerIterator(f.schema,f.table,r,"stop")}return n||(n=[new a5(r,[],_.system_info)]),await E5(n[0],i,_.system_info),o.length>0?c.message=_5:c.message=`Successfully updated '${r}'`,c}a(f5,"updateNode");async function E5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new c5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Lu.upsertNodeRecord(n),u5({type:"nats_update"})}a(E5,"updateNodeTable")});var HM=R((bfe,BM)=>{"use strict";var vM=require("joi"),{string:UM}=vM.types(),h5=et(),PM=U(),m5=re(),p5=st();BM.exports=S5;function S5(e){let t=UM.invalid(m5.get(PM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(p5.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=vM.object({operation:UM.valid(PM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return h5.validateBySchema(e,r)}a(S5,"removeNodeValidator")});var Wd=R((Nfe,kM)=>{"use strict";var{handleHDBError:xM,hdb_errors:T5}=ne(),{HTTP_STATUS_CODES:GM}=T5,g5=HM(),Mu=Y(),FM=ws(),R5=Q(),Kd=U(),qM=st(),NT=St(),A5=re(),{RemotePayloadObject:O5}=Nu(),{NodeSubscription:b5}=ha(),y5=Xc(),N5=Qi(),{broadcast:I5}=rt(),w5=A5.get(Kd.CONFIG_PARAMS.CLUSTERING_NODENAME);kM.exports=C5;async function C5(e){Mu.trace("removeNode called with:",e),FM.checkClusteringEnabled();let t=g5(e);if(t)throw xM(t,t.message,GM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await FM.getNodeRecord(r);if(R5.isEmptyOrZeroLength(n))throw xM(new Error,`Node '${r}' was not found.`,GM.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new O5(Kd.OPERATIONS_ENUM.REMOVE_NODE,w5,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await NT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await NT.updateRemoteConsumer(new b5(l.schema,l.table,!1,!1),r)}catch(d){Mu.error(d)}}try{i=await NT.request(`${r}.${qM.REQUEST_SUFFIX}`,s),Mu.trace("Remove node reply from remote node:",r,i)}catch(u){Mu.error("removeNode received error from request:",u),o=!0}let c=new y5(Kd.SYSTEM_SCHEMA_NAME,Kd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await N5.deleteRecord(c),I5({type:"nats_update"}),i?.status===qM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Mu.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(C5,"removeNode")});var YM=R((wfe,$M)=>{"use strict";var VM=require("joi"),{string:D5,array:L5}=VM.types(),M5=et(),U5=Md();$M.exports=P5;function P5(e){let t=VM.object({operation:D5.valid("configure_cluster").required(),connections:L5.items(U5.validation_schema).required()});return M5.validateBySchema(e,t)}a(P5,"configureClusterValidator")});var IT=R((Dfe,JM)=>{"use strict";var v5=U(),Qd=Y(),B5=Q(),H5=Wd(),x5=Yd(),KM=ws(),G5=YM(),{handleHDBError:WM,hdb_errors:F5}=ne(),{HTTP_STATUS_CODES:QM}=F5,q5="Configure cluster complete.",k5="Failed to configure the cluster. Check the logs for more details.",V5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";JM.exports=$5;async function $5(e){Qd.trace("configure cluster called with:",e),KM.checkClusteringEnabled();let t=G5(e);if(t)throw WM(t,t.message,QM.BAD_REQUEST,void 0,void 0,!0);let r=await KM.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let f=await zM(H5,{operation:v5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(f)}Qd.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],f=await zM(x5,d,d.node_name);s.push(f)}Qd.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let f=_[l];f.status==="rejected"&&(Qd.error(f),o.includes(f.node_name)||o.push(f.node_name)),(f?.result?.message?.includes?.("Successfully")||f?.result?.includes?.("Successfully"))&&(u=!0),!(typeof f.result=="string"&&f.result.includes("Successfully removed")||f.status==="rejected")&&c.push({node_name:f?.node_name,subscriptions:f?.result})}if(B5.isEmptyOrZeroLength(o))return{message:q5,connections:c};if(u)return{message:V5,failed_nodes:o,connections:c};throw WM(new Error,k5,QM.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a($5,"configureCluster");async function zM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(zM,"functionWrapper")});var eU=R((Mfe,ZM)=>{"use strict";var Uu=require("joi"),Y5=et(),{validateSchemaExists:jM,validateTableExists:K5,validateSchemaName:XM}=zn(),W5=Uu.object({operation:Uu.string().valid("purge_stream"),schema:Uu.string().custom(jM).custom(XM).optional(),database:Uu.string().custom(jM).custom(XM).optional(),table:Uu.string().custom(K5).required()});function Q5(e){return Y5.validateBySchema(e,W5)}a(Q5,"purgeStreamValidator");ZM.exports=Q5});var wT=R((Pfe,tU)=>{"use strict";var{handleHDBError:z5,hdb_errors:J5}=ne(),{HTTP_STATUS_CODES:j5}=J5,X5=eU(),Z5=St(),e8=ws();tU.exports=t8;async function t8(e){e.schema=e.schema??e.database;let t=X5(e);if(t)throw z5(t,t.message,j5.BAD_REQUEST,void 0,void 0,!0);e8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await Z5.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(t8,"purgeStream")});var LT=R((Bfe,aU)=>{"use strict";var DT=ws(),r8=St(),sU=re(),zd=U(),_o=st(),n8=Q(),CT=Y(),{RemotePayloadObject:s8}=Nu(),{ErrorCode:rU}=require("nats"),nU=sU.get(zd.CONFIG_PARAMS.CLUSTERING_ENABLED),iU=sU.get(zd.CONFIG_PARAMS.CLUSTERING_NODENAME);aU.exports={clusterStatus:i8,buildNodeStatus:oU};async function i8(){let e={node_name:iU,is_enabled:nU,connections:[]};if(!nU)return e;let t=await DT.getAllNodeRecords();if(n8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(oU(t[n],e.connections));return await Promise.allSettled(r),e}a(i8,"clusterStatus");async function oU(e,t){let r=e.name,n=new s8(zd.OPERATIONS_ENUM.CLUSTER_STATUS,iU,void 0,await DT.getSystemInfo()),s,i,o=_o.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await r8.request(_o.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===_o.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=_o.CLUSTER_STATUS_STATUSES.CLOSED,CT.error(`Error getting node status from ${r} `,s))}catch(u){CT.warn(`Error getting node status from ${r}`,u),u.code===rU.NoResponders?o=_o.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===rU.Timeout?o=_o.CLUSTER_STATUS_STATUSES.TIMEOUT:o=_o.CLUSTER_STATUS_STATUSES.CLOSED}let c=new o8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==zd.PRE_4_0_0_VERSION&&await DT.upsertNodeRecord(u)}catch(u){CT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(oU,"buildNodeStatus");function o8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(o8,"NodeStatusObject")});var UT=R((xfe,cU)=>{"use strict";var{handleHDBError:a8,hdb_errors:c8}=ne(),{HTTP_STATUS_CODES:u8}=c8,l8=St(),_8=ws(),MT=Q(),Jd=require("joi"),d8=et(),f8=2e3,E8=Jd.object({timeout:Jd.number().min(1),connected_nodes:Jd.boolean(),routes:Jd.boolean()});cU.exports=h8;async function h8(e){_8.checkClusteringEnabled();let t=d8.validateBySchema(e,E8);if(t)throw a8(t,t.message,u8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||MT.autoCastBoolean(n),o=s===void 0||MT.autoCastBoolean(s),c={nodes:[]},u=await l8.getServerList(r??f8),_={};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(S=>{h.connected_nodes.includes(S.name.slice(0,-4))||h.connected_nodes.push(S.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(S=>({host:S.split(":")[0],port:MT.autoCast(S.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(h8,"clusterNetwork")});var dU=R((Ffe,_U)=>{"use strict";var PT=require("joi"),uU=et(),{route_constraints:lU}=Bh();_U.exports={setRoutesValidator:m8,deleteRoutesValidator:p8};function m8(e){let t=PT.object({server:PT.valid("hub","leaf").required(),routes:lU.required()});return uU.validateBySchema(e,t)}a(m8,"setRoutesValidator");function p8(e){let t=PT.object({routes:lU.required()});return uU.validateBySchema(e,t)}a(p8,"deleteRoutesValidator")});var BT=R((kfe,mU)=>{"use strict";var fo=lr(),vT=Q(),jd=U(),fU=dU(),{handleHDBError:EU,hdb_errors:S8}=ne(),{HTTP_STATUS_CODES:hU}=S8,T8="cluster routes successfully set",g8="cluster routes successfully deleted";mU.exports={setRoutes:R8,getRoutes:A8,deleteRoutes:O8};function R8(e){let t=fU.setRoutesValidator(e);if(t)throw EU(t,t.message,hU.BAD_REQUEST,void 0,void 0,!0);let r=fo.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=vT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:T8,set:o,skipped:i}}a(R8,"setRoutes");function A8(){let e=fo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(A8,"getRoutes");function O8(e){let t=fU.deleteRoutesValidator(e);if(t)throw EU(t,t.message,hU.BAD_REQUEST,void 0,void 0,!0);let r=fo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let S=n[E];if(d.host===S.host&&d.port===S.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,S=s.length;h<S;h++){let p=s[h];if(d.host===p.host&&d.port===p.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=vT.isEmptyOrZeroLength(n)?null:n,fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=vT.isEmptyOrZeroLength(s)?null:s,fo.updateConfigValue(jd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:g8,deleted:i,skipped:o}}a(O8,"deleteRoutes")});var SU=R(($fe,pU)=>{"use strict";var Pu=require("alasql"),Eo=require("recursive-iterator"),Bn=Y(),b8=Q(),vu=U(),HT=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,N8(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>vu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!vu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][vu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=y8(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(_=>!vu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Pu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function y8(e){return e.filter(t=>t[vu.PERMS_CRUD_ENUM.READ])}a(y8,"filterReadRestrictedAttrs");function N8(e,t,r,n,s){I8(e,t,r,n,s)}a(N8,"interpretAST");function Bu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Bu,"addSchemaTableToMap");function I8(e,t,r,n,s){if(!e){Bn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Pu.yy.Insert?L8(e,t,r):e instanceof Pu.yy.Select?w8(e,t,r,n,s):e instanceof Pu.yy.Update?C8(e,t,r):e instanceof Pu.yy.Delete?D8(e,t,r):Bn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(I8,"getRecordAttributesAST");function w8(e,t,r,n,s){if(!e){Bn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(b8.isEmptyOrZeroLength(i)){Bn.error("No schema specified");return}e.from.forEach(c=>{Bu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Bu(c.table,t,r,n,s)});let o=new Eo(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Bn.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 Eo(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{Bn.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 Eo(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Bn.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 Eo(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Bn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(w8,"getSelectAttributes");function C8(e,t,r){if(!e){Bn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new Eo(e.columns),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&xT(e.table.tableid,s,i.columnid,t,r)}a(C8,"getUpdateAttributes");function D8(e,t,r){if(!e){Bn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new Eo(e.where),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&xT(e.table.tableid,s,i.columnid,t,r)}a(D8,"getDeleteAttributes");function L8(e,t,r){if(!e){Bn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new Eo(e.columns),s=e.into.databaseid;Bu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&xT(e.into.tableid,s,i.columnid,t,r)}a(L8,"getInsertAttributes");function xT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(xT,"pushAttribute");pU.exports=HT});var qT=R((Kfe,AU)=>{var Xd=zi(),TU=require("chalk"),Yr=Y(),gU=require("prompt"),{promisify:M8}=require("util"),GT=U(),U8=require("fs-extra"),P8=require("path"),v8=Q(),B8=Gd(),RU=re();RU.initSync();var H8=require("moment"),x8=M8(gU.get),G8=P8.join(RU.getHdbBasePath(),GT.LICENSE_KEY_DIR_NAME,GT.LICENSE_FILE_NAME,GT.LICENSE_FILE_NAME);AU.exports={getFingerprint:q8,setLicense:F8,parseLicense:FT,register:k8,getRegistrationInfo:$8};async function F8(e){if(e&&e.key&&e.company){try{Yr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await FT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Yr.error(r),Yr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(F8,"setLicense");async function q8(){let e={};try{e=await Xd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Yr.error(r),Yr.error(t),new Error(r)}return e}a(q8,"getFingerprint");async function FT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Yr.info("Validating license input...");let r=Xd.validateLicense(e,t);if(Yr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Yr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Yr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Yr.info("writing license to disk"),await U8.writeFile(G8,JSON.stringify({license_key:e,company:t}))}catch(n){throw Yr.error("Failed to write License"),n}return"Registration successful."}a(FT,"parseLicense");async function k8(){let e=await V8();return FT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(k8,"register");async function V8(){let e=await Xd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:TU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:TU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{gU.start()}catch(n){Yr.error(n)}let r;try{r=await x8(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(V8,"promptForRegistration");async function $8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Xd.getLicense()}catch(r){throw Yr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(v8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=B8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=H8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a($8,"getRegistrationInfo")});var bU=R((Qfe,OU)=>{"use strict";var Y8=st(),kT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+Y8.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};OU.exports=kT});var IU=R((Jfe,NU)=>{"use strict";var yU=st(),VT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+yU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+yU.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"}};NU.exports=VT});var CU=R((Xfe,wU)=>{"use strict";var $T=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};wU.exports=$T});var LU=R((eEe,DU)=>{"use strict";var K8=st(),YT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+K8.SERVER_SUFFIX.ADMIN,this.password=r}};DU.exports=YT});var QT=R((rEe,PU)=>{"use strict";var pa=require("path"),tf=require("fs-extra"),W8=bU(),Q8=IU(),z8=CU(),J8=LU(),KT=Fr(),Ta=Q(),Ar=lr(),ef=U(),Hu=st(),{CONFIG_PARAMS:dt}=ef,ga=Y(),xu=re(),MU=Rs(),WT=St(),Sa="clustering",j8=1e4,UU=50;PU.exports={generateNatsConfig:Z8,removeNatsConfig:e6,getHubConfigPath:X8};function X8(){let e=xu.get(dt.ROOTPATH);return pa.join(e,Sa,Hu.NATS_CONFIG_FILES.HUB_SERVER)}a(X8,"getHubConfigPath");async function Z8(e=!1,t=void 0){xu.initSync();let r=xu.get(dt.ROOTPATH),n=pa.join(r,Sa,Hu.PID_FILES.HUB),s=pa.join(r,Sa,Hu.PID_FILES.LEAF),i=Ar.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=pa.join(r,Sa,Hu.NATS_CONFIG_FILES.HUB_SERVER),c=pa.join(r,Sa,Hu.NATS_CONFIG_FILES.LEAF_SERVER),u=Ar.getConfigFromFile(dt.CLUSTERING_TLS_CERTIFICATE),_=Ar.getConfigFromFile(dt.CLUSTERING_TLS_PRIVATEKEY),l=Ar.getConfigFromFile(dt.CLUSTERING_TLS_CERT_AUTH),d=Ar.getConfigFromFile(dt.CLUSTERING_TLS_INSECURE),f=Ar.getConfigFromFile(dt.CLUSTERING_TLS_VERIFY),E=Ar.getConfigFromFile(dt.CLUSTERING_NODENAME),h=Ar.getConfigFromFile(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await WT.checkNATSServerInstalled()||rf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let S=await KT.listUsers(),p=Ar.getConfigFromFile(dt.CLUSTERING_USER),T=await KT.getClusterUser();(Ta.isEmpty(T)||T.active!==!0)&&rf(`Invalid cluster user '${p}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Zd(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Zd(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Zd(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),await Zd(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let b=[],g=[];for(let[z,J]of S.entries())J.role.role===ef.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(b.push(new J8(J.username,MU.decrypt(J.hash))),g.push(new z8(J.username,MU.decrypt(J.hash))));let L=[],{hub_routes:v}=Ar.getClusteringRoutes();if(!Ta.isEmptyOrZeroLength(v))for(let z of v)L.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${z.host}:${z.port}`);let P=new W8(Ar.getConfigFromFile(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,Ar.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NAME),Ar.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),L,b,g);l==null&&(delete P.tls.ca_file,delete P.leafnodes.tls.ca_file),t=Ta.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===ef.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await tf.writeJson(o,P),ga.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,H=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,j=new Q8(Ar.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[k],[H],b,g,u,_,l,d);l==null&&delete j.tls.ca_file,(t===void 0||t===ef.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await tf.writeJson(c,j),ga.trace(`Leaf server config written to ${c}`))}a(Z8,"generateNatsConfig");async function Zd(e){let t=xu.get(e);return Ta.isEmpty(t)&&rf(`port undefined for '${e}'`),await Ta.isPortTaken(t)&&rf(`'${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(Zd,"isPortAvailable");function rf(e){let t=`Error generating clustering config: ${e}`;ga.error(t),console.error(t),process.exit(1)}a(rf,"generateNatsConfigError");async function e6(e){let{port:t,config_file:r}=WT.getServerConfig(e),{username:n,decrypt_hash:s}=await KT.getClusterUser(),i=0,o=2e3;for(;i<UU;){try{let l=await WT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){ga.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=UU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&ga.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Ta.async_set_timeout(_)}let c="0".repeat(j8),u=pa.join(xu.get(dt.ROOTPATH),Sa,r);await tf.writeFile(u,c),await tf.remove(u),ga.notify(e,"started.")}a(e6,"removeNatsConfig")});var FU=R((sEe,GU)=>{"use strict";var Kr=re(),t6=zi(),he=U(),Gu=st(),Cs=require("path"),{PACKAGE_ROOT:sf}=U(),vU=re(),nf=Q(),Ra="/dev/null",r6=Cs.join(sf,"launchServiceScripts"),BU=Cs.join(sf,"utility/scripts"),n6=Cs.join(BU,he.HDB_RESTART_SCRIPT),HU=Cs.resolve(sf,"dependencies",`${process.platform}-${process.arch}`,Gu.NATS_BINARY_NAME);function xU(){let t=t6.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return nf.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=nf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:sf}}a(xU,"generateMainServerConfig");var s6=9930;function i6(){Kr.initSync(!0);let e=Kr.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join(Kr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=vU.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[Kr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==s6?"-"+n:""),script:HU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Kr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ra,i.error_file=Ra),i}a(i6,"generateNatsHubServerConfig");var o6=9940;function a6(){Kr.initSync(!0);let e=Kr.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join(Kr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=vU.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[Kr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==o6?"-"+n:""),script:HU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Kr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ra,i.error_file=Ra),i}a(a6,"generateNatsLeafServerConfig");function c6(){Kr.initSync();let e=Cs.join(Kr.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:r6,autorestart:!1};return Kr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Ra,t.error_file=Ra),t}a(c6,"generateClusteringUpgradeV4ServiceConfig");function u6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return nf.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=nf.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:BU},script:n6}}a(u6,"generateRestart");function l6(){return{apps:[xU()]}}a(l6,"generateAllServiceConfigs");GU.exports={generateAllServiceConfigs:l6,generateMainServerConfig:xU,generateRestart:u6,generateNatsHubServerConfig:i6,generateNatsLeafServerConfig:a6,generateClusteringUpgradeV4ServiceConfig:c6}});var eP=R((aEe,ZU)=>{"use strict";var ve=U(),_6=Q(),Ls=QT(),of=St(),Ds=st(),hi=FU(),af=re(),mi=Y(),d6=ws(),{startWorker:qU,onMessageFromWorkers:f6}=rt(),E6=ma(),oEe=require("util"),h6=require("child_process"),m6=require("fs"),{execFile:p6}=h6,Ie;ZU.exports={enterPM2Mode:S6,start:pi,stop:zT,reload:VU,restart:$U,list:JT,describe:KU,connect:Ms,kill:O6,startAllServices:b6,startService:jT,getUniqueServicesList:WU,restartAllServices:y6,isServiceRegistered:QU,reloadStopStart:zU,restartHdb:YU,deleteProcess:R6,startClusteringProcesses:jU,startClusteringThreads:XU,isHdbRestartRunning:A6,isClusteringRunning:I6,stopClustering:N6,reloadClustering:w6};var Fu=!1;f6(e=>{e.type==="restart"&&af.initSync(!0)});function S6(){Fu=!0}a(S6,"enterPM2Mode");function Ms(){return Ie||(Ie=require("pm2")),new Promise((e,t)=>{Ie.connect((r,n)=>{mi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var Or,T6=10,kU;function pi(e,t=!1){if(Fu)return g6(e);let r=p6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Or.indexOf(r);o>-1&&Or.splice(o,1),!kU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<T6&&(m6.existsSync(Ls.getHubConfigPath())?pi(e):(await Ls.generateNatsConfig(!0),pi(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=af.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Ds.LOG_LEVELS[f]}if(Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Or=[],!Or&&!t){let i=a(()=>{kU=!0,Or&&(Or.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)}Or.push(r)}a(pi,"start");function g6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.start(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(g6,"startWithPM2");function zT(e){if(!Fu){for(let t of Or||[])t.name===e&&(Or.splice(Or.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.stop(e,async(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.delete(e,(i,o)=>{i&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(o)})})})}a(zT,"stop");function VU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.reload(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(VU,"reload");function $U(e){if(!Fu)for(let t of Or||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.restart(e,(n,s)=>{Ie.disconnect(),t(s)})})}a($U,"restart");function R6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.delete(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(R6,"deleteProcess");async function YU(){await pi(hi.generateRestart())}a(YU,"restartHdb");async function A6(){let e=await JT();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(A6,"isHdbRestartRunning");function JT(){return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ie.list((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(JT,"list");function KU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.describe(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(KU,"describe");function O6(){if(!Fu){for(let e of Or||[])e.kill();Or=[];return}return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ie.killDaemon((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(O6,"kill");async function b6(){try{await jU(),await XU(),await pi(hi.generateAllServiceConfigs())}catch(e){throw Ie?.disconnect(),e}}a(b6,"startAllServices");async function jT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=hi.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=hi.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=hi.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=hi.generateNatsHubServerConfig(),await pi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=hi.generateNatsLeafServerConfig(),await pi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=hi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await pi(r)}catch(r){throw Ie?.disconnect(),r}}a(jT,"startService");async function WU(){try{let e=await JT(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw Ie?.disconnect(),e}}a(WU,"getUniqueServicesList");async function y6(e=[]){try{let t=!1,r=await WU();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await $U(o))}t&&await zU(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ie?.disconnect(),t}}a(y6,"restartAllServices");async function QU(e){if(Or?.find(r=>r.name===e))return!0;let t=await E6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(QU,"isServiceRegistered");async function zU(e){let t=af.get(ve.CONFIG_PARAMS.THREADS_COUNT)??af.get(ve.CONFIG_PARAMS.THREADS),r=await KU(e),n=_6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await zT(e),await jT(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await YU():await VU(e)}a(zU,"reloadStopStart");var JU;async function jU(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await jT(r,e)}}a(jU,"startClusteringProcesses");async function XU(){JU=qU(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await of.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await of.updateLocalStreams();let e=await d6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){mi.info("Starting clustering upgrade 4.0.0 process"),qU(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(XU,"startClusteringThreads");async function N6(){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 JU.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await zT(t)}}a(N6,"stopClustering");async function I6(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await QU(t)===!1)return!1}return!0}a(I6,"isClusteringRunning");async function w6(){await Ls.generateNatsConfig(!0),await of.reloadNATSHub(),await of.reloadNATSLeaf(),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(w6,"reloadClustering")});var aP={};Fe(aP,{compactOnStart:()=>C6,copyDb:()=>oP});async function C6(){ku.notify("Running compact on start"),console.log("Running compact on start");let e=(0,XT.get)(Si.CONFIG_PARAMS.ROOTPATH),t=new Map,r=Er();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}let i=(0,cf.join)(e,"backup",n+".mdb"),o=(0,cf.join)(e,Si.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await tP(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await oP(n,o),console.log("Backing up",n,"to",i),await(0,ho.move)(s,i,{overwrite:!0})}qu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,ho.move)(i,s,{overwrite:!0}),await(0,ho.remove)((0,cf.join)(e,Si.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));qu()}catch(n){ku.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,ZT.updateConfigValue)(Si.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,ho.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw qu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await tP(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
|
|
11
11
|
Total record count before compaction: ${i}, total after: ${c}.
|
|
12
|
-
Database backup has not been removed and can be found here: ${s}`;
|
|
13
|
-
${r.stack}`;throw ng.error(n),mP(new Error)}}}a($6,"getRolePermissions");function Y6(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Ar.SYSTEM_SCHEMA_NAME]=n[Ar.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=K6(t[i]);return}r[i]=gP(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=W6(c,u);r[i].describe||AP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=sg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=sg()})}),r}a(Y6,"translateRolePermissions");function K6(e){let t=gP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=sg(!0,!0,!0,!0,!0)}),t}a(K6,"createStructureUserPermissions");function W6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return Ar.TIME_STAMP_NAMES.includes(d)&&(f=SP(d,l[Yu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=pP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=bP(l),s.attribute_permissions.push(l),c||Q6(l,u)}else if(_!==o){let l;Ar.TIME_STAMP_NAMES.includes(_)?l=SP(_):l=pP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=TP(s),s}else return e.describe=TP(e),e}a(W6,"getTableAttrPerms");function TP(e){return AP.filter(t=>e[t]).length>0}a(TP,"getSchemaTableDescribePerm");function bP(e){return OP.filter(t=>e[t]).length>0}a(bP,"getAttributeDescribePerm");function Q6(e,t){OP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(Q6,"checkForHashPerms")});var IP={};Fe(IP,{Resources:()=>mf,keyArrayToString:()=>Oa,resetResources:()=>z6,resources:()=>Ti});function z6(){return Ti=new mf}function Oa(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var mf,Ti,Ku=ge(()=>{to();mf=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(z6,"resetResources");a(Oa,"keyArrayToString")});var wP={};Fe(wP,{Headers:()=>gi,appendHeader:()=>ag});function ag(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var gi,Wu=ge(()=>{gi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(ag,"appendHeader")});var Qu={};Fe(Qu,{authentication:()=>BP,bypassAuth:()=>r9,login:()=>s9,logout:()=>i9,start:()=>n9});function r9(){vP=!0}async function BP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?Z6?X6:[]:j6?J6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new gi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return pf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),pf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(pf){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let S=s.indexOf(";",h),p=s.indexOf("=",h);u=s.slice(p+1,S===-1?s.length:S),_=await DP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,S)=>{let p=new ba.AuthAuditLog(E,h,vt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);p.auth_strategy=S,u&&(p.session_id=u),r.referer&&(p.referer=r.referer),r.origin&&(p.origin=r.origin),h===vt.AUTH_AUDIT_STATUS.SUCCESS?CP.notify(p):CP.error(p)},"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),l(E,vt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,ba.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=po.get(n),!d){let[E,h]=n.split(" "),S,p;try{switch(E){case"Basic":[S,p]=atob(h).split(":"),d=S||p?await tt.getUser(S,p,e):null;break;case"Bearer":try{d=await(0,Sf.validateOperationToken)(h)}catch(T){if(T.message==="invalid token")try{return await(0,Sf.validateRefreshToken)(h),c({status:-1})}catch{throw T}}break}}catch(T){return t9&&(po.get(h)||(po.set(h,h),l(S,vt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ri({error:T.message},e)})}po.set(n,d),e9&&l(d.username,vt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await tt.getUser(_.user,null,e):(vP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,MP.getSuperUser)());pf&&(e.session.update=function(E){if(!u){u=(0,UP.v4)();let S=`${(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",S):f?.headers?.set&&f.headers.set("Set-Cookie",S)}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,DP.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")&&Ti.loginPath?(f.status=302,f.headers.set("Location",Ti.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 gi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function n9({server:e,port:t}){e.request(BP,{port:t||"all"}),LP||(LP=!0,setInterval(()=>{po=new Map},_n.get(vt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),PP.user.addListener(()=>{po=new Map}))}async function s9(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 i9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var MP,Sf,UP,_n,vt,ba,PP,CP,J6,j6,X6,Z6,DP,pf,vP,e9,t9,po,LP,Tf=ge(()=>{MP=B(xr());or();Ku();Sf=B(bu());Re();UP=require("uuid"),_n=B(re()),vt=B(U()),ba=B(Y()),PP=B(kc());Wu();ya();CP=(0,ba.loggerWithTag)("auth-event");_n.initSync();J6=_n.get(vt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),j6=_n.get(vt.CONFIG_PARAMS.HTTP_CORS),X6=_n.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),Z6=_n.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),DP=ut({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),pf=_n.get(vt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,vP=_n.get(vt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,e9=_n.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,t9=_n.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,po=new Map;tt.onInvalidatedUser(()=>{po=new Map});a(r9,"bypassAuth");a(BP,"authentication");a(n9,"start");a(s9,"login");a(i9,"logout")});var VP=R((IEe,kP)=>{"use strict";var we=require("joi"),HP=require("fs-extra"),xP=require("path"),Ps=et(),GP=re(),FP=U(),qP=Y(),{hdb_errors:o9}=ne(),{HDB_ERROR_MSGS:er}=o9,Us=/^[a-zA-Z0-9-_]+$/;kP.exports={getDropCustomFunctionValidator:c9,setCustomFunctionValidator:u9,addComponentValidator:f9,dropCustomFunctionProjectValidator:E9,packageComponentValidator:h9,deployComponentValidator:m9,setComponentFileValidator:l9,getComponentFileValidator:d9,dropComponentFileValidator:_9};function gf(e,t,r){try{let n=GP.get(FP.CONFIG_PARAMS.COMPONENTSROOT),s=xP.join(n,t);return HP.existsSync(s)?e?t:r.message(er.PROJECT_EXISTS):e?r.message(er.NO_PROJECT):t}catch(n){return qP.error(n),r.message(er.VALIDATION_ERR)}}a(gf,"checkProjectExists");function zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(zu,"checkFilePath");function a9(e,t,r,n){try{let s=GP.get(FP.CONFIG_PARAMS.COMPONENTSROOT),i=xP.join(s,e,t,r+".js");return HP.existsSync(i)?r:n.message(er.NO_FILE)}catch(s){return qP.error(s),n.message(er.VALIDATION_ERR)}}a(a9,"checkFileExists");function c9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().pattern(Us).custom(a9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":er.BAD_FILE_NAME})});return Ps.validateBySchema(e,t)}a(c9,"getDropCustomFunctionValidator");function u9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().custom(zu).required(),function_content:we.string().required()});return Ps.validateBySchema(e,t)}a(u9,"setCustomFunctionValidator");function l9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:we.string().custom(zu).required(),payload:we.string().allow("").optional(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(l9,"setComponentFileValidator");function _9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:we.string().custom(zu).optional()});return Ps.validateBySchema(e,t)}a(_9,"dropComponentFileValidator");function d9(e){let t=we.object({project:we.string().required(),file:we.string().custom(zu).required(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(d9,"getComponentFileValidator");function f9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!1)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(f9,"addComponentValidator");function E9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(E9,"dropCustomFunctionProjectValidator");function h9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),skip_node_modules:we.boolean()});return Ps.validateBySchema(e,t)}a(h9,"packageComponentValidator");function m9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),payload:we.string().optional().messages({"string.pattern.base":er.BAD_PACKAGE}),package:we.string().optional()});return Ps.validateBySchema(e,t)}a(m9,"deployComponentValidator")});var bf=R((CEe,JP)=>{"use strict";var Rf=require("joi"),Af=require("path"),$P=require("fs-extra"),{exec:p9}=require("child_process"),S9=require("util"),YP=S9.promisify(p9),Ju=U(),{handleHDBError:Na,hdb_errors:T9}=ne(),{HTTP_STATUS_CODES:Ia}=T9,ju=re(),g9=et(),wa=Y();ju.initSync();var cg=ju.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),KP="npm install --omit=dev --json",R9=`${KP} --dry-run`;JP.exports={installModules:y9,auditModules:N9,installAllRootModules:A9,uninstallRootModule:O9,linkHarperdb:b9};async function A9(e=!1){await Of(),await Xu(e?"npm install --ignore-scripts":"npm install",ju.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(A9,"installAllRootModules");async function O9(e){await Xu(`npm uninstall ${e}`,ju.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(O9,"uninstallRootModule");async function b9(){await Of(),await Xu(`npm link ${Ju.PACKAGE_ROOT}`,ju.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(b9,"linkHarperdb");async function Xu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await YP(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
12
|
+
Database backup has not been removed and can be found here: ${s}`;ku.error(u),console.error(u)}(0,XT.get)(Si.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,ho.remove)(s))}(0,ZT.updateConfigValue)(Si.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function tP(e){let t=await(0,iP.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function oP(e,t){console.log("copyDb start");let r=Er()[e],n;for(let f in r){n=r[f].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,rP.open)(new nP.default(t)),c=o.openDB(uf.INTERNAL_DBIS_NAME),u,_=0;for(let{key:f,value:E}of s.getRange({})){let h=E.is_hash_attribute||E.isPrimaryKey,S,p;if(h&&(S=E.compression,p=_f(),p?E.compression=p:delete E.compression,S?.dictionary?.toString()===p?.dictionary?.toString()&&(S=null,p=null)),c.put(f,E),!(h||E.indexed))continue;let T=new sP.default(!h,h);T.encoding="binary",T.compression=S;let b=n.openDB(f,T);b.decoder=null,T.compression=p;let g=o.openDB(f,T);g.encoder=null,console.log("copying",f,"from",e,"to",t),await d(b,g,h)}let l=n.openDB(uf.AUDIT_STORE_NAME,lf);console.log("copying audit log"),d(i,l,!1);async function d(f,E,h){let S=0,p=0;for(let{key:T,value:b,version:g}of f.getRange({start:null,versions:h}))u=E.put(T,b,g),S++,p+=(T.length||10)+b.length,_++>5e3&&(await u,console.log("copied",S,"entries",p,"bytes"),_=0);console.log("finish copying, copied",S,"entries",p,"bytes")}a(d,"copyDbi"),await u,o.close(),console.log("copied database "+e+" to "+t)}var rP,cf,ho,XT,nP,sP,uf,Si,iP,ZT,ku,cP=ge(()=>{Re();rP=require("lmdb"),cf=require("path"),ho=require("fs-extra"),XT=B(re()),nP=B(Mc()),sP=B(Lc()),uf=B(ct()),Si=B(U());Zs();iP=B(ri()),ZT=B(lr()),ku=B(Y());a(C6,"compactOnStart");a(tP,"getTotalDBRecordCount");a(oP,"copyDb")});var hf=R((fEe,hP)=>{"use strict";var D6=require("minimist"),{isMainThread:tg,parentPort:_P}=require("worker_threads"),je=U(),{PROCESS_DESCRIPTORS_VALIDATE:Vu}=je,ss=Y(),rg=Q(),ff=QT(),df=St(),dEe=st(),dP=lr(),is=eP(),uP=ma(),{compactOnStart:L6}=(cP(),ie(aP)),M6=yh(),{restartWorkers:Ef,onMessageByType:U6}=rt(),{handleHDBError:P6,hdb_errors:v6}=ne(),{HTTP_STATUS_CODES:B6}=v6,Yu=re();Yu.initSync();var $u=`Restarting HarperDB. This may take up to ${je.RESTART_TIMEOUT_MS/1e3} seconds.`,H6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",lP="Clustering is not enabled so cannot be restarted",x6="Invalid service",Aa,ln;hP.exports={restart:fP,restartService:ng};tg&&U6(je.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ng({service:e.workerType}):fP({operation:"restart"})});async function fP(e){ln=Object.keys(e).length===0,Aa=await is.isServiceRegistered(je.HDB_PROC_DESCRIPTOR);let t=D6(process.argv);if(t.service){await ng(t);return}if(ln&&!Aa){console.error(H6);return}if(ln&&console.log($u),Aa){is.enterPM2Mode(),ss.notify($u);let r=M6(Object.keys(je.CONFIG_PARAM_MAP),!0);return rg.isEmptyOrZeroLength(Object.keys(r))||dP.updateConfigValue(void 0,void 0,r,!0,!0),G6(),$u}return tg?(ss.notify($u),Yu.get(je.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await L6(),setTimeout(()=>{Ef()},50)):_P.postMessage({type:je.ITC_EVENT_TYPES.RESTART}),$u}a(fP,"restart");async function ng(e){let{service:t}=e;if(je.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw P6(new Error,x6,B6.BAD_REQUEST,void 0,void 0,!0);if(Aa=await is.isServiceRegistered(je.HDB_PROC_DESCRIPTOR),!tg)return _P.postMessage({type:je.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Vu.clustering:if(!Yu.get(je.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=lP;break}ln&&console.log("Restarting clustering"),ss.notify("Restarting clustering"),await EP();break;case Vu.clustering_config:case Vu["clustering config"]:if(!Yu.get(je.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=lP;break}ln&&console.log("Restarting clustering_config"),ss.notify("Restarting clustering_config"),await is.reloadClustering();break;case"custom_functions":case"custom functions":case Vu.harperdb:case Vu.http_workers:if(ln&&!Aa){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}ln&&console.log("Restarting http_workers"),ss.notify("Restarting http_workers"),ln?await is.restart(je.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Ef("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(ss.error(r),ln&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(ng,"restartService");async function G6(){await EP(),await is.restart(je.HDB_PROC_DESCRIPTOR),await rg.async_set_timeout(2e3),Yu.get(je.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await eg(),ln&&(await df.closeConnection(),process.exit(0))}a(G6,"restartPM2Mode");async function EP(){if(!dP.getConfigFromFile(je.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await uP.getHDBProcessInfo()).clustering.length===0)ss.trace("Clustering not running, restart will start clustering services"),await ff.generateNatsConfig(!0),await is.startClusteringProcesses(),await is.startClusteringThreads(),await eg(),ln&&await df.closeConnection();else{await ff.generateNatsConfig(!0),Aa?(ss.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await is.restart(je.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await is.restart(je.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await uP.getHDBProcessInfo()).clustering.forEach(s=>{ss.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await rg.async_set_timeout(3e3),await eg(),await df.updateLocalStreams(),ln&&await df.closeConnection(),ss.trace("Restart clustering restarting ingest and reply service threads");let t=Ef(je.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Ef(je.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(EP,"restartClustering");async function eg(){await ff.removeNatsConfig(je.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ff.removeNatsConfig(je.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(eg,"removeNatsConfig")});var NP=R((mEe,yP)=>{"use strict";var hEe=require("lodash"),br=U(),{handleHDBError:mP,hdb_errors:F6}=ne(),{HDB_ERROR_MSGS:q6,HTTP_STATUS_CODES:k6}=F6,sg=Y();yP.exports={getRolePermissions:$6};var mo=Object.create(null),V6=a(e=>({key:e,perms:{}}),"perms_template_obj"),gP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),RP=a((e=!1,t=!1,r=!1,n=!1)=>({[br.PERMS_CRUD_ENUM.READ]:e,[br.PERMS_CRUD_ENUM.INSERT]:t,[br.PERMS_CRUD_ENUM.UPDATE]:r,[br.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),ig=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...RP(t,r,n,s)}),"table_perms_template"),pP=a((e,t=RP())=>({attribute_name:e,describe:bP(t),[Ku]:t[Ku],[og]:t[og],[ag]:t[ag]}),"attr_perms_template"),SP=a((e,t=!1)=>({attribute_name:e,describe:t,[Ku]:t}),"timestamp_attr_perms_template"),{READ:Ku,INSERT:og,UPDATE:ag}=br.PERMS_CRUD_ENUM,AP=Object.values(br.PERMS_CRUD_ENUM),OP=[Ku,og,ag];function $6(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[br.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(mo[t]&&mo[t].key===n)return mo[t].perms;let s=Y6(e,r);return mo[t]?mo[t].key=n:mo[t]=V6(n),mo[t].perms=s,s}catch(r){if(!e[br.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[br.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<br.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw sg.error(n),sg.debug(r),mP(new Error,q6.OUTDATED_PERMS_TRANSLATION_ERROR,k6.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
13
|
+
${r.stack}`;throw sg.error(n),mP(new Error)}}}a($6,"getRolePermissions");function Y6(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[br.SYSTEM_SCHEMA_NAME]=n[br.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=K6(t[i]);return}r[i]=gP(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=W6(c,u);r[i].describe||AP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=ig()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ig()})}),r}a(Y6,"translateRolePermissions");function K6(e){let t=gP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ig(!0,!0,!0,!0,!0)}),t}a(K6,"createStructureUserPermissions");function W6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return br.TIME_STAMP_NAMES.includes(d)&&(f=SP(d,l[Ku])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=pP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=bP(l),s.attribute_permissions.push(l),c||Q6(l,u)}else if(_!==o){let l;br.TIME_STAMP_NAMES.includes(_)?l=SP(_):l=pP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=TP(s),s}else return e.describe=TP(e),e}a(W6,"getTableAttrPerms");function TP(e){return AP.filter(t=>e[t]).length>0}a(TP,"getSchemaTableDescribePerm");function bP(e){return OP.filter(t=>e[t]).length>0}a(bP,"getAttributeDescribePerm");function Q6(e,t){OP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(Q6,"checkForHashPerms")});var IP={};Fe(IP,{Resources:()=>mf,keyArrayToString:()=>Oa,resetResources:()=>z6,resources:()=>Ti});function z6(){return Ti=new mf}function Oa(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var mf,Ti,Wu=ge(()=>{to();mf=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(z6,"resetResources");a(Oa,"keyArrayToString")});var wP={};Fe(wP,{Headers:()=>gi,appendHeader:()=>cg});function cg(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var gi,Qu=ge(()=>{gi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(cg,"appendHeader")});var zu={};Fe(zu,{authentication:()=>BP,bypassAuth:()=>r9,login:()=>s9,logout:()=>i9,start:()=>n9});function r9(){vP=!0}async function BP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?Z6?X6:[]:j6?J6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new gi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return pf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),pf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(pf){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let S=s.indexOf(";",h),p=s.indexOf("=",h);u=s.slice(p+1,S===-1?s.length:S),_=await DP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,S)=>{let p=new ba.AuthAuditLog(E,h,vt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);p.auth_strategy=S,u&&(p.session_id=u),r.referer&&(p.referer=r.referer),r.origin&&(p.origin=r.origin),h===vt.AUTH_AUDIT_STATUS.SUCCESS?CP.notify(p):CP.error(p)},"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),l(E,vt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,ba.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=po.get(n),!d){let[E,h]=n.split(" "),S,p;try{switch(E){case"Basic":[S,p]=atob(h).split(":"),d=S||p?await tt.getUser(S,p,e):null;break;case"Bearer":try{d=await(0,Sf.validateOperationToken)(h)}catch(T){if(T.message==="invalid token")try{return await(0,Sf.validateRefreshToken)(h),c({status:-1})}catch{throw T}}break}}catch(T){return t9&&(po.get(h)||(po.set(h,h),l(S,vt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ri({error:T.message},e)})}po.set(n,d),e9&&l(d.username,vt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await tt.getUser(_.user,null,e):(vP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,MP.getSuperUser)());pf&&(e.session.update=function(E){if(!u){u=(0,UP.v4)();let S=`${(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",S):f?.headers?.set&&f.headers.set("Set-Cookie",S)}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,DP.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")&&Ti.loginPath?(f.status=302,f.headers.set("Location",Ti.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 gi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function n9({server:e,port:t}){e.request(BP,{port:t||"all"}),LP||(LP=!0,setInterval(()=>{po=new Map},_n.get(vt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),PP.user.addListener(()=>{po=new Map}))}async function s9(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 i9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var MP,Sf,UP,_n,vt,ba,PP,CP,J6,j6,X6,Z6,DP,pf,vP,e9,t9,po,LP,Tf=ge(()=>{MP=B(Fr());cr();Wu();Sf=B(yu());Re();UP=require("uuid"),_n=B(re()),vt=B(U()),ba=B(Y()),PP=B(Vc());Qu();ya();CP=(0,ba.loggerWithTag)("auth-event");_n.initSync();J6=_n.get(vt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),j6=_n.get(vt.CONFIG_PARAMS.HTTP_CORS),X6=_n.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),Z6=_n.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),DP=ut({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),pf=_n.get(vt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,vP=_n.get(vt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,e9=_n.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,t9=_n.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,po=new Map;tt.onInvalidatedUser(()=>{po=new Map});a(r9,"bypassAuth");a(BP,"authentication");a(n9,"start");a(s9,"login");a(i9,"logout")});var VP=R((IEe,kP)=>{"use strict";var we=require("joi"),HP=require("fs-extra"),xP=require("path"),Ps=et(),GP=re(),FP=U(),qP=Y(),{hdb_errors:o9}=ne(),{HDB_ERROR_MSGS:tr}=o9,Us=/^[a-zA-Z0-9-_]+$/;kP.exports={getDropCustomFunctionValidator:c9,setCustomFunctionValidator:u9,addComponentValidator:f9,dropCustomFunctionProjectValidator:E9,packageComponentValidator:h9,deployComponentValidator:m9,setComponentFileValidator:l9,getComponentFileValidator:d9,dropComponentFileValidator:_9};function gf(e,t,r){try{let n=GP.get(FP.CONFIG_PARAMS.COMPONENTSROOT),s=xP.join(n,t);return HP.existsSync(s)?e?t:r.message(tr.PROJECT_EXISTS):e?r.message(tr.NO_PROJECT):t}catch(n){return qP.error(n),r.message(tr.VALIDATION_ERR)}}a(gf,"checkProjectExists");function Ju(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Ju,"checkFilePath");function a9(e,t,r,n){try{let s=GP.get(FP.CONFIG_PARAMS.COMPONENTSROOT),i=xP.join(s,e,t,r+".js");return HP.existsSync(i)?r:n.message(tr.NO_FILE)}catch(s){return qP.error(s),n.message(tr.VALIDATION_ERR)}}a(a9,"checkFileExists");function c9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!0)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().pattern(Us).custom(a9.bind(null,e.project,e.type)).custom(Ju).required().messages({"string.pattern.base":tr.BAD_FILE_NAME})});return Ps.validateBySchema(e,t)}a(c9,"getDropCustomFunctionValidator");function u9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!0)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().custom(Ju).required(),function_content:we.string().required()});return Ps.validateBySchema(e,t)}a(u9,"setCustomFunctionValidator");function l9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),file:we.string().custom(Ju).required(),payload:we.string().allow("").optional(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(l9,"setComponentFileValidator");function _9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),file:we.string().custom(Ju).optional()});return Ps.validateBySchema(e,t)}a(_9,"dropComponentFileValidator");function d9(e){let t=we.object({project:we.string().required(),file:we.string().custom(Ju).required(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(d9,"getComponentFileValidator");function f9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!1)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(f9,"addComponentValidator");function E9(e){let t=we.object({project:we.string().pattern(Us).custom(gf.bind(null,!0)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(E9,"dropCustomFunctionProjectValidator");function h9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),skip_node_modules:we.boolean()});return Ps.validateBySchema(e,t)}a(h9,"packageComponentValidator");function m9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),payload:we.string().optional().messages({"string.pattern.base":tr.BAD_PACKAGE}),package:we.string().optional()});return Ps.validateBySchema(e,t)}a(m9,"deployComponentValidator")});var bf=R((CEe,JP)=>{"use strict";var Rf=require("joi"),Af=require("path"),$P=require("fs-extra"),{exec:p9}=require("child_process"),S9=require("util"),YP=S9.promisify(p9),ju=U(),{handleHDBError:Na,hdb_errors:T9}=ne(),{HTTP_STATUS_CODES:Ia}=T9,Xu=re(),g9=et(),wa=Y();Xu.initSync();var ug=Xu.get(ju.CONFIG_PARAMS.COMPONENTSROOT),KP="npm install --omit=dev --json",R9=`${KP} --dry-run`;JP.exports={installModules:y9,auditModules:N9,installAllRootModules:A9,uninstallRootModule:O9,linkHarperdb:b9};async function A9(e=!1){await Of(),await Zu(e?"npm install --ignore-scripts":"npm install",Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(A9,"installAllRootModules");async function O9(e){await Zu(`npm uninstall ${e}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(O9,"uninstallRootModule");async function b9(){await Of(),await Zu(`npm link ${ju.PACKAGE_ROOT}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(b9,"linkHarperdb");async function Zu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await YP(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
14
14
|
`,""))}return n&&!n.includes("Debugger listening")&&wa.error("Error running NPM command:",e,n),wa.trace(r,n),r?.replace(`
|
|
15
|
-
`,"")}a(
|
|
15
|
+
`,"")}a(Zu,"runCommand");async function y9(e){wa.info(`starting installModules for request: ${e}`);let t=zP(e);if(t)throw Na(t,t.message,Ia.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?R9:KP;await Of(),await QP(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 _=Af.join(ug,u),l,d=null;try{let{stdout:f,stderr:E}=await YP(s,{cwd:_});l=f?f.replace(`
|
|
16
16
|
`,""):null,d=E?E.replace(`
|
|
17
17
|
`,""):null}catch(f){f.stderr?i[u].npm_error=WP(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 wa.info(`finished installModules with response ${i}`),i}a(y9,"installModules");function WP(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
|
|
18
|
-
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(WP,"parseNPMStdErr");async function N9(e){wa.info(`starting auditModules for request: ${e}`);let t=zP(e);if(t)throw Na(t,t.message,Ia.BAD_REQUEST);let{projects:r}=e;await Of(),await QP(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Af.join(cg,o);n[o]={npm_output:null,npm_error:null};try{let u=await Xu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=WP(u.stderr)}}return wa.info(`finished auditModules with response ${n}`),n}a(N9,"auditModules");async function Of(){try{return await Xu("npm -v"),!0}catch{throw Na(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ia.BAD_REQUEST,void 0,void 0,!0)}}a(Of,"checkNPMInstalled");async function QP(e){if(!Array.isArray(e)||e.length===0)throw Na(new Error,"projects argument must be an array with at least 1 element",Ia.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Af.join(cg,i.toString());if(!await $P.pathExists(o)){t.push(i);continue}let u=Af.join(o,"package.json");await $P.pathExists(u)||r.push(i)}if(t.length>0)throw Na(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ia.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Na(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ia.BAD_REQUEST,void 0,void 0,!0)}a(QP,"checkProjectPaths");function zP(e){let t=Rf.object({projects:Rf.array().min(1).items(Rf.string()).required(),dry_run:Rf.boolean().default(!1)});return g9.validateBySchema(e,t)}a(zP,"modulesValidator")});var lg=R((LEe,tv)=>{"use strict";var Ca=require("fs-extra"),ug=require("path"),yf=Y(),jP=Q(),Nf=U(),ev=re(),I9=cr();tv.exports=w9;async function w9(){let e=C9(),t=ev.get(Nf.CONFIG_PARAMS.ROOTPATH),r=ug.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Nf.PACKAGE_ROOT}},s=ug.join(t,"node_modules");await Ca.ensureDir(s);let i,o=!0,c=!1;try{i=await Ca.readJson(r)}catch(u){if(jP.isEmptyOrZeroLength(e))return;if(u.code!==Nf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!jP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await XP(_);n.dependencies[u]=l+_}if(!o){yf.notify("Installing components"),await ZP(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await XP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(yf.notify("Removing component",u),c=!0);c&&(yf.notify("Updating components."),await ZP(r,n,i))}a(w9,"installComponents");function C9(){let e=I9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(C9,"getComponentsConfig");async function XP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":ug.extname(e)||await Ca.pathExists(e)?"file:":"github:"}a(XP,"getPkgPrefix");async function ZP(e,t,r){yf.trace("npm installing components package.json",t),await Ca.writeFile(e,JSON.stringify(t,null," "));try{await bf().installAllRootModules(ev.get(Nf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ca.writeFile(e,JSON.stringify(r,null," ")):await Ca.unlink(e),n}}a(ZP,"installPackages")});var fg=R((PEe,iv)=>{"use strict";var ke=require("fs-extra"),_g=require("fast-glob"),Te=require("path"),nv=require("tar-fs"),UEe=require("uuid").v4,dg=require("normalize-path"),os=VP(),Nt=Y(),Ke=U(),gt=re(),Zu=cr(),D9=Q(),{PACKAGE_ROOT:L9}=U(),{handleHDBError:Bt,hdb_errors:M9}=ne(),{basename:U9}=require("path"),P9=lg(),sv=re(),v9=U(),{Readable:B9}=require("stream"),{isMainThread:H9}=require("worker_threads"),{HDB_ERROR_MSGS:So,HTTP_STATUS_CODES:Ht}=M9,x9=Te.join(L9,"application-template"),rv=Te.join(gt.get(Ke.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function G9(){Nt.trace("getting custom api status");let e={};try{e={port:gt.get(Ke.CONFIG_PARAMS.HTTP_PORT),directory:gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,So.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(G9,"customFunctionsStatus");function F9(){Nt.trace("getting custom api endpoints");let e={},t=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT);try{_g.sync(dg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:_g.sync(dg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:_g.sync(dg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,So.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(F9,"getCustomFunctions");function q9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("getting custom api endpoint file content");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,So.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(q9,"getCustomFunction");function k9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("setting custom function file content");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return ke.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,So.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(k9,"setCustomFunction");function V9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function file");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return ke.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,So.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(V9,"dropCustomFunction");function $9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("adding component");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return ke.mkdirSync(s,{recursive:!0}),ke.copySync(x9,s),`Successfully added project: ${n}`}catch(s){throw Bt(new Error,So.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,s)}}a($9,"addComponent");function Y9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function project");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=gt.get(Ke.CONFIG_PARAMS.APPS);if(!D9.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return Zu.updateConfigValue(Ke.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Bt(new Error,So.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(Y9,"dropCustomFunctionProject");async function K9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Nt.trace("packaging component",n);let s;try{s=await ke.realpath(Te.join(r,n))}catch(u){if(u.code!==Ke.NODE_ERROR_CODES.ENOENT)throw u;try{s=await ke.realpath(Te.join(gt.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Ke.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await ke.ensureDir(rv);let i=Te.join(rv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),nv.pack(s,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:n,payload:c}}a(K9,"packageComponent");async function W9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Nt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await ke.ensureDir(o);let f=B9.from(Buffer.from(s,"base64"));await new Promise((h,S)=>{f.pipe(nv.extract(o,{finish:h})).on("error",S)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(Te.join(o,"package"),o),await ke.remove(Te.join(o,"package")))}if(await Zu.addConfig(n,{package:i}),!s){await P9();let f=sv.get(v9.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",n)}if(H9)return;let c=new Map;c.isWorker=!0;let u=(wf(),ie(If)),_;u.setErrorReporter(f=>_=f);let l=U9(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: ${n}`}a(W9,"deployComponent");async function Q9(){let e=Zu.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=Te.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:Te.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"),n=await r(gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{name:gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(gt.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(wf(),ie(If)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(Q9,"getComponents");async function z9(e){let t=os.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let n=Zu.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(sv.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules"):gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Te.join(n,e.project,e.file));return{message:await ke.readFile(Te.join(n,e.project,e.file),s),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 '${Te.join(e.project,e.file)}'`):i}}a(z9,"getComponentFile");async function J9(e){let t=os.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(n),await ke.outputFile(n,e.payload,r)):await ke.ensureDir(n),"Successfully set component: "+e.file}a(J9,"setComponentFile");async function j9(e){let t=os.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(n)&&await ke.remove(n),Zu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(j9,"dropComponent");iv.exports={customFunctionsStatus:G9,getCustomFunctions:F9,getCustomFunction:q9,setCustomFunction:k9,dropCustomFunction:V9,addComponent:$9,dropCustomFunctionProject:Y9,packageComponent:K9,deployComponent:W9,getComponents:Q9,getComponentFile:z9,setComponentFile:J9,dropComponent:j9}});var Eg=R((BEe,av)=>{"use strict";var as=require("joi"),ov=et();av.exports={readTransactionLogValidator:X9,deleteTransactionLogsBeforeValidator:Z9};function X9(e){let t=as.object({schema:as.string().required(),table:as.string().required(),from:as.date().timestamp(),to:as.date().timestamp(),limit:as.number().min(1)});return ov.validateBySchema(e,t)}a(X9,"readTransactionLogValidator");function Z9(e){let t=as.object({schema:as.string().required(),table:as.string().required(),timestamp:as.date().timestamp().required()});return ov.validateBySchema(e,t)}a(Z9,"deleteTransactionLogsBeforeValidator")});var Cf=R((xEe,dv)=>{"use strict";var hg=U(),el=St(),cv=Q(),uv=re(),lv=Rs(),{handleHDBError:Da,hdb_errors:e7}=ne(),{HTTP_STATUS_CODES:La}=e7,{readTransactionLogValidator:t7,deleteTransactionLogsBeforeValidator:r7}=Eg(),_v="This operation relies on clustering and cannot run with it disable.",n7="Logs successfully deleted from transaction log.",s7="All logs successfully deleted from transaction log.";dv.exports={readTransactionLog:i7,deleteTransactionLogsBefore:o7};async function*i7(e){let t=t7(e);if(t)throw Da(t,t.message,La.BAD_REQUEST,void 0,void 0,!0);if(!uv.get(hg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Da(new Error,_v,La.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=cv.checkSchemaTableExist(r,n);if(s)throw Da(new Error,s,La.NOT_FOUND,void 0,void 0,!0);let i=lv.createNatsTableStreamName(r,n),o=await el.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===hg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(i7,"readTransactionLog");async function o7(e){let t=r7(e);if(t)throw Da(t,t.message,La.BAD_REQUEST,void 0,void 0,!0);if(!uv.get(hg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Da(new Error,_v,La.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=cv.checkSchemaTableExist(r,n);if(i)throw Da(new Error,i,La.NOT_FOUND,void 0,void 0,!0);let o=lv.createNatsTableStreamName(r,n),{jsm:c}=await el.getNATSReferences(),u=await el.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=n7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=s7):d=(await el.viewStream(o,parseInt(s),1))[0].nats_sequence,await el.purgeTableStream(r,n,{seq:d}),l}a(o7,"deleteTransactionLogsBefore")});var Ev=R((FEe,fv)=>{"use strict";var mg=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};fv.exports=mg});var mv=R((kEe,hv)=>{"use strict";var pg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};hv.exports=pg});var Tg=R(($Ee,Sv)=>{"use strict";var pv=Ev(),a7=mv(),{HDB_ERROR_MSGS:c7}=Cr(),Sg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=c7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new pv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new a7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new pv(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};Sv.exports=Sg});var Uf=R((KEe,Pv)=>{"use strict";var gg=an(),Df=Br(),fn=Id(),nl=ri(),Rg=Qi(),u7=US(),l7=TL(),sl=xr(),Lf=kS(),It=Y(),_7=YS(),d7=Yd(),f7=bT(),E7=Wd(),h7=NT(),m7=IT(),p7=DT(),S7=MT(),Ag=vT(),vs=Q(),T7=SU(),Og=FT(),Rv=hf(),dn=U(),Av=NP(),g7=ma(),Ov=bu(),bv=(Tf(),ie(Qu)),yv=cr(),Yr=fg(),R7=require("alasql"),Nv=Cf(),Iv=bf(),wv=Tg(),{handleHDBError:Or,hdb_errors:Cv}=ne(),{HDB_ERROR_MSGS:$t,HTTP_STATUS_CODES:tl}=Cv,V=new Map,Dv="delete",Ai="insert",Bs="read",To="update",rl="describe",Tv=nl.describeSchema.name,gv=nl.describeTable.name,Lv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},A7="catchup",O7="handleGetJob",b7="handleGetJobsByStartDate",Mf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},y7=[fn.createTable.name,fn.createAttribute.name,fn.dropTable.name,fn.dropAttribute.name],Mv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(gg.insert.name,new W(!1,[Ai]));V.set(gg.update.name,new W(!1,[To]));V.set(gg.upsert.name,new W(!1,[Ai,To]));V.set(Df.searchByConditions.name,new W(!1,[Bs]));V.set(Df.searchByHash.name,new W(!1,[Bs]));V.set(Df.searchByValue.name,new W(!1,[Bs]));V.set(Df.search.name,new W(!1,[Bs]));V.set(fn.createSchema.name,new W(!0,[]));V.set(fn.createTable.name,new W(!0,[]));V.set(fn.createAttribute.name,new W(!1,[Ai]));V.set(fn.dropSchema.name,new W(!0,[]));V.set(fn.dropTable.name,new W(!0,[]));V.set(fn.dropAttribute.name,new W(!0,[]));V.set(nl.describeSchema.name,new W(!1,[Bs]));V.set(nl.describeTable.name,new W(!1,[Bs]));V.set(Rg.deleteRecord.name,new W(!1,[Dv]));V.set(sl.addUser.name,new W(!0,[]));V.set(sl.alterUser.name,new W(!0,[]));V.set(sl.dropUser.name,new W(!0,[]));V.set(sl.listUsersExternal.name,new W(!0,[]));V.set(Lf.listRoles.name,new W(!0,[]));V.set(Lf.addRole.name,new W(!0,[]));V.set(Lf.alterRole.name,new W(!0,[]));V.set(Lf.dropRole.name,new W(!0,[]));V.set(_7.name,new W(!0,[]));V.set(d7.name,new W(!0,[]));V.set(f7.name,new W(!0,[]));V.set(E7.name,new W(!0,[]));V.set(h7.name,new W(!0,[]));V.set(m7.name,new W(!0,[]));V.set(Ag.setRoutes.name,new W(!0,[]));V.set(Ag.getRoutes.name,new W(!0,[]));V.set(Ag.deleteRoutes.name,new W(!0,[]));V.set(yv.setConfiguration.name,new W(!0,[]));V.set(p7.clusterStatus.name,new W(!0,[]));V.set(S7.name,new W(!0,[]));V.set(Og.getFingerprint.name,new W(!0,[]));V.set(Og.setLicense.name,new W(!0,[]));V.set(Rg.deleteFilesBefore.name,new W(!0,[]));V.set(Rg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Rv.restart.name,new W(!0,[]));V.set(Rv.restartService.name,new W(!0,[]));V.set(u7.name,new W(!0,[]));V.set(l7.name,new W(!0,[Bs]));V.set(g7.systemInformation.name,new W(!0,[]));V.set(yv.getConfiguration.name,new W(!0,[]));V.set(Nv.readTransactionLog.name,new W(!0,[]));V.set(Nv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Iv.installModules.name,new W(!0,[]));V.set(Iv.auditModules.name,new W(!0,[]));V.set(Ov.createTokens.name,new W(!1,[]));V.set(Ov.refreshOperationToken.name,new W(!1,[]));V.set(bv.login.name,new W(!1,[]));V.set(bv.logout.name,new W(!1,[]));V.set(Yr.customFunctionsStatus.name,new W(!0,[]));V.set(Yr.getCustomFunctions.name,new W(!0,[]));V.set(Yr.getComponents.name,new W(!0,[]));V.set(Yr.getComponentFile.name,new W(!0,[]));V.set(Yr.setComponentFile.name,new W(!0,[]));V.set(Yr.dropComponent.name,new W(!0,[]));V.set(Yr.getCustomFunction.name,new W(!0,[]));V.set(Yr.setCustomFunction.name,new W(!0,[]));V.set(Yr.dropCustomFunction.name,new W(!0,[]));V.set(Yr.addComponent.name,new W(!0,[]));V.set(Yr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Yr.packageComponent.name,new W(!0,[]));V.set(Yr.deployComponent.name,new W(!0,[]));V.set(Og.getRegistrationInfo.name,new W(!1,[]));V.set(sl.userInfo.name,new W(!1,[]));V.set(nl.describeAll.name,new W(!1,[]));V.set(O7,new W(!1,[]));V.set(b7,new W(!0,[]));V.set(A7,new W(!0,[]));V.set(Mf.CSV_DATA_LOAD,new W(!1,[Ai,To]));V.set(Mf.CSV_URL_LOAD,new W(!1,[Ai,To]));V.set(Mf.CSV_FILE_LOAD,new W(!1,[Ai,To]));V.set(Mf.IMPORT_FROM_S3,new W(!1,[Ai,To]));V.set(Mv.EXPORT_TO_S3,new W(!0,[]));V.set(Mv.EXPORT_LOCAL,new W(!0,[]));V.set(dn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Dv]));V.set(dn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(dn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Ai]));V.set(dn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[To]));Pv.exports={verifyPerms:I7,verifyPermsAst:N7,verifyBulkLoadAttributePerms:C7};function N7(e,t,r){if(vs.isEmptyOrZeroLength(e))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vs.isEmptyOrZeroLength(t))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vs.isEmptyOrZeroLength(r))throw It.info("verify_perms_ast has a null operation parameter"),Or(new Error);try{let n=new wv,s=new T7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw It.info("No schemas defined in verifyPermsAst(), will not continue."),Or(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Lv[r])throw Or(new Error,$t.DROP_SYSTEM,tl.FORBIDDEN);if(c&&!u)return null;let _=Av.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof R7.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=Uv(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),S=yg(t.role.permission,f,d[E]);bg(h,S,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Or(n)}}a(N7,"verifyPermsAst");function I7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw It.info("null required parameter in verifyPerms"),Or(new Error,$t.DEFAULT_INVALID_REQUEST,tl.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new wv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.isEmptyOrZeroLength(e.hdb_user.role.permission))return It.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem($t.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(dn.SYSTEM_SCHEMA_NAME)||s===dn.SYSTEM_SCHEMA_NAME;if(l&&Lv[r])throw Or(new Error,$t.DROP_SYSTEM,tl.FORBIDDEN);if(u&&!l||_===!0&&(r===fn.createSchema.name||r===fn.dropSchema.name))return null;if(y7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=Av.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Tv||r===gv){if(s===dn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem($t.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Tv&&(!d[s]||!d[s][rl]))return c.handleInvalidItem($t.SCHEMA_NOT_FOUND(s));if(r===gv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][rl]))return c.handleInvalidItem($t.TABLE_NOT_FOUND(s,i))}}let f=Uv(e.hdb_user,r,o,c,n);if(f)return f;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&dn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let S=[],p=d[s].tables[i];p[dn.PERMS_CRUD_ENUM.READ]&&(p.attribute_permissions.length>0?p.attribute_permissions.filter(b=>b[dn.PERMS_CRUD_ENUM.READ]).forEach(b=>{S.push(b.attribute_name)}):S=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=S)}let E=w7(e),h=yg(e.hdb_user.role.permission,s,i);return bg(E,h,r,i,s,c,n),c.getPermsResponse()}a(I7,"verifyPerms");function Uv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw It.info("hasPermissions has an invalid parameter"),Or(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw It.info(`operation ${t} not found.`),Or(new Error,$t.OP_NOT_FOUND(t),tl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return It.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem($t.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][rl]===!1){n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[rl]===!1)n.addInvalidItem($t.TABLE_NOT_FOUND(u,l));else try{let f=[],E=V.get(t).perms;!vs.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let S=E[h],p=d[S];(p==null||p===!1)&&(It.info(`Required ${S} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(S))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=$t.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw It.error(E),It.error(f),Or(Cv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Uv,"hasPermissions");function bg(e,t,r,n,s,i,o){if(!e||!t)throw It.info("no attributes specified in checkAttributePerms."),Or(new Error);let c=V.get(r).perms;if(!c||c==="")throw It.info(`no permissions found for ${r} in checkAttributePerms().`),Or(new Error);if(vs.isEmptyOrZeroLength(t))return It.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[rl]===!1){i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(dn.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Bs)throw Or(new Error,$t.SYSTEM_TIMESTAMP_PERMS_ERR,tl.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(bg,"checkAttributePerms");function w7(e){let t=new Set;try{if(e.action)return t;if(e.operation===dn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){It.info(r)}return t}a(w7,"getRecordAttributes");function yg(e,t,r){let n=new Map;if(vs.isEmpty(e))return It.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{It.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(yg,"getAttributePermissions");function C7(e,t,r,n,s,i,o){let c=new Set(i),u=yg(e,n,s);bg(c,u,t,s,n,o,r)}a(C7,"verifyBulkLoadAttributePerms")});var vf=R((QEe,Gv)=>{"use strict";Gv.exports={evaluateSQL:k7,processAST:xv,convertSQLToAST:Hv,checkASTPermissions:Bv};var D7=an(),vv=require("util"),L7=vv.callbackify(D7.insert),M7=Br().search,U7=iD().update,P7=vv.callbackify(U7),v7=aD().convertDelete,Oi=require("alasql"),B7=Uf(),Pf=Y(),H7=ld(),x7=Q(),il=U(),{hdb_errors:G7,handleHDBError:Ng}=ne(),{HTTP_STATUS_CODES:Ig}=G7;H7(Oi);var F7=403,q7="There was a problem performing this insert. Please check the logs and try again.",wg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function k7(e,t){let r=e.parsed_sql_object;if(!r){r=Hv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Oi.yy.Insert?n=s.into.databaseid:s instanceof Oi.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Oi.yy.Update||s instanceof Oi.yy.Delete?n=s.table.databaseid:Pf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Oi.yy.Select)&&x7.isEmptyOrZeroLength(n))return t("No schema specified",null)}xv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(k7,"evaluateSQL");function Bv(e,t){let r;try{r=B7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Bv,"checkASTPermissions");function Hv(e){let t=new wg;if(!e)throw Ng(new Error,"The 'sql' parameter is missing from the request body",Ig.BAD_REQUEST);try{let r=e.trim(),n=Oi.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
-
`);throw n[1]?Ng(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ig.BAD_REQUEST):Ng(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ig.BAD_REQUEST)}return t}a(Hv,"convertSQLToAST");function xv(e,t,r){try{let n=V7;if(!e.bypass_auth&&!t.permissions_checked){let i=Bv(e,t);if(i&&i.length>0)return r(F7,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case il.VALID_SQL_OPS_ENUM.SELECT:n=M7,s=t.ast.statements[0];break;case il.VALID_SQL_OPS_ENUM.INSERT:n=$7;break;case il.VALID_SQL_OPS_ENUM.UPDATE:n=P7;break;case il.VALID_SQL_OPS_ENUM.DELETE:n=v7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(xv,"processAST");function V7(e,t){Pf.info(e),t("unknown sql statement")}a(V7,"nullFunction");function $7({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=Y7(i,e.values)}catch(o){return r(o)}L7(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Pf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a($7,"convertInsert");function Y7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Oi.compile(`SELECT ${s.toString()} AS [${il.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Pf.error(r),new Error(q7)}}a(Y7,"createDataObjects")});var Cg=R((JEe,qv)=>{"use strict";var{S3:K7,GetObjectCommand:W7}=require("@aws-sdk/client-s3");qv.exports={getFileStreamFromS3:Q7,getS3AuthObj:Fv};async function Q7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Fv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new W7(r))).Body}a(Q7,"getFileStreamFromS3");function Fv(e,t,r){return new K7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Fv,"getS3AuthObj")});var Bf=R((XEe,Jv)=>{"use strict";var Lg=Br(),z7=vf(),J7=Cg(),{AsyncParser:j7,Transform:X7}=require("json2csv"),al=require("stream"),Kr=Q(),Dg=require("fs-extra"),Z7=require("path"),En=Y(),{promisify:$v}=require("util"),ol=Q(),{handleHDBError:Rt,hdb_errors:eee}=ne(),{HDB_ERROR_MSGS:br,HTTP_STATUS_CODES:At}=eee,{streamAsJSON:tee}=(Xh(),ie(xb)),{Upload:ree}=require("@aws-sdk/lib-storage"),kv=["search_by_value","search_by_hash","sql","search_by_conditions"],Vv=["json","csv"],Yv="json",Kv="csv",nee="Successfully exported JSON locally.",see="Successfully exported CSV locally.",iee=1e3,oee=Lg.searchByHash,aee=Lg.searchByValue,cee=$v(z7.evaluateSQL),uee=$v(al.finished);Jv.exports={export_to_s3:fee,export_local:lee,toCsvStream:Wv};async function lee(e){En.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=Qv(e);if(!Kr.isEmpty(t))throw En.error(t),Rt(new Error,t,At.BAD_REQUEST,void 0,void 0,!0);if(Kr.isEmpty(e.path))throw En.error(br.MISSING_VALUE("path")),Rt(new Error,br.MISSING_VALUE("path"),At.BAD_REQUEST,void 0,void 0,!0);let r=(Kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Z7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Kr.buildFolderPath(e.path,r);await _ee(e.path);let s=await zv(e);return await dee(n,e.format,s)}a(lee,"export_local");async function _ee(e){if(En.trace("in confirmPath"),Kr.isEmptyOrZeroLength(e))throw Rt(new Error,`Invalid path: ${e}`,At.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Dg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,En.error(n),Rt(new Error,n,At.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 En.error(r),Rt(new Error,r,At.BAD_REQUEST,void 0,void 0,!0)}return!0}a(_ee,"confirmPath");async function dee(e,t,r){if(En.trace("in saveToLocal"),ol.isEmptyOrZeroLength(e))throw Rt(new Error,br.INVALID_VALUE("file_path"),At.BAD_REQUEST,void 0,void 0,!0);if(ol.isEmptyOrZeroLength(t))throw Rt(new Error,br.INVALID_VALUE("Source format"),At.BAD_REQUEST,void 0,void 0,!0);if(ol.isEmpty(r))throw Rt(new Error,br.NOT_FOUND("Data"),At.BAD_REQUEST,void 0,void 0,!0);if(t===Yv){let n=Dg.createWriteStream(e);return tee(r).pipe(n),await uee(n),{message:nee,path:e}}else if(t===Kv){let n=Dg.createWriteStream(e),s=al.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new j7(i,c).fromInput(s).toOutput(n).promise(!1),{message:see,path:e}}throw Rt(new Error,br.INVALID_VALUE("format"),At.BAD_REQUEST)}a(dee,"saveToLocal");async function fee(e){if(!e.s3||Object.keys(e.s3).length===0)throw Rt(new Error,br.MISSING_VALUE("S3 object"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Rt(new Error,br.MISSING_VALUE("aws_access_key_id"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Rt(new Error,br.MISSING_VALUE("aws_secret_access_key"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.bucket))throw Rt(new Error,br.MISSING_VALUE("bucket"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.key))throw Rt(new Error,br.MISSING_VALUE("key"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.region))throw Rt(new Error,br.MISSING_VALUE("region"),At.BAD_REQUEST);let t=Qv(e);if(!Kr.isEmpty(t))throw Rt(new Error,t,At.BAD_REQUEST);En.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await zv(e)}catch(u){throw En.error(u),u}let n,s=await J7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new al.PassThrough;if(e.format===Kv){i=e.s3.key+".csv";let u=Wv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===Yv){i=e.s3.key+".json";let u=new al.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%iee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Rt(new Error,br.INVALID_VALUE("format"),At.BAD_REQUEST);return new ree({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(fee,"export_to_s3");function Wv(e,t){let r=al.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new X7(n,s);return r.pipe(i)}a(Wv,"toCsvStream");function Qv(e){if(En.trace("in exportCoreValidation"),Kr.isEmpty(e.format))return"format missing";if(Vv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Vv.join(", ")}`;let t=e.search_operation.operation;if(Kr.isEmpty(t))return"search_operation.operation missing";if(kv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${kv.join(", ")}`}a(Qv,"exportCoreValidation");async function zv(e){En.trace("in getRecords");let t,r;if(ol.isEmpty(e.search_operation)||ol.isEmptyOrZeroLength(e.search_operation.operation))throw Rt(new Error,br.INVALID_VALUE("Search operation"),At.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=aee;break;case"search_by_hash":t=oee;break;case"search_by_conditions":t=Lg.searchByConditions;break;case"sql":t=cee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,En.error(r),Rt(new Error,r,At.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(zv,"getRecords")});var s0={};Fe(s0,{contentTypes:()=>Bg,findBestSerializer:()=>xf,getDeserializer:()=>Ro,registerContentHandlers:()=>Hg,serialize:()=>Gf,serializeMessage:()=>Ri});function Eee(e){try{return e?.[0]===123?vg(e):e}catch{return e}}function Hg(e){e.register(mee,{serializers:[{regex:/^application\/json$/,serializer:bc},{regex:/^application\/cbor$/,serializer:function(t){return new go.EncoderStream(ul).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Hf.Readable.from((0,cs.encodeIter)(t,ul)):(0,cs.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,n)=>{try{n(null,(0,cs.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,go.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function xf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let S=h.indexOf("=");f[h.substring(0,S)]=h.substring(S+1)}d=+f.q;let E=xt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(xt.keys()).join(", "))}};n=xt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Gf(e,t,r){let n=Xv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=xf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>Xv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function Ri(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return cl(e);let r=t.serialize;if(r)return r(e);let n=xf(t);return r=t.serialize=n.serializer.serialize,r(e)}function pee(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Ro(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=xt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=xt.get(e)?.deserialize||Zv(e,n);return o=>pee(o).then(i)}return e&&xt.get(e)?.deserialize||Zv(e,n)}function Zv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return vg(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 n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var Mg,cs,go,Hs,Hf,e0,Ug,Pg,t0,r0,cl,vg,ul,xt,Bg,jv,n0,hee,mee,Xv,ya=ge(()=>{Xh();Mg=B(Bf()),cs=require("msgpackr"),go=require("cbor-x"),Hs=require("zlib"),Hf=require("stream");or();e0=require("../../index"),Ug=B(re()),Pg=B(U()),t0=B(require("yaml")),r0=Ug.default.get(Pg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,cl=r0?Gi:JSON.stringify,vg=r0?jh:JSON.parse,ul={useRecords:!1,useToJSON:!0},xt=new Map,Bg=xt;tt.contentTypes=Bg;(0,e0._assignPackageExport)("contentTypes",Bg);xt.set("application/json",{serializeStream:bc,serialize:cl,deserialize:vg,q:.8});jv=new go.Encoder(ul);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new go.EncoderStream(ul).end(e)},serialize:jv.encode,deserialize:jv.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Hf.Readable.from((0,cs.encodeIter)(e,ul)):(0,cs.pack)(e)},serialize:cs.pack,deserialize:cs.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Mg.toCsvStream)(e,e?.getColumns?.())},q:.1});xt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});xt.set("text/yaml",{serialize(e){return t0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return Hf.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+`
|
|
20
|
-
`),e.data){let r=e.data;typeof r=="object"&&(r=
|
|
18
|
+
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(WP,"parseNPMStdErr");async function N9(e){wa.info(`starting auditModules for request: ${e}`);let t=zP(e);if(t)throw Na(t,t.message,Ia.BAD_REQUEST);let{projects:r}=e;await Of(),await QP(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Af.join(ug,o);n[o]={npm_output:null,npm_error:null};try{let u=await Zu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=WP(u.stderr)}}return wa.info(`finished auditModules with response ${n}`),n}a(N9,"auditModules");async function Of(){try{return await Zu("npm -v"),!0}catch{throw Na(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ia.BAD_REQUEST,void 0,void 0,!0)}}a(Of,"checkNPMInstalled");async function QP(e){if(!Array.isArray(e)||e.length===0)throw Na(new Error,"projects argument must be an array with at least 1 element",Ia.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Af.join(ug,i.toString());if(!await $P.pathExists(o)){t.push(i);continue}let u=Af.join(o,"package.json");await $P.pathExists(u)||r.push(i)}if(t.length>0)throw Na(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ia.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Na(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ia.BAD_REQUEST,void 0,void 0,!0)}a(QP,"checkProjectPaths");function zP(e){let t=Rf.object({projects:Rf.array().min(1).items(Rf.string()).required(),dry_run:Rf.boolean().default(!1)});return g9.validateBySchema(e,t)}a(zP,"modulesValidator")});var _g=R((LEe,tv)=>{"use strict";var Ca=require("fs-extra"),lg=require("path"),yf=Y(),jP=Q(),Nf=U(),ev=re(),I9=lr();tv.exports=w9;async function w9(){let e=C9(),t=ev.get(Nf.CONFIG_PARAMS.ROOTPATH),r=lg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Nf.PACKAGE_ROOT}},s=lg.join(t,"node_modules");await Ca.ensureDir(s);let i,o=!0,c=!1;try{i=await Ca.readJson(r)}catch(u){if(jP.isEmptyOrZeroLength(e))return;if(u.code!==Nf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!jP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await XP(_);n.dependencies[u]=l+_}if(!o){yf.notify("Installing components"),await ZP(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await XP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(yf.notify("Removing component",u),c=!0);c&&(yf.notify("Updating components."),await ZP(r,n,i))}a(w9,"installComponents");function C9(){let e=I9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(C9,"getComponentsConfig");async function XP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":lg.extname(e)||await Ca.pathExists(e)?"file:":"github:"}a(XP,"getPkgPrefix");async function ZP(e,t,r){yf.trace("npm installing components package.json",t),await Ca.writeFile(e,JSON.stringify(t,null," "));try{await bf().installAllRootModules(ev.get(Nf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ca.writeFile(e,JSON.stringify(r,null," ")):await Ca.unlink(e),n}}a(ZP,"installPackages")});var Eg=R((PEe,iv)=>{"use strict";var ke=require("fs-extra"),dg=require("fast-glob"),Te=require("path"),nv=require("tar-fs"),UEe=require("uuid").v4,fg=require("normalize-path"),os=VP(),Nt=Y(),Ke=U(),gt=re(),el=lr(),D9=Q(),{PACKAGE_ROOT:L9}=U(),{handleHDBError:Bt,hdb_errors:M9}=ne(),{basename:U9}=require("path"),P9=_g(),sv=re(),v9=U(),{Readable:B9}=require("stream"),{isMainThread:H9}=require("worker_threads"),{HDB_ERROR_MSGS:So,HTTP_STATUS_CODES:Ht}=M9,x9=Te.join(L9,"application-template"),rv=Te.join(gt.get(Ke.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function G9(){Nt.trace("getting custom api status");let e={};try{e={port:gt.get(Ke.CONFIG_PARAMS.HTTP_PORT),directory:gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,So.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(G9,"customFunctionsStatus");function F9(){Nt.trace("getting custom api endpoints");let e={},t=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT);try{dg.sync(fg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:dg.sync(fg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:dg.sync(fg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,So.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(F9,"getCustomFunctions");function q9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("getting custom api endpoint file content");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,So.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(q9,"getCustomFunction");function k9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("setting custom function file content");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return ke.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,So.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(k9,"setCustomFunction");function V9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function file");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return ke.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,So.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(V9,"dropCustomFunction");function $9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("adding component");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return ke.mkdirSync(s,{recursive:!0}),ke.copySync(x9,s),`Successfully added project: ${n}`}catch(s){throw Bt(new Error,So.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,s)}}a($9,"addComponent");function Y9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function project");let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=gt.get(Ke.CONFIG_PARAMS.APPS);if(!D9.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return el.updateConfigValue(Ke.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Bt(new Error,So.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(Y9,"dropCustomFunctionProject");async function K9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Nt.trace("packaging component",n);let s;try{s=await ke.realpath(Te.join(r,n))}catch(u){if(u.code!==Ke.NODE_ERROR_CODES.ENOENT)throw u;try{s=await ke.realpath(Te.join(gt.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Ke.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await ke.ensureDir(rv);let i=Te.join(rv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),nv.pack(s,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:n,payload:c}}a(K9,"packageComponent");async function W9(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Nt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await ke.ensureDir(o);let f=B9.from(Buffer.from(s,"base64"));await new Promise((h,S)=>{f.pipe(nv.extract(o,{finish:h})).on("error",S)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(Te.join(o,"package"),o),await ke.remove(Te.join(o,"package")))}if(await el.addConfig(n,{package:i}),!s){await P9();let f=sv.get(v9.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",n)}if(H9)return;let c=new Map;c.isWorker=!0;let u=(wf(),ie(If)),_;u.setErrorReporter(f=>_=f);let l=U9(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: ${n}`}a(W9,"deployComponent");async function Q9(){let e=el.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=Te.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:Te.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"),n=await r(gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{name:gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(gt.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(wf(),ie(If)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(Q9,"getComponents");async function z9(e){let t=os.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let n=el.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(sv.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules"):gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Te.join(n,e.project,e.file));return{message:await ke.readFile(Te.join(n,e.project,e.file),s),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 '${Te.join(e.project,e.file)}'`):i}}a(z9,"getComponentFile");async function J9(e){let t=os.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(n),await ke.outputFile(n,e.payload,r)):await ke.ensureDir(n),"Successfully set component: "+e.file}a(J9,"setComponentFile");async function j9(e){let t=os.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(gt.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(n)&&await ke.remove(n),el.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(j9,"dropComponent");iv.exports={customFunctionsStatus:G9,getCustomFunctions:F9,getCustomFunction:q9,setCustomFunction:k9,dropCustomFunction:V9,addComponent:$9,dropCustomFunctionProject:Y9,packageComponent:K9,deployComponent:W9,getComponents:Q9,getComponentFile:z9,setComponentFile:J9,dropComponent:j9}});var hg=R((BEe,av)=>{"use strict";var as=require("joi"),ov=et();av.exports={readTransactionLogValidator:X9,deleteTransactionLogsBeforeValidator:Z9};function X9(e){let t=as.object({schema:as.string().required(),table:as.string().required(),from:as.date().timestamp(),to:as.date().timestamp(),limit:as.number().min(1)});return ov.validateBySchema(e,t)}a(X9,"readTransactionLogValidator");function Z9(e){let t=as.object({schema:as.string().required(),table:as.string().required(),timestamp:as.date().timestamp().required()});return ov.validateBySchema(e,t)}a(Z9,"deleteTransactionLogsBeforeValidator")});var Cf=R((xEe,dv)=>{"use strict";var mg=U(),tl=St(),cv=Q(),uv=re(),lv=Rs(),{handleHDBError:Da,hdb_errors:e7}=ne(),{HTTP_STATUS_CODES:La}=e7,{readTransactionLogValidator:t7,deleteTransactionLogsBeforeValidator:r7}=hg(),_v="This operation relies on clustering and cannot run with it disable.",n7="Logs successfully deleted from transaction log.",s7="All logs successfully deleted from transaction log.";dv.exports={readTransactionLog:i7,deleteTransactionLogsBefore:o7};async function*i7(e){let t=t7(e);if(t)throw Da(t,t.message,La.BAD_REQUEST,void 0,void 0,!0);if(!uv.get(mg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Da(new Error,_v,La.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=cv.checkSchemaTableExist(r,n);if(s)throw Da(new Error,s,La.NOT_FOUND,void 0,void 0,!0);let i=lv.createNatsTableStreamName(r,n),o=await tl.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===mg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(i7,"readTransactionLog");async function o7(e){let t=r7(e);if(t)throw Da(t,t.message,La.BAD_REQUEST,void 0,void 0,!0);if(!uv.get(mg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Da(new Error,_v,La.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=cv.checkSchemaTableExist(r,n);if(i)throw Da(new Error,i,La.NOT_FOUND,void 0,void 0,!0);let o=lv.createNatsTableStreamName(r,n),{jsm:c}=await tl.getNATSReferences(),u=await tl.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=n7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=s7):d=(await tl.viewStream(o,parseInt(s),1))[0].nats_sequence,await tl.purgeTableStream(r,n,{seq:d}),l}a(o7,"deleteTransactionLogsBefore")});var Ev=R((FEe,fv)=>{"use strict";var pg=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};fv.exports=pg});var mv=R((kEe,hv)=>{"use strict";var Sg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};hv.exports=Sg});var gg=R(($Ee,Sv)=>{"use strict";var pv=Ev(),a7=mv(),{HDB_ERROR_MSGS:c7}=Lr(),Tg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=c7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new pv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new a7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new pv(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};Sv.exports=Tg});var Uf=R((KEe,Pv)=>{"use strict";var Rg=an(),Df=xr(),fn=Id(),sl=ri(),Ag=Qi(),u7=PS(),l7=TL(),il=Fr(),Lf=VS(),It=Y(),_7=KS(),d7=Yd(),f7=yT(),E7=Wd(),h7=IT(),m7=wT(),p7=LT(),S7=UT(),Og=BT(),vs=Q(),T7=SU(),bg=qT(),Rv=hf(),dn=U(),Av=NP(),g7=ma(),Ov=yu(),bv=(Tf(),ie(zu)),yv=lr(),Wr=Eg(),R7=require("alasql"),Nv=Cf(),Iv=bf(),wv=gg(),{handleHDBError:yr,hdb_errors:Cv}=ne(),{HDB_ERROR_MSGS:$t,HTTP_STATUS_CODES:rl}=Cv,V=new Map,Dv="delete",Ai="insert",Bs="read",To="update",nl="describe",Tv=sl.describeSchema.name,gv=sl.describeTable.name,Lv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},A7="catchup",O7="handleGetJob",b7="handleGetJobsByStartDate",Mf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},y7=[fn.createTable.name,fn.createAttribute.name,fn.dropTable.name,fn.dropAttribute.name],Mv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(Rg.insert.name,new W(!1,[Ai]));V.set(Rg.update.name,new W(!1,[To]));V.set(Rg.upsert.name,new W(!1,[Ai,To]));V.set(Df.searchByConditions.name,new W(!1,[Bs]));V.set(Df.searchByHash.name,new W(!1,[Bs]));V.set(Df.searchByValue.name,new W(!1,[Bs]));V.set(Df.search.name,new W(!1,[Bs]));V.set(fn.createSchema.name,new W(!0,[]));V.set(fn.createTable.name,new W(!0,[]));V.set(fn.createAttribute.name,new W(!1,[Ai]));V.set(fn.dropSchema.name,new W(!0,[]));V.set(fn.dropTable.name,new W(!0,[]));V.set(fn.dropAttribute.name,new W(!0,[]));V.set(sl.describeSchema.name,new W(!1,[Bs]));V.set(sl.describeTable.name,new W(!1,[Bs]));V.set(Ag.deleteRecord.name,new W(!1,[Dv]));V.set(il.addUser.name,new W(!0,[]));V.set(il.alterUser.name,new W(!0,[]));V.set(il.dropUser.name,new W(!0,[]));V.set(il.listUsersExternal.name,new W(!0,[]));V.set(Lf.listRoles.name,new W(!0,[]));V.set(Lf.addRole.name,new W(!0,[]));V.set(Lf.alterRole.name,new W(!0,[]));V.set(Lf.dropRole.name,new W(!0,[]));V.set(_7.name,new W(!0,[]));V.set(d7.name,new W(!0,[]));V.set(f7.name,new W(!0,[]));V.set(E7.name,new W(!0,[]));V.set(h7.name,new W(!0,[]));V.set(m7.name,new W(!0,[]));V.set(Og.setRoutes.name,new W(!0,[]));V.set(Og.getRoutes.name,new W(!0,[]));V.set(Og.deleteRoutes.name,new W(!0,[]));V.set(yv.setConfiguration.name,new W(!0,[]));V.set(p7.clusterStatus.name,new W(!0,[]));V.set(S7.name,new W(!0,[]));V.set(bg.getFingerprint.name,new W(!0,[]));V.set(bg.setLicense.name,new W(!0,[]));V.set(Ag.deleteFilesBefore.name,new W(!0,[]));V.set(Ag.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Rv.restart.name,new W(!0,[]));V.set(Rv.restartService.name,new W(!0,[]));V.set(u7.name,new W(!0,[]));V.set(l7.name,new W(!0,[Bs]));V.set(g7.systemInformation.name,new W(!0,[]));V.set(yv.getConfiguration.name,new W(!0,[]));V.set(Nv.readTransactionLog.name,new W(!0,[]));V.set(Nv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Iv.installModules.name,new W(!0,[]));V.set(Iv.auditModules.name,new W(!0,[]));V.set(Ov.createTokens.name,new W(!1,[]));V.set(Ov.refreshOperationToken.name,new W(!1,[]));V.set(bv.login.name,new W(!1,[]));V.set(bv.logout.name,new W(!1,[]));V.set(Wr.customFunctionsStatus.name,new W(!0,[]));V.set(Wr.getCustomFunctions.name,new W(!0,[]));V.set(Wr.getComponents.name,new W(!0,[]));V.set(Wr.getComponentFile.name,new W(!0,[]));V.set(Wr.setComponentFile.name,new W(!0,[]));V.set(Wr.dropComponent.name,new W(!0,[]));V.set(Wr.getCustomFunction.name,new W(!0,[]));V.set(Wr.setCustomFunction.name,new W(!0,[]));V.set(Wr.dropCustomFunction.name,new W(!0,[]));V.set(Wr.addComponent.name,new W(!0,[]));V.set(Wr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Wr.packageComponent.name,new W(!0,[]));V.set(Wr.deployComponent.name,new W(!0,[]));V.set(bg.getRegistrationInfo.name,new W(!1,[]));V.set(il.userInfo.name,new W(!1,[]));V.set(sl.describeAll.name,new W(!1,[]));V.set(O7,new W(!1,[]));V.set(b7,new W(!0,[]));V.set(A7,new W(!0,[]));V.set(Mf.CSV_DATA_LOAD,new W(!1,[Ai,To]));V.set(Mf.CSV_URL_LOAD,new W(!1,[Ai,To]));V.set(Mf.CSV_FILE_LOAD,new W(!1,[Ai,To]));V.set(Mf.IMPORT_FROM_S3,new W(!1,[Ai,To]));V.set(Mv.EXPORT_TO_S3,new W(!0,[]));V.set(Mv.EXPORT_LOCAL,new W(!0,[]));V.set(dn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Dv]));V.set(dn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(dn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Ai]));V.set(dn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[To]));Pv.exports={verifyPerms:I7,verifyPermsAst:N7,verifyBulkLoadAttributePerms:C7};function N7(e,t,r){if(vs.isEmptyOrZeroLength(e))throw It.info("verify_perms_ast has an empty user parameter"),yr(new Error);if(vs.isEmptyOrZeroLength(t))throw It.info("verify_perms_ast has an empty user parameter"),yr(new Error);if(vs.isEmptyOrZeroLength(r))throw It.info("verify_perms_ast has a null operation parameter"),yr(new Error);try{let n=new wv,s=new T7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw It.info("No schemas defined in verifyPermsAst(), will not continue."),yr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Lv[r])throw yr(new Error,$t.DROP_SYSTEM,rl.FORBIDDEN);if(c&&!u)return null;let _=Av.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof R7.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=Uv(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),S=Ng(t.role.permission,f,d[E]);yg(h,S,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw yr(n)}}a(N7,"verifyPermsAst");function I7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw It.info("null required parameter in verifyPerms"),yr(new Error,$t.DEFAULT_INVALID_REQUEST,rl.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new wv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.isEmptyOrZeroLength(e.hdb_user.role.permission))return It.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem($t.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(dn.SYSTEM_SCHEMA_NAME)||s===dn.SYSTEM_SCHEMA_NAME;if(l&&Lv[r])throw yr(new Error,$t.DROP_SYSTEM,rl.FORBIDDEN);if(u&&!l||_===!0&&(r===fn.createSchema.name||r===fn.dropSchema.name))return null;if(y7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=Av.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Tv||r===gv){if(s===dn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem($t.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Tv&&(!d[s]||!d[s][nl]))return c.handleInvalidItem($t.SCHEMA_NOT_FOUND(s));if(r===gv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][nl]))return c.handleInvalidItem($t.TABLE_NOT_FOUND(s,i))}}let f=Uv(e.hdb_user,r,o,c,n);if(f)return f;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&dn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let S=[],p=d[s].tables[i];p[dn.PERMS_CRUD_ENUM.READ]&&(p.attribute_permissions.length>0?p.attribute_permissions.filter(b=>b[dn.PERMS_CRUD_ENUM.READ]).forEach(b=>{S.push(b.attribute_name)}):S=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=S)}let E=w7(e),h=Ng(e.hdb_user.role.permission,s,i);return yg(E,h,r,i,s,c,n),c.getPermsResponse()}a(I7,"verifyPerms");function Uv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw It.info("hasPermissions has an invalid parameter"),yr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw It.info(`operation ${t} not found.`),yr(new Error,$t.OP_NOT_FOUND(t),rl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return It.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem($t.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][nl]===!1){n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[nl]===!1)n.addInvalidItem($t.TABLE_NOT_FOUND(u,l));else try{let f=[],E=V.get(t).perms;!vs.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let S=E[h],p=d[S];(p==null||p===!1)&&(It.info(`Required ${S} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(S))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=$t.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw It.error(E),It.error(f),yr(Cv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Uv,"hasPermissions");function yg(e,t,r,n,s,i,o){if(!e||!t)throw It.info("no attributes specified in checkAttributePerms."),yr(new Error);let c=V.get(r).perms;if(!c||c==="")throw It.info(`no permissions found for ${r} in checkAttributePerms().`),yr(new Error);if(vs.isEmptyOrZeroLength(t))return It.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[nl]===!1){i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(dn.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Bs)throw yr(new Error,$t.SYSTEM_TIMESTAMP_PERMS_ERR,rl.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(yg,"checkAttributePerms");function w7(e){let t=new Set;try{if(e.action)return t;if(e.operation===dn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){It.info(r)}return t}a(w7,"getRecordAttributes");function Ng(e,t,r){let n=new Map;if(vs.isEmpty(e))return It.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{It.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Ng,"getAttributePermissions");function C7(e,t,r,n,s,i,o){let c=new Set(i),u=Ng(e,n,s);yg(c,u,t,s,n,o,r)}a(C7,"verifyBulkLoadAttributePerms")});var vf=R((QEe,Gv)=>{"use strict";Gv.exports={evaluateSQL:k7,processAST:xv,convertSQLToAST:Hv,checkASTPermissions:Bv};var D7=an(),vv=require("util"),L7=vv.callbackify(D7.insert),M7=xr().search,U7=iD().update,P7=vv.callbackify(U7),v7=aD().convertDelete,Oi=require("alasql"),B7=Uf(),Pf=Y(),H7=ld(),x7=Q(),ol=U(),{hdb_errors:G7,handleHDBError:Ig}=ne(),{HTTP_STATUS_CODES:wg}=G7;H7(Oi);var F7=403,q7="There was a problem performing this insert. Please check the logs and try again.",Cg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function k7(e,t){let r=e.parsed_sql_object;if(!r){r=Hv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Oi.yy.Insert?n=s.into.databaseid:s instanceof Oi.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Oi.yy.Update||s instanceof Oi.yy.Delete?n=s.table.databaseid:Pf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Oi.yy.Select)&&x7.isEmptyOrZeroLength(n))return t("No schema specified",null)}xv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(k7,"evaluateSQL");function Bv(e,t){let r;try{r=B7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Bv,"checkASTPermissions");function Hv(e){let t=new Cg;if(!e)throw Ig(new Error,"The 'sql' parameter is missing from the request body",wg.BAD_REQUEST);try{let r=e.trim(),n=Oi.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
+
`);throw n[1]?Ig(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,wg.BAD_REQUEST):Ig(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",wg.BAD_REQUEST)}return t}a(Hv,"convertSQLToAST");function xv(e,t,r){try{let n=V7;if(!e.bypass_auth&&!t.permissions_checked){let i=Bv(e,t);if(i&&i.length>0)return r(F7,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ol.VALID_SQL_OPS_ENUM.SELECT:n=M7,s=t.ast.statements[0];break;case ol.VALID_SQL_OPS_ENUM.INSERT:n=$7;break;case ol.VALID_SQL_OPS_ENUM.UPDATE:n=P7;break;case ol.VALID_SQL_OPS_ENUM.DELETE:n=v7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(xv,"processAST");function V7(e,t){Pf.info(e),t("unknown sql statement")}a(V7,"nullFunction");function $7({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=Y7(i,e.values)}catch(o){return r(o)}L7(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Pf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a($7,"convertInsert");function Y7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Oi.compile(`SELECT ${s.toString()} AS [${ol.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Pf.error(r),new Error(q7)}}a(Y7,"createDataObjects")});var Dg=R((JEe,qv)=>{"use strict";var{S3:K7,GetObjectCommand:W7}=require("@aws-sdk/client-s3");qv.exports={getFileStreamFromS3:Q7,getS3AuthObj:Fv};async function Q7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Fv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new W7(r))).Body}a(Q7,"getFileStreamFromS3");function Fv(e,t,r){return new K7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Fv,"getS3AuthObj")});var Bf=R((XEe,Jv)=>{"use strict";var Mg=xr(),z7=vf(),J7=Dg(),{AsyncParser:j7,Transform:X7}=require("json2csv"),cl=require("stream"),Qr=Q(),Lg=require("fs-extra"),Z7=require("path"),En=Y(),{promisify:$v}=require("util"),al=Q(),{handleHDBError:Rt,hdb_errors:eee}=ne(),{HDB_ERROR_MSGS:Nr,HTTP_STATUS_CODES:At}=eee,{streamAsJSON:tee}=(Zh(),ie(xb)),{Upload:ree}=require("@aws-sdk/lib-storage"),kv=["search_by_value","search_by_hash","sql","search_by_conditions"],Vv=["json","csv"],Yv="json",Kv="csv",nee="Successfully exported JSON locally.",see="Successfully exported CSV locally.",iee=1e3,oee=Mg.searchByHash,aee=Mg.searchByValue,cee=$v(z7.evaluateSQL),uee=$v(cl.finished);Jv.exports={export_to_s3:fee,export_local:lee,toCsvStream:Wv};async function lee(e){En.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=Qv(e);if(!Qr.isEmpty(t))throw En.error(t),Rt(new Error,t,At.BAD_REQUEST,void 0,void 0,!0);if(Qr.isEmpty(e.path))throw En.error(Nr.MISSING_VALUE("path")),Rt(new Error,Nr.MISSING_VALUE("path"),At.BAD_REQUEST,void 0,void 0,!0);let r=(Qr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Z7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Qr.buildFolderPath(e.path,r);await _ee(e.path);let s=await zv(e);return await dee(n,e.format,s)}a(lee,"export_local");async function _ee(e){if(En.trace("in confirmPath"),Qr.isEmptyOrZeroLength(e))throw Rt(new Error,`Invalid path: ${e}`,At.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Lg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,En.error(n),Rt(new Error,n,At.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 En.error(r),Rt(new Error,r,At.BAD_REQUEST,void 0,void 0,!0)}return!0}a(_ee,"confirmPath");async function dee(e,t,r){if(En.trace("in saveToLocal"),al.isEmptyOrZeroLength(e))throw Rt(new Error,Nr.INVALID_VALUE("file_path"),At.BAD_REQUEST,void 0,void 0,!0);if(al.isEmptyOrZeroLength(t))throw Rt(new Error,Nr.INVALID_VALUE("Source format"),At.BAD_REQUEST,void 0,void 0,!0);if(al.isEmpty(r))throw Rt(new Error,Nr.NOT_FOUND("Data"),At.BAD_REQUEST,void 0,void 0,!0);if(t===Yv){let n=Lg.createWriteStream(e);return tee(r).pipe(n),await uee(n),{message:nee,path:e}}else if(t===Kv){let n=Lg.createWriteStream(e),s=cl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new j7(i,c).fromInput(s).toOutput(n).promise(!1),{message:see,path:e}}throw Rt(new Error,Nr.INVALID_VALUE("format"),At.BAD_REQUEST)}a(dee,"saveToLocal");async function fee(e){if(!e.s3||Object.keys(e.s3).length===0)throw Rt(new Error,Nr.MISSING_VALUE("S3 object"),At.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Rt(new Error,Nr.MISSING_VALUE("aws_access_key_id"),At.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Rt(new Error,Nr.MISSING_VALUE("aws_secret_access_key"),At.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.bucket))throw Rt(new Error,Nr.MISSING_VALUE("bucket"),At.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.key))throw Rt(new Error,Nr.MISSING_VALUE("key"),At.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.region))throw Rt(new Error,Nr.MISSING_VALUE("region"),At.BAD_REQUEST);let t=Qv(e);if(!Qr.isEmpty(t))throw Rt(new Error,t,At.BAD_REQUEST);En.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await zv(e)}catch(u){throw En.error(u),u}let n,s=await J7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new cl.PassThrough;if(e.format===Kv){i=e.s3.key+".csv";let u=Wv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===Yv){i=e.s3.key+".json";let u=new cl.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%iee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Rt(new Error,Nr.INVALID_VALUE("format"),At.BAD_REQUEST);return new ree({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(fee,"export_to_s3");function Wv(e,t){let r=cl.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new X7(n,s);return r.pipe(i)}a(Wv,"toCsvStream");function Qv(e){if(En.trace("in exportCoreValidation"),Qr.isEmpty(e.format))return"format missing";if(Vv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Vv.join(", ")}`;let t=e.search_operation.operation;if(Qr.isEmpty(t))return"search_operation.operation missing";if(kv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${kv.join(", ")}`}a(Qv,"exportCoreValidation");async function zv(e){En.trace("in getRecords");let t,r;if(al.isEmpty(e.search_operation)||al.isEmptyOrZeroLength(e.search_operation.operation))throw Rt(new Error,Nr.INVALID_VALUE("Search operation"),At.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=aee;break;case"search_by_hash":t=oee;break;case"search_by_conditions":t=Mg.searchByConditions;break;case"sql":t=cee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,En.error(r),Rt(new Error,r,At.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(zv,"getRecords")});var s0={};Fe(s0,{contentTypes:()=>Hg,findBestSerializer:()=>xf,getDeserializer:()=>Ro,registerContentHandlers:()=>xg,serialize:()=>Gf,serializeMessage:()=>Ri});function Eee(e){try{return e?.[0]===123?Bg(e):e}catch{return e}}function xg(e){e.register(mee,{serializers:[{regex:/^application\/json$/,serializer:yc},{regex:/^application\/cbor$/,serializer:function(t){return new go.EncoderStream(ll).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Hf.Readable.from((0,cs.encodeIter)(t,ll)):(0,cs.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Ug.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,cs.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,go.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function xf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let S=h.indexOf("=");f[h.substring(0,S)]=h.substring(S+1)}d=+f.q;let E=xt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(xt.keys()).join(", "))}};n=xt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Gf(e,t,r){let n=Xv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=xf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>Xv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function Ri(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return ul(e);let r=t.serialize;if(r)return r(e);let n=xf(t);return r=t.serialize=n.serializer.serialize,r(e)}function pee(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Ro(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=xt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=xt.get(e)?.deserialize||Zv(e,n);return o=>pee(o).then(i)}return e&&xt.get(e)?.deserialize||Zv(e,n)}function Zv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Bg(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 n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var Ug,cs,go,Hs,Hf,e0,Pg,vg,t0,r0,ul,Bg,ll,xt,Hg,jv,n0,hee,mee,Xv,ya=ge(()=>{Zh();Ug=B(Bf()),cs=require("msgpackr"),go=require("cbor-x"),Hs=require("zlib"),Hf=require("stream");cr();e0=require("../../index"),Pg=B(re()),vg=B(U()),t0=B(require("yaml")),r0=Pg.default.get(vg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,ul=r0?Gi:JSON.stringify,Bg=r0?Xh:JSON.parse,ll={useRecords:!1,useToJSON:!0},xt=new Map,Hg=xt;tt.contentTypes=Hg;(0,e0._assignPackageExport)("contentTypes",Hg);xt.set("application/json",{serializeStream:yc,serialize:ul,deserialize:Bg,q:.8});jv=new go.Encoder(ll);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new go.EncoderStream(ll).end(e)},serialize:jv.encode,deserialize:jv.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Hf.Readable.from((0,cs.encodeIter)(e,ll)):(0,cs.pack)(e)},serialize:cs.pack,deserialize:cs.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Ug.toCsvStream)(e,e?.getColumns?.())},q:.1});xt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});xt.set("text/yaml",{serialize(e){return t0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return Hf.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+`
|
|
20
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=ul(r)),t+="data: "+r+`
|
|
21
21
|
`}return e.id&&(t+="id: "+e.id+`
|
|
22
22
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
23
23
|
`),t+`
|
|
24
|
-
`}else return typeof e=="object"?`data: ${
|
|
24
|
+
`}else return typeof e=="object"?`data: ${ul(e)}
|
|
25
25
|
|
|
26
26
|
`:`data: ${e}
|
|
27
27
|
|
|
28
|
-
`},compressible:!1,q:.8});xt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});n0={type:"application/json",serializeStream:bc,serialize:cl,deserialize:Eee,q:.8};xt.set("*/*",n0);xt.set("",n0);a(Eee,"tryJSONParse");a(Hg,"registerContentHandlers");hee=require("fastify-plugin"),mee=hee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=xf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(xf,"findBestSerializer");Xv=Ug.default.get(Pg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Gf,"serialize");a(Ri,"serializeMessage");a(pee,"streamToBuffer");a(Ro,"getDeserializer");a(Zv,"deserializerUnknownType");a(See,"transformIterable")});function Fg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],S=_(h);d=d.concat(S)}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?Fg(d.conditions,d.operator,r,n,s,i,o,c):Pa(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,S)=>{if(h.conditions){let b=h.operator==="or",g=l(h.conditions,!b,E);return b?(L,v)=>g.some(P=>P(L,v)):(L,v)=>g.every(P=>P(L,v))}let p=(h.attribute||h[0])===r.primaryKey,T=kg(h,r,i,c,p,E);return f&&S<d.length-1&&E&&(E=Iee(r.primaryStore,h.estimated_count,E)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Pa(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let b=o[0],g=Gs(n.attributes,b);if(g.relationship){if(o.length<2)throw new Wr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let L=g.definition?.tableClass||g.elements?.definition?.tableClass,v=new Map,P=Pa({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,L,s,v);if(g.relationship.to){i[o[0]]=v;let k=!!Gs(L.attributes,g.relationship.to)?.elements;P=Oee(P,g,L.primaryStore,k,v)}if(g.relationship.from){let k=a(H=>Pa({attribute:g.relationship.from,value:H},t,r,n,s,v),"searchEntry");g.elements?(i[o[0]]=v,P=bee(P,g,L.primaryStore,v,k)):P=P.flatMap(k)}return P}else if(o.length===1)o=o[0];else throw new Wr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(qg[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]=us.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 Wr.ClientError(`Unknown query comparator "${u}"`)}if(r){let b=_;_=l,l=b,b=!f,f=!d,d=b}let h=o===n.primaryKey||o==null,S=h?n.primaryStore:n.indices[o],p;if(!S||S.isIndexing||E||c===null&&!S.indexNulls){if(s===!1&&!S)throw new Wr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&E)throw new Wr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(S?.isIndexing)throw new Wr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!S.indexNulls)throw new Wr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(p=kg(e),!p)throw new Wr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let b=S.getRange(T).map(p?function({key:g,value:L}){return this.isSync?L&&p(L)?g:bi.SKIP:new Promise((v,P)=>setImmediate(()=>{try{v(L&&p(L)?g:bi.SKIP)}catch(k){P(k)}}))}:g=>g.value==null?bi.SKIP:g);return b.hasEntries=!0,b}else return S?S.getRange(T).map(p?function({key:b,value:g}){return this.isSync?p({[o]:b})?g:bi.SKIP:new Promise((L,v)=>setImmediate(()=>{try{L(p({[o]:b})?g:bi.SKIP)}catch(P){v(P)}}))}:({value:b})=>b):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:b,value:g}){return this.isSync?g&&p(g)?b:bi.SKIP:new Promise((L,v)=>setImmediate(()=>{try{L(g&&p(g)?b:bi.SKIP)}catch(P){v(P)}}))})}function Gs(e,t){if(Array.isArray(t))if(t.length>1){let r=Gs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Gs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function Oee(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Hn(l),o=!0);let E=s.get(f);E?E.push(d):s.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!s.filters?.some(E=>!E(d)))if(n)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function bee(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Hn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Hn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(f=>!f(d)))continue}_.set(Hn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function kg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Gs(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=kg({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 S=t.propertyResolvers?.[l],p,T=a((b,g)=>{let L,v;if(S){if(S.from&&h.idFilter){if(!p)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:S.from,value:k};p=_(S.from,h.idFilter,!0,!0)}else p=_(S.from,h.idFilter,!1,!0);let P=p(b);return p.idFilter&&(T.idFilter=p.idFilter),P}v=S(b,r,g),L=v?.value}else L=b[l];return L?Array.isArray(L)?L.some(h):h(L,v):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),qg[o]||o){case xg.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,us.compareKeys)(l,u[0])>=0&&(0,us.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,us.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,us.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,us.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,us.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,us.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Wr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&qf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let S=0,p=3;function T(b){let g=b[l],L;if(typeof g!="object"||!g||E?L=d(g):Array.isArray(g)?L=g.some(d):g instanceof Date&&(L=d(g.getTime())),f&&(p++,!L&&!T.idFilter&&++S/p*(i-p)>h)){let v=Pa(e,r.transaction.getReadTxn(),!1,t).map(Hn),P=new Set(v);T.idFilter=k=>P.has(Hn(k)),T.idFilter.idSet=P}return L}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function qf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/xs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=qg[n]||n,n===xg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=qf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xs(e.indices[i.relationship.from])/(xs(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=xs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Ree*xs(e.primaryStore)+1:n==="between"?r.estimated_count=gee*xs(e.primaryStore)+1:n==="sort"?r.estimated_count=xs(e.primaryStore)+1:r.estimated_count=Tee*xs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function kf(e){if(e)if(yi=e,Ma.lastIndex=0,yee.test(e))try{let t=ll(new Ua,"");if(yr!==yi.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 ${yr} in '${yi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function ll(e,t){let r=Ma,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(yi);){yr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=i0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=_l(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Aee[d],u=Gg[i]?i0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_l(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&o0(h,l),Ff(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_l(l)),s=void 0;break;case"(":Ma.lastIndex=yr;let E=ll(l?[]:new Ua,")");switch(l){case"":Ff(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=a0(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}yi[yr]===","?r.lastIndex=++yr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Ma.lastIndex=yr,f=ll([],"}"),f.name=l,e.push(f),yi[yr]===","?r.lastIndex=++yr:o=!0;break;case"[":Ma.lastIndex=yr,l?(f=ll(new Ua,"]"),f.name=l):f=ll(e.conditions?new Ua:[],"]"),e.conditions?(Ff(e,_),e.conditions.push(f),s=null):e.push(f),yi[yr]===","?r.lastIndex=++yr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&o0(h,l),Ff(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(_l(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?Nee:Ma,r.lastIndex=yr),yr===yi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Ff(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 _l(e){return e.indexOf(".")>-1?e.split(".").map(_l):decodeURIComponent(e)}function i0(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 Wr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function o0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Wr.ClientError("wildcard can only be used at the end of a string")}function a0(e){let t=c0(e[0]);return e.length>1&&(t.next=a0(e.slice(1))),t}function c0(e){if(Array.isArray(e)){let t=c0(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 Hn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function Iee(e,t,r){return t*r/xs(e)}var Wr,xg,us,bi,Tee,gee,Ree,Aee,Gg,qg,yee,Ma,Nee,yr,yi,Ua,Vf=ge(()=>{Wr=B(ne()),xg=B(ct()),us=require("ordered-binary"),bi=require("lmdb"),Tee=.3,gee=.1,Ree=.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(Fg,"executeConditions");a(Pa,"searchByIndex");a(Gs,"findAttribute");a(Oee,"joinTo");a(bee,"joinFrom");qg={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(kg,"filterByType");a(qf,"estimateCondition");yee=/[()[\]|!<>.]|(=\w*=)/,Ma=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Nee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(kf,"parseQuery");a(ll,"parseBlock");a(Ff,"assignOperator");a(_l,"decodeProperty");a(i0,"typedDecoding");a(o0,"wildcardDecoding");a(a0,"toSortObject");a(c0,"toSortEntry");Ua=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(Hn,"flattenKey");a(xs,"estimatedEntryCount");a(Iee,"intersectionEstimate")});function f0(e){let t={openapi:wee,info:{title:"HarperDB HTTP REST interface",version:(0,d0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:g,name:L,elements:v,relationship:P,definition:k}of o){if(P)g==="array"?_[L]={type:"array",items:{$ref:Ni+v.type}}:_[L]={$ref:Ni+g};else{let H=k??v?.definition;if(H){if(!t.components.schemas[H.type]){let j={};H.properties.forEach(z=>{j[z.name]=new Kg(Vg[z.type],z.type)}),t.components.schemas[H.type]=new _0(j)}g==="array"?_[L]={type:"array",items:{$ref:Ni+H.type}}:_[L]={$ref:Ni+H.type}}else g==="array"?v.type==="Any"||v.type=="ID"?_[L]={type:"array",items:{format:v.type}}:_[L]={type:"array",items:new Kg(Vg[v.type],v.type)}:g==="Any"||g=="ID"?_[L]={format:g}:_[L]=new Kg(Vg[g],g)}l.push(new Wg(L,"query",_[L]))}let d=Object.keys(_),f=new Wg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Wg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new _0(_);let h=u.post!==Resource.prototype.post||u.update,S=typeof u.put=="function",p=typeof u.get=="function",T=typeof u.delete=="function",b="/"+s+"/";h&&(t.paths[b]={},t.paths[b].post=new Cee(i,r,"create a new record auto-assigning a primary key")),p&&(t.paths[b]||(t.paths[b]={}),t.paths[b].get=new $g(l,r,{200:new Yg({$ref:Ni+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new l0(l,r,"delete all the records that match the provided query",{204:new u0})),b="/"+s+"/{"+c+"}",p&&(t.paths[b]={},t.paths[b].get=new $g([f],r,{200:new Yg({$ref:Ni+i})},"retrieve a record by its primary key")),S&&(t.paths[b]||(t.paths[b]={}),t.paths[b].put=new Dee([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new l0([f],r,"delete a record with the given primary key",{204:new u0})),p&&E.schema.enum.length>0&&(b="/"+s+"/{"+c+"}.{property}",t.paths[b]={},t.paths[b].get=new $g([f,E],r,{200:new Yg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function Cee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ni+e}}}},this.security=t,this.responses={200:{description:Qg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function $g(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Yg(e){this.description=Qg,this.content={"application/json":{schema:e}}}function u0(){this.description="successfully processed request, no content returned to client"}function Dee(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ni+r}}}},this.responses={200:{description:Qg}}}function l0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function _0(e){this.type="object",this.properties=e}function Kg(e,t){this.type=e,this.format=t}function Wg(e,t,r){this.name=e,this.in=t,this.schema=r}var d0,wee,Vg,Ni,Qg,E0=ge(()=>{d0=B(Gd()),wee="3.0.3",Vg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ni="#/components/schemas/",Qg="successful operation";a(f0,"generateJsonApi");a(Cee,"Post");a($g,"Get");a(Yg,"Response200");a(u0,"Response204");a(Dee,"Put");a(l0,"Delete");a(_0,"ResourceSchema");a(Kg,"Type");a(Wg,"Parameter")});var Yf={};Fe(Yf,{start:()=>Uee});async function Mee(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&kf(e);let s=new gi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==h0){let h=$f.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await ze(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=Ro(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new va.ClientError(h,400)}if(e.authorize=!0,i===h0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return f0($f);throw new va.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new va.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new va.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,zg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){Lee[0]=d;let h=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),S=r["if-none-match"];S&&h==S?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),zg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Gf(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?Ao.warn(i):Ao.info(i):Ao.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Gf(i.contentType?i:i.toString(),e,o),o}}function Uee(e){zg=e,!m0&&(m0=!0,$f=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Mee(t,r)}),e.server.ws(async(t,r,n)=>{dl++;let s=new Nn;p0||(p0=!0,lu(l=>{dl>0&&l.push({metric:"ws-connections",connections:dl,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ao.warn(l)});let o;t.on("message",a(function(d){o||(o=Ro(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{dl--,cn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=$f.getMatch(u);if(cn(!!_,"connection","ws","connect"),!_)t.send(Ri(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,kr(h=>({count:h.count,total:dl}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ri(E.value,r);t.send(h),kr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Ao,va,Yt,Lee,zg,h0,m0,$f,p0,dl,S0=ge(()=>{ya();Is();Ao=B(Y()),va=B(ne());Vf();Ac();to();Wu();E0();Yt=new Uint8Array(8),Lee=new Float64Array(Yt.buffer,0,1),zg={},h0="openapi";a(Mee,"http");dl=0;a(Uee,"start")});var Jg=R((mhe,T0)=>{var{recordAction:Kf,recordActionBinary:Pee}=(Is(),ie(_u)),vee=require("fastify-plugin"),Bee=200;T0.exports=vee(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Kf(o,"duration",_,d,l),Pee(s.raw.statusCode<400,"success",_,d,l);let f=Bee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Kf(performance.now()-c,"transfer",_,d,l),Kf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Kf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var rR=R((The,O0)=>{var Jf=require("clone"),jf=et(),Hee=Q(),Qf=U(),phe=Y(),jg=require("fs"),Zg=require("joi"),{string:zf}=Zg.types(),{hdb_errors:xee,handleHDBError:Wf}=ne(),{HDB_ERROR_MSGS:She,HTTP_STATUS_CODES:Xg}=xee,{common_validators:Ba}=zn(),g0=" is required",Gee=["insert","update","upsert"],eR={database:{presence:!1,format:Ba.schema_format,length:Ba.schema_length},schema:{presence:!1,format:Ba.schema_format,length:Ba.schema_length},table:{presence:!0,format:Ba.schema_format,length:Ba.schema_length},action:{inclusion:{within:Gee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Fee={schema:zf.required(),table:zf.required(),action:zf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:qee,AWS_SECRET:kee,AWS_BUCKET:Vee,AWS_FILE_KEY:$ee,REGION:Yee}=Qf.S3_BUCKET_AUTH_KEYS,Kee={s3:{presence:!0},[`s3.${qee}`]:{presence:!0,type:"String"},[`s3.${kee}`]:{presence:!0,type:"String"},[`s3.${Vee}`]:{presence:!0,type:"String"},[`s3.${$ee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Yee}`]:{presence:!0,type:"String"}},R0=Jf(eR);R0.data.presence={message:g0};var A0=Jf(eR);A0.file_path.presence={message:g0};var Wee=Object.assign(Jf(eR),Kee),tR=Jf(Fee);tR.csv_url=zf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();tR.passthrough_headers=Zg.object();function Qee(e){let t=jf.validateObject(e,R0);return Xf(e,t)}a(Qee,"dataObject");function zee(e){let t=jf.validateBySchema(e,Zg.object(tR));return Xf(e,t)}a(zee,"urlObject");function Jee(e){let t=jf.validateObject(e,A0);return Xf(e,t)}a(Jee,"fileObject");function jee(e){let t=jf.validateObject(e,Wee);return Xf(e,t)}a(jee,"s3FileObject");function Xf(e,t){if(!t){let r=Hee.checkGlobalSchemaTable(e.schema,e.table);if(r)return Wf(new Error,r,Xg.BAD_REQUEST);if(e.operation===Qf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{jg.accessSync(e.file_path,jg.constants.R_OK|jg.constants.F_OK)}catch(n){return n.code===Qf.NODE_ERROR_CODES.ENOENT?Wf(n,`No such file or directory ${n.path}`,Xg.BAD_REQUEST):n.code===Qf.NODE_ERROR_CODES.EACCES?Wf(n,`Permission denied ${n.path}`,Xg.BAD_REQUEST):Wf(n)}}return t}a(Xf,"postValidateChecks");O0.exports={dataObject:Qee,urlObject:zee,fileObject:Jee,s3FileObject:jee}});var nR=R((Rhe,b0)=>{"use strict";var fl=Y(),Zf=U();async function Xee(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===Zf.OPERATIONS_ENUM.INSERT||t.operation===Zf.OPERATIONS_ENUM.UPDATE||t.operation===Zf.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===Zf.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(fl.info(i.message),i):i.http_resp_msg?(fl.error(`Error calling operation: ${e.name}`),fl.error(i.http_resp_msg),i):(fl.error(`Error calling operation: ${e.name}`),fl.error(i),i)}}a(Xee,"callOperationFunctionAsAwait");b0.exports={callOperationFunctionAsAwait:Xee}});var N0=R((Ohe,y0)=>{"use strict";var sR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},iR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};y0.exports={BulkLoadFileObject:sR,BulkLoadDataObject:iR}});var w0=R((yhe,I0)=>{"use strict";var oR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};I0.exports=oR});var dR=R((Lhe,Y0)=>{"use strict";var eE=an(),rE=rR(),Zee=require("needle"),xn=U(),Ihe=st(),Ha=Q(),{handleHDBError:it,hdb_errors:H0}=ne(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:bo}=H0,xa=Y(),aR=require("papaparse");Ha.promisifyPapaParse();var Gn=require("fs-extra"),ete=require("path"),{chain:C0}=require("stream-chain"),D0=require("stream-json/streamers/StreamArray"),L0=require("stream-json/utils/Batch"),M0=require("stream-chain/utils/comp"),{finished:U0}=require("stream"),tte=re(),x0=nR(),rte=Cg(),{BulkLoadFileObject:uR,BulkLoadDataObject:nte}=N0(),lR=Tg(),{verifyBulkLoadAttributePerms:G0}=Uf(),whe=w0(),Che=St(),Dhe=Rs(),{databases:ste}=(Re(),ie(qe)),{coerceType:ite}=(nE(),ie(fR)),P0="No records parsed from csv file.",Oo=`${tte.get("HDB_ROOT")}/tmp`,{schema_regex:ote}=zn(),v0=1024*1024*2,B0=5e3,ate={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};Y0.exports={csvDataLoad:cte,csvURLLoad:ute,csvFileLoad:lte,importFromS3:_te};async function cte(e,t){let r=rE.dataObject(e);if(r)throw it(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=k0(e.schema,e.table),i=aR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:cR.bind(null,s),dynamicTyping:!1}),o=new lR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&G0(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,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new nte(e.action,e.schema,e.table,i.data);return n=await x0.callOperationFunctionAsAwait(V0,u,null),n.message===P0?P0:$0(n.records,n.number_written)}catch(s){throw yo(s)}}a(cte,"csvDataLoad");async function ute(e){let t=rE.urlObject(e);if(t)throw it(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Oo}/${r}`;try{await dte(e,r)}catch(s){throw xa.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+s),it(s,bo(wt.DOWNLOAD_FILE_ERR(r)))}try{let s=new uR(this.job_operation_function.name,e.action,e.schema,e.table,n,xn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await _R(s);return await tE(n),i}catch(s){throw await tE(n),yo(s)}}a(ute,"csvURLLoad");async function lte(e){let t=rE.fileObject(e);if(t)throw it(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new uR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,xn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await _R(r)}catch(n){throw yo(n)}}a(lte,"csvFileLoad");async function _te(e){let t=rE.s3FileObject(e);if(t)throw it(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=ete.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Oo}/${s}`;let i=new uR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await fte(s,e);let o=await _R(i);return await tE(r),o}catch(n){throw await tE(r),yo(n)}}a(_te,"importFromS3");async function dte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Zee("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw it(n,s,n.statusCode,xn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}hte(r,e.csv_url),await Ete(t,r.raw)}a(dte,"downloadCSVFile");async function fte(e,t){try{let r=`${Oo}/${e}`;await Gn.mkdirp(Oo),await Gn.writeFile(`${Oo}/${e}`,"",{flag:"a+"});let n=await Gn.createWriteStream(r),s=await rte.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){xa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw xa.error(wt.S3_DOWNLOAD_ERR+" - "+r),it(r,bo(wt.S3_DOWNLOAD_ERR))}}a(fte,"downloadFileFromS3");async function Ete(e,t){try{await Gn.mkdirp(Oo),await Gn.writeFile(`${Oo}/${e}`,t)}catch(r){throw xa.error(wt.WRITE_TEMP_FILE_ERR),it(r,bo(wt.DEFAULT_BULK_LOAD_ERR))}}a(Ete,"writeFileToTempFolder");async function tE(e){if(e)try{await Gn.access(e),await Gn.unlink(e)}catch{xa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(tE,"deleteTempFile");function hte(e,t){if(e.statusCode!==H0.HTTP_STATUS_CODES.OK)throw it(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!ate[e.headers["content-type"]])throw it(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw it(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a(hte,"validateURLResponse");async function _R(e){try{let t;switch(e.file_type){case xn.VALID_S3_FILE_TYPES.CSV:t=await mte(e);break;case xn.VALID_S3_FILE_TYPES.JSON:t=await pte(e);break;default:throw it(new Error,wt.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,xn.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return $0(t.records,t.number_written)}catch(t){throw yo(t)}}a(_R,"fileLoad");async function F0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await eE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&G0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=it(c);r(u)}}a(F0,"validateChunk");async function q0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Ha.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Ha.isEmpty(c)&&!Ha.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 x0.callOperationFunctionAsAwait(V0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=it(c,bo(wt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(q0,"insertChunk");async function mte(e){let t={records:0,number_written:0},r=k0(e.schema,e.table);try{let n=new lR,s=Gn.createReadStream(e.file_path,{highWaterMark:v0});s.setEncoding("utf8"),await aR.parsePromise(s,F0.bind(null,e,n),cR.bind(null,r));let i=n.getPermsResponse();if(i)throw it(new Error,i,Kt.BAD_REQUEST);return s=Gn.createReadStream(e.file_path,{highWaterMark:v0}),s.setEncoding("utf8"),await aR.parsePromise(s,q0.bind(null,e,t),cR.bind(null,r)),s.destroy(),t}catch(n){throw it(n,bo(wt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+n)}}a(mte,"callPapaParse");function k0(e,t){let r=ste[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>ite(i,s));return n}a(k0,"createTransformMap");function cR(e,t,r){let n=e.get(r);return n?n(t):Ha.autoCast(t)}a(cR,"typeFunction");async function pte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new lR,s=C0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),D0.withParser(),c=>c.value,new L0({batchSize:B0}),M0(async c=>{await F0(e,n,r,c)})]);await new Promise((c,u)=>{U0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw it(new Error,i,Kt.BAD_REQUEST);let o=C0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),D0.withParser(),c=>c.value,new L0({batchSize:B0}),M0(async c=>{await q0(e,t,r,c)})]);return await new Promise((c,u)=>{U0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw it(n,bo(wt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+n)}}a(pte,"insertJson");async function V0(e){let t={};try{e.data&&e.data.length>0&&Ste(e.data[0])?t=await Tte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",xa.info(t.message))}catch(r){throw yo(r)}return t}a(V0,"callBulkFileLoad");function Ste(e){let t=Object.keys(e);for(let r of t)if(!ote.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Ste,"validateColumnNames");async function Tte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=eE.insert;break;case"update":i=eE.update;break;case"upsert":i=eE.upsert;break;default:throw it(new Error,wt.INVALID_ACTION_PARAM_ERR(n),Kt.BAD_REQUEST,xn.LOG_LEVELS.ERROR,wt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Ha.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw yo(o)}}a(Tte,"bulkFileLoad");function $0(e,t){return`successfully loaded ${t} of ${e} records`}a($0,"buildResponseMsg");function yo(e){return it(e,bo(wt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(yo,"buildTopLevelErrMsg")});var W0=R((Uhe,K0)=>{"use strict";var ER=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};K0.exports=ER});var J0=R((vhe,z0)=>{"use strict";var gte=U(),Q0=require("moment"),Rte=require("uuid").v4,hR=class{static{a(this,"JobObject")}constructor(){this.id=Rte(),this.type=void 0,this.start_datetime=Q0().valueOf(),this.created_datetime=Q0().valueOf(),this.end_datetime=void 0,this.status=gte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};z0.exports=hR});var iE=R((Hhe,rB)=>{"use strict";var Ate=require("uuid").v4,Z0=an(),eB=Br(),Ote=Zn(),bte=ra(),yte=W0(),ot=U(),Nte=J0(),Ite=QS(),hn=Y(),wte=xc(),Ga=Q(),{promisify:Cte}=require("util"),No=require("moment"),Dte=vf(),sE=rR(),j0=Vm(),{deleteTransactionLogsBeforeValidator:Lte}=Eg(),{handleHDBError:Mte,hdb_errors:Ute}=ne(),{HTTP_STATUS_CODES:Pte}=Ute,X0=eB.searchByValue,vte=eB.searchByHash,Bte=Z0.insert,Hte=Cte(Dte.evaluateSQL),xte=Z0.update;rB.exports={addJob:qte,updateJob:Vte,handleGetJob:Gte,handleGetJobsByStartDate:Fte,getJobById:tB};async function Gte(e){try{let t=await tB(e.id);return Ga.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 hn.error("There was an error getting job",t),new Error(r)}}a(Gte,"handleGetJob");async function Fte(e){try{let t=await kte(e);if(hn.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=No(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=No(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 hn.error(r),new Error(r)}}a(Fte,"handleGetJobsByStartDate");async function qte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ga.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return hn.info(l),t.error=l,t}if(!ot.JOB_TYPE_ENUM[e.operation])return hn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case ot.OPERATIONS_ENUM.CSV_FILE_LOAD:n=sE.fileObject(e);break;case ot.OPERATIONS_ENUM.CSV_URL_LOAD:n=sE.urlObject(e);break;case ot.OPERATIONS_ENUM.CSV_DATA_LOAD:n=sE.dataObject(e);break;case ot.OPERATIONS_ENUM.IMPORT_FROM_S3:n=sE.s3FileObject(e);break;case ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=j0(e,"date");break;case ot.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=j0(e,"timestamp");break;case ot.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Lte(e);break;default:break}if(n)throw Mte(n,n.message,Pte.BAD_REQUEST,void 0,void 0,!0);let s=new Nte;s.type=e.operation===ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Ote(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await X0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return hn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Ate();try{o=await X0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return hn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return hn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new wte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await Bte(u)}catch(l){return hn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,hn.trace(l)}return t}a(qte,"addJob");async function kte(e){let t=No(e.from_date,No.ISO_8601),r=No(e.to_date,No.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new yte(n,e.hdb_user);try{return await Hte(s)}catch(i){throw hn.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(kte,"getJobsInDateRange");async function tB(e){if(Ga.isEmptyOrZeroLength(e))return Ga.errorizeMessage("Invalid job ID specified.");let t=new bte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await vte(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return hn.error(n),Ga.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(tB,"getJobById");async function Vte(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ga.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=No().valueOf());let t=new Ite(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await xte(t),r}a(Vte,"updateJob")});var cB=R((Ghe,aB)=>{"use strict";var nB=Q(),Nr=U(),$te=require("moment"),oE=dR(),aE=Y(),sB=iE(),iB=Bf(),oB=Qi(),Yte=rt(),Kte=Cf(),mR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Wte(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(nB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(nB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Nr.JOB_TYPE_ENUM.csv_file_load:await Fs(e,oE.csvFileLoad);break;case Nr.JOB_TYPE_ENUM.csv_url_load:await Fs(e,oE.csvURLLoad);break;case Nr.JOB_TYPE_ENUM.csv_data_load:await Fs(e,oE.csvDataLoad);break;case Nr.JOB_TYPE_ENUM.import_from_s3:await Fs(e,oE.importFromS3);break;case Nr.JOB_TYPE_ENUM.empty_trash:break;case Nr.JOB_TYPE_ENUM.export_local:await Fs(e,iB.export_local);break;case Nr.JOB_TYPE_ENUM.export_to_s3:await Fs(e,iB.export_to_s3);break;case Nr.JOB_TYPE_ENUM.delete_files_before:case Nr.JOB_TYPE_ENUM.delete_records_before:await Fs(e,oB.deleteFilesBefore);break;case Nr.JOB_TYPE_ENUM.delete_audit_logs_before:await Fs(e,oB.deleteAuditLogsBefore);break;case Nr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Fs(e,Kte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Wte,"parseMessage");async function Fs(e,t){try{e.job.status=Nr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=$te().valueOf(),await sB.updateJob(e.job),await Qte(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):aE.error(`There was an error running ${t.name} job with id ${e.job.id}`),aE.error(n),e.job.message=n,e.job.status=Nr.JOB_STATUS_ENUM.ERROR;try{await sB.updateJob(e.job)}catch(s){throw aE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Fs,"runJob");async function Qte(e){aE.trace("launching job thread:",e),Yte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Qte,"launchJobThread");aB.exports={parseMessage:Wte,RunnerMessage:mR}});var lB=R((qhe,uB)=>{"use strict";var pR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};uB.exports=pR});var bR=R((Vhe,OR)=>{"use strict";var dE=Br(),gR=vf(),cE=dR(),qs=Id(),uE=ri(),hl=Qi(),zte=US(),El=xr(),lE=kS(),Wt=fg(),_E=Y(),Jte=YS(),jte=Yd(),_B=bT(),Xte=Wd(),Zte=NT(),ere=IT(),tre=DT(),rre=MT(),SR=vT(),dB=Bf(),nre=Uf(),RR=iE(),F=U(),{hdb_errors:pl,handleHDBError:ml}=ne(),{HTTP_STATUS_CODES:fB}=pl,TR=FT(),EB=hf(),OB=require("util"),Fa=an(),sre=As(),ire=ma(),hB=cB(),mB=bu(),pB=(Tf(),ie(Qu)),SB=cr(),TB=Cf(),gB=bf(),{setServerUtilities:ore}=(nE(),ie(fR)),{CONTEXT:are}=(In(),ie(Lp)),{_assignPackageExport:cre}=require("../../index"),{transformReq:ure}=Q(),{server:lre}=(or(),ie(Bi)),tr=_E.loggerWithTag("operation"),_re=nR(),RB=dE.searchByHash,dre=dE.searchByValue,fre=OB.promisify(dE.search),Ere=OB.promisify(gR.evaluateSQL),hre={[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},$=lB();async function bB(e,t){try{if(e.body.operation!=="read_log"&&(_E.log_level===F.LOG_LEVELS.INFO||_E.log_level===F.LOG_LEVELS.DEBUG||_E.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;tr.info(o)}}catch(n){tr.error(n)}let r=await _re.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return hre[e.body.operation]&&sre.setSchemaDataToGlobal(n=>{n&&tr.error(n)}),r}a(bB,"processLocalTransaction");var AB=pre();OR.exports={chooseOperation:yB,getOperationFunction:NB,operation:AR,processLocalTransaction:bB};ore(OR.exports);lre.operation=AR;function yB(e){let t;try{t=NB(e)}catch(s){throw tr.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=gR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=gR.checkASTPermissions(e,i);if(o)throw tr.error(`${fB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),ml(new Error,o,pl.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 s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=nre.verifyPerms(i,s);if(o)throw tr.error(`${fB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),ml(new Error,o,pl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw ml(s,"There was an error when trying to choose an operation path")}return r}a(yB,"chooseOperation");function NB(e){if(tr.trace(`getOperationFunction with operation: ${e.operation}`),AB.has(e.operation))return AB.get(e.operation);throw ml(new Error,pl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),pl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(NB,"getOperationFunction");cre("operation",AR);function AR(e,t){e.hdb_user=this[are]?.user,e.bypass_auth=!t;let r=yB(e);return bB({body:e},r)}a(AR,"operation");async function mre(e){tr.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await Fa.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await Fa.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await Fa.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await hl.deleteRecord(i);break;default:tr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){tr.info("Invalid operation in transaction"),tr.error(o)}}a(mre,"catchup");async function ls(e){ure(e);let t,r;try{r=await RR.addJob(e),t=r.createdJob,tr.info("addJob result",r);let n=new hB.RunnerMessage(t,e);return await hB.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw tr.error(s),ml(n,s)}}a(ls,"executeJob");function pre(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new $(Fa.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new $(Fa.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new $(Fa.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new $(dE.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new $(RB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new $(RB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(dre)),e.set(F.OPERATIONS_ENUM.SEARCH,new $(fre)),e.set(F.OPERATIONS_ENUM.SQL,new $(Ere)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new $(ls,cE.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new $(ls,cE.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new $(ls,cE.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new $(ls,cE.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new $(qs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new $(qs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new $(qs.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new $(qs.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new $(qs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new $(qs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new $(qs.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new $(qs.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new $(uE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new $(uE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new $(uE.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new $(uE.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new $(hl.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 $(lE.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new $(lE.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new $(lE.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new $(lE.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new $(El.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new $(Jte)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new $(jte)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new $(_B)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(_B)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new $(Xte)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(Zte)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new $(ere)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new $(SB.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new $(tre.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new $(rre)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(SR.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(SR.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(SR.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new $(ls,dB.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new $(ls,hl.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new $(ls,hl.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new $(ls,dB.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(RR.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new $(RR.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 $(EB.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new $(EB.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new $(mre)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $(ire.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(ls,hl.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(zte)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(mB.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(mB.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new $(pB.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new $(pB.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new $(SB.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $(Wt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $(Wt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $(Wt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new $(Wt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $(Wt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new $(Wt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $(Wt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $(Wt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $(Wt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $(Wt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new $(Wt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $(Wt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $(Wt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $(Wt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $(Wt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $(Wt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(TB.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(ls,TB.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $(gB.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $(gB.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new $(qs.getBackup)),e}a(pre,"initializeOperationFunctionMap")});var EE=R((Yhe,CB)=>{"use strict";var yR=U(),Sre=Q(),Sl=Y(),{handleHDBError:NR,hdb_errors:fE}=ne(),{isMainThread:Tre}=require("worker_threads"),{Readable:gre}=require("stream"),IB=require("os"),Rre=require("util"),Are=rT(),Ore=Rre.promisify(Are.authorize),wB=bR(),{createGzip:bre,constants:yre}=require("zlib");function Nre(e){let t=`Found an uncaught exception with message: ${e.message}. ${IB.EOL}Stack: ${e.stack} ${IB.EOL}Terminating ${Tre?"HDB":"thread"}.`;console.error(t),Sl.fatal(t),process.exit(1)}a(Nre,"handleServerUncaughtException");function Ire(e,t,r){if(Sl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:fE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(Ire,"serverErrorHandler");function wre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=NR(new Error,"Invalid JSON.",fE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Sre.isEmpty(e.body.operation)){let n=NR(new Error,"Request body must include an 'operation' property.",fE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(wre,"reqBodyValidationHandler");function Cre(e,t,r){let n;e.body.operation!==yR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==yR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==yR.OPERATIONS_ENUM.LOGOUT?Ore(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Sl.warn(s),Sl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(NR(s,i,fE.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(Cre,"authHandler");async function Dre(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=wB.chooseOperation(e.body);let s=await wB.processLocalTransaction(e,n);if(s instanceof gre&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(bre({level:yre.Z_BEST_SPEED})))}return s}catch(s){throw Sl.error(s),s}}a(Dre,"handlePostRequest");CB.exports={authHandler:Cre,handlePostRequest:Dre,handleServerUncaughtException:Nre,serverErrorHandler:Ire,reqBodyValidationHandler:wre}});var UB=R((Whe,MB)=>{"use strict";var Lre=require("fastify-plugin"),{handlePostRequest:DB,authHandler:Mre,reqBodyValidationHandler:Ure}=EE();async function Pre(e){e.decorate("hdbCore",{preValidation:[Ure,Mre],request:t=>LB(DB(t,response)),requestWithoutAuthentication:(t,r)=>LB(DB(t,r,!0))})}a(Pre,"hdbCore");async function LB(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(LB,"convertAsyncIterators");MB.exports=Lre(Pre)});var BB=R((Jhe,vB)=>{"use strict";var zhe=require("fs"),IR=re();IR.initSync();var{CONFIG_PARAMS:PB}=U(),vre=1024*1024*1024;function Bre(e){let t=IR.get(PB.HTTP_TIMEOUT),r=IR.get(PB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:vre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Bre,"getServerOptions");vB.exports=Bre});var GB=R((Xhe,xB)=>{"use strict";var wR=re();wR.initSync();var{CONFIG_PARAMS:HB}=U();function Hre(){let e=wR.get(HB.HTTP_CORSACCESSLIST),t=wR.get(HB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(Hre,"getCORSOptions");xB.exports=Hre});var kB=R((eme,qB)=>{"use strict";var FB=re();FB.initSync();var xre=U();function Gre(){return FB.get(xre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Gre,"getHeaderTimeoutConfig");qB.exports=Gre});var DR={};Fe(DR,{customFunctionsServer:()=>kre,ready:()=>nH,start:()=>qre});function qre(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=rH(t),tt.http((await ks).server));let o=await ks,c=(0,CR.dirname)(s),u=(0,CR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!VB.has(c)){VB.add(c);try{o.register($re(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:nH}}async function kre(){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 Vre();let e=zB.get(JB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await rH(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 Vre(){try{Ve.info("Custom Functions starting configuration."),await jB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function $re(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,$B.existsSync)(e)&&r.register(QB.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ve.error(s.message):s&&Ve.error(s),o()})}catch(n){Ve.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function rH(e){Ve.info("Custom Functions starting buildServer.");let t=(0,XB.default)(e),r=(0,YB.default)(t);r.server.headersTimeout=(0,eH.default)(),r.setErrorHandler(tH.serverErrorHandler);let n=(0,ZB.default)();return n&&r.register(KB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(WB.default),await r.register(Fre),await r.after(),Hg(r),Ve.info("Custom Functions completed buildServer."),r}function nH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var CR,$B,YB,KB,WB,QB,zB,JB,Ve,Fre,jB,XB,ZB,eH,tH,ks,VB,sH=ge(()=>{CR=require("path"),$B=require("fs"),YB=B(require("fastify")),KB=B(require("@fastify/cors")),WB=B(Jg()),QB=B(require("@fastify/autoload")),zB=B(re()),JB=B(U()),Ve=B(Y()),Fre=B(UB()),jB=B(xr()),XB=B(BB()),ZB=B(GB()),eH=B(kB()),tH=B(EE());ya();or();VB=new Set;a(qre,"start");a(kre,"customFunctionsServer");a(Vre,"setUp");a($re,"buildRouteFolder");a(rH,"buildServer");a(nH,"ready")});var LR={};Fe(LR,{start:()=>Yre});function Yre(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,uH.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){oH||(oH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=iH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,aH.default)(s,(0,cH.realpathSync)(o))}}return i(s)},{runFirst:!0})),iH.set(r,n)}}}var aH,cH,uH,iH,oH,lH=ge(()=>{aH=B(require("send")),cH=require("fs"),uH=B(require("serve-static")),iH=new Map;a(Yre,"start")});function Qre(e,t=1,r){if(MR++,(0,Io.startWorker)("server/threads/threadServer.js",{name:pE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===pE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Wre.push(s),await s,qa.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=mE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=qa.indexOf(n);o>-1&&qa.splice(o,1)}if(a(i,"removeWorker"),ka){let o=ka;ka=[];for(let c of o)EH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{UR?UR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Io.shutdownWorkers)(),MR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function hH(e=0,t){if(typeof e=="string")try{(0,SE.existsSync)(e)&&(0,SE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=zre:r=Jre(t):r=vR;let n=(0,Va.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=EH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),UR=!0,r(o,(c,u)=>{if(!c){if(_H){let l=o._socket||new Va.Socket({handle:o,writable:!0,readable:!0});_H.deliverSocket(l,e,u),l.resume()}else MR>0?(ka.length===0&&setTimeout(()=>{ka.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,ka.push(o)):(console.log("start up a dynamic thread to handle request"),Qre(0));kr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Va.Socket({handle:o,writable:!0,readable:!0});ene(l,c,e)}kr(!0,"socket-routed")})};let s=ou();PR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function vR(e,t){let r,n=0;for(let s of qa){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=hE)return hE=i,t(r);n=i}hE=0,t(r)}function zre(e,t){let r={};e.getpeername(r);let n=r.address,s=$a.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);vR(e,o=>{$a.set(n,{worker:o,lastUsed:i}),t(o)})}function Jre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Va.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=$a.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);vR(n,d=>{$a.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Xre(){hE=0;for(let e of qa)e.expectedIdle=e.recentELU.idle+jre,e.requests=1;qa.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function ene(e,t,r){let n=Zre++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),mE.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),mE.delete(n)),s.event=="destroy"&&(e.destroy(),mE.delete(n))})}var Io,Va,pE,PR,SE,fH,Kre,qa,ka,EH,_H,MR,Wre,UR,hE,dH,$a,jre,mE,Zre,mH=ge(()=>{Io=B(rt()),Va=require("net"),pE=B(U()),PR=B(Y()),SE=require("fs");Is();fH=require("worker_threads"),Kre=B(zi()),qa=[],ka=[],EH=[],MR=0,Wre=[];fH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Qre,"startHTTPWorker");a(hH,"startSocketServer");hE=0;a(vR,"findMostIdleWorker");dH=36e5,$a=new Map;a(zre,"findByRemoteAddressAffinity");a(Jre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of $a)r.lastUsed+dH<e&&$a.delete(t)},dH).unref();jre=1e3;a(Xre,"updateWorkerIdleness");(0,Io.setMonitorListener)(Xre);mE=new Map,Zre=1;a(ene,"proxySocket")});var GR={};Fe(GR,{Request:()=>BR,createReuseportFd:()=>TE});var pH,BR,HR,xR,TE,gE=ge(()=>{pH=require("os"),BR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new xR(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 HR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},HR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},xR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,pH.platform)()!="win32"&&(TE=require("node-unix-socket").createReuseportFd)});var RH=R((hme,gH)=>{"use strict";var tne=require("cluster"),wo=re();wo.initSync();var TH=U(),lme=require("util"),Vs=Y(),_me=require("fs"),rne=require("fastify"),dme=ou(),nne=require("@fastify/cors"),sne=require("@fastify/compress"),ine=require("@fastify/static"),one=Jg(),ane=require("path"),{PACKAGE_ROOT:cne}=U(),une=As(),lne=Q(),_ne=xr(),dne=zi(),{server:fne}=(or(),ie(Bi)),{node_request_key:fme}=(gE(),ie(GR)),{authHandler:Ene,handlePostRequest:hne,serverErrorHandler:mne,reqBodyValidationHandler:pne}=EE(),Eme=require("net"),{registerContentHandlers:Sne}=(ya(),ie(s0)),Tne=6e4,gne=1024*1024*1024,Rne="TRUE",{CONFIG_PARAMS:Tl}=TH,Ya;gH.exports={hdbServer:SH,start:SH};async function SH(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=tne.isMaster,await Ane();let t=e.securePort>0;Ya=One(t),await Ya.ready(),e||(e={}),e.isOperationsServer=!0;try{fne.http(Ya.server,e),Ya.server.closeIdleConnections||await Ya.listen({port:0,host:"::"})}catch(r){throw Ya.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(SH,"operationsServer");async function Ane(){Vs.trace("Configuring HarperDB process."),une.setSchemaDataToGlobal(),await _ne.setUsersToGlobal(),await dne.getLicense()}a(Ane,"setUp");function One(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=bne(e),r=rne(t);r.server.headersTimeout=Nne(),r.setErrorHandler(mne);let n=yne();n&&r.register(nne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(one),r.register(sne),r.register(ine,{root:ane.join(cne,"studio/build-local")}),Sne(r);let s=wo.get(TH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!lne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[pne,Ene],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),hne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(One,"buildServer");function bne(e){let t=wo.get(Tl.OPERATIONSAPI_NETWORK_TIMEOUT),r=wo.get(Tl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:gne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(bne,"getServerOptions");function yne(){let e=wo.get(Tl.OPERATIONSAPI_NETWORK_CORS),t=wo.get(Tl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Rne)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(yne,"getCORSOpts");function Nne(){return wo.get(Tl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Tne}a(Nne,"getHeaderTimeoutConfig")});var bE={};Fe(bE,{disableNATS:()=>wne,publishToStream:()=>OE,setNATSReplicator:()=>FR,setPublishToStream:()=>Cne,setSubscription:()=>$R,start:()=>Ine});function Ine(){gl.default.get(Rl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Lne()}function wne(e=!0){NH=e}function Cne(e,t){OE=e,$R=t}function Lne(){if(NH||process.env._DISABLE_NATS)return;let e=dr(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];FR(s,r,i)}}KR((r,n)=>{FR(r.tableName,r.databaseName,r),n&&wH(r)}),!AH&&(AH=!0)}function FR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends qt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ue],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ue]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ue],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ue],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ue]})}static defineSchema(i){wH(i)}static subscribe(){let i=new Nn;return $R(t,e,i),i}static subscribeOnThisThread(i){return i<(gl.default.get(Rl.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Dne)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new RE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=IH;return i}a(n,"getNATSTransaction")}function wH(e){let t=gl.default.get(Rl.default.CONFIG_PARAMS.CLUSTERING_NODENAME);OE(`${kR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,VR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var OH,kR,VR,bH,yH,gl,Rl,AE,NH,OE,$R,Dne,IH,AH,RE,qR,YR=ge(()=>{Re();In();OH=B(St()),kR=B(st()),VR=B(Rs());Ac();bH=B(RS()),yH=B(Mr()),gl=B(re()),Rl=B(U()),AE=B(Y());a(Ine,"start");a(wne,"disableNATS");OE=OH.publishToStream,$R=bH.setSubscription;a(Cne,"setPublishToStream");Dne=2;a(Lne,"assignReplicationSource");a(FR,"setNATSReplicator");a(wH,"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 n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=gl.default.get(Rl.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(AE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(OE(`${kR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,VR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw AE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},qR=class extends RE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,yH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};IH=new qR});var VH=R(Co=>{"use strict";var{isMainThread:PH,parentPort:Ol,threadId:yE}=require("worker_threads"),{Socket:Mne,createServer:Une}=require("net"),{createServer:Pne,IncomingMessage:vne}=require("http"),{createServer:Bne}=require("https"),{readFileSync:Ka,unlinkSync:CH,existsSync:Hne}=require("fs"),rr=Y(),Ce=re(),ft=U(),{server:CE}=(or(),ie(Bi)),{WebSocketServer:xne}=require("ws"),{createServer:Gne}=require("tls"),{getTicketKeys:Fne,restartNumber:qne,getWorkerIndex:IE}=rt(),{Headers:vH,appendHeader:kne}=(Wu(),ie(wP)),{recordAction:Al,recordActionBinary:Vne}=(Is(),ie(_u)),{Request:BH,createReuseportFd:DH}=(gE(),ie(GR)),{checkMemoryLimit:$ne}=zi(),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};var xH=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG);if(xH){let e;if(PH)e=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){rr.info("Could not close debugger",t)}});else{let t=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&IE()>=0&&(e=t+IE())}if(e){let t=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){rr.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){qne<=1&&rr.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:Ame,CONFIG_PARAMS:Yne}=ft;Ce.initSync();var Kne=Ce.get(Yne.HTTP_SESSIONAFFINITY),_s={};Co.registerServer=jR;Co.httpServer=XR;Co.deliverSocket=JR;Co.startServers=GH;Co.when_components_loaded=null;CE.http=XR;CE.request=Jne;CE.socket=jne;CE.ws=Xne;var WR={},NE={},Wne,Ii={},wE={},Qne=[],QR=[];function GH(){return Co.when_components_loaded=ZR().loadRootComponents(!0).then(()=>{Ol?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)JR(n,r,s);else if(t.requestId)zne(t);else if(t.type===ft.ITC_EVENT_TYPES.SHUTDOWN){rr.trace("received shutdown request",yE);for(let i in _s){let o=_s[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?rr.info(`Closing ${E.length} idle connections`):f&&rr.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,S=E.length;h<S;h++){let p=E[h].socket;p._httpMessage&&!p._httpMessage.finished&&!f||(f?p.destroySoon():p.end(`HTTP/1.1 408 Request Timeout\r
|
|
28
|
+
`},compressible:!1,q:.8});xt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});n0={type:"application/json",serializeStream:yc,serialize:ul,deserialize:Eee,q:.8};xt.set("*/*",n0);xt.set("",n0);a(Eee,"tryJSONParse");a(xg,"registerContentHandlers");hee=require("fastify-plugin"),mee=hee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=xf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(xf,"findBestSerializer");Xv=Pg.default.get(vg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Gf,"serialize");a(Ri,"serializeMessage");a(pee,"streamToBuffer");a(Ro,"getDeserializer");a(Zv,"deserializerUnknownType");a(See,"transformIterable")});function qg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],S=_(h);d=d.concat(S)}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?qg(d.conditions,d.operator,r,n,s,i,o,c):Pa(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,S)=>{if(h.conditions){let b=h.operator==="or",g=l(h.conditions,!b,E);return b?(L,v)=>g.some(P=>P(L,v)):(L,v)=>g.every(P=>P(L,v))}let p=(h.attribute||h[0])===r.primaryKey,T=Vg(h,r,i,c,p,E);return f&&S<d.length-1&&E&&(E=Iee(r.primaryStore,h.estimated_count,E)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Pa(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let b=o[0],g=Gs(n.attributes,b);if(g.relationship){if(o.length<2)throw new zr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let L=g.definition?.tableClass||g.elements?.definition?.tableClass,v=new Map,P=Pa({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,L,s,v);if(g.relationship.to){i[o[0]]=v;let k=!!Gs(L.attributes,g.relationship.to)?.elements;P=Oee(P,g,L.primaryStore,k,v)}if(g.relationship.from){let k=a(H=>Pa({attribute:g.relationship.from,value:H},t,r,n,s,v),"searchEntry");g.elements?(i[o[0]]=v,P=bee(P,g,L.primaryStore,v,k)):P=P.flatMap(k)}return P}else if(o.length===1)o=o[0];else throw new zr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(kg[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]=us.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 zr.ClientError(`Unknown query comparator "${u}"`)}if(r){let b=_;_=l,l=b,b=!f,f=!d,d=b}let h=o===n.primaryKey||o==null,S=h?n.primaryStore:n.indices[o],p;if(!S||S.isIndexing||E||c===null&&!S.indexNulls){if(s===!1&&!S)throw new zr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&E)throw new zr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(S?.isIndexing)throw new zr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!S.indexNulls)throw new zr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(p=Vg(e),!p)throw new zr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let b=S.getRange(T).map(p?function({key:g,value:L}){return this.isSync?L&&p(L)?g:bi.SKIP:new Promise((v,P)=>setImmediate(()=>{try{v(L&&p(L)?g:bi.SKIP)}catch(k){P(k)}}))}:g=>g.value==null?bi.SKIP:g);return b.hasEntries=!0,b}else return S?S.getRange(T).map(p?function({key:b,value:g}){return this.isSync?p({[o]:b})?g:bi.SKIP:new Promise((L,v)=>setImmediate(()=>{try{L(p({[o]:b})?g:bi.SKIP)}catch(P){v(P)}}))}:({value:b})=>b):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:b,value:g}){return this.isSync?g&&p(g)?b:bi.SKIP:new Promise((L,v)=>setImmediate(()=>{try{L(g&&p(g)?b:bi.SKIP)}catch(P){v(P)}}))})}function Gs(e,t){if(Array.isArray(t))if(t.length>1){let r=Gs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Gs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function Oee(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Hn(l),o=!0);let E=s.get(f);E?E.push(d):s.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!s.filters?.some(E=>!E(d)))if(n)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function bee(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Hn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Hn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(f=>!f(d)))continue}_.set(Hn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Vg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Gs(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Vg({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 S=t.propertyResolvers?.[l],p,T=a((b,g)=>{let L,v;if(S){if(S.from&&h.idFilter){if(!p)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:S.from,value:k};p=_(S.from,h.idFilter,!0,!0)}else p=_(S.from,h.idFilter,!1,!0);let P=p(b);return p.idFilter&&(T.idFilter=p.idFilter),P}v=S(b,r,g),L=v?.value}else L=b[l];return L?Array.isArray(L)?L.some(h):h(L,v):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),kg[o]||o){case Gg.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,us.compareKeys)(l,u[0])>=0&&(0,us.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,us.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,us.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,us.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,us.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,us.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new zr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&qf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let S=0,p=3;function T(b){let g=b[l],L;if(typeof g!="object"||!g||E?L=d(g):Array.isArray(g)?L=g.some(d):g instanceof Date&&(L=d(g.getTime())),f&&(p++,!L&&!T.idFilter&&++S/p*(i-p)>h)){let v=Pa(e,r.transaction.getReadTxn(),!1,t).map(Hn),P=new Set(v);T.idFilter=k=>P.has(Hn(k)),T.idFilter.idSet=P}return L}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function qf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/xs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=kg[n]||n,n===Gg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=qf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xs(e.indices[i.relationship.from])/(xs(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=xs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Ree*xs(e.primaryStore)+1:n==="between"?r.estimated_count=gee*xs(e.primaryStore)+1:n==="sort"?r.estimated_count=xs(e.primaryStore)+1:r.estimated_count=Tee*xs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function kf(e){if(e)if(yi=e,Ma.lastIndex=0,yee.test(e))try{let t=_l(new Ua,"");if(Ir!==yi.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 ${Ir} in '${yi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function _l(e,t){let r=Ma,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(yi);){Ir=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=i0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=dl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Aee[d],u=Fg[i]?i0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=dl(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&o0(h,l),Ff(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(dl(l)),s=void 0;break;case"(":Ma.lastIndex=Ir;let E=_l(l?[]:new Ua,")");switch(l){case"":Ff(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=a0(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}yi[Ir]===","?r.lastIndex=++Ir:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Ma.lastIndex=Ir,f=_l([],"}"),f.name=l,e.push(f),yi[Ir]===","?r.lastIndex=++Ir:o=!0;break;case"[":Ma.lastIndex=Ir,l?(f=_l(new Ua,"]"),f.name=l):f=_l(e.conditions?new Ua:[],"]"),e.conditions?(Ff(e,_),e.conditions.push(f),s=null):e.push(f),yi[Ir]===","?r.lastIndex=++Ir:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&o0(h,l),Ff(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(dl(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?Nee:Ma,r.lastIndex=Ir),Ir===yi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Ff(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 dl(e){return e.indexOf(".")>-1?e.split(".").map(dl):decodeURIComponent(e)}function i0(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 zr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function o0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new zr.ClientError("wildcard can only be used at the end of a string")}function a0(e){let t=c0(e[0]);return e.length>1&&(t.next=a0(e.slice(1))),t}function c0(e){if(Array.isArray(e)){let t=c0(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 Hn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function Iee(e,t,r){return t*r/xs(e)}var zr,Gg,us,bi,Tee,gee,Ree,Aee,Fg,kg,yee,Ma,Nee,Ir,yi,Ua,Vf=ge(()=>{zr=B(ne()),Gg=B(ct()),us=require("ordered-binary"),bi=require("lmdb"),Tee=.3,gee=.1,Ree=.05,Aee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Fg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(qg,"executeConditions");a(Pa,"searchByIndex");a(Gs,"findAttribute");a(Oee,"joinTo");a(bee,"joinFrom");kg={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(Vg,"filterByType");a(qf,"estimateCondition");yee=/[()[\]|!<>.]|(=\w*=)/,Ma=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Nee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(kf,"parseQuery");a(_l,"parseBlock");a(Ff,"assignOperator");a(dl,"decodeProperty");a(i0,"typedDecoding");a(o0,"wildcardDecoding");a(a0,"toSortObject");a(c0,"toSortEntry");Ua=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(Hn,"flattenKey");a(xs,"estimatedEntryCount");a(Iee,"intersectionEstimate")});function f0(e){let t={openapi:wee,info:{title:"HarperDB HTTP REST interface",version:(0,d0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:g,name:L,elements:v,relationship:P,definition:k}of o){if(P)g==="array"?_[L]={type:"array",items:{$ref:Ni+v.type}}:_[L]={$ref:Ni+g};else{let H=k??v?.definition;if(H){if(!t.components.schemas[H.type]){let j={};H.properties.forEach(z=>{j[z.name]=new Wg($g[z.type],z.type)}),t.components.schemas[H.type]=new _0(j)}g==="array"?_[L]={type:"array",items:{$ref:Ni+H.type}}:_[L]={$ref:Ni+H.type}}else g==="array"?v.type==="Any"||v.type=="ID"?_[L]={type:"array",items:{format:v.type}}:_[L]={type:"array",items:new Wg($g[v.type],v.type)}:g==="Any"||g=="ID"?_[L]={format:g}:_[L]=new Wg($g[g],g)}l.push(new Qg(L,"query",_[L]))}let d=Object.keys(_),f=new Qg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Qg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new _0(_);let h=u.post!==Resource.prototype.post||u.update,S=typeof u.put=="function",p=typeof u.get=="function",T=typeof u.delete=="function",b="/"+s+"/";h&&(t.paths[b]={},t.paths[b].post=new Cee(i,r,"create a new record auto-assigning a primary key")),p&&(t.paths[b]||(t.paths[b]={}),t.paths[b].get=new Yg(l,r,{200:new Kg({$ref:Ni+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new l0(l,r,"delete all the records that match the provided query",{204:new u0})),b="/"+s+"/{"+c+"}",p&&(t.paths[b]={},t.paths[b].get=new Yg([f],r,{200:new Kg({$ref:Ni+i})},"retrieve a record by its primary key")),S&&(t.paths[b]||(t.paths[b]={}),t.paths[b].put=new Dee([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new l0([f],r,"delete a record with the given primary key",{204:new u0})),p&&E.schema.enum.length>0&&(b="/"+s+"/{"+c+"}.{property}",t.paths[b]={},t.paths[b].get=new Yg([f,E],r,{200:new Kg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function Cee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ni+e}}}},this.security=t,this.responses={200:{description:zg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Yg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Kg(e){this.description=zg,this.content={"application/json":{schema:e}}}function u0(){this.description="successfully processed request, no content returned to client"}function Dee(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ni+r}}}},this.responses={200:{description:zg}}}function l0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function _0(e){this.type="object",this.properties=e}function Wg(e,t){this.type=e,this.format=t}function Qg(e,t,r){this.name=e,this.in=t,this.schema=r}var d0,wee,$g,Ni,zg,E0=ge(()=>{d0=B(Gd()),wee="3.0.3",$g={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ni="#/components/schemas/",zg="successful operation";a(f0,"generateJsonApi");a(Cee,"Post");a(Yg,"Get");a(Kg,"Response200");a(u0,"Response204");a(Dee,"Put");a(l0,"Delete");a(_0,"ResourceSchema");a(Wg,"Type");a(Qg,"Parameter")});var Yf={};Fe(Yf,{start:()=>Uee});async function Mee(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&kf(e);let s=new gi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==h0){let h=$f.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await ze(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=Ro(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new va.ClientError(h,400)}if(e.authorize=!0,i===h0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return f0($f);throw new va.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new va.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new va.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,Jg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){Lee[0]=d;let h=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),S=r["if-none-match"];S&&h==S?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),Jg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Gf(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?Ao.warn(i):Ao.info(i):Ao.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Gf(i.contentType?i:i.toString(),e,o),o}}function Uee(e){Jg=e,!m0&&(m0=!0,$f=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Mee(t,r)}),e.server.ws(async(t,r,n)=>{fl++;let s=new Nn;p0||(p0=!0,_u(l=>{fl>0&&l.push({metric:"ws-connections",connections:fl,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ao.warn(l)});let o;t.on("message",a(function(d){o||(o=Ro(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{fl--,cn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=$f.getMatch(u);if(cn(!!_,"connection","ws","connect"),!_)t.send(Ri(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,$r(h=>({count:h.count,total:fl}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ri(E.value,r);t.send(h),$r(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Ao,va,Yt,Lee,Jg,h0,m0,$f,p0,fl,S0=ge(()=>{ya();Is();Ao=B(Y()),va=B(ne());Vf();Oc();to();Qu();E0();Yt=new Uint8Array(8),Lee=new Float64Array(Yt.buffer,0,1),Jg={},h0="openapi";a(Mee,"http");fl=0;a(Uee,"start")});var jg=R((mhe,T0)=>{var{recordAction:Kf,recordActionBinary:Pee}=(Is(),ie(du)),vee=require("fastify-plugin"),Bee=200;T0.exports=vee(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Kf(o,"duration",_,d,l),Pee(s.raw.statusCode<400,"success",_,d,l);let f=Bee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Kf(performance.now()-c,"transfer",_,d,l),Kf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Kf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var nR=R((The,O0)=>{var Jf=require("clone"),jf=et(),Hee=Q(),Qf=U(),phe=Y(),Xg=require("fs"),eR=require("joi"),{string:zf}=eR.types(),{hdb_errors:xee,handleHDBError:Wf}=ne(),{HDB_ERROR_MSGS:She,HTTP_STATUS_CODES:Zg}=xee,{common_validators:Ba}=zn(),g0=" is required",Gee=["insert","update","upsert"],tR={database:{presence:!1,format:Ba.schema_format,length:Ba.schema_length},schema:{presence:!1,format:Ba.schema_format,length:Ba.schema_length},table:{presence:!0,format:Ba.schema_format,length:Ba.schema_length},action:{inclusion:{within:Gee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Fee={schema:zf.required(),table:zf.required(),action:zf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:qee,AWS_SECRET:kee,AWS_BUCKET:Vee,AWS_FILE_KEY:$ee,REGION:Yee}=Qf.S3_BUCKET_AUTH_KEYS,Kee={s3:{presence:!0},[`s3.${qee}`]:{presence:!0,type:"String"},[`s3.${kee}`]:{presence:!0,type:"String"},[`s3.${Vee}`]:{presence:!0,type:"String"},[`s3.${$ee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Yee}`]:{presence:!0,type:"String"}},R0=Jf(tR);R0.data.presence={message:g0};var A0=Jf(tR);A0.file_path.presence={message:g0};var Wee=Object.assign(Jf(tR),Kee),rR=Jf(Fee);rR.csv_url=zf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();rR.passthrough_headers=eR.object();function Qee(e){let t=jf.validateObject(e,R0);return Xf(e,t)}a(Qee,"dataObject");function zee(e){let t=jf.validateBySchema(e,eR.object(rR));return Xf(e,t)}a(zee,"urlObject");function Jee(e){let t=jf.validateObject(e,A0);return Xf(e,t)}a(Jee,"fileObject");function jee(e){let t=jf.validateObject(e,Wee);return Xf(e,t)}a(jee,"s3FileObject");function Xf(e,t){if(!t){let r=Hee.checkGlobalSchemaTable(e.schema,e.table);if(r)return Wf(new Error,r,Zg.BAD_REQUEST);if(e.operation===Qf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Xg.accessSync(e.file_path,Xg.constants.R_OK|Xg.constants.F_OK)}catch(n){return n.code===Qf.NODE_ERROR_CODES.ENOENT?Wf(n,`No such file or directory ${n.path}`,Zg.BAD_REQUEST):n.code===Qf.NODE_ERROR_CODES.EACCES?Wf(n,`Permission denied ${n.path}`,Zg.BAD_REQUEST):Wf(n)}}return t}a(Xf,"postValidateChecks");O0.exports={dataObject:Qee,urlObject:zee,fileObject:Jee,s3FileObject:jee}});var sR=R((Rhe,b0)=>{"use strict";var El=Y(),Zf=U();async function Xee(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===Zf.OPERATIONS_ENUM.INSERT||t.operation===Zf.OPERATIONS_ENUM.UPDATE||t.operation===Zf.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===Zf.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(El.info(i.message),i):i.http_resp_msg?(El.error(`Error calling operation: ${e.name}`),El.error(i.http_resp_msg),i):(El.error(`Error calling operation: ${e.name}`),El.error(i),i)}}a(Xee,"callOperationFunctionAsAwait");b0.exports={callOperationFunctionAsAwait:Xee}});var N0=R((Ohe,y0)=>{"use strict";var iR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},oR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};y0.exports={BulkLoadFileObject:iR,BulkLoadDataObject:oR}});var w0=R((yhe,I0)=>{"use strict";var aR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};I0.exports=aR});var fR=R((Lhe,Y0)=>{"use strict";var eE=an(),rE=nR(),Zee=require("needle"),xn=U(),Ihe=st(),Ha=Q(),{handleHDBError:it,hdb_errors:H0}=ne(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:bo}=H0,xa=Y(),cR=require("papaparse");Ha.promisifyPapaParse();var Gn=require("fs-extra"),ete=require("path"),{chain:C0}=require("stream-chain"),D0=require("stream-json/streamers/StreamArray"),L0=require("stream-json/utils/Batch"),M0=require("stream-chain/utils/comp"),{finished:U0}=require("stream"),tte=re(),x0=sR(),rte=Dg(),{BulkLoadFileObject:lR,BulkLoadDataObject:nte}=N0(),_R=gg(),{verifyBulkLoadAttributePerms:G0}=Uf(),whe=w0(),Che=St(),Dhe=Rs(),{databases:ste}=(Re(),ie(qe)),{coerceType:ite}=(nE(),ie(ER)),P0="No records parsed from csv file.",Oo=`${tte.get("HDB_ROOT")}/tmp`,{schema_regex:ote}=zn(),v0=1024*1024*2,B0=5e3,ate={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};Y0.exports={csvDataLoad:cte,csvURLLoad:ute,csvFileLoad:lte,importFromS3:_te};async function cte(e,t){let r=rE.dataObject(e);if(r)throw it(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=k0(e.schema,e.table),i=cR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:uR.bind(null,s),dynamicTyping:!1}),o=new _R;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&G0(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,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new nte(e.action,e.schema,e.table,i.data);return n=await x0.callOperationFunctionAsAwait(V0,u,null),n.message===P0?P0:$0(n.records,n.number_written)}catch(s){throw yo(s)}}a(cte,"csvDataLoad");async function ute(e){let t=rE.urlObject(e);if(t)throw it(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Oo}/${r}`;try{await dte(e,r)}catch(s){throw xa.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+s),it(s,bo(wt.DOWNLOAD_FILE_ERR(r)))}try{let s=new lR(this.job_operation_function.name,e.action,e.schema,e.table,n,xn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await dR(s);return await tE(n),i}catch(s){throw await tE(n),yo(s)}}a(ute,"csvURLLoad");async function lte(e){let t=rE.fileObject(e);if(t)throw it(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new lR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,xn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await dR(r)}catch(n){throw yo(n)}}a(lte,"csvFileLoad");async function _te(e){let t=rE.s3FileObject(e);if(t)throw it(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=ete.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Oo}/${s}`;let i=new lR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await fte(s,e);let o=await dR(i);return await tE(r),o}catch(n){throw await tE(r),yo(n)}}a(_te,"importFromS3");async function dte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Zee("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw it(n,s,n.statusCode,xn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}hte(r,e.csv_url),await Ete(t,r.raw)}a(dte,"downloadCSVFile");async function fte(e,t){try{let r=`${Oo}/${e}`;await Gn.mkdirp(Oo),await Gn.writeFile(`${Oo}/${e}`,"",{flag:"a+"});let n=await Gn.createWriteStream(r),s=await rte.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){xa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw xa.error(wt.S3_DOWNLOAD_ERR+" - "+r),it(r,bo(wt.S3_DOWNLOAD_ERR))}}a(fte,"downloadFileFromS3");async function Ete(e,t){try{await Gn.mkdirp(Oo),await Gn.writeFile(`${Oo}/${e}`,t)}catch(r){throw xa.error(wt.WRITE_TEMP_FILE_ERR),it(r,bo(wt.DEFAULT_BULK_LOAD_ERR))}}a(Ete,"writeFileToTempFolder");async function tE(e){if(e)try{await Gn.access(e),await Gn.unlink(e)}catch{xa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(tE,"deleteTempFile");function hte(e,t){if(e.statusCode!==H0.HTTP_STATUS_CODES.OK)throw it(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!ate[e.headers["content-type"]])throw it(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw it(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a(hte,"validateURLResponse");async function dR(e){try{let t;switch(e.file_type){case xn.VALID_S3_FILE_TYPES.CSV:t=await mte(e);break;case xn.VALID_S3_FILE_TYPES.JSON:t=await pte(e);break;default:throw it(new Error,wt.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,xn.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return $0(t.records,t.number_written)}catch(t){throw yo(t)}}a(dR,"fileLoad");async function F0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await eE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&G0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=it(c);r(u)}}a(F0,"validateChunk");async function q0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Ha.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Ha.isEmpty(c)&&!Ha.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 x0.callOperationFunctionAsAwait(V0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=it(c,bo(wt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(q0,"insertChunk");async function mte(e){let t={records:0,number_written:0},r=k0(e.schema,e.table);try{let n=new _R,s=Gn.createReadStream(e.file_path,{highWaterMark:v0});s.setEncoding("utf8"),await cR.parsePromise(s,F0.bind(null,e,n),uR.bind(null,r));let i=n.getPermsResponse();if(i)throw it(new Error,i,Kt.BAD_REQUEST);return s=Gn.createReadStream(e.file_path,{highWaterMark:v0}),s.setEncoding("utf8"),await cR.parsePromise(s,q0.bind(null,e,t),uR.bind(null,r)),s.destroy(),t}catch(n){throw it(n,bo(wt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+n)}}a(mte,"callPapaParse");function k0(e,t){let r=ste[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>ite(i,s));return n}a(k0,"createTransformMap");function uR(e,t,r){let n=e.get(r);return n?n(t):Ha.autoCast(t)}a(uR,"typeFunction");async function pte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new _R,s=C0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),D0.withParser(),c=>c.value,new L0({batchSize:B0}),M0(async c=>{await F0(e,n,r,c)})]);await new Promise((c,u)=>{U0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw it(new Error,i,Kt.BAD_REQUEST);let o=C0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),D0.withParser(),c=>c.value,new L0({batchSize:B0}),M0(async c=>{await q0(e,t,r,c)})]);return await new Promise((c,u)=>{U0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw it(n,bo(wt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+n)}}a(pte,"insertJson");async function V0(e){let t={};try{e.data&&e.data.length>0&&Ste(e.data[0])?t=await Tte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",xa.info(t.message))}catch(r){throw yo(r)}return t}a(V0,"callBulkFileLoad");function Ste(e){let t=Object.keys(e);for(let r of t)if(!ote.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Ste,"validateColumnNames");async function Tte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=eE.insert;break;case"update":i=eE.update;break;case"upsert":i=eE.upsert;break;default:throw it(new Error,wt.INVALID_ACTION_PARAM_ERR(n),Kt.BAD_REQUEST,xn.LOG_LEVELS.ERROR,wt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Ha.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw yo(o)}}a(Tte,"bulkFileLoad");function $0(e,t){return`successfully loaded ${t} of ${e} records`}a($0,"buildResponseMsg");function yo(e){return it(e,bo(wt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(yo,"buildTopLevelErrMsg")});var W0=R((Uhe,K0)=>{"use strict";var hR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};K0.exports=hR});var J0=R((vhe,z0)=>{"use strict";var gte=U(),Q0=require("moment"),Rte=require("uuid").v4,mR=class{static{a(this,"JobObject")}constructor(){this.id=Rte(),this.type=void 0,this.start_datetime=Q0().valueOf(),this.created_datetime=Q0().valueOf(),this.end_datetime=void 0,this.status=gte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};z0.exports=mR});var iE=R((Hhe,rB)=>{"use strict";var Ate=require("uuid").v4,Z0=an(),eB=xr(),Ote=Zn(),bte=ra(),yte=W0(),ot=U(),Nte=J0(),Ite=zS(),hn=Y(),wte=Gc(),Ga=Q(),{promisify:Cte}=require("util"),No=require("moment"),Dte=vf(),sE=nR(),j0=$m(),{deleteTransactionLogsBeforeValidator:Lte}=hg(),{handleHDBError:Mte,hdb_errors:Ute}=ne(),{HTTP_STATUS_CODES:Pte}=Ute,X0=eB.searchByValue,vte=eB.searchByHash,Bte=Z0.insert,Hte=Cte(Dte.evaluateSQL),xte=Z0.update;rB.exports={addJob:qte,updateJob:Vte,handleGetJob:Gte,handleGetJobsByStartDate:Fte,getJobById:tB};async function Gte(e){try{let t=await tB(e.id);return Ga.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 hn.error("There was an error getting job",t),new Error(r)}}a(Gte,"handleGetJob");async function Fte(e){try{let t=await kte(e);if(hn.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=No(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=No(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 hn.error(r),new Error(r)}}a(Fte,"handleGetJobsByStartDate");async function qte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ga.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return hn.info(l),t.error=l,t}if(!ot.JOB_TYPE_ENUM[e.operation])return hn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case ot.OPERATIONS_ENUM.CSV_FILE_LOAD:n=sE.fileObject(e);break;case ot.OPERATIONS_ENUM.CSV_URL_LOAD:n=sE.urlObject(e);break;case ot.OPERATIONS_ENUM.CSV_DATA_LOAD:n=sE.dataObject(e);break;case ot.OPERATIONS_ENUM.IMPORT_FROM_S3:n=sE.s3FileObject(e);break;case ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=j0(e,"date");break;case ot.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=j0(e,"timestamp");break;case ot.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Lte(e);break;default:break}if(n)throw Mte(n,n.message,Pte.BAD_REQUEST,void 0,void 0,!0);let s=new Nte;s.type=e.operation===ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Ote(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await X0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return hn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Ate();try{o=await X0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return hn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return hn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new wte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await Bte(u)}catch(l){return hn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,hn.trace(l)}return t}a(qte,"addJob");async function kte(e){let t=No(e.from_date,No.ISO_8601),r=No(e.to_date,No.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new yte(n,e.hdb_user);try{return await Hte(s)}catch(i){throw hn.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(kte,"getJobsInDateRange");async function tB(e){if(Ga.isEmptyOrZeroLength(e))return Ga.errorizeMessage("Invalid job ID specified.");let t=new bte(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await vte(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return hn.error(n),Ga.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(tB,"getJobById");async function Vte(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ga.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=No().valueOf());let t=new Ite(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await xte(t),r}a(Vte,"updateJob")});var cB=R((Ghe,aB)=>{"use strict";var nB=Q(),wr=U(),$te=require("moment"),oE=fR(),aE=Y(),sB=iE(),iB=Bf(),oB=Qi(),Yte=rt(),Kte=Cf(),pR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Wte(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(nB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(nB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case wr.JOB_TYPE_ENUM.csv_file_load:await Fs(e,oE.csvFileLoad);break;case wr.JOB_TYPE_ENUM.csv_url_load:await Fs(e,oE.csvURLLoad);break;case wr.JOB_TYPE_ENUM.csv_data_load:await Fs(e,oE.csvDataLoad);break;case wr.JOB_TYPE_ENUM.import_from_s3:await Fs(e,oE.importFromS3);break;case wr.JOB_TYPE_ENUM.empty_trash:break;case wr.JOB_TYPE_ENUM.export_local:await Fs(e,iB.export_local);break;case wr.JOB_TYPE_ENUM.export_to_s3:await Fs(e,iB.export_to_s3);break;case wr.JOB_TYPE_ENUM.delete_files_before:case wr.JOB_TYPE_ENUM.delete_records_before:await Fs(e,oB.deleteFilesBefore);break;case wr.JOB_TYPE_ENUM.delete_audit_logs_before:await Fs(e,oB.deleteAuditLogsBefore);break;case wr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Fs(e,Kte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Wte,"parseMessage");async function Fs(e,t){try{e.job.status=wr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=$te().valueOf(),await sB.updateJob(e.job),await Qte(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):aE.error(`There was an error running ${t.name} job with id ${e.job.id}`),aE.error(n),e.job.message=n,e.job.status=wr.JOB_STATUS_ENUM.ERROR;try{await sB.updateJob(e.job)}catch(s){throw aE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Fs,"runJob");async function Qte(e){aE.trace("launching job thread:",e),Yte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[wr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Qte,"launchJobThread");aB.exports={parseMessage:Wte,RunnerMessage:pR}});var lB=R((qhe,uB)=>{"use strict";var SR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};uB.exports=SR});var yR=R((Vhe,bR)=>{"use strict";var dE=xr(),RR=vf(),cE=fR(),qs=Id(),uE=ri(),ml=Qi(),zte=PS(),hl=Fr(),lE=VS(),Wt=Eg(),_E=Y(),Jte=KS(),jte=Yd(),_B=yT(),Xte=Wd(),Zte=IT(),ere=wT(),tre=LT(),rre=UT(),TR=BT(),dB=Bf(),nre=Uf(),AR=iE(),F=U(),{hdb_errors:Sl,handleHDBError:pl}=ne(),{HTTP_STATUS_CODES:fB}=Sl,gR=qT(),EB=hf(),OB=require("util"),Fa=an(),sre=As(),ire=ma(),hB=cB(),mB=yu(),pB=(Tf(),ie(zu)),SB=lr(),TB=Cf(),gB=bf(),{setServerUtilities:ore}=(nE(),ie(ER)),{CONTEXT:are}=(In(),ie(Mp)),{_assignPackageExport:cre}=require("../../index"),{transformReq:ure}=Q(),{server:lre}=(cr(),ie(Bi)),rr=_E.loggerWithTag("operation"),_re=sR(),RB=dE.searchByHash,dre=dE.searchByValue,fre=OB.promisify(dE.search),Ere=OB.promisify(RR.evaluateSQL),hre={[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},$=lB();async function bB(e,t){try{if(e.body.operation!=="read_log"&&(_E.log_level===F.LOG_LEVELS.INFO||_E.log_level===F.LOG_LEVELS.DEBUG||_E.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;rr.info(o)}}catch(n){rr.error(n)}let r=await _re.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return hre[e.body.operation]&&sre.setSchemaDataToGlobal(n=>{n&&rr.error(n)}),r}a(bB,"processLocalTransaction");var AB=pre();bR.exports={chooseOperation:yB,getOperationFunction:NB,operation:OR,processLocalTransaction:bB};ore(bR.exports);lre.operation=OR;function yB(e){let t;try{t=NB(e)}catch(s){throw rr.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=RR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=RR.checkASTPermissions(e,i);if(o)throw rr.error(`${fB.FORBIDDEN} from operation ${e.operation}`),rr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),pl(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 s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=nre.verifyPerms(i,s);if(o)throw rr.error(`${fB.FORBIDDEN} from operation ${e.operation}`),rr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw pl(s,"There was an error when trying to choose an operation path")}return r}a(yB,"chooseOperation");function NB(e){if(rr.trace(`getOperationFunction with operation: ${e.operation}`),AB.has(e.operation))return AB.get(e.operation);throw pl(new Error,Sl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Sl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(NB,"getOperationFunction");cre("operation",OR);function OR(e,t){e.hdb_user=this[are]?.user,e.bypass_auth=!t;let r=yB(e);return bB({body:e},r)}a(OR,"operation");async function mre(e){rr.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await Fa.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await Fa.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await Fa.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await ml.deleteRecord(i);break;default:rr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){rr.info("Invalid operation in transaction"),rr.error(o)}}a(mre,"catchup");async function ls(e){ure(e);let t,r;try{r=await AR.addJob(e),t=r.createdJob,rr.info("addJob result",r);let n=new hB.RunnerMessage(t,e);return await hB.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw rr.error(s),pl(n,s)}}a(ls,"executeJob");function pre(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new $(Fa.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new $(Fa.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new $(Fa.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new $(dE.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new $(RB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new $(RB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(dre)),e.set(F.OPERATIONS_ENUM.SEARCH,new $(fre)),e.set(F.OPERATIONS_ENUM.SQL,new $(Ere)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new $(ls,cE.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new $(ls,cE.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new $(ls,cE.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new $(ls,cE.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new $(qs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new $(qs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new $(qs.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new $(qs.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new $(qs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new $(qs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new $(qs.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new $(qs.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new $(uE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new $(uE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new $(uE.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new $(uE.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new $(ml.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new $(hl.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new $(hl.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new $(hl.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new $(hl.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new $(lE.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new $(lE.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new $(lE.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new $(lE.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new $(hl.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new $(Jte)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new $(jte)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new $(_B)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(_B)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new $(Xte)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(Zte)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new $(ere)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new $(SB.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new $(tre.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new $(rre)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(TR.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(TR.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(TR.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new $(ls,dB.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new $(ls,ml.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new $(ls,ml.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new $(ls,dB.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(AR.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new $(AR.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new $(gR.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new $(gR.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new $(gR.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new $(EB.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new $(EB.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new $(mre)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $(ire.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(ls,ml.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(zte)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(mB.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(mB.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new $(pB.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new $(pB.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new $(SB.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $(Wt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $(Wt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $(Wt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new $(Wt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $(Wt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new $(Wt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $(Wt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $(Wt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $(Wt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $(Wt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new $(Wt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $(Wt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $(Wt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $(Wt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $(Wt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $(Wt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(TB.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(ls,TB.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $(gB.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $(gB.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new $(qs.getBackup)),e}a(pre,"initializeOperationFunctionMap")});var EE=R((Yhe,CB)=>{"use strict";var NR=U(),Sre=Q(),Tl=Y(),{handleHDBError:IR,hdb_errors:fE}=ne(),{isMainThread:Tre}=require("worker_threads"),{Readable:gre}=require("stream"),IB=require("os"),Rre=require("util"),Are=nT(),Ore=Rre.promisify(Are.authorize),wB=yR(),{createGzip:bre,constants:yre}=require("zlib");function Nre(e){let t=`Found an uncaught exception with message: ${e.message}. ${IB.EOL}Stack: ${e.stack} ${IB.EOL}Terminating ${Tre?"HDB":"thread"}.`;console.error(t),Tl.fatal(t),process.exit(1)}a(Nre,"handleServerUncaughtException");function Ire(e,t,r){if(Tl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:fE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(Ire,"serverErrorHandler");function wre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=IR(new Error,"Invalid JSON.",fE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Sre.isEmpty(e.body.operation)){let n=IR(new Error,"Request body must include an 'operation' property.",fE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(wre,"reqBodyValidationHandler");function Cre(e,t,r){let n;e.body.operation!==NR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==NR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==NR.OPERATIONS_ENUM.LOGOUT?Ore(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Tl.warn(s),Tl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(IR(s,i,fE.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(Cre,"authHandler");async function Dre(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=wB.chooseOperation(e.body);let s=await wB.processLocalTransaction(e,n);if(s instanceof gre&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(bre({level:yre.Z_BEST_SPEED})))}return s}catch(s){throw Tl.error(s),s}}a(Dre,"handlePostRequest");CB.exports={authHandler:Cre,handlePostRequest:Dre,handleServerUncaughtException:Nre,serverErrorHandler:Ire,reqBodyValidationHandler:wre}});var UB=R((Whe,MB)=>{"use strict";var Lre=require("fastify-plugin"),{handlePostRequest:DB,authHandler:Mre,reqBodyValidationHandler:Ure}=EE();async function Pre(e){e.decorate("hdbCore",{preValidation:[Ure,Mre],request:t=>LB(DB(t,response)),requestWithoutAuthentication:(t,r)=>LB(DB(t,r,!0))})}a(Pre,"hdbCore");async function LB(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(LB,"convertAsyncIterators");MB.exports=Lre(Pre)});var BB=R((Jhe,vB)=>{"use strict";var zhe=require("fs"),wR=re();wR.initSync();var{CONFIG_PARAMS:PB}=U(),vre=1024*1024*1024;function Bre(e){let t=wR.get(PB.HTTP_TIMEOUT),r=wR.get(PB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:vre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Bre,"getServerOptions");vB.exports=Bre});var GB=R((Xhe,xB)=>{"use strict";var CR=re();CR.initSync();var{CONFIG_PARAMS:HB}=U();function Hre(){let e=CR.get(HB.HTTP_CORSACCESSLIST),t=CR.get(HB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(Hre,"getCORSOptions");xB.exports=Hre});var kB=R((eme,qB)=>{"use strict";var FB=re();FB.initSync();var xre=U();function Gre(){return FB.get(xre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Gre,"getHeaderTimeoutConfig");qB.exports=Gre});var LR={};Fe(LR,{customFunctionsServer:()=>kre,ready:()=>nH,start:()=>qre});function qre(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=rH(t),tt.http((await ks).server));let o=await ks,c=(0,DR.dirname)(s),u=(0,DR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!VB.has(c)){VB.add(c);try{o.register($re(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:nH}}async function kre(){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 Vre();let e=zB.get(JB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await rH(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 Vre(){try{Ve.info("Custom Functions starting configuration."),await jB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function $re(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,$B.existsSync)(e)&&r.register(QB.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ve.error(s.message):s&&Ve.error(s),o()})}catch(n){Ve.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function rH(e){Ve.info("Custom Functions starting buildServer.");let t=(0,XB.default)(e),r=(0,YB.default)(t);r.server.headersTimeout=(0,eH.default)(),r.setErrorHandler(tH.serverErrorHandler);let n=(0,ZB.default)();return n&&r.register(KB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(WB.default),await r.register(Fre),await r.after(),xg(r),Ve.info("Custom Functions completed buildServer."),r}function nH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var DR,$B,YB,KB,WB,QB,zB,JB,Ve,Fre,jB,XB,ZB,eH,tH,ks,VB,sH=ge(()=>{DR=require("path"),$B=require("fs"),YB=B(require("fastify")),KB=B(require("@fastify/cors")),WB=B(jg()),QB=B(require("@fastify/autoload")),zB=B(re()),JB=B(U()),Ve=B(Y()),Fre=B(UB()),jB=B(Fr()),XB=B(BB()),ZB=B(GB()),eH=B(kB()),tH=B(EE());ya();cr();VB=new Set;a(qre,"start");a(kre,"customFunctionsServer");a(Vre,"setUp");a($re,"buildRouteFolder");a(rH,"buildServer");a(nH,"ready")});var MR={};Fe(MR,{start:()=>Yre});function Yre(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,uH.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){oH||(oH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=iH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,aH.default)(s,(0,cH.realpathSync)(o))}}return i(s)},{runFirst:!0})),iH.set(r,n)}}}var aH,cH,uH,iH,oH,lH=ge(()=>{aH=B(require("send")),cH=require("fs"),uH=B(require("serve-static")),iH=new Map;a(Yre,"start")});function Qre(e,t=1,r){if(UR++,(0,Io.startWorker)("server/threads/threadServer.js",{name:pE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===pE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Wre.push(s),await s,qa.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=mE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=qa.indexOf(n);o>-1&&qa.splice(o,1)}if(a(i,"removeWorker"),ka){let o=ka;ka=[];for(let c of o)EH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{PR?PR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Io.shutdownWorkers)(),UR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function hH(e=0,t){if(typeof e=="string")try{(0,SE.existsSync)(e)&&(0,SE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=zre:r=Jre(t):r=BR;let n=(0,Va.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=EH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),PR=!0,r(o,(c,u)=>{if(!c){if(_H){let l=o._socket||new Va.Socket({handle:o,writable:!0,readable:!0});_H.deliverSocket(l,e,u),l.resume()}else UR>0?(ka.length===0&&setTimeout(()=>{ka.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,ka.push(o)):(console.log("start up a dynamic thread to handle request"),Qre(0));$r(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Va.Socket({handle:o,writable:!0,readable:!0});ene(l,c,e)}$r(!0,"socket-routed")})};let s=au();vR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function BR(e,t){let r,n=0;for(let s of qa){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=hE)return hE=i,t(r);n=i}hE=0,t(r)}function zre(e,t){let r={};e.getpeername(r);let n=r.address,s=$a.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);BR(e,o=>{$a.set(n,{worker:o,lastUsed:i}),t(o)})}function Jre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Va.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=$a.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);BR(n,d=>{$a.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Xre(){hE=0;for(let e of qa)e.expectedIdle=e.recentELU.idle+jre,e.requests=1;qa.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function ene(e,t,r){let n=Zre++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),mE.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),mE.delete(n)),s.event=="destroy"&&(e.destroy(),mE.delete(n))})}var Io,Va,pE,vR,SE,fH,Kre,qa,ka,EH,_H,UR,Wre,PR,hE,dH,$a,jre,mE,Zre,mH=ge(()=>{Io=B(rt()),Va=require("net"),pE=B(U()),vR=B(Y()),SE=require("fs");Is();fH=require("worker_threads"),Kre=B(zi()),qa=[],ka=[],EH=[],UR=0,Wre=[];fH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Qre,"startHTTPWorker");a(hH,"startSocketServer");hE=0;a(BR,"findMostIdleWorker");dH=36e5,$a=new Map;a(zre,"findByRemoteAddressAffinity");a(Jre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of $a)r.lastUsed+dH<e&&$a.delete(t)},dH).unref();jre=1e3;a(Xre,"updateWorkerIdleness");(0,Io.setMonitorListener)(Xre);mE=new Map,Zre=1;a(ene,"proxySocket")});var FR={};Fe(FR,{Request:()=>HR,createReuseportFd:()=>TE});var pH,HR,xR,GR,TE,gE=ge(()=>{pH=require("os"),HR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new GR(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 xR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},xR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},GR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,pH.platform)()!="win32"&&(TE=require("node-unix-socket").createReuseportFd)});var RH=R((hme,gH)=>{"use strict";var tne=require("cluster"),wo=re();wo.initSync();var TH=U(),lme=require("util"),Vs=Y(),_me=require("fs"),rne=require("fastify"),dme=au(),nne=require("@fastify/cors"),sne=require("@fastify/compress"),ine=require("@fastify/static"),one=jg(),ane=require("path"),{PACKAGE_ROOT:cne}=U(),une=As(),lne=Q(),_ne=Fr(),dne=zi(),{server:fne}=(cr(),ie(Bi)),{node_request_key:fme}=(gE(),ie(FR)),{authHandler:Ene,handlePostRequest:hne,serverErrorHandler:mne,reqBodyValidationHandler:pne}=EE(),Eme=require("net"),{registerContentHandlers:Sne}=(ya(),ie(s0)),Tne=6e4,gne=1024*1024*1024,Rne="TRUE",{CONFIG_PARAMS:gl}=TH,Ya;gH.exports={hdbServer:SH,start:SH};async function SH(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=tne.isMaster,await Ane();let t=e.securePort>0;Ya=One(t),await Ya.ready(),e||(e={}),e.isOperationsServer=!0;try{fne.http(Ya.server,e),Ya.server.closeIdleConnections||await Ya.listen({port:0,host:"::"})}catch(r){throw Ya.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(SH,"operationsServer");async function Ane(){Vs.trace("Configuring HarperDB process."),une.setSchemaDataToGlobal(),await _ne.setUsersToGlobal(),await dne.getLicense()}a(Ane,"setUp");function One(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=bne(e),r=rne(t);r.server.headersTimeout=Nne(),r.setErrorHandler(mne);let n=yne();n&&r.register(nne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(one),r.register(sne),r.register(ine,{root:ane.join(cne,"studio/build-local")}),Sne(r);let s=wo.get(TH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!lne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[pne,Ene],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),hne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(One,"buildServer");function bne(e){let t=wo.get(gl.OPERATIONSAPI_NETWORK_TIMEOUT),r=wo.get(gl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:gne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(bne,"getServerOptions");function yne(){let e=wo.get(gl.OPERATIONSAPI_NETWORK_CORS),t=wo.get(gl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Rne)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(yne,"getCORSOpts");function Nne(){return wo.get(gl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Tne}a(Nne,"getHeaderTimeoutConfig")});var bE={};Fe(bE,{disableNATS:()=>wne,publishToStream:()=>OE,setNATSReplicator:()=>qR,setPublishToStream:()=>Cne,setSubscription:()=>YR,start:()=>Ine});function Ine(){Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Lne()}function wne(e=!0){NH=e}function Cne(e,t){OE=e,YR=t}function Lne(){if(NH||process.env._DISABLE_NATS)return;let e=Er(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];qR(s,r,i)}}WR((r,n)=>{qR(r.tableName,r.databaseName,r),n&&wH(r)}),!AH&&(AH=!0)}function qR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends qt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ue],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ue]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ue],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ue],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ue]})}static defineSchema(i){wH(i)}static subscribe(){let i=new Nn;return YR(t,e,i),i}static subscribeOnThisThread(i){return i<(Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Dne)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new RE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=IH;return i}a(n,"getNATSTransaction")}function wH(e){let t=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME);OE(`${VR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,$R.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var OH,VR,$R,bH,yH,Rl,Al,AE,NH,OE,YR,Dne,IH,AH,RE,kR,KR=ge(()=>{Re();In();OH=B(St()),VR=B(st()),$R=B(Rs());Oc();bH=B(AS()),yH=B(Pr()),Rl=B(re()),Al=B(U()),AE=B(Y());a(Ine,"start");a(wne,"disableNATS");OE=OH.publishToStream,YR=bH.setSubscription;a(Cne,"setPublishToStream");Dne=2;a(Lne,"assignReplicationSource");a(qR,"setNATSReplicator");a(wH,"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 n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(AE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(OE(`${VR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,$R.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw AE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},kR=class extends RE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,yH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};IH=new kR});var VH=R(Co=>{"use strict";var{isMainThread:PH,parentPort:bl,threadId:yE}=require("worker_threads"),{Socket:Mne,createServer:Une}=require("net"),{createServer:Pne,IncomingMessage:vne}=require("http"),{createServer:Bne}=require("https"),{readFileSync:Ka,unlinkSync:CH,existsSync:Hne}=require("fs"),nr=Y(),Ce=re(),ft=U(),{server:CE}=(cr(),ie(Bi)),{WebSocketServer:xne}=require("ws"),{createServer:Gne}=require("tls"),{getTicketKeys:Fne,restartNumber:qne,getWorkerIndex:IE}=rt(),{Headers:vH,appendHeader:kne}=(Qu(),ie(wP)),{recordAction:Ol,recordActionBinary:Vne}=(Is(),ie(du)),{Request:BH,createReuseportFd:DH}=(gE(),ie(FR)),{checkMemoryLimit:$ne}=zi(),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};var xH=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG);if(xH){let e;if(PH)e=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){nr.info("Could not close debugger",t)}});else{let t=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&IE()>=0&&(e=t+IE())}if(e){let t=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=Ce.get(ft.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){nr.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){qne<=1&&nr.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:Ame,CONFIG_PARAMS:Yne}=ft;Ce.initSync();var Kne=Ce.get(Yne.HTTP_SESSIONAFFINITY),_s={};Co.registerServer=XR;Co.httpServer=ZR;Co.deliverSocket=jR;Co.startServers=GH;Co.when_components_loaded=null;CE.http=ZR;CE.request=Jne;CE.socket=jne;CE.ws=Xne;var QR={},NE={},Wne,Ii={},wE={},Qne=[],zR=[];function GH(){return Co.when_components_loaded=eA().loadRootComponents(!0).then(()=>{bl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)jR(n,r,s);else if(t.requestId)zne(t);else if(t.type===ft.ITC_EVENT_TYPES.SHUTDOWN){nr.trace("received shutdown request",yE);for(let i in _s){let o=_s[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?nr.info(`Closing ${E.length} idle connections`):f&&nr.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,S=E.length;h<S;h++){let p=E[h].socket;p._httpMessage&&!p._httpMessage.finished&&!f||(f?p.destroySoon():p.end(`HTTP/1.1 408 Request Timeout\r
|
|
29
29
|
Connection: close\r
|
|
30
30
|
\r
|
|
31
|
-
`))}},25).unref()}o.close?.(()=>{if(Ce.get(ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&IE()==0)try{CH(Ce.get(ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,yE),o.cantCleanupProperly||
|
|
32
|
-
`)}a(UH,"defaultNotFound")});async function WH({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await eA.get(e,{returnNonexistent:!0});s=new nA(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await eA.get(e);i&&i.delete()}s=new LE(e,t)}return n&&(n.id=e,n.user={username:t?.username},bl.put(n)),s}function tA(){return DE++,DE>65500&&(DE=1),DE}function rA(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Ti.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var $H,wi,YH,KH,eA,bl,DE,LE,nA,QH=ge(()=>{Re();Ku();$H=B(Mr()),wi=B(Y());to();YH=B(rt()),KH=B(VH());or();eA=ut({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),bl=ut({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,YH.getWorkerIndex)()===0&&(async()=>{await KH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of bl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await tt.getUser(r.user.username)),ze(r,()=>{try{rA(r,t,r)}catch{(0,wi.warn)("Failed to publish will",t)}bl.delete(e.id,r)})}})();a(WH,"getSession");DE=1;a(tA,"getNextMessageId");LE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,wi.trace)("Resuming subscription from",s,"from",o);let E=Ti.getMatch(_);if(!E){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let T=f.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,T.indexOf("+")===T.length-1)f.onlyChildren=!0,f.url="/"+T.slice(0,T.length-1);else{let b=T.split("/"),g;for(let P=0;P<b.length;P++)if(b[P].indexOf("+")>-1)if(b[P]==="+")g=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&g)throw new Error("Filters can not be combined");let L=!0;b[b.length-1]==="#"&&(b.length--,L=!1),g&&(n=a(P=>{let k=P.id;if(!Array.isArray(k)||L&&k.length!==b.length)return!1;for(let H=0;H<b.length;H++)if(b[H]!=="+"&&b[H]!==k[H])return!1;return!0},"filter"));let v=b.indexOf("+");f.url="/"+(v>-1?b.slice(0,v):b).concat("").join("/")}}let h=E.path,S=E.Resource,p=await ze(f,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let b=await S.subscribe(f,T);if(!b)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!b[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let g of b)try{let L;if(g.type&&g.type!=="put"&&g.type!=="delete"&&g.type!=="message"&&g.type!=="patch"||n&&!n(g))continue;r?(g.topic=s,L=this.needsAcknowledge(g)):(g.acknowledge?.(),L=tA());let v=g.id;Array.isArray(v)&&(v=Oa(v)),v==null&&(v=""),this.listener(h+"/"+v,g.value,L,t)}catch(L){(0,wi.warn)(L)}})(),b});return p.topic=s,p.qos=t.qos,this.subscriptions.push(p),p}resume(){}needsAcknowledge(t){let r=tA();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return rA(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){let r=this.createContext();ze(r,async()=>{if(!t){let n=await bl.get(this.sessionId);n?.doesExist()&&await rA(n,n.data,r)}await bl.delete(this.sessionId)}).catch(n=>{(0,wi.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(rA,"publish");nA=class extends LE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=tA(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,wi.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,$H.getNextMonotonicTime)()),(0,wi.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),eA.put(this.sessionRecord)}}});var oA={};Fe(oA,{bypassAuth:()=>Zne,start:()=>ese});function Zne(){XH=!0}function ese({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){Qr.debug("Received WSS connection for MQTT from",_._socket.remoteAddress);let{onMessage:f,onClose:E}=JH(_,(h,S)=>{if(_.send(h),S&&_._socket.writableNeedDrain)return new Promise(p=>this._socket.once("drain",p))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{Qr.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(Qr.debug("Received connection for MQTT from",_.remoteAddress),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),(0,yl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&sA.notify({username:l.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})):Qr.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(E){Qr.error(E)}else if(u.required)return Qr.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&XH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,jH.getSuperUser)(),Qr.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:f}=JH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{Qr.info("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function JH(e,t,r,n,s){zH||(zH=!0,lu(d=>{ME>0&&d.push({metric:"mqtt-connections",connections:ME,byThread:!0})}));let i;ME++;let o,c={protocolVersion:4},u=(0,UE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){ME--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),cn(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await tt.getUser(d.username,d.password.toString(),r),(0,yl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&sA.notify({username:n.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,yl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&sA.error({username:n.username,status:zr.AUTH_AUDIT_STATUS.FAILURE,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return cn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let g=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?g(d.will.payload):void 0,delete d.will.payload}o=WH({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(g){return Qr.error(g),cn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:g.code||5,returnCode:g.code||128})}cn(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((g,L,v,P)=>{try{let k=g.indexOf("/",1),H=k>0?g.slice(0,k):g;f({cmd:"publish",topic:g,payload:E(L),messageId:v||Math.floor(Math.random()*1e8),qos:P.qos},H)}catch(k){Qr.error(k),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let g of d.subscriptions){let L;try{L=(await o.addSubscription(g,g.qos>=1)).qos||0}catch(v){Qr.error(v),L=c.protocolVersion<5?128:v.statusCode===403?135:v.statusCode===404?143:128}h.push(L)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let g=[];for(let L of d.unsubscriptions)g.push(o.removeSubscription(L)?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 S=d.qos===2?"pubrec":"puback",p=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type"))),T=d.payload?.length>0?p(d.payload):void 0,b;try{b=await o.publish(d,T)}catch(g){Qr.warn(g),d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:b===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),cn(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){Qr.error(h),f({cmd:"disconnect"})}function f(h,S){let p=(0,UE.generate)(h,c);t(p),kr(p.length,"bytes-sent",S,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ri(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var UE,jH,yl,zr,iA,sA,Qr,XH,zH,ME,ZH=ge(()=>{UE=require("mqtt-packet");QH();jH=B(xr());ya();Is();or();yl=B(re()),zr=B(U()),iA=B(Y()),sA=(0,iA.loggerWithTag)("auth-event"),Qr=(0,iA.loggerWithTag)("mqtt"),XH=(0,yl.get)(zr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Zne,"bypassAuth");a(ese,"start");ME=0;a(JH,"onSocket")});var If={};Fe(If,{component_errors:()=>Qa,loadComponent:()=>PE,loadComponentDirectories:()=>cx,setErrorReporter:()=>sse});function cx(e,t){t&&(cA=t),e&&(uA=e);let r=[];if((0,Fn.existsSync)(aA)){let s=(0,Fn.readdirSync)(aA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ot.join)(aA,o);r.push(PE(c,cA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(PE(n,cA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{ax=!0})}function sse(e){Il=e}async function PE(e,t,r,n,s,i){if(!tx.has(e)){tx.set(e,!0),s&&(uA=s);try{let o;n&&(Qa=new Map);let c=(0,Ot.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Fn.existsSync)(c)?o=n?(0,ox.getConfigObj)():(0,rx.parseDocument)((0,Fn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=lA;let u=[],_=n;for(let l in o){let d=o[l];if(Qa.set(n?l:(0,Ot.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let b=e,g;for(;!(0,Fn.existsSync)(g=(0,Ot.join)(b,"node_modules",l));)if(b=(0,Ot.dirname)(b),b.length<(0,ix.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=nse[l];if(!f)continue;u.push(f);let h=a(b=>(b.origin=r,ut(b)),"ensureTable"),S=d.network||(d.port||d.securePort)&&d,p=S?.securePort||S?.https&&S.port,T=!S?.https&&S?.port;if(Wa.isMainThread&&(f=await f.startOnMainThread?.({server:tt,ensureTable:h,port:T,securePort:p,resources:t,...d})||f,n&&S))for(let b of[T,p])try{if(+b&&!ex.includes(b)){let g=_A.get(dA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&Nl.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!TE)&&(ex.push(b),hH(b,g))}}catch(g){console.error("Error listening on socket",b,g,l)}if(t.isWorker&&(f=await f.start?.({server:tt,ensureTable:h,port:T,securePort:p,resources:t,...d})||f),uA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,sx.handleHDBError)("Can not reference parent directories");let b=(0,Ot.join)(e,d.files).replace(/\\/g,"/"),g=b.indexOf("/*");if(g>-1&&d.files!==lA[l]?.files&&!(0,Fn.existsSync)(b.slice(0,g)))throw new Error(`The path '${b.slice(0,g)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let L=(0,Ot.basename)(e),v=d.path||"/";v=v.startsWith("/")?v:v.startsWith("./")?"/"+L+v.slice(2):v==="."?"/"+L:"/"+L+"/"+v;let P,k,H;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",k=(0,Ot.join)(e,z)}else(H=b.indexOf("/*"))>-1&&(k=b.slice(0,H+1),P=(0,Ot.relative)(e,k));let j=!1;if(Wa.isMainThread&&f.setupDirectory&&(j=await f.setupDirectory?.(v,k,t)),t.isWorker&&f.handleDirectory&&(j=await f.handleDirectory?.(v,k,t)),j)continue;for(let z of await(0,nx.default)(b,{onlyFiles:!1,objectMode:!0})){let{path:J,dirent:me}=z;_=!0;let ce=(0,Ot.relative)(e,J).replace(/\\/g,"/");if(P)if(ce.startsWith(P))ce=ce.slice(P.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 de=v+(v.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let Le=await rse(J);Wa.isMainThread&&await f.setupFile?.(Le,de,J,t),t.isWorker&&await f.handleFile?.(Le,de,J,t)}else Wa.isMainThread&&await f.setupDirectory?.(de,J,t),t.isWorker&&await f.handleDirectory?.(de,J,t)}catch(Le){Le.message=`Could not load ${me.isFile()?"file":"directory"} '${J}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Le.message}`,Il?.(Le),((0,za.getWorkerIndex)()===0?console:Nl.default).error(Le),t.set(d.path||"/",new wl(Le)),Qa.set(n?l:(0,Ot.basename)(e),Le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Ot.basename)(e)}' due to: ${h.message}`,Il?.(h),((0,za.getWorkerIndex)()===0?console:Nl.default).error(h),t.set(d.path||"/",new wl(h),null,!0),Qa.set(n?l:(0,Ot.basename)(e),h.message)}}if(Wa.isMainThread&&!ax&&i&&(0,za.watchDir)(e,async()=>cx()),o.extensionModule)return await d_((0,Ot.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;Il?.(new Error(l)),((0,za.getWorkerIndex)()===0?console:Nl.default).error(l),Qa.set((0,Ot.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Il?.(o),t.set("",new wl(o))}}}var Fn,Ot,Wa,rx,_A,dA,nx,za,Nl,sx,ix,tse,ox,rse,aA,uA,ax,cA,Qa,nse,lA,ex,tx,Il,wl,wf=ge(()=>{Fn=require("fs"),Ot=require("path"),Wa=require("worker_threads"),rx=require("yaml"),_A=B(re()),dA=B(U());Nb();Db();Lb();S0();sH();lH();nx=B(require("fast-glob")),za=B(rt()),Nl=B(Y());Yh();or();sx=B(ne());In();Re();mH();ix=B(re()),tse=B(RH());Tf();YR();ZH();ox=B(cr());gE();({readFile:rse}=Fn.promises),aA=_A.get(dA.CONFIG_PARAMS.COMPONENTSROOT),uA=new Map,Qa=new Map;a(cx,"loadComponentDirectories");nse={REST:Yf,rest:Yf,graphqlSchema:$h,jsResource:Wh,fastifyRoutes:DR,login:zh,static:LR,operationsApi:tse,customFunctions:{},http:{},clustering:bE,authentication:Qu,mqtt:oA},lA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(lA,"static",{value:{files:"web/**"}});ex=[],tx=new Map;a(sse,"setErrorReporter");a(PE,"loadComponent");wl=class extends qt{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 ZR=R((Qme,lx)=>{var{isMainThread:ux}=require("worker_threads"),{getTables:ise}=(Re(),ie(qe)),{loadComponentDirectories:ose,loadComponent:ase}=(wf(),ie(If)),{resetResources:cse}=(Ku(),ie(IP)),use=lg(),lse=cr(),{dirname:_se}=require("path"),{getConnection:dse}=St(),fse=re(),Ese=U(),fA=new Map;async function hse(e=!1){!ux&&fse.get(Ese.CONFIG_PARAMS.CLUSTERING_ENABLED)&&dse();try{ux&&await use()}catch(n){console.error(n)}let t=cse();ise(),t.isWorker=e,await ase(_se(lse.getConfigFilePath()),t,"hdb",!0,fA),await ose(fA,t);let r=[];for(let[n]of fA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(hse,"loadRootComponents");lx.exports.loadRootComponents=hse});var rt=R((Jme,Di)=>{"use strict";var{Worker:mse,MessageChannel:pse,parentPort:ds,isMainThread:SA,threadId:Sse,workerData:$s}=require("worker_threads"),{PACKAGE_ROOT:Tse}=U(),{join:Ex,isAbsolute:gse,extname:Rse}=require("path"),{server:hx}=(or(),ie(Bi)),{watch:Ase,readdir:Ose}=require("fs/promises"),{totalmem:_x}=require("os"),Cl=U(),mx=re(),Ys=Y(),{randomBytes:bse}=require("crypto"),{_assignPackageExport:yse}=require("../../index"),Nse=U(),dx=1024*1024,Ci=[],mn=[],Ise=50,TA=1e4,wse="restart",px="request_thread_info",Sx="resource_report",Tx="thread_info",gx="added-port",Cse="ack",EA;yse("threads",mn);Di.exports={startWorker:hA,restartWorkers:RA,shutdownWorkers:Pse,workers:Ci,setMonitorListener:kse,onMessageFromWorkers:vse,onMessageByType:Ix,broadcast:Hse,broadcastWithAcknowledgement:Gse,setChildListenerByType:Use,getWorkerIndex:Rx,getWorkerCount:Ax,getTicketKeys:bx,setMainIsWorker:Lse,setTerminateTimeout:Dse,restartNumber:$s?.restartNumber||1};mn.onMessageByType=Ix;mn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=mn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var gA;function Dse(e){TA=e}a(Dse,"setTerminateTimeout");function Rx(){return $s?$s.workerIndex:gA?0:void 0}a(Rx,"getWorkerIndex");function Ax(){return $s?$s.workerCount:gA?1:void 0}a(Ax,"getWorkerCount");function Lse(e){gA=e}a(Lse,"setMainIsWorker");var Ox=1,vE;function bx(){return vE||(vE=SA?bse(48):$s.ticketKeys,vE)}a(bx,"getTicketKeys");Object.defineProperty(hx,"workerIndex",{get(){return Rx()}});Object.defineProperty(hx,"workerCount",{get(){return Ax()}});var yx={[px](e,t){Fse(t)},[Sx](e,t){qse(t,e)}};function hA(e,t={}){let r=process.constrainedMemory?.()||_x();r=Math.min(r,_x(),2e4*dx);let n=mx.get(Cl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/dx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of mn){let _=new pse;_.existingPort=u,i.push(_),o.push(_.port2)}Rse(e)||(e+=".js");let c=new mse(gse(e)?e:Ex(Tse,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Ox=t.threadCount,name:t.name,restartNumber:Di.exports.restartNumber,ticketKeys:bx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:gx,port:u,threadId:c.threadId},[u]);return HE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>hA(e,t),c.on("error",u=>{console.error("Worker error:",u),Ys.error("Worker error:",u)}),c.on("exit",u=>{Ci.splice(Ci.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Ise?(t.unexpectedRestarts=c.unexpectedRestarts+1,hA(e,t)):Ys.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{yx[u.type]?.(u,c)}),Ci.push(c),$se(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(hA,"startWorker");var Mse=[Cl.THREAD_TYPES.HTTP];async function RA(e=null,t=Math.max(Ox>3,1),r=!0){if(SA){if(r){let{loadRootComponents:o}=ZR();await o()}Di.exports.restartNumber++,t<1&&(t=t*Ci.length);let n=[],s=[];for(let o of Ci.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ys.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Di.exports.restartNumber,type:Cl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Mse.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),TA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===Nse.ITC_EVENT_TYPES.CHILD_STARTED&&(Ys.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");Ys.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=hf();r&&(e==="http"||!e)&&mx.get(Cl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ds.postMessage({type:wse,workerType:e})}a(RA,"restartWorkers");function Use(e,t){yx[e]=t}a(Use,"setChildListenerByType");function Pse(e){return RA(e,1/0,!1)}a(Pse,"shutdownWorkers");var Nx=[];function vse(e){Nx.push(e)}a(vse,"onMessageFromWorkers");var mA=new Map;function Ix(e,t){let r=mA.get(e);r||mA.set(e,r=[]),r.push(t)}a(Ix,"onMessageByType");var Bse=10;async function Hse(e){let t=0;for(let r of mn)try{r.postMessage(e),t++>Bse&&(t=0,await new Promise(setImmediate))}catch(n){Ys.error("Unable to send message to worker",n)}}a(Hse,"broadcast");var BE=new Map,xse=1;function Gse(e){return new Promise(t=>{let r=0;for(let n of mn)try{let s=xse++,i=a(()=>{BE.delete(s),--r===0&&t(),n!==ds&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,BE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of BE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ys.error("Unable to send message to worker",s)}r===0&&t()})}a(Gse,"broadcastWithAcknowledgement");function Fse(e){e.postMessage({type:Tx,workers:wx()})}a(Fse,"sendThreadInfo");function wx(){let e=Date.now();return Ci.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(wx,"getChildWorkerInfo");function qse(e,t){e.resources=t,e.resources.updated=Date.now()}a(qse,"recordResourceReport");var pA;function kse(e){pA=e}a(kse,"setMonitorListener");var Vse=1e3,fx=!1;function $se(){fx||(fx=!0,setInterval(()=>{for(let e of Ci){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}pA&&pA()},Vse).unref())}a($se,"startMonitoring");var Yse=1e3;if(ds){HE(ds);for(let e=0,t=$s.addPorts.length;e<t;e++){let r=$s.addPorts[e];r.threadId=$s.addThreadIds[e],HE(r)}setInterval(()=>{let e=process.memoryUsage();ds.postMessage({type:Sx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Yse).unref(),EA=a(()=>new Promise((e,t)=>{ds.on("message",r),ds.postMessage({type:px});function r(n){n.type===Tx&&(ds.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else EA=wx;Di.exports.getThreadInfo=EA;function HE(e,t){mn.push(e),e.on("message",r=>{if(r.type===gx)r.port.threadId=r.threadId,HE(r.port);else if(r.type===Cse){let n=BE.get(r.id);n&&n()}else{for(let s of Nx)s(r,e);let n=mA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ys.error(i)}}}).on("close",()=>{mn.splice(mn.indexOf(e),1)}).on("exit",()=>{mn.splice(mn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(HE,"addPort");if(SA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await Ose(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Ex(n,i.name));try{for await(let{filename:i}of Ase(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await RA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");Di.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else ds.on("message",async e=>{let{type:t}=e;t===Cl.ITC_EVENT_TYPES.SHUTDOWN&&(Di.exports.restartNumber=e.restartNumber,ds.unref(),setTimeout(()=>{Ys.warn("Thread did not voluntarily terminate",Sse),process.exit(0)},TA).unref())})});var gC={};Fe(gC,{AUDIT_STORE_OPTIONS:()=>lf,createAuditEntry:()=>p_,openAuditStore:()=>qE,readAuditEntry:()=>Ut,setAuditRetention:()=>Wse,transactionKeyEncoder:()=>Hx});function qE(e){let t=e.auditStore=e.openDB(Px.AUDIT_STORE_NAME,lf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=xE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-AA})){if((_[0]&15)===yA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Kse){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,AA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,FE.getWorkerIndex)()===(0,FE.getWorkerCount)()-1&&s(xE),t}function Wse(e,t=xE){AA=e,xE=t}function p_(e,t,r,n,s,i,o){let c=xx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Ja.setFloat64(0,n):pn.set(_m),u=9),f(0),f(t),d(r),Ja.setFloat64(u,e),u+=8,s?d(s):pn[u++]=0,pn[n?8:0]=c;let l=pn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,ja.writeKey)(E,pn,u);let S=u-h-1;S>127?S>16383?(IA.error("Key or username was too large for audit entry",E),u=h+1,pn[h]=0):(pn.copyWithin(h+2,h+1,u),Ja.setUint16(h,S|32768),u++):pn[h]=S}function f(E){E<128?pn[u++]=E:E<16384?(Ja.setUint16(u,E|32768),u+=2):E<1056964608?(Ja.setUint32(u,E|3221225472),u+=4):(pn[u]=255,Ja.setUint32(u+1,E),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new NA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:xx[n&7],tableId:i,get recordId(){return Ux(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Ux(e,l,d):void 0},getValue(f,E,h){if(n&OA||n&bA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&bA&&h)return wA(f.getEntry(this.recordId),h,f)}}}catch(t){return IA.error("Reading audit entry error",t,e),{}}}function Ux(e,t,r){let n=e.subarray(t,r);return(0,ja.readKey)(n,0,r-t)}var ja,GE,Px,vx,FE,Bx,IA,pn,Ja,Hx,lf,AA,Kse,xE,OA,bA,Cx,yA,Dx,Lx,Mx,xx,NA,Zs=ge(()=>{ja=require("ordered-binary"),GE=B(re()),Px=B(ct()),vx=B(U()),FE=B(rt()),Bx=B(Q());Cc();IA=B(Y());kE();(0,GE.initSync)();pn=Buffer.alloc(1024),Ja=new DataView(pn.buffer,pn.byteOffset,1024),Hx={writeKey(e,t,r){return e===wc?(t.set(wc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,ja.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,ja.readKey)(e,t,r)}},lf={encoding:"binary",keyEncoder:Hx},AA=(0,Bx.convertToMS)((0,GE.get)(vx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Kse=1e3,xE=1e4;a(qE,"openAuditStore");a(Wse,"setAuditRetention");OA=16,bA=32,Cx=1,yA=2,Dx=3,Lx=4,Mx=5,xx={put:Cx|OA,[Cx]:"put",delete:yA,[yA]:"delete",message:Dx|OA,[Dx]:"message",invalidate:Lx,[Lx]:"invalidate",patch:Mx|bA,[Mx]:"patch"};a(p_,"createAuditEntry");a(Ut,"readAuditEntry");NA=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(Ux,"readKeySafely")});var CA={};Fe(CA,{add:()=>VE,applyReverse:()=>Gx,getRecordAtTime:()=>wA,rebuildUpdateBefore:()=>$E});function VE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function $E(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,VE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function Gx(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Qse[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=Fx}}function wA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ut(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":Gx(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===Fx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ut(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var Qse,Fx,kE=ge(()=>{Zs();a(VE,"add");VE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Qse={add:VE};a($E,"rebuildUpdateBefore");a(Gx,"applyReverse");Fx={};a(wA,"getRecordAtTime")});function Jr(e){return e[Ct]||(e[Ct]=Object.create(null))}function zE(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[ye])},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 Sn.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Jr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be an object, attempt to assign ${l}`);Jr(this)[c]=l},"set")}_={get(){let l=this[Ct];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[_e]?.[c];return f.update(E)}return f}let d=this[_e]?.[c];if(d&&typeof d=="object"){let f=kx(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,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Ct];return u?.[o]!==void 0?u[o]:this[_e]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Sn.ClientError("Can not add a property to a sealed table schema");Jr(this)[o]=c}),i("deleteProperty",function(o){Jr(this)[o]=void 0}),i("toJSON",function(){let o=this[Ct],c;for(let _ in o){c||(c=Object.assign({},this[_e]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[_e])),Object.assign(c,this)),c||this[_e]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function kx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=s}},zE(r,t)),new r(e)):new YE(e);case Array:let n=new WE(e.length);n[_e]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=kx(o,t?.elements)),n[s]=o}return n;default:return e}}function ad(e){let t=e[Ct],r;for(let s in t){r||(r=Object.assign({},e[_e]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=ad(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[_e])),Object.assign(r,e)),r||e[_e]}function Lo(e,t=e[Ct]){let r;if(qx.call(e,_e)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Lo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[_e]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=CA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Lo(s);r[n]=s}return r?Object.freeze(r):qx.call(e,_e)?e[_e]:e}function KE(e){let t=e[_e];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Do]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[_e]===s){if(KE(i))return!0}else return!0}}else{let r=e[Ct];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[_e]===i){if(KE(s))return!0}else return!0}else return!0}}return!1}var Sn,Ct,YE,qx,Do,WE,QE,cd=ge(()=>{In();Sn=B(ne());kE();Ct=Symbol("own-data");a(Jr,"getChanges");a(zE,"assignTrackedAccessors");a(kx,"trackObject");YE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=t}};zE(YE,{});a(ad,"collapseData");qx=Object.prototype.hasOwnProperty;a(Lo,"deepFreeze");a(KE,"hasChanges");Do=Symbol.for("has-array-changes"),WE=class extends Array{static{a(this,"TrackedArray")}[Do];constructor(t){super(t)}splice(...t){return this[Do]=!0,super.splice(...t)}push(...t){return this[Do]=!0,super.push(...t)}pop(){return this[Do]=!0,super.pop()}unshift(...t){return this[Do]=!0,super.unshift(...t)}shift(){return this[Do]=!0,super.shift()}};WE.prototype.constructor=Array;QE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Lp={};Fe(Lp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Ue,IS_COLLECTION:()=>Tn,RECORD_PROPERTY:()=>_e,Resource:()=>qt,snake_case:()=>Jse,transformForSelect:()=>jE});function Jse(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Vx(e,t){if(Dl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Dl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new LA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Dl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function jr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[ye]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[ye]||i):l=i:(l=s,c=l[Ue]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let S=this.parseQuery(c.slice(E+1));u?u=Object.assign(S,u):u=S,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return ze(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(S=>{if(!S)throw new JE(o.user);return typeof l?.then=="function"?l.then(p=>e(E,u,o,p)):e(E,u,o,l)});if(!h)throw new JE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Xr(e,t){let r=new Kx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function DA(e,t,r){let n=e[_e];if(n){let s=e[Ct];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function jE(e,t){let r=t?.propertyResolvers,n=t[ye],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):DA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(DA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(DA(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=jE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var $x,Yx,Kx,ye,Ue,Tn,_e,zse,qt,JE,Dl,LA,In=ge(()=>{$x=require("crypto");Ac();Yx=require("../../index"),Kx=B(ne());cd();to();Vf();ye=Symbol.for("context"),Ue=Symbol.for("primary-key"),Tn=Symbol("is-collection"),_e=Symbol("stored-record"),zse={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},qt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ue]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=jr(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=jE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=jr(function(t,r,n,s){if(Array.isArray(s)&&t[Tn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Xr(t,"put")},{hasContent:!0,type:"update"});static patch=jr(function(t,r,n,s){return t.patch?t.patch(s,r):Xr(t,"patch")},{hasContent:!0,type:"update"});static delete=jr(function(t,r,n,s){return t.delete?t.delete(r):Xr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,$x.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Xr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=jr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Xr(t,"delete")},{hasContent:!1,type:"update"});static post=jr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=jr(function(t,r,n,s){return t.connect?t.connect(s,r):Xr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=jr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Xr(t,"subscribe")},{type:"read"});static publish=jr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.publish?t.publish(s,r):Xr(t,"publish")},{hasContent:!0,type:"create"});static search=jr(function(t,r,n,s){let i=t.search?t.search(r):Xr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=jE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=jr(function(t,r,n,s){return t.search?t.search(s,r):Xr(t,"search")},{hasContent:!0,type:"read"});static copy=jr(function(t,r,n,s){return t.copy?t.copy(s,r):Xr(t,"copy")},{type:"create"});static move=jr(function(t,r,n,s){return t.move?t.move(s,r):Xr(t,"move")},{type:"delete"});post(t){if(this[Tn])return this.constructor.create(this[Ue],t,this[ye]);Xr(this,"post")}static isCollection(t){return t?.[Tn]}static coerceId(t){return t}static parseQuery(t){return kf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&zse[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:Vx(t,this),isCollection:Dl}}let i=Vx(t,this);return Dl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[ye],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Ue]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Ue],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Tn]=!0),s}subscribe(t){return new Nn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Nn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Ue]}getContext(){return this[ye]}};qt.prototype[ye]=null;(0,Yx._assignPackageExport)("Resource",qt);a(Jse,"snake_case");JE=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(Vx,"pathToId");LA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(jr,"transactional");a(Xr,"missingMethod");a(DA,"selectFromObject");a(jE,"transformForSelect")});function Qx(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;Xa||((0,XE.onMessageByType)(Wx,l=>{zx(l.path)}),Xa=Object.create(null));let o=Xa[s]||(Xa[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Oa(t);let u=new UA(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function zx(e,t){if(!Xa)return;let r=Xa[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Ut(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Oa(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,MA.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let S;h.supportsTransactions&&h.txnInProgress!==o.version&&(S=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,S)}catch(S){console.error(S),(0,MA.info)(S)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Jx(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,XE.broadcast)({type:Wx,path:s}),zx(s,!0)})}}var MA,XE,Wx,Xa,Spe,UA,jx=ge(()=>{MA=B(Y()),XE=B(rt());Ac();Ku();Zs();Wx="transaction",Spe=Buffer.alloc(4096);a(Qx,"addSubscription");UA=class extends Nn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(zx,"notifyFromTransactionData");a(Jx,"listenToCommits")});var fR={};Fe(fR,{coerceType:()=>ZE,makeTable:()=>rh,setServerUtilities:()=>iie,updateResource:()=>eh});function rh(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:f,evictionMS:E,audit:h,trackDeletes:S}=e,{attributes:p}=e;p||(p=[]),Jx(i,u);let T=Em(i,n,u),b=0,g,L,v={},P=Promise.resolve(),k,H,j;for(let K of p)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(H=K),K.expiresAt&&(j=K),K.isPrimaryKey&&(v=K);let z,J=[],me=[],ce=1,de=2,Le={},Be={},Lt=864e5,Vl,$l,Ks,YA=!1,fh,Eh,wG=i.getRange({start:!1,end:!1}).constructor,CG=10,DG=6;h&&QA();class We extends qt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=H;static propertyResolvers;static sources=[];static get expirationMS(){return f}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),L=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(D=>{let N=this.sources.slice(0,-1);if(N=N.filter(M=>M[D]&&(!M[D].reliesOnPrototype||M.prototype[D])),N.length>0)if(N.length===1){let M=N[0];return(q,C,x)=>{if(q?.source!==M)return M[D](C,x,q)}}else return(M,q,C)=>{let x=[];for(let G of N){if(M?.source===G)break;x.push(G[D](q,C,M))}return Promise.all(x)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(D=>{if(y[D]&&(!y[D].reliesOnPrototype||y.prototype[D]))return(N,M,q)=>{if(!N?.source)return y[D](M,q,N)}},"getApplyToCanonicalSource");return Le={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Be={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let D=!1,N=a(async(M,q)=>{let C=M.value,x=M.table?nt[c][M.table]:We;if(c===kn.SYSTEM_SCHEMA_NAME&&(M.table===kn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||M.table===kn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),M.id===void 0&&(M.id=C[x.primaryKey],M.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(M));M.source=m;let G=await x.getResource(M.id,q,Za);switch(M.type){case"put":return G._writeUpdate(C,!0,Za);case"patch":return G._writeUpdate(C,!1,Za);case"delete":return G._writeDelete(Za);case"publish":return G._writePublish(C,Za);case"invalidate":return G.invalidate(Za);default:Xe.error("Unknown operation",M.type,M.id)}},"writeUpdate");try{let M=m.subscribe;M&&S==null&&(S=!0);let q=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Uo.getWorkerIndex)()):(0,Uo.getWorkerIndex)()===0,C=M&&q&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let x;for await(let G of C)try{if(!(G.type==="transaction"?G.writes[0]:G)){Xe.error("Bad subscription event",G);continue}if(G.source=m,x)if(G.beginTxn)x.resolve();else{N(G,x);continue}if(G.type==="end_txn")continue;let pe=ze(G,()=>{if(G.type==="transaction"){let ee=[];for(let Pe of G.writes)try{ee.push(N(Pe,G))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ae}return Promise.all(ee)}else if(G.type==="define_schema"){let ee=this.attributes.slice(0),Pe;for(let ae of G.attributes)ee.find(Ge=>Ge.name===ae.name)||(ee.push(ae),Pe=!0);Pe&&(ut({table:s,database:c,attributes:ee,origin:"cluster"}),Hl.signalSchemaChange(new xl.SchemaEventMsg(process.pid,kn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,N(G,G),new Promise(ee=>{x.resolve=ee})):N(G,G)});D&&(await pe,Hl.signalUserChange(new xl.UserEventMsg(process.pid))),G.onCommit&&(pe?.then?pe.then(G.onCommit):G.onCommit())}catch(se){Xe.error("error in subscription handler",se)}}}catch(M){Xe.error(M)}})(),this}static getResource(m,A,I){let y=super.getResource(m,A,I);if(m!=null){nc(m);try{if(y.hasOwnProperty(_e))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!I?.async||i.cache?.get(m),D=An(A),N=D.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return hh(m,A,{transaction:N},O,M=>{if(M?eh(y,M):y[_e]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new gn.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let q=mh(m,M,A,y);if(q)return D?.disregardReadTxn(),y[PA]=!0,BA(q,C=>(eh(y,C),y))}return y})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return y}ensureLoaded(){let m=mh(this[Ue],this[Zr],this[ye]);if(m)return this[PA]=!0,BA(m,A=>{this[Zr]=A,this[_e]=A.value,this[vl]=A.version})}static setTTLExpiration(m){if(typeof m=="number")f=m*1e3,E||(E=0);else if(m&&typeof m=="object")f=m.expiration*1e3,E=(m.eviction||0)*1e3,Lt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");Lt=Lt||(f+E)/4,Sh()}static enableAuditing(m=!0){h=m,m&&QA(),We.audit=m}static coerceId(m){return m===""?null:ZE(m,v)}static async dropTable(){if(delete nt[c][s],c===o){for(let m of p)l.remove(We.tableName+"/"+m.name),r[m.name]?.drop();l.remove(We.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));Hl.signalSchemaChange(new xl.SchemaEventMsg(process.pid,kn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Tn])return this.search(m);if(this[Ue]===null){if(m?.conditions)return this.search(m);let A=We.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let I=Kl(m);if(I?.read){if(I.isSuperUser)return!0;let y=I.attribute_permissions,O=A?.select;if(y?.length>0||YA&&O){if(A||(A={}),O){let D=y?.length>0&&vA(y,"read");A.select=O.map(N=>{let M=N.name||N;if(!D||D[M]){let q=Ks[M]?.definition?.tableClass;if(q){if(N.name||(N={name:N}),!q.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=y.filter(D=>D.read&&!Ks[D.attribute_name]).map(D=>D.attribute_name);return A}else return!0}}allowUpdate(m,A){let I=Kl(m);if(I?.update){let y=I.attribute_permissions;if(y?.length>0){let O=vA(y,"update");for(let D in A)if(!O[D])return!1;for(let D of y){let N=D.attribute_name;!D.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[Tn]){let I=Kl(m);if(I?.insert){let y=I.attribute_permissions;if(y?.length>0){let O=vA(y,"insert");for(let D in A)if(!O[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Kl(m)?.delete}update(m,A){if(!An(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[Ct]=m):(y=this[Ct],y&&(m=Object.assign(y,m)),this[Ct]=y=m)),this._writeUpdate(this[Ct],A),this}addTo(m,A){if(typeof A=="number")this[Ll]===Zx?this.set(m,(+this.getProperty(m)||0)+A):(this[Ll]||this.update(),this.set(m,new QE(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[ye],I=this[Ue];nc(I),An(this[ye]).addWrite({key:I,store:i,invalidated:!0,entry:this[Zr],nodeName:this[ye]?.nodeName,before:Le.invalidate?.bind(this,A,I),beforeIntermediate:Be.invalidate?.bind(this,A,I),commit:(O,D)=>{if(D?.version>O)return;let N=null;for(let M in r)N||(N={}),N[M]=this.getProperty(M);T(I,N,this[Zr],O,Ml,h,this[ye],0,"invalidate")}})}static evict(m,A,I){let y=this.Source,O;if(!((L||h)&&(!A||(O=i.getEntry(m),!O||!A)||O.version!==I))){if(L){if(i.hasLock(m,O.version))return;let D;for(let N in r)D||(D={}),D[N]=A[N];if(D)return T(m,D,O,I,Ul,null,null,0,null,!0)}return i.ifVersion(m,I,()=>{Yl(m,A,null)}),h?T(m,null,O,I,Ul,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,iG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,I){let y=this[ye],O=An(y),D=this[Ue];nc(D);let N=this[Zr];this[Ll]=A?Zx:rie;let M={key:D,store:i,entry:N,nodeName:y?.nodeName,validate:q=>{m||(m=this[Ct]),A||m&&KE(m)?y?.source||(O.checkOverloaded(),this.validate(m,!A),H&&(m[H.name]=H.type==="Date"?new Date(q):H.type==="String"?new Date(q).toISOString():q),A&&(t&&m[t]!==D&&(m[t]=D),k&&(N?.value?m[k.name]=N?.value[k.name]:m[k.name]=k.type==="Date"?new Date(q):k.type==="String"?new Date(q).toISOString():q),m=Lo(m))):O.removeWrite(M)},before:A?Le.put?()=>Le.put(y,D,m):null:Le.patch?()=>Le.patch(y,D,m):Le.put?()=>Le.put(y,D,Lo(this)):null,beforeIntermediate:A?Be.put?()=>Be.put(y,D,m):null:Be.patch?()=>Be.patch(y,D,m):Be.put?()=>Be.put(y,D,Lo(this)):null,commit:(q,C,x)=>{if(x){if(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),this[Zr]=C,C?.value?.[_e])throw new Error("Can not assign a record to a record, check for circular references");A||(this[_e]=C?.value??null)}this[Ct]=m,this[vl]=q;let G=C?.value,se=m;if(this[Ll]=0,C?.version>=q)if(h){let ae=C.localTime,Ge=C.version;for(;se&&(ae>q||Ge>=q&&ae>0);){let te=u.get(ae);if(!te)break;let X=Ut(te);if(Ge=X.version,Ge>q){if(X.type==="patch"){let Oe=X.getValue(i);se=$E(se,Oe)}else if(X.type==="put"||X.type==="delete")return}else if(Ge===q)return;ae=X.previousLocalTime}}else{if(A)return;se=$E(se,G)}let pe;if(A?pe=se:(this[_e]=G,pe=A?se:Lo(this,se)),this[_e]=pe,pe?.[_e])throw new Error("Can not assign a record to a record, check for circular references");let ee;A||(ee=m),Yl(D,G,pe);let Pe=A?"put":"patch";T(D,pe,C,q,0,h,y,y.expiresAt||(f?f+Date.now():0),Pe,!1,ee)}};O.addWrite(M)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Tn]){for await(let A of this.search(m))(await We.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let A=An(this[ye]),I=this[Ue];nc(I);let y=this[ye];return A.addWrite({key:I,store:i,resource:this,nodeName:y?.nodeName,before:Le.delete?.bind(this,y,I),beforeIntermediate:Be.delete?.bind(this,y,I),commit:(O,D,N)=>{let M=D?.value;N&&(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),eh(this,D)),!(D?.version>O)&&(Yl(this[Ue],M),Xe.trace("Write delete entry",I,O),h||S?(T(I,null,this[Zr],O,0,h,this[ye],0,"delete"),h||Sh()):i.remove(this[Ue]))}}),!0}search(m){let A=this[ye],I=An(A);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ue]&&(y=[{attribute:null,comparator:"prefix",value:this[Ue]}].concat(y));let O,D={};function N(X,Oe){let He;switch(Oe){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');He=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Oe)}let Vn=He&&{},Ws;for(let $e of X){if($e.conditions){$e.conditions=N($e.conditions,$e.operator);continue}let Gt=$e[0]??$e.attribute,rn=Gt==null?v:Gs(p,Gt);if(rn){if(He){let $n=Hn(Gt),Ft=Vn[$n];Ft?(Ft.push($e),Ws=!0):Vn[$n]=[$e]}(rn.type||Gg[$e.comparator])&&($e[1]===void 0?$e.value=q($e.value,rn):$e[1]=q($e[1],rn))}else if(Gt!=null)throw(0,gn.handleHDBError)(new Error,`${Gt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(Ws)for(let $e in Vn){let Gt=Vn[$e],rn=Gt.length;if(rn>1)for(let $n=0;$n<rn;$n++){let Ft=Gt[$n];if(Ft.comparator==="ge"||Ft.comparator==="greater_than_equal")for(let Qs=0;Qs<rn;Qs++){let Ho=Gt[Qs];(Ho.comparator==="le"||Ho.comparator==="less_than_equal")&&(Ft.comparator="between",Ft.value=[Ft.value,Ho.value],X.splice(X.indexOf(Ho),1))}if(Ft.comparator==="equals"||!Ft.comparator){for(let Qs=0;Qs<rn;Qs++)if(Qs!==$n){let Ho=Gt[Qs];X.splice(X.indexOf(Ho),1)}break}}}return X}a(N,"prepareConditions");function M(X,Oe){if(m.enforceExecutionOrder)return X;for(let He of X)He.conditions&&(He.conditions=M(He.conditions,He.operator));return X.length>1&&Oe!=="or"?(0,sG.sortBy)(X,qf(We)):X}a(M,"orderConditions");function q(X,Oe){return Array.isArray(X)?X.map(He=>ZE(He,Oe)):ZE(X,Oe)}a(q,"coerceTypedValues");let C=m.operator;(y.length>0||C)&&(y=N(y,C));let x=typeof m.sort=="object"&&m.sort,G;if(x&&C!=="or"){let X=x.attribute;if(O=y.find(Oe=>Hn(Oe.attribute)===Hn(X)),!O){if(!Gs(p,X))throw(0,gn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);O={attribute:X,comparator:"sort"},y.push(O)}O.descending=!!x.descending}y=M(y,C),x&&(y[0]===O?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&y.splice(y.indexOf(O),1),G=x));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:C,postOrdering:G,selectApplied:!!se};let pe=I.useReadTxn(),ee=Fg(y,C,We,pe,m,A,(X,Oe)=>KA(X,se,A,pe,Oe),D),Pe=m.ensureLoaded!==!1;G||(ee=te(ee));let ae=We.transformEntryForSelect(se,A,pe,D,Pe,!0),Ge=We.transformToOrderedSelect(ee,se,G,pe,A,ae);function te(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(te,"applyOffset"),G&&(Ge=te(Ge)),Ge.onDone=()=>{Ge.onDone=null,I.doneReadTxn()},Ge.selectApplied=!0,Ge.getColumns=()=>{if(se){let X=[];for(let Oe of se)Oe==="*"?X.push(...p.map(He=>He.name)):X.push(Oe.name||Oe);return X}return p.map(X=>X.name)},Ge}static transformToOrderedSelect(m,A,I,y,O,D){let N=new wG;if(I){m=KA(m,A,y,O,null);let M;N.iterate=function(){let C,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=I.dbOrderedAttribute,pe,ee,Pe=!0;function ae(te){let X=te.next&&ae(te.next),Oe=te.descending;return(He,Vn)=>{let Ws=ph(He,te.attribute,y),$e=ph(Vn,te.attribute,y),Gt=Oe?(0,Po.compareKeys)($e,Ws):(0,Po.compareKeys)(Ws,$e);return Gt===0?X?.(He,Vn)||0:Gt}}a(ae,"createComparator");let Ge=ae(I);return{async next(){let te;if(C)if(te=C.next(),te.done){if(G)return N.onDone&&N.onDone(),te}else return{value:await D.call(this,te.value)};M=[],pe&&M.push(pe);do if(te=await x.next(),te.done){if(G=!0,M.length)break;return N.onDone&&N.onDone(),te}else{let X=te.value;if(X?.then&&(X=await X),se){let Oe=ph(X,se,y);if(Pe)Pe=!1,ee=Oe;else if(Oe!==ee){ee=Oe,pe=X;break}}M.push(X)}while(!0);return I.isGrouped,M.sort(Ge),C=M[Symbol.iterator](),te=C.next(),te.done?(N.onDone&&N.onDone(),te):{value:await D.call(this,te.value)}},return(){N.onDone&&N.onDone(),x.return()},throw(){N.onDone&&N.onDone(),x.throw()}}};let q=a(C=>{if(typeof A=="object"&&Array.isArray(C.attribute))for(let x=0;x<A.length;x++){let G=A[x],se;if(G.name===C.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=C.attribute.slice(1),se.descending=C.descending}else G===C.attribute[0]&&(A[x]=se={name:G,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&q(C.next)},"applySortingOnSelect");q(I)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(D);return N}static transformEntryForSelect(m,A,I,y,O,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(x=>x?.key??x,"transform");return m===t?C:m.asArray?x=>[C(x)]:x=>({[t]:C(x)})}let N;O&&L&&!m?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(N=!0);let M,q=a(function(C){let x;if(C!=null){if(fh=C,x=C.value||C.deref?.(),!x&&(C.key===void 0||C.deref)){if(C=hh(C.key??C,A,{transaction:I,lazy:m?.length<4},this.isSync,G=>G),C?.then)return C.then(q.bind(this));x=C?.value}if(N&&(C.metadataFlags&(Ml|Ul)||C.expiresAt&&C.expiresAt<Date.now())){let G=mh(C.key??C,C,A);if(G?.then)return G.then(q)}}if(x==null)return D?Mo.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((ee,Pe)=>{let ae;typeof ee=="object"?ae=ee.name:ae=ee;let Ge=Ks?.[ae],te;if(Ge){let X=y?.[ae];if(X)if(X.hasMappings){let He=Ge.from?x[Ge.from]:Hn(C.key);te=X.get(He),te||(te=[])}else te=X.fromRecord?.(x);else te=Ge(x,A,C);let Oe=a(He=>{if(He&&typeof He=="object"){let Vn=Ge.definition?.tableClass||We;M||(M={});let Ws=M[ae]||(M[ae]=Vn.transformEntryForSelect(ae===ee?null:ee.select||(Array.isArray(ee)?ee:null),A,I,X,O));if(Array.isArray(He)){let $e=[],Gt=Vn.transformToOrderedSelect(He,ee.select,typeof ee.sort=="object"&&ee.sort,A,I,Ws)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),rn=a(Ft=>{for(;!Ft.done;){if(Ft?.then)return Ft.then(rn);$e.push(Ft.value),Ft=Gt.next()}Pe($e,ae)},"nextValue"),$n=rn(Gt.next());$n&&(G||(G=[]),G.push($n));return}else if(He=Ws.call(this,He),He?.then){G||(G=[]),G.push(He.then($e=>Pe($e,ae)));return}}Pe(He,ae)},"handleResolvedValue");te?.then?(G||(G=[]),G.push(te.then(Oe))):Oe(te);return}else te=x[ae],te&&typeof te=="object"&&ae!==ee&&(te=We.transformEntryForSelect(ee.select||ee,A,I,null)({value:te}));Pe(te,ae)},"selectAttribute"),pe;if(typeof m=="string")se(m,ee=>{pe=ee});else if(Array.isArray(m))if(m.asArray)pe=[],m.forEach((ee,Pe)=>{ee==="*"?m[Pe]=x:se(ee,ae=>pe[Pe]=ae)});else{pe={};let ee=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ae in x)pe[ae]=x[ae];else se(Pe,(ae,Ge)=>{ae===void 0&&ee&&(ae=null),pe[Ge]=ae})}else throw new gn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>pe):pe}return x},"transform");return q}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||ut({table:s,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let A=!m.rawEvents,I=Qx(We,this[Ue]??null,function(N,M,q,C){try{let x=M.getValue?.(i,A);if(!x&&M.type==="patch"&&A){let G=i.getEntry(N);G?.version===M.version?x=G.value:x=M.getValue?.(i,!0,q),M.type="put"}this.send({id:N,timestamp:q,value:x,version:M.version,type:M.type,beginTxn:C})}catch(x){Xe.error(x)}},m.startTime||0,this[Tn]);this[Tn]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let y=this[Ue],O=m.previousCount;O>1e3&&(O=1e3);let D=m.startTime;if(this[Tn]){if(D){if(O)throw new gn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:M}of u.getRange({start:D,exclusiveStart:!0})){let q=Ut(M);if(q.tableId!==n)continue;let C=q.recordId;if(y==null||rG(y,C)){let x=q.getValue(i,A,N);I.send({id:C,timestamp:N,value:x,version:q.version,type:q.type})}I.startTime=N}}else if(O){let N=[];for(let{key:M,value:q}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Ut(q);if(C.tableId!==n)continue;let x=C.recordId;if(y==null||rG(y,x)){let G=C.getValue(i,A,M);if(N.push({id:x,timestamp:M,value:G,version:C.version,type:C.type}),--O<=0)break}}catch(C){Xe.error("Error getting history entry",M,C)}for(let M=N.length;M>0;)I.send(N[--M]);N[0]&&(I.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:M,version:q,localTime:C}of i.getRange({start:y??!1,end:y==null?void 0:[y,Po.MAXIMUM_KEY],versions:!0}))M&&I.send({id:N,timestamp:C,value:M,version:q,type:"put"})}else{O&&!D&&(D=0);let N=this[Zr]?.localTime;if(N===fm&&(i.cache?.delete(y),this[Zr]=i.getEntry(y),Xe.trace("re-retrieved record",N,this[Zr]?.localTime),N=this[Zr]?.localTime),Xe.trace("Subscription from",D,"from",y,N),D<N){let M=[],q=N;do{let C=u.get(q);if(C){m.omitCurrent=!0;let x=Ut(C),G=x.getValue(i,A,q);A&&(x.type="put"),M.push({id:y,value:G,timestamp:q,...x}),q=x.previousLocalTime}else break;O&&O--}while(q>D&&O!==0);for(let C=M.length;C>0;)I.send(M[--C]);I.startTime=N}!m.omitCurrent&&this.doesExist()&&I.send({id:y,timestamp:N,value:this,version:this[vl],type:"put"})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[_e]||this[Ll])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let I=An(this[ye]),y=this[Ue]||null;nc(y);let O=this[ye];I.addWrite({key:y,store:i,entry:this[Zr],nodeName:O?.nodeName,validate:()=>{O?.source||(I.checkOverloaded(),this.validate(m))},before:Le.publish?.bind(this,O,y,m),beforeIntermediate:Be.publish?.bind(this,O,y,m),commit:(D,N,M)=>{N===void 0&&S&&!h&&Sh(),T(y,N?.value??null,N,N?.version||D,0,!0,O,N?.expiresAt,"message",!1,m)}})}validate(m,A){let I,y=a((O,D,N)=>{if(D.type&&O!=null)if(A&&O.__op__&&(O=O.value),D.properties){typeof O!="object"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be an object${D.type?" ("+D.type+")":""}`);let M=D.properties;for(let q=0,C=M.length;q<C;q++){let x=M[q],G=y(O[x.name],x,N+"."+x.name);G&&(O[x.name]=G)}if(D.sealed&&O!=null&&typeof O=="object")for(let q in O)M.find(C=>C.name===q)||(I||(I=[])).push(`Property ${q} is not allowed within object in property ${N}`)}else switch(D.type){case"Int":(typeof O!="number"||O>>0!==O)&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(M=>typeof M=="string")||(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(D.elements)for(let M=0,q=O.length;M<q;M++){let C=O[M],x=y(C,D.elements,N+"[*]");x&&(O[M]=x)}}else(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a Buffer or Uint8Array`);break}D.nullable===!1&&O==null&&(I||(I=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let O=0,D=p.length;O<D;O++){let N=p[O];if(!N.relationship&&(!A||N.name in m)){let M=y(m[N.name],N,N.name);M&&(m[N.name]=M)}}if(d)for(let O in m)p.find(D=>D.name===O)||(I||(I=[])).push(`Property ${O} is not allowed`);if(I)throw new gn.ClientError(I.join(". "))}getUpdatedTime(){return this[vl]}wasLoadedFromSource(){return L?!!this[PA]:void 0}static async addAttributes(m){let A=p.slice(0);for(let I of m){if(!I.name)throw new gn.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new gn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(I)}return ut({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static async removeAttributes(m){let A=p.filter(I=>!m.includes(I.name));return ut({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,I=5e3,y=1e3,O;A>I&&!m?.exactCount&&(O=y);let D=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:O}))N!=null&&D++;if(O){let N=D;D=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))Pe!=null&&D++;let M=O*2,q=(D+N)/M,C=Math.pow((D-N+1)/O/2,2)+q*(1-q)/M,x=Math.max(Math.sqrt(C)*A,1),G=Math.round(q*A),se=Math.max(G-1.96*x,0),pe=Math.min(G+1.96*x,A),ee=Math.pow(10,Math.round(Math.log10(x)));return ee>G&&(ee=ee/10),D=Math.round(G/ee)*ee,{recordCount:D,estimatedRange:[Math.round(se),Math.round(pe)]}}return{recordCount:D}}static updatedAttributes(){Ks=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)"),YA=!0,A.to)m.elements?.definition?(Ks[m.name]=m.resolve=(I,y,O)=>{let D=I[A.from?A.from:t],N=m.elements.definition.tableClass;return O?Pa({attribute:A.to,value:D},An(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:A.to,value:D}],y).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 "${s}" must have an array type referencing a table as the elements`);else if(A.from){let I=m.definition||m.elements?.definition;I?(Ks[m.name]=m.resolve=(y,O,D)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let M,q=N.map(C=>{let x=D?I.tableClass.primaryStore.getEntry(C,{transaction:An(O).getReadTxn()}):I.tableClass.get(C,O);return x?.then&&(M=!0),x});return A.filterMissing?M?Promise.all(q).then(C=>C.filter(nG)):q.filter(nG):M?Promise.all(q):q}return D?I.tableClass.primaryStore.getEntry(N,{transaction:An(O).getReadTxn()}):I.tableClass.get(N,O)}},m.set=(y,O)=>{if(Array.isArray(O)){let D=O.map(N=>N[Ue]||N[I.tableClass.primaryKey]);y[A.from]=D}else{let D=O[Ue]||O[I.tableClass.primaryKey];y[A.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}zE(this,this)}static async deleteHistory(m=0){let A;for(let{key:I,value:y}of u.getRange({start:0,end:m}))await Pl(),Ut(y).tableId===n&&(A=u.remove(I));await A}static async*getHistory(m=0,A=1/0){for(let{key:I,value:y}of u.getRange({start:m,end:A})){await Pl();let O=Ut(y);O.tableId===n&&(yield{id:O.recordId,localTime:I,version:O.version,type:O.type,value:O.getValue(i,!0,I),user:O.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 y=I.localTime;if(!y)throw new Error("The entry does not have a local audit time");let O=0;do{await Pl();let D=u.get(y);if(D){let N=Ut(D);A.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(O<1e3&&y);return A.reverse()}static cleanup(){z?.remove()}}We.updatedAttributes();let LG=We.prototype;return LG[tie]=!0,f&&We.setTTLExpiration(f/1e3),j&&MG(),We;function Yl(K,m,A){let I;for(let y in r){let O=r[y],D=O.isIndexing,N=A?.[y],M=m?.[y];if(N===M&&!D)continue;I=!0;let q=O.indexNulls,C=(0,Bl.getIndexedValues)(N,q),x=(0,Bl.getIndexedValues)(M,q);if(x?.length>0){let G=new Set(x);if(C=C?C.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],x=Array.from(G),(x.length>0||C.length>0)&&Xx){let se=x.concat(C).map(pe=>({key:pe,value:K}));O.prefetch(se,tG)}for(let se=0,pe=x.length;se<pe;se++)O.remove(x[se],K)}else C?.length>0&&Xx&&O.prefetch(C.map(G=>({key:G,value:K})),tG);if(C)for(let G=0,se=C.length;G<se;G++)O.put(C[G],K)}return I}a(Yl,"updateIndices");function nc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>eG)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,Po.writeKey)(K,nie,0)>eG)throw new Error("Primary key size is too large: "+K.length);return!0}a(nc,"checkValidId");function hh(K,m,A,I,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,K);let D=i.getEntry(K,A);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),y(D,K)},"whenPrefetched");return I?O():ce>0?(ce--,O()):new Promise((D,N)=>{ce===0?(ce--,i.prefetch([K],()=>{M(),q()})):(J.push(K),me.push(q),J.length>DG&&(ce--,M()));function M(){if(J.length>0){let C=me;i.prefetch(J,()=>{ce===-1?M():ce++;for(let x of C)x()}),J=[],me=[],de>2&&de--}else ce=de,de<CG&&de++}a(M,"prefetch");function q(){try{D(O())}catch(C){N(C)}}a(q,"load")})}a(hh,"loadLocalRecord");function Kl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return sie;let A=m[c],I,y=A?.tables;if(y)return y[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(Kl,"getTablePermissions");function mh(K,m,A,I){if(L){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Ml|Ul)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,cn(!y,"cache-hit",s)),y){let O=WA(K,m,A).then(D=>(D?.value?.[_e]&&Xe.error("Can not assign a record with a record property"),A&&(D?.version>(A.lastModified||0)&&(A.lastModified=D.version),A.lastRefreshed=Date.now()),D));if(A?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(O.catch(D=>Xe.warn(D)),A?.onlyIfCached&&!I.doesExist())throw new gn.ServerError("Entry is not cached",504);return}else return O}}}a(mh,"ensureLoadedFromSource");function An(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 eo,m.lmdbDb=i,m;m=A}while(!0)}else return new id}a(An,"txnForContext");function ph(K,m,A){if(!K)return;fh=K;let I=K.value||K.deref?.()||(fh=i.getEntry(K.key))?.value;if(typeof m=="object"){let O=Ks,D=I;for(let N=0,M=m.length;N<M;N++){let q=m[N],C=O?.[q];D=C&&D?C(D,A,!0)?.value:D?.[q],O=C?.definition?.tableClass?.propertyResolvers}return D}let y=Ks[m];return y?y(I,A):I[m]}a(ph,"getAttributeValue");function KA(K,m,A,I,y){let O=y?.length,D={transaction:I,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function M(q,C){let x=q?.value;if(!x)return Mo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](x,q))return Mo.SKIP;return C!==void 0&&(q.key=C),q}if(a(M,"processEntry"),O>0||!K.hasEntries){let q=K.map(C=>{if(N=null,typeof C=="object"&&C?.key!==void 0)return O>0?M(C):C;if(C==null)return Mo.SKIP;for(let x=0;x<O;x++){let se=y[x].idFilter;if(se){if(!se(C))return Mo.SKIP;N||(N=[]),N.push(x)}}return hh(C,A,D,!1,M)});return Array.isArray(K)&&(q=q.filter(C=>C!==Mo.SKIP)),q.hasEntries=!0,q}return K}a(KA,"transformToEntries");async function WA(K,m,A){let I=m?.metadataFlags,y=m?.version,O,D;if(!i.attemptLock(K,y,()=>{clearTimeout(D);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Ml|Ul)?O(WA(K,i.getEntry(K),A)):O(C)}))return new Promise(C=>{O=C,D=setTimeout(()=>{i.unlock(K,y)},eie)});let N=m?.value,M={requestContext:A,replacingRecord:N,replacingVersion:y,source:null,resourceCache:A?.resourceCache},q=A?.responseHeaders;return new Promise((C,x)=>{let G;BA(ze(M,async se=>{let pe=performance.now(),ee,Pe,ae;try{for(let Oe of We.sources)if(Oe.get&&(!Oe.get.reliesOnPrototype||Oe.prototype.get)&&(M.source=Oe,ee=await Oe.get(K,M),ee))break;ae=I&Ml;let te=M.lastModified||ae&&y;Pe=ae||te>y||!N,te||(te=(0,Bl.getNextMonotonicTime)());let X=performance.now()-pe;if(kr(X,"cache-resolution",s),q&&ag(q,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=te,f&&!M.expiresAt&&(M.expiresAt=Date.now()+f),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]!==K&&(ee[t]=K)}G=!0,C({version:te,value:ee})}catch(te){te.message+=` while resolving record ${K} for ${s}`,N&&((te.code==="ECONNRESET"||te.code==="ECONNREFUSED"||te.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(te.statusCode===500||te.statusCode===502||te.statusCode===503||te.statusCode===504))?(C({version:y,value:N}),Xe.trace(te.message,"(returned stale record)")):x(te),M.transaction.abort();return}if(A?.noCacheStore){M.transaction.abort();return}An(M).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(te,X)=>{if(X?.version!==y)return;let Oe=Yl(K,N,ee);ee?(Be.put?.(M,K,ee),T(K,ee,X,te,0,h&&Pe||null,M,M.expiresAt,"put",!!ae)):(Be.delete?.(M,K),h||S?T(K,null,X,te,0,h&&Pe||null,M,0,"delete",!!ae):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&Xe.error("Error committing cache update",se)})})}a(WA,"getFromSource");function Sh(){if(Lt!==Vl&&(Vl=Lt,(0,Uo.getWorkerIndex)()===(0,Uo.getWorkerCount)()-1)){if($l&&clearTimeout($l),!Lt)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())/Lt)*Lt+K.getTime(),A=a(I=>{Xe.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),$l=setTimeout(()=>P=P.then(async()=>{if(A(Math.max(I+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout($l);return}let y=50,O=new Array(y),D=0;Xe.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:M,value:q,version:C,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;q===null&&!h&&C+Zse<Date.now()?G=i.remove(M,C):x&&x+E<Date.now()&&(G=We.evict(M,q,C),N++),G&&(await O[D],O[D]=G.catch(se=>{Xe.error("Cleanup error",se)}),++D>=y&&(D=0)),await Pl()}Xe.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){Xe.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Sh,"scheduleCleanup");function QA(){z=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(QA,"addDeleteRemoval");function MG(){(0,Uo.getWorkerIndex)()===0&&setInterval(async()=>{if(!Eh){Eh=!0;try{let K=j.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${j} must be indexed`);for(let A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let I of m.getValues(A)){let y=i.getEntry(I);y?.value?y.value[K]<Date.now()&&We.evict(I,y.value,y.version):i.ifVersion(I,y?.version,()=>m.remove(A,I))}await Pl()}}catch(K){Xe.error("Error in evicting old records",K)}finally{Eh=!1}}},Xse).unref()}a(MG,"runRecordExpirationEviction")}function vA(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function tG(){}function iie(e){iG=e}function ZE(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,th.autoCast)(e):e}function rG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function BA(e,t,r){return e?.then?e.then(t,r):t(e)}function eh(e,t){e[Zr]=t,e[_e]=t?.value??null,e[vl]=t?.version}function nG(e){return e!=null}function qn(e){try{return JSON.stringify(e)}catch{return e}}var kn,Mo,Bl,sG,Gl,gn,Hl,xl,Xe,Po,Uo,th,jse,iG,Xse,Zse,Xx,eie,vl,tie,Zr,Ll,Zx,rie,PA,Za,Ml,Ul,nie,eG,sie,Bpe,oie,Pl,nE=ge(()=>{kn=B(U()),Mo=require("lmdb"),Bl=B(Mr()),sG=require("lodash");In();Zp();Gl=B(re());jx();gn=B(ne()),Hl=B(Os()),xl=B(Ln());Re();Vf();Xe=B(Y());cd();to();Po=require("ordered-binary"),Uo=B(rt());Zs();th=B(Q());Cc();Is();kE();Wu();jse=new Uint8Array(9);jse[8]=192;Xse=6e4,Zse=864e5;Gl.initSync();Xx=Gl.get(kn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),eie=1e4,vl=Symbol.for("version"),tie=Symbol.for("incremental-update"),Zr=Symbol("entry"),Ll=Symbol("is-saving"),Zx=1,rie=2,PA=Symbol("loaded-from-source"),Za={isNotification:!0,ensureLoaded:!1},Ml=1,Ul=8,nie=Buffer.allocUnsafeSlow(8192),eG=1978,sie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},Bpe=(0,th.convertToMS)(Gl.get(kn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(rh,"makeTable");a(vA,"attributesAsObject");a(tG,"noop");a(iie,"setServerUtilities");oie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(ZE,"coerceType");a(rG,"isDescendantId");Pl=a(()=>new Promise(setImmediate),"rest");a(BA,"when");a(eh,"updateResource");a(nG,"exists");a(qn,"stringify")});var qe={};Fe(qe,{database:()=>ru,databases:()=>nt,dropDatabase:()=>sS,dropTableMeta:()=>_ie,getDatabases:()=>dr,getDefaultCompression:()=>_f,getTables:()=>aie,onUpdatedTable:()=>KR,readMetaDb:()=>Fl,resetDatabases:()=>Fu,table:()=>ut,tables:()=>Ur});function aie(){return ah||dr(),Ur||{}}function dr(){if(ah)return nt;ah=!0,rc=new Map;let e=(0,Et.getHdbBasePath)()&&(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),t=(0,Et.get)(Dt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,en.existsSync)(e)?e:(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,en.existsSync)(e))for(let r of(0,en.readdirSync)(e,{withFileTypes:!0})){let n=(0,Ze.basename)(r.name,".mdb");r.isFile()&&(0,Ze.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Fl((0,Ze.join)(e,r.name),null,n)}if((0,en.existsSync)((0,tc.getBaseSchemaPath)())){for(let r of(0,en.readdirSync)((0,tc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Ze.join)((0,tc.getBaseSchemaPath)(),r.name),s=(0,Ze.join)((0,tc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,en.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Ze.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Ze.join)(s,i.name);Fl((0,Ze.join)(n,i.name),(0,Ze.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,en.existsSync)(s))for(let o of(0,en.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Ze.extname)(o.name).toLowerCase()===".mdb"&&Fl((0,Ze.join)(s,o.name),(0,Ze.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,Ze.join)(c.path,(0,Ze.basename)(o+".mdb"));(0,en.existsSync)(u)&&Fl(u,o,r,null,!0)}}for(let r in nt){let n=rc.get(r);if(n){let s=nt[r];r.includes("delete")&&Rn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Rn.trace(`delete table class ${i}`),delete s[i])}else if(delete nt[r],r==="data"){for(let s in Ur)delete Ur[s];delete Ur[uh]}}return rc=null,nt}}function Fu(){ah=!1;for(let[,e]of Li)e.needsDeletion=!0;dr();for(let[e,t]of Li)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Li.delete(e));return nt}function Fl(e,t,r=GA,n,s){let i=new HA.default(e,!1);try{let o=Li.get(e);o?o.needsDeletion=!1:(o=(0,sh.open)(i),Li.set(e,o));let c=new vo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(nh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,en.existsSync)(n)&&(i.path=n,_=(0,sh.open)(i),_.isLegacy=!0):_=qE(o));let l=uG(r),d=l[uh],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[S,p]=E.toString().split("/");p===""?p=h.name:p||(p=S,S=t,h.name||(h.name=p,h.indexed=!h.is_hash_attribute)),d?.add(S);let T=f.get(S);T||f.set(S,T={attributes:[]}),(p==null||h.is_hash_attribute)&&(T.primary=h),p!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:S,primary:p}=h;if(!p){for(let J of S)if(J.is_hash_attribute||J.isPrimaryKey){p=J;break}if(!p){Rn.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(S)}`);continue}}let T=l[E],b={},g=[],L,v,P=typeof p.audit=="boolean"?p.audit:(0,Et.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=p.trackDeletes,H=p.expiration,j=p.eviction,z=p.sealed;if(T)b=T.indices,g=T.attributes,T.schemaVersion++;else{L=p.tableId,L?L>=(u.get(ec)||0)&&u.putSync(ec,L+1):(p.tableId=L=u.get(ec),L||(L=1),u.putSync(ec,L+1),u.putSync(p.key,p));let J=new vo.default(!p.is_hash_attribute,p.is_hash_attribute);if(J.compression=p.compression,J.compression){let me=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||cG;J.compression.threshold=me}v=S_(o.openDB(p.key,J)),v.rootStore=o,v.tableId=L}for(let J of S){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!b[J.name]){let ce=new vo.default(!J.is_hash_attribute,J.is_hash_attribute);b[J.name]=o.openDB(J.key,ce),b[J.name].indexNulls=J.indexNulls}let me=g.find(ce=>ce.name===J.name);me?g.splice(g.indexOf(me),1,J):g.push(J)}}catch(me){Rn.error("Error trying to update attribute",J,g,b,me)}}if(!T){T=lG(l,E,rh({primaryStore:v,auditStore:_,audit:P,sealed:z,expirationMS:H&&H*1e3,evictionMS:j&&j*1e3,trackDeletes:k,tableName:E,tableId:L,primaryKey:p.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:b,attributes:S,schemaDefined:p.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let J of FA)J(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function uG(e){let t=nt[e];if(t||(e==="data"?t=nt[e]=Ur:e==="system"?Object.defineProperty(nt,"system",{value:t=Object.create(null),configurable:!0}):t=nt[e]=Object.create(null)),rc&&!rc.has(e)){let r=new Set;t[uh]=r,rc.set(e,r)}return t}function lG(e,t,r){return e[t]=r,r}function ru({database:e,table:t}){e||(e=GA),dr();let r=uG(e),n=(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),s=(0,Et.get)(Dt.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_PATH)||((0,en.existsSync)(n)?n:(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME));let o=(0,Ze.join)(n,(i?t:e)+".mdb"),c=Li.get(o);if(!c){let u=new HA.default(o,!1);c=(0,sh.open)(u),Li.set(o,c)}return c}async function sS(e){if(!nt[e])throw new Error("Schema does not exist");let t=nt[e];for(let r in t){let s=t[r].primaryStore.rootStore;Li.delete(s.path),s.status==="open"&&(await s.close(),await ch.remove(s.path))}if(e==="data"){for(let r in Ur)delete Ur[r];delete Ur[uh]}delete nt[e]}function ut({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=GA);let d=ru({database:t,table:e}),f=nt[t],E=f?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,S,p,T;_==null&&(_=!0);let b=new vo.default(!1);for(let H of i)H.attribute?(H.name=H.attribute,H.indexed=!0):H.attribute=H.name,H.expiresAt&&(H.indexed=!0);let g,L;if(E){if(h=E.primaryKey,E.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);E.attributes.splice(0,E.attributes.length,...i)}else{let H=d.auditStore;H||(H=qE(d)),S=i.find(me=>me.isPrimaryKey)||{},h=S.name,S.is_hash_attribute=!0,S.schemaDefined=_,S.compression=_f(),u&&(S.trackDeletes=!0),o=S.audit=typeof o=="boolean"?o:(0,Et.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(S.expiration=r),n&&(S.eviction=n),typeof c=="boolean"&&(S.sealed=c),l&&(S.origins?S.origins.includes(l)||S.origins.push(l):S.origins=[l]),Rn.trace(`${e} table loading, opening primary store`);let j=new vo.default(!1,!0);j.compression=S.compression;let z=e+"/",J=S_(d.openDB(z,j));J.rootStore=d,T=d.dbisDb=d.openDB(nh.INTERNAL_DBIS_NAME,b),J.tableId=T.get(ec),J.tableId||(J.tableId=1),T.putSync(ec,J.tableId+1),S.tableId=J.tableId,E=lG(f,e,rh({primaryStore:J,auditStore:H,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),E.schemaVersion=1,g=!0,k(),T.put(z,S)}p=E.indices,T=T||(d.dbisDb=d.openDB(nh.INTERNAL_DBIS_NAME,b)),E.dbisDB=T;let v=[];for(let{key:H,value:j}of T.getRange({start:!0})){let[z,J]=H.toString().split("/");if(J===""&&(J=j.name),J){if(z!==e)continue}else J=z;if(!i.find(ce=>ce.name===J)?.indexed&&j.indexed&&!j.isPrimaryKey){k(),g=!0,T.remove(H);let ce=E.indices[z];ce&&v.push(ce)}}let P=[];try{for(let H of i||[]){if(H.relationship)continue;let j=e+"/"+(H.name||"");Object.defineProperty(H,"key",{value:j,configurable:!0});let z=T.get(j);if(H.isPrimaryKey){if(z=z||T.get(j=e+"/")||{},o!==E.audit||c!==c||(+r||void 0)!==(+z.expiration||void 0)||(+n||void 0)!==(+z.eviction||void 0)){let me=Object.assign({},z);typeof o=="boolean"&&(o&&E.enableAuditing(o),me.audit=o),r&&(me.expiration=+r),n&&(me.eviction=+n),c!==void 0&&(me.sealed=c),g=!0,k(),T.put(j,me)}continue}z?.attribute&&!z.name&&(z.indexed=!0);let J=!z||z.type!==H.type||z.indexed!==H.indexed||z.nullable!==H.nullable||JSON.stringify(z.attributes)!==JSON.stringify(H.attributes)||JSON.stringify(z.elements)!==JSON.stringify(H.elements);if(H.indexed){let me=new vo.default(!0,!1),ce=d.openDB(j,me);(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(g=!0,k(),z=T.get(j),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(g=!0,H.indexNulls===void 0&&(H.indexNulls=!0),E.primaryStore.getStats().entryCount>0&&(H.lastIndexedKey=z?.lastIndexedKey||!1,H.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(H,"dbi",{value:ce}),P.push(H))),T.put(j,H)),z?.indexNulls&&H.indexNulls===void 0&&(H.indexNulls=!0),ce.indexNulls=H.indexNulls,p[H.name]=ce}else J&&(g=!0,k(),T.put(j,H))}}finally{L&&L()}if(g&&(E.schemaVersion++,E.updatedAttributes()),Rn.trace(`${e} table loading, running index`),P.length>0||v.length>0?E.indexingOperation=lie(E,P,v):g&&ih.signalSchemaChange(new oh.SchemaEventMsg(process.pid,"schema-change",E.databaseName,E.tableName)),E.origin=l,g)for(let H of FA)H(E,l!=="cluster");return(r||n||s)&&E.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),Rn.trace(`${e} table loaded`),E;function k(){L||d.transactionSync(()=>({then(H){L=H}}))}a(k,"startTxn")}async function lie(e,t,r){try{let n=e.schemaVersion;await ih.signalSchemaChange(new oh.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,S=(0,oG.getIndexedValues)(l[h]);if(S)for(let p=0,T=S.length;p<T;p++)E.dbi.put(S[p],_)}}),s.then(()=>u--,f=>{u--,Rn.error(f)}),ql.workerData&&ql.workerData.restartNumber!==aG.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>cie?await s:u>uie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await ih.signalSchemaChange(new oh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){Rn.error("Error in indexing",n)}}function _ie({table:e,database:t}){let r=ru({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function KR(e){FA.push(e)}function _f(){let e=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||cG,n={startingOffset:32};return t&&(n.dictionary=ch.readFileSync(t)),r&&(n.threshold=r),e&&n}var Et,nh,sh,Ze,en,tc,vo,HA,Dt,ch,xA,oG,ih,oh,ql,Rn,aG,GA,uh,cG,Ur,nt,ec,FA,ah,Li,rc,cie,uie,Re=ge(()=>{Et=B(re()),nh=B(ct()),sh=require("lmdb"),Ze=require("path"),en=require("fs"),tc=B(Qe());nE();vo=B(Dc()),HA=B(Lc()),Dt=B(U()),ch=B(require("fs-extra")),xA=require("../../index"),oG=B(Mr()),ih=B(Os()),oh=B(Ln()),ql=require("worker_threads"),Rn=B(Y()),aG=B(rt());Zs();Cc();GA="data",uh=Symbol("defined-tables"),cG=((0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,Et.initSync)();Ur=Object.create(null),nt=Object.create(null);(0,xA._assignPackageExport)("databases",nt);(0,xA._assignPackageExport)("tables",Ur);ec=Symbol.for("next-table-id"),FA=[],Li=new Map;a(aie,"getTables");a(dr,"getDatabases");a(Fu,"resetDatabases");a(Fl,"readMetaDb");a(uG,"ensureDB");a(lG,"setTable");a(ru,"database");a(sS,"dropDatabase");a(ut,"table");cie=1e3,uie=10;a(lie,"runIndexing");a(_ie,"dropTableMeta");a(KR,"onUpdatedTable");a(_f,"getDefaultCompression")});var Q=R((Ype,bG)=>{"use strict";var Mi=require("path"),hG=require("fs-extra"),Ir=Y(),_G=require("fs-extra"),lh=require("os"),die=require("net"),fie=require("recursive-iterator"),at=U(),Eie=IO(),dG=require("papaparse"),_h=require("moment"),{inspect:hie}=require("util"),fG=require("is-number"),$pe=require("lodash"),mie=require("minimist"),pie=require("https"),Sie=require("http"),{hdb_errors:dh}=ne(),Tie=/^((\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)))$/,mG=require("util").promisify(setTimeout),gie=100,Rie=5,Aie="",Oie=4,EG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};bG.exports={isEmpty:tn,isEmptyOrZeroLength:Es,arrayHasEmptyValues:Nie,arrayHasEmptyOrZeroLengthValues:Iie,buildFolderPath:wie,isBoolean:pG,errorizeMessage:bie,stripFileExtension:Die,autoCast:Lie,autoCastJSON:SG,autoCastJSONDeep:kA,removeDir:Mie,compareVersions:Uie,isCompatibleDataVersion:Pie,escapeRawValue:vie,unescapeValue:Bie,stringifyProps:Hie,timeoutPromise:Gie,isClusterOperation:qie,getClusterUser:Vie,checkGlobalSchemaTable:kie,getHomeDir:gG,getPropsFilePath:xie,promisifyPapaParse:$ie,removeBOM:RG,createEventPromise:Yie,checkProcessRunning:Kie,checkSchemaTableExist:Wie,checkSchemaExists:AG,checkTableExists:OG,getStartOfTomorrowInSeconds:Qie,getLimitKey:zie,isObject:Cie,isNotEmptyAndHasValue:yie,autoCasterIsNumberCheck:TG,backtickASTSchemaItems:Jie,isPortTaken:Fie,createForkArgs:jie,autoCastBoolean:Xie,async_set_timeout:mG,getTableHashAttribute:Zie,doesSchemaExist:eoe,doesTableExist:toe,stringifyObj:roe,ms_to_time:noe,changeExtension:soe,getEnvCliRootPath:VA,noBootFile:ioe,httpRequest:ooe,transformReq:aoe,convertToMS:coe,PACKAGE_ROOT:at.PACKAGE_ROOT};function bie(e){return e instanceof Error?e:new Error(e)}a(bie,"errorizeMessage");function tn(e){return e==null}a(tn,"isEmpty");function yie(e){return!tn(e)&&(e||e===0||e===""||pG(e))}a(yie,"isNotEmptyAndHasValue");function Es(e){return tn(e)||e.length===0||e.size===0}a(Es,"isEmptyOrZeroLength");function Nie(e){if(tn(e))return!0;for(let t=0;t<e.length;t++)if(tn(e[t]))return!0;return!1}a(Nie,"arrayHasEmptyValues");function Iie(e){if(Es(e))return!0;for(let t=0;t<e.length;t++)if(Es(e[t]))return!0;return!1}a(Iie,"arrayHasEmptyOrZeroLengthValues");function wie(...e){try{return e.join(Mi.sep)}catch{console.error(e)}}a(wie,"buildFolderPath");function pG(e){return tn(e)?!1:e===!0||e===!1}a(pG,"isBoolean");function Cie(e){return tn(e)?!1:typeof e=="object"}a(Cie,"isObject");function Die(e){return Es(e)?Aie:e.slice(0,-Oie)}a(Die,"stripFileExtension");function Lie(e){return tn(e)||e===""||typeof e!="string"?e:EG[e]!==void 0?EG[e]:TG(e)===!0?Number(e):Tie.test(e)?new Date(e):e}a(Lie,"autoCast");function SG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(SG,"autoCastJSON");function kA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=kA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=kA(r);n!==r&&(e[t]=n)}return e}else return SG(e)}a(kA,"autoCastJSONDeep");function TG(e){if(e.startsWith("0.")&&fG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&fG(e))}a(TG,"autoCasterIsNumberCheck");async function Mie(e){if(Es(e))throw new Error(`Directory path: ${e} does not exist`);try{await _G.emptyDir(e),await _G.remove(e)}catch(t){throw Ir.error(`Error removing files in ${e} -- ${t}`),t}}a(Mie,"removeDir");function Uie(e,t){if(Es(e)){Ir.info("Invalid current version sent as parameter.");return}if(Es(t)){Ir.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(Uie,"compareVersions");function Pie(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Pie,"isCompatibleDataVersion");function vie(e){if(tn(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(vie,"escapeRawValue");function Bie(e){if(tn(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(Bie,"unescapeValue");function Hie(e,t){if(tn(e))return Ir.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+lh.EOL}!Es(n)&&n[0]===";"?r+=" "+n+s+lh.EOL:Es(n)||(r+=n+"="+s+lh.EOL)}catch{Ir.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Hie,"stringifyProps");function gG(){let e;try{e=lh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(gG,"getHomeDir");function xie(){let e=Mi.join(gG(),at.HDB_HOME_DIR_NAME,at.BOOT_PROPS_FILE_NAME);return hG.existsSync(e)||(e=Mi.join(__dirname,"../","hdb_boot_properties.file")),e}a(xie,"getPropsFilePath");function Gie(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Gie,"timeoutPromise");async function Fie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=die.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Fie,"isPortTaken");function qie(e){try{return at.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ir.error(`Error checking operation against cluster ops ${t}`)}return!1}a(qie,"isClusterOperation");function kie(e,t){let r=(Re(),ie(qe)).getDatabases();if(!r[e])return dh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return dh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(kie,"checkGlobalSchemaTable");function Vie(e,t){if(tn(t)){Ir.warn("No CLUSTERING_USER defined, clustering disabled");return}if(tn(e)||Es(e)){Ir.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Ir.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Ir.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Vie,"getClusterUser");function $ie(){dG.parsePromise=function(e,t,r){return new Promise(function(n,s){dG.parse(e,{header:!0,transformHeader:RG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a($ie,"promisifyPapaParse");function RG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(RG,"removeBOM");function Yie(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Ir.info(`Got cluster status event response: ${hie(s)}`);try{i.cancel()}catch{Ir.error("Error trying to cancel timeout.")}n(s)})})}a(Yie,"createEventPromise");async function Kie(e){let t=!0,r=0;do await mG(gie*r++),(await Eie.findPs(e)).length>0&&(t=!1);while(t&&r<Rie);if(t)throw new Error(`process ${e} was not started`)}a(Kie,"checkProcessRunning");function Wie(e,t){let r=AG(e);if(r)return r;let n=OG(e,t);if(n)return n}a(Wie,"checkSchemaTableExist");function AG(e){let{getDatabases:t}=(Re(),ie(qe));if(!t()[e])return dh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(AG,"checkSchemaExists");function OG(e,t){let{getDatabases:r}=(Re(),ie(qe));if(!r()[e][t])return dh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(OG,"checkTableExists");function Qie(){let e=_h().utc().add(1,at.MOMENT_DAYS_TAG).startOf(at.MOMENT_DAYS_TAG).unix(),t=_h().utc().unix();return e-t}a(Qie,"getStartOfTomorrowInSeconds");function zie(){return _h().utc().format("DD-MM-YYYY")}a(zie,"getLimitKey");function Jie(e){try{let t=new fie(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){Ir.error("Got an error back ticking items."),Ir.error(t)}}a(Jie,"backtickASTSchemaItems");function jie(e){return[e]}a(jie,"createForkArgs");function Xie(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Xie,"autoCastBoolean");function Zie(e,t){let{getDatabases:r}=(Re(),ie(qe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Zie,"getTableHashAttribute");function eoe(e){let{getDatabases:t}=(Re(),ie(qe));return t()[e]!==void 0}a(eoe,"doesSchemaExist");function toe(e,t){let{getDatabases:r}=(Re(),ie(qe));return r()[e]?.[t]!==void 0}a(toe,"doesTableExist");function roe(e){try{return JSON.stringify(e)}catch{return e}}a(roe,"stringifyObj");function noe(e){let t=_h.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(noe,"ms_to_time");function soe(e,t){let r=Mi.basename(e,Mi.extname(e));return Mi.join(Mi.dirname(e),r+t)}a(soe,"changeExtension");function VA(){if(process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=mie(process.argv);if(e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(VA,"getEnvCliRootPath");var qA;function ioe(){if(qA)return qA;let e=VA();VA()&&hG.pathExistsSync(Mi.join(e,at.HDB_CONFIG_FILE))&&(qA=!0)}a(ioe,"noBootFile");function ooe(e,t){let r;return e.protocol==="http:"?r=Sie:r=pie,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(ooe,"httpRequest");function aoe(e){if(!e.schema&&!e.database){e.schema=at.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(aoe,"transformReq");function coe(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(coe,"convertToMS")});var $A=U(),yG=Q(),kl=Y(),uoe=As(),loe=xr(),_oe=bR(),{start:doe}=(YR(),ie(bE)),{closeConnection:foe}=St(),NG=require("moment"),IG=iE(),{cloneDeep:Eoe}=require("lodash"),hoe=process.env[$A.PROCESS_NAME_ENV_PROP],Bo=hoe.substring(4);a(async function(){let t={id:Bo,request:void 0},r=0;try{kl.notify("Starting job:",Bo),doe(),uoe.setSchemaDataToGlobal(),await loe.setUsersToGlobal();let n=await IG.getJobById(Bo);if(yG.isEmptyOrZeroLength(n))throw new Error(`Unable to find a record in hdb_job for job: ${Bo}`);let{request:s}=n[0];if(yG.isEmptyOrZeroLength(s))throw new Error("Did not find job request in hdb_job table, unable to proceed");s=Eoe(s);let i=_oe.getOperationFunction(s);kl.trace("Running operation:",s.operation,"for job",Bo);let o=await i.job_operation_function(s);kl.trace("Result from job:",Bo,o),t.status=$A.JOB_STATUS_ENUM.COMPLETE,t.message=o,t.end_datetime=NG().valueOf(),kl.notify("Successfully completed job:",Bo)}catch(n){r=1,kl.error(n),t.status=$A.JOB_STATUS_ENUM.ERROR,t.message=n.message?n.message:n,t.end_datetime=NG().valueOf()}finally{await IG.updateJob(t),await foe(),setTimeout(()=>{process.exit(r)},3e3).unref()}},"job")();
|
|
31
|
+
`))}},25).unref()}o.close?.(()=>{if(Ce.get(ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&IE()==0)try{CH(Ce.get(ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,yE),o.cantCleanupProperly||nr.warn("Had to forcefully exit the thread",yE),process.exit(0)},5e3).unref()})}if(xH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){nr.info("Could not close debugger",i)}}}).ref();let e=[];if(DH&&!Kne)for(let t in _s){let r=_s[t];if(isNaN(t)&&IE()==0){Hne(t)&&CH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),nr.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=DH(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),nr.trace("Listening on port "+t,yE)}).on("error",i)}))}Promise.all(e).then(()=>{bl?.postMessage({type:ft.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(GH,"startServers");PH||GH();function jR(e,t,r){let n=e?.read?e:new Mne({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=_s[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=_s[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(nr.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(jR,"deliverSocket");var MH=new Map;function zne(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=MH.get(s),r){case"connection":i=jR(void 0,t),MH.set(s,i),i.write=(c,u,_)=>(bl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(bl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),bl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(zne,"proxyRequest");function XR(e,t,r=!0){!+t&&t!==Ce.get(ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(Ce.get(ft.CONFIG_PARAMS.HTTP_PORT),10));let n=_s[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",UH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else _s[t]=e;e.on("unhandled",UH)}a(XR,"registerServer");function FH(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=[],Ce.get(ft.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:Ce.get(ft.CONFIG_PARAMS.HTTP_PORT),secure:Ce.get(ft.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),Ce.get(ft.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:Ce.get(ft.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&Ce.get(ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:Ce.get(ft.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(FH,"getPorts");function ZR(e,t){for(let{port:r,secure:n}of FH(t))qH(r,n,t?.isOperationsServer),typeof e=="function"?zR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,XR(e,r,!1)),wE[r]=JR(zR,r),Wne=JR(Qne,r)}a(ZR,"httpServer");function qH(e,t,r){if(!Ii[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:Ce.get(n+"_keepAliveTimeout"),headersTimeout:Ce.get(n+"_headersTimeout"),requestTimeout:Ce.get(n+"_timeout")},i=Ce.get(n+"_mtls"),o=Ce.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=Ce.get(n+"tls_privateKey"),_=Ce.get(n+"tls_certificate"),l=Ce.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:Ka(u),ciphers:Ce.get("tls_ciphers"),cert:Ka(_),ca:l&&Ka(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:Fne(),maxHeaderSize:Ce.get(ft.CONFIG_PARAMS.HTTP_MAXHEADERSIZE)})}let c=$ne();Ii[e]=(t?Bne:Pne)(s,async(u,_)=>{try{let d=performance.now(),f=new BH(u,_);r&&(f.isOperationsServer=!0);let E=await wE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=kH(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 v of E.headers||[])_.setHeader(v[0],v[1]);return u.baseRequest=f,_.baseResponse=E,Ii[e].emit("unhandled",u,_)}let h=E.status||200,S=performance.now(),p=S-d,T=E.body,b;if(!E.handlesHeaders){let v=E.headers||new vH;T?T.length>=0&&(typeof T=="string"?v.set("Content-Length",Buffer.byteLength(T)):v.set("Content-Length",T.length),b=!0):(v.set("Content-Length","0"),b=!0);let P=`hdb;dur=${p.toFixed(2)}`;E.wasCacheMiss&&(P+=", miss"),kne(v,"Server-Timing",P,!0),_.writeHead(h,v&&(v[Symbol.iterator]?Array.from(v):v)),b&&_.end(T)}let g=f.handlerPath,L=f.method;if(Ol(p,"duration",g,L,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),Vne(h<400,"success",g,L),!b)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let v=0;T.on("data",P=>{v+=P.length}),T.on("end",()=>{Ol(performance.now()-S,"transfer",g,L),Ol(v,"bytes-sent",g,L)})}else T?.then?T.then(v=>{_.end(v)},l):_.end(T)}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?nr.warn(d):nr.info(d):nr.error(d)}a(l,"onError")}),i&&(Ii[e].mtlsConfig=i),t&&(Ii[e].on("secureConnection",u=>{u._parent.startTime&&Ol(performance.now()-u._parent.startTime,"tls-handshake",e),Ol(u.isSessionReused(),"tls-reused",e)}),Ii[e].isSecure=!0),XR(Ii[e],e)}return Ii[e]}a(qH,"getHTTPServer");function JR(e,t){let r=kH;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(JR,"makeCallbackChain");function kH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new vH}}a(kH,"unhandled");function Jne(e,t){ZR(e,{requestOnly:!0,...t})}a(Jne,"onRequest");function jne(e,t){let r;if(t.securePort){let n=Ce.get("tls_privateKey"),s=Ce.get("tls_certificate"),i=t.mtls?.certificateAuthority||Ce.get("tls_certificateAuthority");r=Gne({ciphers:Ce.get("tls_ciphers"),key:Ka(n),cert:Ka(s),ca:i&&Ka(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),_s[t.securePort]=r}return t.port&&(r=Une(e),_s[t.port]=r),r}a(jne,"onSocket");Object.defineProperty(vne.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Xne(e,t){let r;for(let{port:n,secure:s}of FH(t)){NE[n]||(NE[n]=new xne({server:r=qH(n,s)}),NE[n].on("connection",async(c,u)=>{try{let _=new BH(u);_.isWebSocket=!0;let l=wE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=QR[n];if(d){let E;for(let h=0;h<f.length;h++){let S=f[h];S.protocol===d&&(E=!0,S.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(_){nr.warn("Error handling WebSocket connection",_)}}),NE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=QR[n];o||(o=QR[n]=[]),o.push({listener:e,protocol:i}),wE[n]=JR(zR,n)}return r}a(Xne,"onWebSocket");function UH(e,t){t.writeHead(404),t.end(`Not found
|
|
32
|
+
`)}a(UH,"defaultNotFound")});async function WH({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await tA.get(e,{returnNonexistent:!0});s=new sA(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await tA.get(e);i&&i.delete()}s=new LE(e,t)}return n&&(n.id=e,n.user={username:t?.username},yl.put(n)),s}function rA(){return DE++,DE>65500&&(DE=1),DE}function nA(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Ti.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var $H,wi,YH,KH,tA,yl,DE,LE,sA,QH=ge(()=>{Re();Wu();$H=B(Pr()),wi=B(Y());to();YH=B(rt()),KH=B(VH());cr();tA=ut({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),yl=ut({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,YH.getWorkerIndex)()===0&&(async()=>{await KH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of yl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await tt.getUser(r.user.username)),ze(r,()=>{try{nA(r,t,r)}catch{(0,wi.warn)("Failed to publish will",t)}yl.delete(e.id,r)})}})();a(WH,"getSession");DE=1;a(rA,"getNextMessageId");LE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,wi.trace)("Resuming subscription from",s,"from",o);let E=Ti.getMatch(_);if(!E){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let T=f.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,T.indexOf("+")===T.length-1)f.onlyChildren=!0,f.url="/"+T.slice(0,T.length-1);else{let b=T.split("/"),g;for(let P=0;P<b.length;P++)if(b[P].indexOf("+")>-1)if(b[P]==="+")g=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&g)throw new Error("Filters can not be combined");let L=!0;b[b.length-1]==="#"&&(b.length--,L=!1),g&&(n=a(P=>{let k=P.id;if(!Array.isArray(k)||L&&k.length!==b.length)return!1;for(let H=0;H<b.length;H++)if(b[H]!=="+"&&b[H]!==k[H])return!1;return!0},"filter"));let v=b.indexOf("+");f.url="/"+(v>-1?b.slice(0,v):b).concat("").join("/")}}let h=E.path,S=E.Resource,p=await ze(f,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let b=await S.subscribe(f,T);if(!b)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!b[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let g of b)try{let L;if(g.type&&g.type!=="put"&&g.type!=="delete"&&g.type!=="message"&&g.type!=="patch"||n&&!n(g))continue;r?(g.topic=s,L=this.needsAcknowledge(g)):(g.acknowledge?.(),L=rA());let v=g.id;Array.isArray(v)&&(v=Oa(v)),v==null&&(v=""),this.listener(h+"/"+v,g.value,L,t)}catch(L){(0,wi.warn)(L)}})(),b});return p.topic=s,p.qos=t.qos,this.subscriptions.push(p),p}resume(){}needsAcknowledge(t){let r=rA();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return nA(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){let r=this.createContext();ze(r,async()=>{if(!t){let n=await yl.get(this.sessionId);n?.doesExist()&&await nA(n,n.data,r)}await yl.delete(this.sessionId)}).catch(n=>{(0,wi.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(nA,"publish");sA=class extends LE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=rA(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,wi.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,$H.getNextMonotonicTime)()),(0,wi.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),tA.put(this.sessionRecord)}}});var oA={};Fe(oA,{bypassAuth:()=>Zne,start:()=>ese});function Zne(){XH=!0}function ese({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){sr.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:f,onClose:E}=JH(_,(h,S)=>{if(_.send(h),S&&_._socket.writableNeedDrain)return new Promise(p=>this._socket.once("drain",p))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{sr.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(sr.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let E=u.user;if(E!==null){(E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN);try{l=await e.getUser(E,null,null),(0,Wa.get)(Qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&UE.notify({username:l?.username,status:Qt.AUTH_AUDIT_STATUS.SUCCESS,type:Qt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Wa.get)(Qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&UE.error({username:E,status:Qt.AUTH_AUDIT_STATUS.FAILURE,type:Qt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else sr.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(E){sr.error(E)}else if(u.required)return sr.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&XH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,jH.getSuperUser)(),sr.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:f}=JH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{sr.info("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function JH(e,t,r,n,s){zH||(zH=!0,_u(d=>{ME>0&&d.push({metric:"mqtt-connections",connections:ME,byThread:!0})}));let i;ME++;let o,c={protocolVersion:4},u=(0,PE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){ME--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),cn(!1,"connection","mqtt","disconnect"),sr.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await tt.getUser(d.username,d.password.toString(),r),(0,Wa.get)(Qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&UE.notify({username:n?.username,status:Qt.AUTH_AUDIT_STATUS.SUCCESS,type:Qt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,Wa.get)(Qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&UE.error({username:d.username,status:Qt.AUTH_AUDIT_STATUS.FAILURE,type:Qt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return cn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let g=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?g(d.will.payload):void 0,delete d.will.payload}o=WH({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(g){return sr.error(g),cn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:g.code||5,returnCode:g.code||128})}cn(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((g,L,v,P)=>{try{let k=g.indexOf("/",1),H=k>0?g.slice(0,k):g;f({cmd:"publish",topic:g,payload:E(L),messageId:v||Math.floor(Math.random()*1e8),qos:P.qos},H)}catch(k){sr.error(k),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let g of d.subscriptions){let L;try{L=(await o.addSubscription(g,g.qos>=1)).qos||0}catch(v){sr.error(v),L=c.protocolVersion<5?128:v.statusCode===403?135:v.statusCode===404?143:128}h.push(L)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let g=[];for(let L of d.unsubscriptions)g.push(o.removeSubscription(L)?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 S=d.qos===2?"pubrec":"puback",p=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type"))),T=d.payload?.length>0?p(d.payload):void 0,b;try{b=await o.publish(d,T)}catch(g){sr.warn(g),d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:b===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),cn(!0,"connection","mqtt","disconnect"),sr.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(h){sr.error(h),f({cmd:"disconnect"})}function f(h,S){let p=(0,PE.generate)(h,c);t(p),$r(p.length,"bytes-sent",S,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ri(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var PE,jH,Wa,Qt,iA,UE,sr,XH,zH,ME,ZH=ge(()=>{PE=require("mqtt-packet");QH();jH=B(Fr());ya();Is();cr();Wa=B(re()),Qt=B(U()),iA=B(Y()),UE=(0,iA.loggerWithTag)("auth-event"),sr=(0,iA.loggerWithTag)("mqtt"),XH=(0,Wa.get)(Qt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Zne,"bypassAuth");a(ese,"start");ME=0;a(JH,"onSocket")});var If={};Fe(If,{component_errors:()=>za,loadComponent:()=>vE,loadComponentDirectories:()=>cx,setErrorReporter:()=>sse});function cx(e,t){t&&(cA=t),e&&(uA=e);let r=[];if((0,Fn.existsSync)(aA)){let s=(0,Fn.readdirSync)(aA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ot.join)(aA,o);r.push(vE(c,cA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(vE(n,cA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{ax=!0})}function sse(e){Il=e}async function vE(e,t,r,n,s,i){if(!tx.has(e)){tx.set(e,!0),s&&(uA=s);try{let o;n&&(za=new Map);let c=(0,Ot.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Fn.existsSync)(c)?o=n?(0,ox.getConfigObj)():(0,rx.parseDocument)((0,Fn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=lA;let u=[],_=n;for(let l in o){let d=o[l];if(za.set(n?l:(0,Ot.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let b=e,g;for(;!(0,Fn.existsSync)(g=(0,Ot.join)(b,"node_modules",l));)if(b=(0,Ot.dirname)(b),b.length<(0,ix.getHdbBasePath)().length){g=null;break}if(g)f=await vE(g,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=nse[l];if(!f)continue;u.push(f);let h=a(b=>(b.origin=r,ut(b)),"ensureTable"),S=d.network||(d.port||d.securePort)&&d,p=S?.securePort||S?.https&&S.port,T=!S?.https&&S?.port;if(Qa.isMainThread&&(f=await f.startOnMainThread?.({server:tt,ensureTable:h,port:T,securePort:p,resources:t,...d})||f,n&&S))for(let b of[T,p])try{if(+b&&!ex.includes(b)){let g=_A.get(dA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&Nl.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!TE)&&(ex.push(b),hH(b,g))}}catch(g){console.error("Error listening on socket",b,g,l)}if(t.isWorker&&(f=await f.start?.({server:tt,ensureTable:h,port:T,securePort:p,resources:t,...d})||f),uA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,sx.handleHDBError)("Can not reference parent directories");let b=(0,Ot.join)(e,d.files).replace(/\\/g,"/"),g=b.indexOf("/*");if(g>-1&&d.files!==lA[l]?.files&&!(0,Fn.existsSync)(b.slice(0,g)))throw new Error(`The path '${b.slice(0,g)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let L=(0,Ot.basename)(e),v=d.path||"/";v=v.startsWith("/")?v:v.startsWith("./")?"/"+L+v.slice(2):v==="."?"/"+L:"/"+L+"/"+v;let P,k,H;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",k=(0,Ot.join)(e,z)}else(H=b.indexOf("/*"))>-1&&(k=b.slice(0,H+1),P=(0,Ot.relative)(e,k));let j=!1;if(Qa.isMainThread&&f.setupDirectory&&(j=await f.setupDirectory?.(v,k,t)),t.isWorker&&f.handleDirectory&&(j=await f.handleDirectory?.(v,k,t)),j)continue;for(let z of await(0,nx.default)(b,{onlyFiles:!1,objectMode:!0})){let{path:J,dirent:me}=z;_=!0;let ce=(0,Ot.relative)(e,J).replace(/\\/g,"/");if(P)if(ce.startsWith(P))ce=ce.slice(P.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 de=v+(v.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let Le=await rse(J);Qa.isMainThread&&await f.setupFile?.(Le,de,J,t),t.isWorker&&await f.handleFile?.(Le,de,J,t)}else Qa.isMainThread&&await f.setupDirectory?.(de,J,t),t.isWorker&&await f.handleDirectory?.(de,J,t)}catch(Le){Le.message=`Could not load ${me.isFile()?"file":"directory"} '${J}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Le.message}`,Il?.(Le),((0,Ja.getWorkerIndex)()===0?console:Nl.default).error(Le),t.set(d.path||"/",new wl(Le)),za.set(n?l:(0,Ot.basename)(e),Le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Ot.basename)(e)}' due to: ${h.message}`,Il?.(h),((0,Ja.getWorkerIndex)()===0?console:Nl.default).error(h),t.set(d.path||"/",new wl(h),null,!0),za.set(n?l:(0,Ot.basename)(e),h.message)}}if(Qa.isMainThread&&!ax&&i&&(0,Ja.watchDir)(e,async()=>cx()),o.extensionModule)return await d_((0,Ot.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;Il?.(new Error(l)),((0,Ja.getWorkerIndex)()===0?console:Nl.default).error(l),za.set((0,Ot.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Il?.(o),t.set("",new wl(o))}}}var Fn,Ot,Qa,rx,_A,dA,nx,Ja,Nl,sx,ix,tse,ox,rse,aA,uA,ax,cA,za,nse,lA,ex,tx,Il,wl,wf=ge(()=>{Fn=require("fs"),Ot=require("path"),Qa=require("worker_threads"),rx=require("yaml"),_A=B(re()),dA=B(U());Nb();Db();Lb();S0();sH();lH();nx=B(require("fast-glob")),Ja=B(rt()),Nl=B(Y());Kh();cr();sx=B(ne());In();Re();mH();ix=B(re()),tse=B(RH());Tf();KR();ZH();ox=B(lr());gE();({readFile:rse}=Fn.promises),aA=_A.get(dA.CONFIG_PARAMS.COMPONENTSROOT),uA=new Map,za=new Map;a(cx,"loadComponentDirectories");nse={REST:Yf,rest:Yf,graphqlSchema:Yh,jsResource:Qh,fastifyRoutes:LR,login:Jh,static:MR,operationsApi:tse,customFunctions:{},http:{},clustering:bE,authentication:zu,mqtt:oA},lA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(lA,"static",{value:{files:"web/**"}});ex=[],tx=new Map;a(sse,"setErrorReporter");a(vE,"loadComponent");wl=class extends qt{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 eA=R((Qme,lx)=>{var{isMainThread:ux}=require("worker_threads"),{getTables:ise}=(Re(),ie(qe)),{loadComponentDirectories:ose,loadComponent:ase}=(wf(),ie(If)),{resetResources:cse}=(Wu(),ie(IP)),use=_g(),lse=lr(),{dirname:_se}=require("path"),{getConnection:dse}=St(),fse=re(),Ese=U(),fA=new Map;async function hse(e=!1){!ux&&fse.get(Ese.CONFIG_PARAMS.CLUSTERING_ENABLED)&&dse();try{ux&&await use()}catch(n){console.error(n)}let t=cse();ise(),t.isWorker=e,await ase(_se(lse.getConfigFilePath()),t,"hdb",!0,fA),await ose(fA,t);let r=[];for(let[n]of fA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(hse,"loadRootComponents");lx.exports.loadRootComponents=hse});var rt=R((Jme,Di)=>{"use strict";var{Worker:mse,MessageChannel:pse,parentPort:ds,isMainThread:SA,threadId:Sse,workerData:$s}=require("worker_threads"),{PACKAGE_ROOT:Tse}=U(),{join:Ex,isAbsolute:gse,extname:Rse}=require("path"),{server:hx}=(cr(),ie(Bi)),{watch:Ase,readdir:Ose}=require("fs/promises"),{totalmem:_x}=require("os"),Cl=U(),mx=re(),Ys=Y(),{randomBytes:bse}=require("crypto"),{_assignPackageExport:yse}=require("../../index"),Nse=U(),dx=1024*1024,Ci=[],mn=[],Ise=50,TA=1e4,wse="restart",px="request_thread_info",Sx="resource_report",Tx="thread_info",gx="added-port",Cse="ack",EA;yse("threads",mn);Di.exports={startWorker:hA,restartWorkers:RA,shutdownWorkers:Pse,workers:Ci,setMonitorListener:kse,onMessageFromWorkers:vse,onMessageByType:Ix,broadcast:Hse,broadcastWithAcknowledgement:Gse,setChildListenerByType:Use,getWorkerIndex:Rx,getWorkerCount:Ax,getTicketKeys:bx,setMainIsWorker:Lse,setTerminateTimeout:Dse,restartNumber:$s?.restartNumber||1};mn.onMessageByType=Ix;mn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=mn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var gA;function Dse(e){TA=e}a(Dse,"setTerminateTimeout");function Rx(){return $s?$s.workerIndex:gA?0:void 0}a(Rx,"getWorkerIndex");function Ax(){return $s?$s.workerCount:gA?1:void 0}a(Ax,"getWorkerCount");function Lse(e){gA=e}a(Lse,"setMainIsWorker");var Ox=1,BE;function bx(){return BE||(BE=SA?bse(48):$s.ticketKeys,BE)}a(bx,"getTicketKeys");Object.defineProperty(hx,"workerIndex",{get(){return Rx()}});Object.defineProperty(hx,"workerCount",{get(){return Ax()}});var yx={[px](e,t){Fse(t)},[Sx](e,t){qse(t,e)}};function hA(e,t={}){let r=process.constrainedMemory?.()||_x();r=Math.min(r,_x(),2e4*dx);let n=mx.get(Cl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/dx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of mn){let _=new pse;_.existingPort=u,i.push(_),o.push(_.port2)}Rse(e)||(e+=".js");let c=new mse(gse(e)?e:Ex(Tse,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Ox=t.threadCount,name:t.name,restartNumber:Di.exports.restartNumber,ticketKeys:bx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:gx,port:u,threadId:c.threadId},[u]);return xE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>hA(e,t),c.on("error",u=>{console.error("Worker error:",u),Ys.error("Worker error:",u)}),c.on("exit",u=>{Ci.splice(Ci.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Ise?(t.unexpectedRestarts=c.unexpectedRestarts+1,hA(e,t)):Ys.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{yx[u.type]?.(u,c)}),Ci.push(c),$se(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(hA,"startWorker");var Mse=[Cl.THREAD_TYPES.HTTP];async function RA(e=null,t=Math.max(Ox>3,1),r=!0){if(SA){if(r){let{loadRootComponents:o}=eA();await o()}Di.exports.restartNumber++,t<1&&(t=t*Ci.length);let n=[],s=[];for(let o of Ci.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ys.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Di.exports.restartNumber,type:Cl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Mse.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),TA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===Nse.ITC_EVENT_TYPES.CHILD_STARTED&&(Ys.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");Ys.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=hf();r&&(e==="http"||!e)&&mx.get(Cl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ds.postMessage({type:wse,workerType:e})}a(RA,"restartWorkers");function Use(e,t){yx[e]=t}a(Use,"setChildListenerByType");function Pse(e){return RA(e,1/0,!1)}a(Pse,"shutdownWorkers");var Nx=[];function vse(e){Nx.push(e)}a(vse,"onMessageFromWorkers");var mA=new Map;function Ix(e,t){let r=mA.get(e);r||mA.set(e,r=[]),r.push(t)}a(Ix,"onMessageByType");var Bse=10;async function Hse(e){let t=0;for(let r of mn)try{r.postMessage(e),t++>Bse&&(t=0,await new Promise(setImmediate))}catch(n){Ys.error("Unable to send message to worker",n)}}a(Hse,"broadcast");var HE=new Map,xse=1;function Gse(e){return new Promise(t=>{let r=0;for(let n of mn)try{let s=xse++,i=a(()=>{HE.delete(s),--r===0&&t(),n!==ds&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,HE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of HE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ys.error("Unable to send message to worker",s)}r===0&&t()})}a(Gse,"broadcastWithAcknowledgement");function Fse(e){e.postMessage({type:Tx,workers:wx()})}a(Fse,"sendThreadInfo");function wx(){let e=Date.now();return Ci.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(wx,"getChildWorkerInfo");function qse(e,t){e.resources=t,e.resources.updated=Date.now()}a(qse,"recordResourceReport");var pA;function kse(e){pA=e}a(kse,"setMonitorListener");var Vse=1e3,fx=!1;function $se(){fx||(fx=!0,setInterval(()=>{for(let e of Ci){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}pA&&pA()},Vse).unref())}a($se,"startMonitoring");var Yse=1e3;if(ds){xE(ds);for(let e=0,t=$s.addPorts.length;e<t;e++){let r=$s.addPorts[e];r.threadId=$s.addThreadIds[e],xE(r)}setInterval(()=>{let e=process.memoryUsage();ds.postMessage({type:Sx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Yse).unref(),EA=a(()=>new Promise((e,t)=>{ds.on("message",r),ds.postMessage({type:px});function r(n){n.type===Tx&&(ds.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else EA=wx;Di.exports.getThreadInfo=EA;function xE(e,t){mn.push(e),e.on("message",r=>{if(r.type===gx)r.port.threadId=r.threadId,xE(r.port);else if(r.type===Cse){let n=HE.get(r.id);n&&n()}else{for(let s of Nx)s(r,e);let n=mA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ys.error(i)}}}).on("close",()=>{mn.splice(mn.indexOf(e),1)}).on("exit",()=>{mn.splice(mn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(xE,"addPort");if(SA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await Ose(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Ex(n,i.name));try{for await(let{filename:i}of Ase(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await RA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");Di.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else ds.on("message",async e=>{let{type:t}=e;t===Cl.ITC_EVENT_TYPES.SHUTDOWN&&(Di.exports.restartNumber=e.restartNumber,ds.unref(),setTimeout(()=>{Ys.warn("Thread did not voluntarily terminate",Sse),process.exit(0)},TA).unref())})});var gC={};Fe(gC,{AUDIT_STORE_OPTIONS:()=>lf,createAuditEntry:()=>p_,openAuditStore:()=>kE,readAuditEntry:()=>Ut,setAuditRetention:()=>Wse,transactionKeyEncoder:()=>Hx});function kE(e){let t=e.auditStore=e.openDB(Px.AUDIT_STORE_NAME,lf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=GE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-AA})){if((_[0]&15)===yA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Kse){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,AA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,qE.getWorkerIndex)()===(0,qE.getWorkerCount)()-1&&s(GE),t}function Wse(e,t=GE){AA=e,GE=t}function p_(e,t,r,n,s,i,o){let c=xx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?ja.setFloat64(0,n):pn.set(dm),u=9),f(0),f(t),d(r),ja.setFloat64(u,e),u+=8,s?d(s):pn[u++]=0,pn[n?8:0]=c;let l=pn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Xa.writeKey)(E,pn,u);let S=u-h-1;S>127?S>16383?(IA.error("Key or username was too large for audit entry",E),u=h+1,pn[h]=0):(pn.copyWithin(h+2,h+1,u),ja.setUint16(h,S|32768),u++):pn[h]=S}function f(E){E<128?pn[u++]=E:E<16384?(ja.setUint16(u,E|32768),u+=2):E<1056964608?(ja.setUint32(u,E|3221225472),u+=4):(pn[u]=255,ja.setUint32(u+1,E),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new NA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:xx[n&7],tableId:i,get recordId(){return Ux(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Ux(e,l,d):void 0},getValue(f,E,h){if(n&OA||n&bA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&bA&&h)return wA(f.getEntry(this.recordId),h,f)}}}catch(t){return IA.error("Reading audit entry error",t,e),{}}}function Ux(e,t,r){let n=e.subarray(t,r);return(0,Xa.readKey)(n,0,r-t)}var Xa,FE,Px,vx,qE,Bx,IA,pn,ja,Hx,lf,AA,Kse,GE,OA,bA,Cx,yA,Dx,Lx,Mx,xx,NA,Zs=ge(()=>{Xa=require("ordered-binary"),FE=B(re()),Px=B(ct()),vx=B(U()),qE=B(rt()),Bx=B(Q());Dc();IA=B(Y());VE();(0,FE.initSync)();pn=Buffer.alloc(1024),ja=new DataView(pn.buffer,pn.byteOffset,1024),Hx={writeKey(e,t,r){return e===Cc?(t.set(Cc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Xa.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,Xa.readKey)(e,t,r)}},lf={encoding:"binary",keyEncoder:Hx},AA=(0,Bx.convertToMS)((0,FE.get)(vx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Kse=1e3,GE=1e4;a(kE,"openAuditStore");a(Wse,"setAuditRetention");OA=16,bA=32,Cx=1,yA=2,Dx=3,Lx=4,Mx=5,xx={put:Cx|OA,[Cx]:"put",delete:yA,[yA]:"delete",message:Dx|OA,[Dx]:"message",invalidate:Lx,[Lx]:"invalidate",patch:Mx|bA,[Mx]:"patch"};a(p_,"createAuditEntry");a(Ut,"readAuditEntry");NA=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(Ux,"readKeySafely")});var CA={};Fe(CA,{add:()=>$E,applyReverse:()=>Gx,getRecordAtTime:()=>wA,rebuildUpdateBefore:()=>YE});function $E(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function YE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,$E(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function Gx(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Qse[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=Fx}}function wA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ut(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":Gx(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===Fx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ut(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var Qse,Fx,VE=ge(()=>{Zs();a($E,"add");$E.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Qse={add:$E};a(YE,"rebuildUpdateBefore");a(Gx,"applyReverse");Fx={};a(wA,"getRecordAtTime")});function Jr(e){return e[Ct]||(e[Ct]=Object.create(null))}function JE(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[ye])},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 Sn.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Jr(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 Sn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Jr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Sn.ClientError(`${c} must be an object, attempt to assign ${l}`);Jr(this)[c]=l},"set")}_={get(){let l=this[Ct];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[_e]?.[c];return f.update(E)}return f}let d=this[_e]?.[c];if(d&&typeof d=="object"){let f=kx(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,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Ct];return u?.[o]!==void 0?u[o]:this[_e]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Sn.ClientError("Can not add a property to a sealed table schema");Jr(this)[o]=c}),i("deleteProperty",function(o){Jr(this)[o]=void 0}),i("toJSON",function(){let o=this[Ct],c;for(let _ in o){c||(c=Object.assign({},this[_e]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[_e])),Object.assign(c,this)),c||this[_e]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function kx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=s}},JE(r,t)),new r(e)):new KE(e);case Array:let n=new QE(e.length);n[_e]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=kx(o,t?.elements)),n[s]=o}return n;default:return e}}function ad(e){let t=e[Ct],r;for(let s in t){r||(r=Object.assign({},e[_e]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=ad(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[_e])),Object.assign(r,e)),r||e[_e]}function Lo(e,t=e[Ct]){let r;if(qx.call(e,_e)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Lo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[_e]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=CA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Lo(s);r[n]=s}return r?Object.freeze(r):qx.call(e,_e)?e[_e]:e}function WE(e){let t=e[_e];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Do]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[_e]===s){if(WE(i))return!0}else return!0}}else{let r=e[Ct];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[_e]===i){if(WE(s))return!0}else return!0}else return!0}}return!1}var Sn,Ct,KE,qx,Do,QE,zE,cd=ge(()=>{In();Sn=B(ne());VE();Ct=Symbol("own-data");a(Jr,"getChanges");a(JE,"assignTrackedAccessors");a(kx,"trackObject");KE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=t}};JE(KE,{});a(ad,"collapseData");qx=Object.prototype.hasOwnProperty;a(Lo,"deepFreeze");a(WE,"hasChanges");Do=Symbol.for("has-array-changes"),QE=class extends Array{static{a(this,"TrackedArray")}[Do];constructor(t){super(t)}splice(...t){return this[Do]=!0,super.splice(...t)}push(...t){return this[Do]=!0,super.push(...t)}pop(){return this[Do]=!0,super.pop()}unshift(...t){return this[Do]=!0,super.unshift(...t)}shift(){return this[Do]=!0,super.shift()}};QE.prototype.constructor=Array;zE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Mp={};Fe(Mp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Ue,IS_COLLECTION:()=>Tn,RECORD_PROPERTY:()=>_e,Resource:()=>qt,snake_case:()=>Jse,transformForSelect:()=>XE});function Jse(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Vx(e,t){if(Dl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Dl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new LA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Dl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function jr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[ye]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[ye]||i):l=i:(l=s,c=l[Ue]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let S=this.parseQuery(c.slice(E+1));u?u=Object.assign(S,u):u=S,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return ze(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(S=>{if(!S)throw new jE(o.user);return typeof l?.then=="function"?l.then(p=>e(E,u,o,p)):e(E,u,o,l)});if(!h)throw new jE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Xr(e,t){let r=new Kx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function DA(e,t,r){let n=e[_e];if(n){let s=e[Ct];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function XE(e,t){let r=t?.propertyResolvers,n=t[ye],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):DA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(DA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(DA(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=XE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var $x,Yx,Kx,ye,Ue,Tn,_e,zse,qt,jE,Dl,LA,In=ge(()=>{$x=require("crypto");Oc();Yx=require("../../index"),Kx=B(ne());cd();to();Vf();ye=Symbol.for("context"),Ue=Symbol.for("primary-key"),Tn=Symbol("is-collection"),_e=Symbol("stored-record"),zse={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},qt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ue]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=jr(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=XE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=jr(function(t,r,n,s){if(Array.isArray(s)&&t[Tn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Xr(t,"put")},{hasContent:!0,type:"update"});static patch=jr(function(t,r,n,s){return t.patch?t.patch(s,r):Xr(t,"patch")},{hasContent:!0,type:"update"});static delete=jr(function(t,r,n,s){return t.delete?t.delete(r):Xr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,$x.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Xr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=jr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Xr(t,"delete")},{hasContent:!1,type:"update"});static post=jr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=jr(function(t,r,n,s){return t.connect?t.connect(s,r):Xr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=jr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Xr(t,"subscribe")},{type:"read"});static publish=jr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.publish?t.publish(s,r):Xr(t,"publish")},{hasContent:!0,type:"create"});static search=jr(function(t,r,n,s){let i=t.search?t.search(r):Xr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=XE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=jr(function(t,r,n,s){return t.search?t.search(s,r):Xr(t,"search")},{hasContent:!0,type:"read"});static copy=jr(function(t,r,n,s){return t.copy?t.copy(s,r):Xr(t,"copy")},{type:"create"});static move=jr(function(t,r,n,s){return t.move?t.move(s,r):Xr(t,"move")},{type:"delete"});post(t){if(this[Tn])return this.constructor.create(this[Ue],t,this[ye]);Xr(this,"post")}static isCollection(t){return t?.[Tn]}static coerceId(t){return t}static parseQuery(t){return kf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&zse[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:Vx(t,this),isCollection:Dl}}let i=Vx(t,this);return Dl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[ye],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Ue]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Ue],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Tn]=!0),s}subscribe(t){return new Nn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Nn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Ue]}getContext(){return this[ye]}};qt.prototype[ye]=null;(0,Yx._assignPackageExport)("Resource",qt);a(Jse,"snake_case");jE=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(Vx,"pathToId");LA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(jr,"transactional");a(Xr,"missingMethod");a(DA,"selectFromObject");a(XE,"transformForSelect")});function Qx(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;Za||((0,ZE.onMessageByType)(Wx,l=>{zx(l.path)}),Za=Object.create(null));let o=Za[s]||(Za[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Oa(t);let u=new UA(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function zx(e,t){if(!Za)return;let r=Za[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Ut(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Oa(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,MA.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let S;h.supportsTransactions&&h.txnInProgress!==o.version&&(S=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,S)}catch(S){console.error(S),(0,MA.info)(S)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Jx(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,ZE.broadcast)({type:Wx,path:s}),zx(s,!0)})}}var MA,ZE,Wx,Za,Spe,UA,jx=ge(()=>{MA=B(Y()),ZE=B(rt());Oc();Wu();Zs();Wx="transaction",Spe=Buffer.alloc(4096);a(Qx,"addSubscription");UA=class extends Nn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(zx,"notifyFromTransactionData");a(Jx,"listenToCommits")});var ER={};Fe(ER,{coerceType:()=>eh,makeTable:()=>nh,setServerUtilities:()=>iie,updateResource:()=>th});function nh(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:f,evictionMS:E,audit:h,trackDeletes:S}=e,{attributes:p}=e;p||(p=[]),Jx(i,u);let T=hm(i,n,u),b=0,g,L,v={},P=Promise.resolve(),k,H,j;for(let K of p)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(H=K),K.expiresAt&&(j=K),K.isPrimaryKey&&(v=K);let z,J=[],me=[],ce=1,de=2,Le={},Be={},Lt=864e5,Vl,$l,Ks,YA=!1,Eh,hh,wG=i.getRange({start:!1,end:!1}).constructor,CG=10,DG=6;h&&QA();class We extends qt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=H;static propertyResolvers;static sources=[];static get expirationMS(){return f}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),L=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(D=>{let N=this.sources.slice(0,-1);if(N=N.filter(M=>M[D]&&(!M[D].reliesOnPrototype||M.prototype[D])),N.length>0)if(N.length===1){let M=N[0];return(q,C,x)=>{if(q?.source!==M)return M[D](C,x,q)}}else return(M,q,C)=>{let x=[];for(let G of N){if(M?.source===G)break;x.push(G[D](q,C,M))}return Promise.all(x)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(D=>{if(y[D]&&(!y[D].reliesOnPrototype||y.prototype[D]))return(N,M,q)=>{if(!N?.source)return y[D](M,q,N)}},"getApplyToCanonicalSource");return Le={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Be={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let D=!1,N=a(async(M,q)=>{let C=M.value,x=M.table?nt[c][M.table]:We;if(c===kn.SYSTEM_SCHEMA_NAME&&(M.table===kn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||M.table===kn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),M.id===void 0&&(M.id=C[x.primaryKey],M.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(M));M.source=m;let G=await x.getResource(M.id,q,ec);switch(M.type){case"put":return G._writeUpdate(C,!0,ec);case"patch":return G._writeUpdate(C,!1,ec);case"delete":return G._writeDelete(ec);case"publish":return G._writePublish(C,ec);case"invalidate":return G.invalidate(ec);default:Xe.error("Unknown operation",M.type,M.id)}},"writeUpdate");try{let M=m.subscribe;M&&S==null&&(S=!0);let q=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Uo.getWorkerIndex)()):(0,Uo.getWorkerIndex)()===0,C=M&&q&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let x;for await(let G of C)try{if(!(G.type==="transaction"?G.writes[0]:G)){Xe.error("Bad subscription event",G);continue}if(G.source=m,x)if(G.beginTxn)x.resolve();else{N(G,x);continue}if(G.type==="end_txn")continue;let pe=ze(G,()=>{if(G.type==="transaction"){let ee=[];for(let Pe of G.writes)try{ee.push(N(Pe,G))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ae}return Promise.all(ee)}else if(G.type==="define_schema"){let ee=this.attributes.slice(0),Pe;for(let ae of G.attributes)ee.find(Ge=>Ge.name===ae.name)||(ee.push(ae),Pe=!0);Pe&&(ut({table:s,database:c,attributes:ee,origin:"cluster"}),Hl.signalSchemaChange(new xl.SchemaEventMsg(process.pid,kn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,N(G,G),new Promise(ee=>{x.resolve=ee})):N(G,G)});D&&(await pe,Hl.signalUserChange(new xl.UserEventMsg(process.pid))),G.onCommit&&(pe?.then?pe.then(G.onCommit):G.onCommit())}catch(se){Xe.error("error in subscription handler",se)}}}catch(M){Xe.error(M)}})(),this}static getResource(m,A,I){let y=super.getResource(m,A,I);if(m!=null){sc(m);try{if(y.hasOwnProperty(_e))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!I?.async||i.cache?.get(m),D=An(A),N=D.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return mh(m,A,{transaction:N},O,M=>{if(M?th(y,M):y[_e]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new gn.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let q=ph(m,M,A,y);if(q)return D?.disregardReadTxn(),y[PA]=!0,BA(q,C=>(th(y,C),y))}return y})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return y}ensureLoaded(){let m=ph(this[Ue],this[Zr],this[ye]);if(m)return this[PA]=!0,BA(m,A=>{this[Zr]=A,this[_e]=A.value,this[vl]=A.version})}static setTTLExpiration(m){if(typeof m=="number")f=m*1e3,E||(E=0);else if(m&&typeof m=="object")f=m.expiration*1e3,E=(m.eviction||0)*1e3,Lt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");Lt=Lt||(f+E)/4,Th()}static enableAuditing(m=!0){h=m,m&&QA(),We.audit=m}static coerceId(m){return m===""?null:eh(m,v)}static async dropTable(){if(delete nt[c][s],c===o){for(let m of p)l.remove(We.tableName+"/"+m.name),r[m.name]?.drop();l.remove(We.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));Hl.signalSchemaChange(new xl.SchemaEventMsg(process.pid,kn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Tn])return this.search(m);if(this[Ue]===null){if(m?.conditions)return this.search(m);let A=We.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let I=Kl(m);if(I?.read){if(I.isSuperUser)return!0;let y=I.attribute_permissions,O=A?.select;if(y?.length>0||YA&&O){if(A||(A={}),O){let D=y?.length>0&&vA(y,"read");A.select=O.map(N=>{let M=N.name||N;if(!D||D[M]){let q=Ks[M]?.definition?.tableClass;if(q){if(N.name||(N={name:N}),!q.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=y.filter(D=>D.read&&!Ks[D.attribute_name]).map(D=>D.attribute_name);return A}else return!0}}allowUpdate(m,A){let I=Kl(m);if(I?.update){let y=I.attribute_permissions;if(y?.length>0){let O=vA(y,"update");for(let D in A)if(!O[D])return!1;for(let D of y){let N=D.attribute_name;!D.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[Tn]){let I=Kl(m);if(I?.insert){let y=I.attribute_permissions;if(y?.length>0){let O=vA(y,"insert");for(let D in A)if(!O[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Kl(m)?.delete}update(m,A){if(!An(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[Ct]=m):(y=this[Ct],y&&(m=Object.assign(y,m)),this[Ct]=y=m)),this._writeUpdate(this[Ct],A),this}addTo(m,A){if(typeof A=="number")this[Ll]===Zx?this.set(m,(+this.getProperty(m)||0)+A):(this[Ll]||this.update(),this.set(m,new zE(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[ye],I=this[Ue];sc(I),An(this[ye]).addWrite({key:I,store:i,invalidated:!0,entry:this[Zr],nodeName:this[ye]?.nodeName,before:Le.invalidate?.bind(this,A,I),beforeIntermediate:Be.invalidate?.bind(this,A,I),commit:(O,D)=>{if(D?.version>O)return;let N=null;for(let M in r)N||(N={}),N[M]=this.getProperty(M);T(I,N,this[Zr],O,Ml,h,this[ye],0,"invalidate")}})}static evict(m,A,I){let y=this.Source,O;if(!((L||h)&&(!A||(O=i.getEntry(m),!O||!A)||O.version!==I))){if(L){if(i.hasLock(m,O.version))return;let D;for(let N in r)D||(D={}),D[N]=A[N];if(D)return T(m,D,O,I,Ul,null,null,0,null,!0)}return i.ifVersion(m,I,()=>{Yl(m,A,null)}),h?T(m,null,O,I,Ul,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,iG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,I){let y=this[ye],O=An(y),D=this[Ue];sc(D);let N=this[Zr];this[Ll]=A?Zx:rie;let M={key:D,store:i,entry:N,nodeName:y?.nodeName,validate:q=>{m||(m=this[Ct]),A||m&&WE(m)?y?.source||(O.checkOverloaded(),this.validate(m,!A),H&&(m[H.name]=H.type==="Date"?new Date(q):H.type==="String"?new Date(q).toISOString():q),A&&(t&&m[t]!==D&&(m[t]=D),k&&(N?.value?m[k.name]=N?.value[k.name]:m[k.name]=k.type==="Date"?new Date(q):k.type==="String"?new Date(q).toISOString():q),m=Lo(m))):O.removeWrite(M)},before:A?Le.put?()=>Le.put(y,D,m):null:Le.patch?()=>Le.patch(y,D,m):Le.put?()=>Le.put(y,D,Lo(this)):null,beforeIntermediate:A?Be.put?()=>Be.put(y,D,m):null:Be.patch?()=>Be.patch(y,D,m):Be.put?()=>Be.put(y,D,Lo(this)):null,commit:(q,C,x)=>{if(x){if(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),this[Zr]=C,C?.value?.[_e])throw new Error("Can not assign a record to a record, check for circular references");A||(this[_e]=C?.value??null)}this[Ct]=m,this[vl]=q;let G=C?.value,se=m;if(this[Ll]=0,C?.version>=q)if(h){let ae=C.localTime,Ge=C.version;for(;se&&(ae>q||Ge>=q&&ae>0);){let te=u.get(ae);if(!te)break;let X=Ut(te);if(Ge=X.version,Ge>q){if(X.type==="patch"){let Oe=X.getValue(i);se=YE(se,Oe)}else if(X.type==="put"||X.type==="delete")return}else if(Ge===q)return;ae=X.previousLocalTime}}else{if(A)return;se=YE(se,G)}let pe;if(A?pe=se:(this[_e]=G,pe=A?se:Lo(this,se)),this[_e]=pe,pe?.[_e])throw new Error("Can not assign a record to a record, check for circular references");let ee;A||(ee=m),Yl(D,G,pe);let Pe=A?"put":"patch";T(D,pe,C,q,0,h,y,y.expiresAt||(f?f+Date.now():0),Pe,!1,ee)}};O.addWrite(M)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Tn]){for await(let A of this.search(m))(await We.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let A=An(this[ye]),I=this[Ue];sc(I);let y=this[ye];return A.addWrite({key:I,store:i,resource:this,nodeName:y?.nodeName,before:Le.delete?.bind(this,y,I),beforeIntermediate:Be.delete?.bind(this,y,I),commit:(O,D,N)=>{let M=D?.value;N&&(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),th(this,D)),!(D?.version>O)&&(Yl(this[Ue],M),Xe.trace("Write delete entry",I,O),h||S?(T(I,null,this[Zr],O,0,h,this[ye],0,"delete"),h||Th()):i.remove(this[Ue]))}}),!0}search(m){let A=this[ye],I=An(A);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ue]&&(y=[{attribute:null,comparator:"prefix",value:this[Ue]}].concat(y));let O,D={};function N(X,Oe){let He;switch(Oe){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');He=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Oe)}let Vn=He&&{},Ws;for(let $e of X){if($e.conditions){$e.conditions=N($e.conditions,$e.operator);continue}let Gt=$e[0]??$e.attribute,rn=Gt==null?v:Gs(p,Gt);if(rn){if(He){let $n=Hn(Gt),Ft=Vn[$n];Ft?(Ft.push($e),Ws=!0):Vn[$n]=[$e]}(rn.type||Fg[$e.comparator])&&($e[1]===void 0?$e.value=q($e.value,rn):$e[1]=q($e[1],rn))}else if(Gt!=null)throw(0,gn.handleHDBError)(new Error,`${Gt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(Ws)for(let $e in Vn){let Gt=Vn[$e],rn=Gt.length;if(rn>1)for(let $n=0;$n<rn;$n++){let Ft=Gt[$n];if(Ft.comparator==="ge"||Ft.comparator==="greater_than_equal")for(let Qs=0;Qs<rn;Qs++){let Ho=Gt[Qs];(Ho.comparator==="le"||Ho.comparator==="less_than_equal")&&(Ft.comparator="between",Ft.value=[Ft.value,Ho.value],X.splice(X.indexOf(Ho),1))}if(Ft.comparator==="equals"||!Ft.comparator){for(let Qs=0;Qs<rn;Qs++)if(Qs!==$n){let Ho=Gt[Qs];X.splice(X.indexOf(Ho),1)}break}}}return X}a(N,"prepareConditions");function M(X,Oe){if(m.enforceExecutionOrder)return X;for(let He of X)He.conditions&&(He.conditions=M(He.conditions,He.operator));return X.length>1&&Oe!=="or"?(0,sG.sortBy)(X,qf(We)):X}a(M,"orderConditions");function q(X,Oe){return Array.isArray(X)?X.map(He=>eh(He,Oe)):eh(X,Oe)}a(q,"coerceTypedValues");let C=m.operator;(y.length>0||C)&&(y=N(y,C));let x=typeof m.sort=="object"&&m.sort,G;if(x&&C!=="or"){let X=x.attribute;if(O=y.find(Oe=>Hn(Oe.attribute)===Hn(X)),!O){if(!Gs(p,X))throw(0,gn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);O={attribute:X,comparator:"sort"},y.push(O)}O.descending=!!x.descending}y=M(y,C),x&&(y[0]===O?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&y.splice(y.indexOf(O),1),G=x));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:C,postOrdering:G,selectApplied:!!se};let pe=I.useReadTxn(),ee=qg(y,C,We,pe,m,A,(X,Oe)=>KA(X,se,A,pe,Oe),D),Pe=m.ensureLoaded!==!1;G||(ee=te(ee));let ae=We.transformEntryForSelect(se,A,pe,D,Pe,!0),Ge=We.transformToOrderedSelect(ee,se,G,pe,A,ae);function te(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(te,"applyOffset"),G&&(Ge=te(Ge)),Ge.onDone=()=>{Ge.onDone=null,I.doneReadTxn()},Ge.selectApplied=!0,Ge.getColumns=()=>{if(se){let X=[];for(let Oe of se)Oe==="*"?X.push(...p.map(He=>He.name)):X.push(Oe.name||Oe);return X}return p.map(X=>X.name)},Ge}static transformToOrderedSelect(m,A,I,y,O,D){let N=new wG;if(I){m=KA(m,A,y,O,null);let M;N.iterate=function(){let C,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=I.dbOrderedAttribute,pe,ee,Pe=!0;function ae(te){let X=te.next&&ae(te.next),Oe=te.descending;return(He,Vn)=>{let Ws=Sh(He,te.attribute,y),$e=Sh(Vn,te.attribute,y),Gt=Oe?(0,Po.compareKeys)($e,Ws):(0,Po.compareKeys)(Ws,$e);return Gt===0?X?.(He,Vn)||0:Gt}}a(ae,"createComparator");let Ge=ae(I);return{async next(){let te;if(C)if(te=C.next(),te.done){if(G)return N.onDone&&N.onDone(),te}else return{value:await D.call(this,te.value)};M=[],pe&&M.push(pe);do if(te=await x.next(),te.done){if(G=!0,M.length)break;return N.onDone&&N.onDone(),te}else{let X=te.value;if(X?.then&&(X=await X),se){let Oe=Sh(X,se,y);if(Pe)Pe=!1,ee=Oe;else if(Oe!==ee){ee=Oe,pe=X;break}}M.push(X)}while(!0);return I.isGrouped,M.sort(Ge),C=M[Symbol.iterator](),te=C.next(),te.done?(N.onDone&&N.onDone(),te):{value:await D.call(this,te.value)}},return(){N.onDone&&N.onDone(),x.return()},throw(){N.onDone&&N.onDone(),x.throw()}}};let q=a(C=>{if(typeof A=="object"&&Array.isArray(C.attribute))for(let x=0;x<A.length;x++){let G=A[x],se;if(G.name===C.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=C.attribute.slice(1),se.descending=C.descending}else G===C.attribute[0]&&(A[x]=se={name:G,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&q(C.next)},"applySortingOnSelect");q(I)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(D);return N}static transformEntryForSelect(m,A,I,y,O,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(x=>(A?.transaction?.stale&&(A.transaction.stale=!1),x?.key??x),"transform");return m===t?C:m.asArray?x=>[C(x)]:x=>({[t]:C(x)})}let N;O&&L&&!m?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(N=!0);let M,q=a(function(C){let x;if(A?.transaction?.stale&&(A.transaction.stale=!1),C!=null){if(Eh=C,x=C.value||C.deref?.(),!x&&(C.key===void 0||C.deref)){if(C=mh(C.key??C,A,{transaction:I,lazy:m?.length<4},this.isSync,G=>G),C?.then)return C.then(q.bind(this));x=C?.value}if(N&&(C.metadataFlags&(Ml|Ul)||C.expiresAt&&C.expiresAt<Date.now())){let G=ph(C.key??C,C,A);if(G?.then)return G.then(q)}}if(x==null)return D?Mo.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((ee,Pe)=>{let ae;typeof ee=="object"?ae=ee.name:ae=ee;let Ge=Ks?.[ae],te;if(Ge){let X=y?.[ae];if(X)if(X.hasMappings){let He=Ge.from?x[Ge.from]:Hn(C.key);te=X.get(He),te||(te=[])}else te=X.fromRecord?.(x);else te=Ge(x,A,C);let Oe=a(He=>{if(He&&typeof He=="object"){let Vn=Ge.definition?.tableClass||We;M||(M={});let Ws=M[ae]||(M[ae]=Vn.transformEntryForSelect(ae===ee?null:ee.select||(Array.isArray(ee)?ee:null),A,I,X,O));if(Array.isArray(He)){let $e=[],Gt=Vn.transformToOrderedSelect(He,ee.select,typeof ee.sort=="object"&&ee.sort,A,I,Ws)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),rn=a(Ft=>{for(;!Ft.done;){if(Ft?.then)return Ft.then(rn);$e.push(Ft.value),Ft=Gt.next()}Pe($e,ae)},"nextValue"),$n=rn(Gt.next());$n&&(G||(G=[]),G.push($n));return}else if(He=Ws.call(this,He),He?.then){G||(G=[]),G.push(He.then($e=>Pe($e,ae)));return}}Pe(He,ae)},"handleResolvedValue");te?.then?(G||(G=[]),G.push(te.then(Oe))):Oe(te);return}else te=x[ae],te&&typeof te=="object"&&ae!==ee&&(te=We.transformEntryForSelect(ee.select||ee,A,I,null)({value:te}));Pe(te,ae)},"selectAttribute"),pe;if(typeof m=="string")se(m,ee=>{pe=ee});else if(Array.isArray(m))if(m.asArray)pe=[],m.forEach((ee,Pe)=>{ee==="*"?m[Pe]=x:se(ee,ae=>pe[Pe]=ae)});else{pe={};let ee=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ae in x)pe[ae]=x[ae];else se(Pe,(ae,Ge)=>{ae===void 0&&ee&&(ae=null),pe[Ge]=ae})}else throw new gn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>pe):pe}return x},"transform");return q}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||ut({table:s,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let A=!m.rawEvents,I=Qx(We,this[Ue]??null,function(N,M,q,C){try{let x=M.getValue?.(i,A);if(!x&&M.type==="patch"&&A){let G=i.getEntry(N);G?.version===M.version?x=G.value:x=M.getValue?.(i,!0,q),M.type="put"}this.send({id:N,timestamp:q,value:x,version:M.version,type:M.type,beginTxn:C})}catch(x){Xe.error(x)}},m.startTime||0,this[Tn]);this[Tn]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let y=this[Ue],O=m.previousCount;O>1e3&&(O=1e3);let D=m.startTime;if(this[Tn]){if(D){if(O)throw new gn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:M}of u.getRange({start:D,exclusiveStart:!0})){let q=Ut(M);if(q.tableId!==n)continue;let C=q.recordId;if(y==null||rG(y,C)){let x=q.getValue(i,A,N);I.send({id:C,timestamp:N,value:x,version:q.version,type:q.type})}I.startTime=N}}else if(O){let N=[];for(let{key:M,value:q}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Ut(q);if(C.tableId!==n)continue;let x=C.recordId;if(y==null||rG(y,x)){let G=C.getValue(i,A,M);if(N.push({id:x,timestamp:M,value:G,version:C.version,type:C.type}),--O<=0)break}}catch(C){Xe.error("Error getting history entry",M,C)}for(let M=N.length;M>0;)I.send(N[--M]);N[0]&&(I.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:M,version:q,localTime:C}of i.getRange({start:y??!1,end:y==null?void 0:[y,Po.MAXIMUM_KEY],versions:!0}))M&&I.send({id:N,timestamp:C,value:M,version:q,type:"put"})}else{O&&!D&&(D=0);let N=this[Zr]?.localTime;if(N===Em&&(i.cache?.delete(y),this[Zr]=i.getEntry(y),Xe.trace("re-retrieved record",N,this[Zr]?.localTime),N=this[Zr]?.localTime),Xe.trace("Subscription from",D,"from",y,N),D<N){let M=[],q=N;do{let C=u.get(q);if(C){m.omitCurrent=!0;let x=Ut(C),G=x.getValue(i,A,q);A&&(x.type="put"),M.push({id:y,value:G,timestamp:q,...x}),q=x.previousLocalTime}else break;O&&O--}while(q>D&&O!==0);for(let C=M.length;C>0;)I.send(M[--C]);I.startTime=N}!m.omitCurrent&&this.doesExist()&&I.send({id:y,timestamp:N,value:this,version:this[vl],type:"put"})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[_e]||this[Ll])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let I=An(this[ye]),y=this[Ue]||null;sc(y);let O=this[ye];I.addWrite({key:y,store:i,entry:this[Zr],nodeName:O?.nodeName,validate:()=>{O?.source||(I.checkOverloaded(),this.validate(m))},before:Le.publish?.bind(this,O,y,m),beforeIntermediate:Be.publish?.bind(this,O,y,m),commit:(D,N,M)=>{N===void 0&&S&&!h&&Th(),T(y,N?.value??null,N,N?.version||D,0,!0,O,N?.expiresAt,"message",!1,m)}})}validate(m,A){let I,y=a((O,D,N)=>{if(D.type&&O!=null)if(A&&O.__op__&&(O=O.value),D.properties){typeof O!="object"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be an object${D.type?" ("+D.type+")":""}`);let M=D.properties;for(let q=0,C=M.length;q<C;q++){let x=M[q],G=y(O[x.name],x,N+"."+x.name);G&&(O[x.name]=G)}if(D.sealed&&O!=null&&typeof O=="object")for(let q in O)M.find(C=>C.name===q)||(I||(I=[])).push(`Property ${q} is not allowed within object in property ${N}`)}else switch(D.type){case"Int":(typeof O!="number"||O>>0!==O)&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(M=>typeof M=="string")||(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(D.elements)for(let M=0,q=O.length;M<q;M++){let C=O[M],x=y(C,D.elements,N+"[*]");x&&(O[M]=x)}}else(I||(I=[])).push(`Value ${qn(O)} in property ${N} must be a Buffer or Uint8Array`);break}D.nullable===!1&&O==null&&(I||(I=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let O=0,D=p.length;O<D;O++){let N=p[O];if(!N.relationship&&(!A||N.name in m)){let M=y(m[N.name],N,N.name);M&&(m[N.name]=M)}}if(d)for(let O in m)p.find(D=>D.name===O)||(I||(I=[])).push(`Property ${O} is not allowed`);if(I)throw new gn.ClientError(I.join(". "))}getUpdatedTime(){return this[vl]}wasLoadedFromSource(){return L?!!this[PA]:void 0}static async addAttributes(m){let A=p.slice(0);for(let I of m){if(!I.name)throw new gn.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new gn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(I)}return ut({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static async removeAttributes(m){let A=p.filter(I=>!m.includes(I.name));return ut({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,I=5e3,y=1e3,O;A>I&&!m?.exactCount&&(O=y);let D=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:O}))N!=null&&D++;if(O){let N=D;D=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))Pe!=null&&D++;let M=O*2,q=(D+N)/M,C=Math.pow((D-N+1)/O/2,2)+q*(1-q)/M,x=Math.max(Math.sqrt(C)*A,1),G=Math.round(q*A),se=Math.max(G-1.96*x,0),pe=Math.min(G+1.96*x,A),ee=Math.pow(10,Math.round(Math.log10(x)));return ee>G&&(ee=ee/10),D=Math.round(G/ee)*ee,{recordCount:D,estimatedRange:[Math.round(se),Math.round(pe)]}}return{recordCount:D}}static updatedAttributes(){Ks=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)"),YA=!0,A.to)m.elements?.definition?(Ks[m.name]=m.resolve=(I,y,O)=>{let D=I[A.from?A.from:t],N=m.elements.definition.tableClass;return O?Pa({attribute:A.to,value:D},An(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:A.to,value:D}],y).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 "${s}" must have an array type referencing a table as the elements`);else if(A.from){let I=m.definition||m.elements?.definition;I?(Ks[m.name]=m.resolve=(y,O,D)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let M,q=N.map(C=>{let x=D?I.tableClass.primaryStore.getEntry(C,{transaction:An(O).getReadTxn()}):I.tableClass.get(C,O);return x?.then&&(M=!0),x});return A.filterMissing?M?Promise.all(q).then(C=>C.filter(nG)):q.filter(nG):M?Promise.all(q):q}return D?I.tableClass.primaryStore.getEntry(N,{transaction:An(O).getReadTxn()}):I.tableClass.get(N,O)}},m.set=(y,O)=>{if(Array.isArray(O)){let D=O.map(N=>N[Ue]||N[I.tableClass.primaryKey]);y[A.from]=D}else{let D=O[Ue]||O[I.tableClass.primaryKey];y[A.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}JE(this,this)}static async deleteHistory(m=0){let A;for(let{key:I,value:y}of u.getRange({start:0,end:m}))await Pl(),Ut(y).tableId===n&&(A=u.remove(I));await A}static async*getHistory(m=0,A=1/0){for(let{key:I,value:y}of u.getRange({start:m,end:A})){await Pl();let O=Ut(y);O.tableId===n&&(yield{id:O.recordId,localTime:I,version:O.version,type:O.type,value:O.getValue(i,!0,I),user:O.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 y=I.localTime;if(!y)throw new Error("The entry does not have a local audit time");let O=0;do{await Pl();let D=u.get(y);if(D){let N=Ut(D);A.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(O<1e3&&y);return A.reverse()}static cleanup(){z?.remove()}}We.updatedAttributes();let LG=We.prototype;return LG[tie]=!0,f&&We.setTTLExpiration(f/1e3),j&&MG(),We;function Yl(K,m,A){let I;for(let y in r){let O=r[y],D=O.isIndexing,N=A?.[y],M=m?.[y];if(N===M&&!D)continue;I=!0;let q=O.indexNulls,C=(0,Bl.getIndexedValues)(N,q),x=(0,Bl.getIndexedValues)(M,q);if(x?.length>0){let G=new Set(x);if(C=C?C.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],x=Array.from(G),(x.length>0||C.length>0)&&Xx){let se=x.concat(C).map(pe=>({key:pe,value:K}));O.prefetch(se,tG)}for(let se=0,pe=x.length;se<pe;se++)O.remove(x[se],K)}else C?.length>0&&Xx&&O.prefetch(C.map(G=>({key:G,value:K})),tG);if(C)for(let G=0,se=C.length;G<se;G++)O.put(C[G],K)}return I}a(Yl,"updateIndices");function sc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>eG)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,Po.writeKey)(K,nie,0)>eG)throw new Error("Primary key size is too large: "+K.length);return!0}a(sc,"checkValidId");function mh(K,m,A,I,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,K);let D=i.getEntry(K,A);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),y(D,K)},"whenPrefetched");return I?O():ce>0?(ce--,O()):new Promise((D,N)=>{ce===0?(ce--,i.prefetch([K],()=>{M(),q()})):(J.push(K),me.push(q),J.length>DG&&(ce--,M()));function M(){if(J.length>0){let C=me;i.prefetch(J,()=>{ce===-1?M():ce++;for(let x of C)x()}),J=[],me=[],de>2&&de--}else ce=de,de<CG&&de++}a(M,"prefetch");function q(){try{D(O())}catch(C){N(C)}}a(q,"load")})}a(mh,"loadLocalRecord");function Kl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return sie;let A=m[c],I,y=A?.tables;if(y)return y[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(Kl,"getTablePermissions");function ph(K,m,A,I){if(L){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Ml|Ul)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,cn(!y,"cache-hit",s)),y){let O=WA(K,m,A).then(D=>(D?.value?.[_e]&&Xe.error("Can not assign a record with a record property"),A&&(D?.version>(A.lastModified||0)&&(A.lastModified=D.version),A.lastRefreshed=Date.now()),D));if(A?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(O.catch(D=>Xe.warn(D)),A?.onlyIfCached&&!I.doesExist())throw new gn.ServerError("Entry is not cached",504);return}else return O}}}a(ph,"ensureLoadedFromSource");function An(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 eo,m.lmdbDb=i,m;m=A}while(!0)}else return new id}a(An,"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 O=Ks,D=I;for(let N=0,M=m.length;N<M;N++){let q=m[N],C=O?.[q];D=C&&D?C(D,A,!0)?.value:D?.[q],O=C?.definition?.tableClass?.propertyResolvers}return D}let y=Ks[m];return y?y(I,A):I[m]}a(Sh,"getAttributeValue");function KA(K,m,A,I,y){let O=y?.length,D={transaction:I,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function M(q,C){let x=q?.value;if(!x)return Mo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](x,q))return Mo.SKIP;return C!==void 0&&(q.key=C),q}if(a(M,"processEntry"),O>0||!K.hasEntries){let q=K.map(C=>{if(N=null,typeof C=="object"&&C?.key!==void 0)return O>0?M(C):C;if(C==null)return Mo.SKIP;for(let x=0;x<O;x++){let se=y[x].idFilter;if(se){if(!se(C))return Mo.SKIP;N||(N=[]),N.push(x)}}return mh(C,A,D,!1,M)});return Array.isArray(K)&&(q=q.filter(C=>C!==Mo.SKIP)),q.hasEntries=!0,q}return K}a(KA,"transformToEntries");async function WA(K,m,A){let I=m?.metadataFlags,y=m?.version,O,D;if(!i.attemptLock(K,y,()=>{clearTimeout(D);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Ml|Ul)?O(WA(K,i.getEntry(K),A)):O(C)}))return new Promise(C=>{O=C,D=setTimeout(()=>{i.unlock(K,y)},eie)});let N=m?.value,M={requestContext:A,replacingRecord:N,replacingVersion:y,source:null,resourceCache:A?.resourceCache},q=A?.responseHeaders;return new Promise((C,x)=>{let G;BA(ze(M,async se=>{let pe=performance.now(),ee,Pe,ae;try{for(let Oe of We.sources)if(Oe.get&&(!Oe.get.reliesOnPrototype||Oe.prototype.get)&&(M.source=Oe,ee=await Oe.get(K,M),ee))break;ae=I&Ml;let te=M.lastModified||ae&&y;Pe=ae||te>y||!N,te||(te=(0,Bl.getNextMonotonicTime)());let X=performance.now()-pe;if($r(X,"cache-resolution",s),q&&cg(q,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=te,f&&!M.expiresAt&&(M.expiresAt=Date.now()+f),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]!==K&&(ee[t]=K)}G=!0,C({version:te,value:ee})}catch(te){te.message+=` while resolving record ${K} for ${s}`,N&&((te.code==="ECONNRESET"||te.code==="ECONNREFUSED"||te.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(te.statusCode===500||te.statusCode===502||te.statusCode===503||te.statusCode===504))?(C({version:y,value:N}),Xe.trace(te.message,"(returned stale record)")):x(te),M.transaction.abort();return}if(A?.noCacheStore){M.transaction.abort();return}An(M).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(te,X)=>{if(X?.version!==y)return;let Oe=Yl(K,N,ee);ee?(Be.put?.(M,K,ee),T(K,ee,X,te,0,h&&Pe||null,M,M.expiresAt,"put",!!ae)):(Be.delete?.(M,K),h||S?T(K,null,X,te,0,h&&Pe||null,M,0,"delete",!!ae):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&Xe.error("Error committing cache update",se)})})}a(WA,"getFromSource");function Th(){if(Lt!==Vl&&(Vl=Lt,(0,Uo.getWorkerIndex)()===(0,Uo.getWorkerCount)()-1)){if($l&&clearTimeout($l),!Lt)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())/Lt)*Lt+K.getTime(),A=a(I=>{Xe.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),$l=setTimeout(()=>P=P.then(async()=>{if(A(Math.max(I+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout($l);return}let y=50,O=new Array(y),D=0;Xe.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:M,value:q,version:C,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;q===null&&!h&&C+Zse<Date.now()?G=i.remove(M,C):x&&x+E<Date.now()&&(G=We.evict(M,q,C),N++),G&&(await O[D],O[D]=G.catch(se=>{Xe.error("Cleanup error",se)}),++D>=y&&(D=0)),await Pl()}Xe.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){Xe.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Th,"scheduleCleanup");function QA(){z=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(QA,"addDeleteRemoval");function MG(){(0,Uo.getWorkerIndex)()===0&&setInterval(async()=>{if(!hh){hh=!0;try{let K=j.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${j} must be indexed`);for(let A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let I of m.getValues(A)){let y=i.getEntry(I);y?.value?y.value[K]<Date.now()&&We.evict(I,y.value,y.version):i.ifVersion(I,y?.version,()=>m.remove(A,I))}await Pl()}}catch(K){Xe.error("Error in evicting old records",K)}finally{hh=!1}}},Xse).unref()}a(MG,"runRecordExpirationEviction")}function vA(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function tG(){}function iie(e){iG=e}function eh(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,rh.autoCast)(e):e}function rG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function BA(e,t,r){return e?.then?e.then(t,r):t(e)}function th(e,t){e[Zr]=t,e[_e]=t?.value??null,e[vl]=t?.version}function nG(e){return e!=null}function qn(e){try{return JSON.stringify(e)}catch{return e}}var kn,Mo,Bl,sG,Gl,gn,Hl,xl,Xe,Po,Uo,rh,jse,iG,Xse,Zse,Xx,eie,vl,tie,Zr,Ll,Zx,rie,PA,ec,Ml,Ul,nie,eG,sie,Bpe,oie,Pl,nE=ge(()=>{kn=B(U()),Mo=require("lmdb"),Bl=B(Pr()),sG=require("lodash");In();eS();Gl=B(re());jx();gn=B(ne()),Hl=B(Os()),xl=B(Ln());Re();Vf();Xe=B(Y());cd();to();Po=require("ordered-binary"),Uo=B(rt());Zs();rh=B(Q());Dc();Is();VE();Qu();jse=new Uint8Array(9);jse[8]=192;Xse=6e4,Zse=864e5;Gl.initSync();Xx=Gl.get(kn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),eie=1e4,vl=Symbol.for("version"),tie=Symbol.for("incremental-update"),Zr=Symbol("entry"),Ll=Symbol("is-saving"),Zx=1,rie=2,PA=Symbol("loaded-from-source"),ec={isNotification:!0,ensureLoaded:!1},Ml=1,Ul=8,nie=Buffer.allocUnsafeSlow(8192),eG=1978,sie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},Bpe=(0,rh.convertToMS)(Gl.get(kn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(nh,"makeTable");a(vA,"attributesAsObject");a(tG,"noop");a(iie,"setServerUtilities");oie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(eh,"coerceType");a(rG,"isDescendantId");Pl=a(()=>new Promise(setImmediate),"rest");a(BA,"when");a(th,"updateResource");a(nG,"exists");a(qn,"stringify")});var qe={};Fe(qe,{database:()=>nu,databases:()=>nt,dropDatabase:()=>iS,dropTableMeta:()=>_ie,getDatabases:()=>Er,getDefaultCompression:()=>_f,getTables:()=>aie,onUpdatedTable:()=>WR,readMetaDb:()=>Fl,resetDatabases:()=>qu,table:()=>ut,tables:()=>vr});function aie(){return ch||Er(),vr||{}}function Er(){if(ch)return nt;ch=!0,nc=new Map;let e=(0,Et.getHdbBasePath)()&&(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),t=(0,Et.get)(Dt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,en.existsSync)(e)?e:(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,en.existsSync)(e))for(let r of(0,en.readdirSync)(e,{withFileTypes:!0})){let n=(0,Ze.basename)(r.name,".mdb");r.isFile()&&(0,Ze.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Fl((0,Ze.join)(e,r.name),null,n)}if((0,en.existsSync)((0,rc.getBaseSchemaPath)())){for(let r of(0,en.readdirSync)((0,rc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Ze.join)((0,rc.getBaseSchemaPath)(),r.name),s=(0,Ze.join)((0,rc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,en.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Ze.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Ze.join)(s,i.name);Fl((0,Ze.join)(n,i.name),(0,Ze.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,en.existsSync)(s))for(let o of(0,en.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Ze.extname)(o.name).toLowerCase()===".mdb"&&Fl((0,Ze.join)(s,o.name),(0,Ze.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,Ze.join)(c.path,(0,Ze.basename)(o+".mdb"));(0,en.existsSync)(u)&&Fl(u,o,r,null,!0)}}for(let r in nt){let n=nc.get(r);if(n){let s=nt[r];r.includes("delete")&&Rn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Rn.trace(`delete table class ${i}`),delete s[i])}else if(delete nt[r],r==="data"){for(let s in vr)delete vr[s];delete vr[lh]}}return nc=null,nt}}function qu(){ch=!1;for(let[,e]of Li)e.needsDeletion=!0;Er();for(let[e,t]of Li)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Li.delete(e));return nt}function Fl(e,t,r=GA,n,s){let i=new HA.default(e,!1);try{let o=Li.get(e);o?o.needsDeletion=!1:(o=(0,ih.open)(i),Li.set(e,o));let c=new vo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(sh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,en.existsSync)(n)&&(i.path=n,_=(0,ih.open)(i),_.isLegacy=!0):_=kE(o));let l=uG(r),d=l[lh],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[S,p]=E.toString().split("/");p===""?p=h.name:p||(p=S,S=t,h.name||(h.name=p,h.indexed=!h.is_hash_attribute)),d?.add(S);let T=f.get(S);T||f.set(S,T={attributes:[]}),(p==null||h.is_hash_attribute)&&(T.primary=h),p!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:S,primary:p}=h;if(!p){for(let J of S)if(J.is_hash_attribute||J.isPrimaryKey){p=J;break}if(!p){Rn.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(S)}`);continue}}let T=l[E],b={},g=[],L,v,P=typeof p.audit=="boolean"?p.audit:(0,Et.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=p.trackDeletes,H=p.expiration,j=p.eviction,z=p.sealed;if(T)b=T.indices,g=T.attributes,T.schemaVersion++;else{L=p.tableId,L?L>=(u.get(tc)||0)&&u.putSync(tc,L+1):(p.tableId=L=u.get(tc),L||(L=1),u.putSync(tc,L+1),u.putSync(p.key,p));let J=new vo.default(!p.is_hash_attribute,p.is_hash_attribute);if(J.compression=p.compression,J.compression){let me=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||cG;J.compression.threshold=me}v=S_(o.openDB(p.key,J)),v.rootStore=o,v.tableId=L}for(let J of S){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!b[J.name]){let ce=new vo.default(!J.is_hash_attribute,J.is_hash_attribute);b[J.name]=o.openDB(J.key,ce),b[J.name].indexNulls=J.indexNulls}let me=g.find(ce=>ce.name===J.name);me?g.splice(g.indexOf(me),1,J):g.push(J)}}catch(me){Rn.error("Error trying to update attribute",J,g,b,me)}}if(!T){T=lG(l,E,nh({primaryStore:v,auditStore:_,audit:P,sealed:z,expirationMS:H&&H*1e3,evictionMS:j&&j*1e3,trackDeletes:k,tableName:E,tableId:L,primaryKey:p.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:b,attributes:S,schemaDefined:p.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let J of FA)J(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function uG(e){let t=nt[e];if(t||(e==="data"?t=nt[e]=vr:e==="system"?Object.defineProperty(nt,"system",{value:t=Object.create(null),configurable:!0}):t=nt[e]=Object.create(null)),nc&&!nc.has(e)){let r=new Set;t[lh]=r,nc.set(e,r)}return t}function lG(e,t,r){return e[t]=r,r}function nu({database:e,table:t}){e||(e=GA),Er();let r=uG(e),n=(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),s=(0,Et.get)(Dt.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_PATH)||((0,en.existsSync)(n)?n:(0,Ze.join)((0,Et.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME));let o=(0,Ze.join)(n,(i?t:e)+".mdb"),c=Li.get(o);if(!c){let u=new HA.default(o,!1);c=(0,ih.open)(u),Li.set(o,c)}return c}async function iS(e){if(!nt[e])throw new Error("Schema does not exist");let t=nt[e];for(let r in t){let s=t[r].primaryStore.rootStore;Li.delete(s.path),s.status==="open"&&(await s.close(),await uh.remove(s.path))}if(e==="data"){for(let r in vr)delete vr[r];delete vr[lh]}delete nt[e]}function ut({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=GA);let d=nu({database:t,table:e}),f=nt[t],E=f?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,S,p,T;_==null&&(_=!0);let b=new vo.default(!1);for(let H of i)H.attribute?(H.name=H.attribute,H.indexed=!0):H.attribute=H.name,H.expiresAt&&(H.indexed=!0);let g,L;if(E){if(h=E.primaryKey,E.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);E.attributes.splice(0,E.attributes.length,...i)}else{let H=d.auditStore;H||(H=kE(d)),S=i.find(me=>me.isPrimaryKey)||{},h=S.name,S.is_hash_attribute=!0,S.schemaDefined=_,S.compression=_f(),u&&(S.trackDeletes=!0),o=S.audit=typeof o=="boolean"?o:(0,Et.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(S.expiration=r),n&&(S.eviction=n),typeof c=="boolean"&&(S.sealed=c),l&&(S.origins?S.origins.includes(l)||S.origins.push(l):S.origins=[l]),Rn.trace(`${e} table loading, opening primary store`);let j=new vo.default(!1,!0);j.compression=S.compression;let z=e+"/",J=S_(d.openDB(z,j));J.rootStore=d,T=d.dbisDb=d.openDB(sh.INTERNAL_DBIS_NAME,b),J.tableId=T.get(tc),J.tableId||(J.tableId=1),T.putSync(tc,J.tableId+1),S.tableId=J.tableId,E=lG(f,e,nh({primaryStore:J,auditStore:H,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),E.schemaVersion=1,g=!0,k(),T.put(z,S)}p=E.indices,T=T||(d.dbisDb=d.openDB(sh.INTERNAL_DBIS_NAME,b)),E.dbisDB=T;let v=[];for(let{key:H,value:j}of T.getRange({start:!0})){let[z,J]=H.toString().split("/");if(J===""&&(J=j.name),J){if(z!==e)continue}else J=z;if(!i.find(ce=>ce.name===J)?.indexed&&j.indexed&&!j.isPrimaryKey){k(),g=!0,T.remove(H);let ce=E.indices[z];ce&&v.push(ce)}}let P=[];try{for(let H of i||[]){if(H.relationship)continue;let j=e+"/"+(H.name||"");Object.defineProperty(H,"key",{value:j,configurable:!0});let z=T.get(j);if(H.isPrimaryKey){if(z=z||T.get(j=e+"/")||{},o!==E.audit||c!==c||(+r||void 0)!==(+z.expiration||void 0)||(+n||void 0)!==(+z.eviction||void 0)){let me=Object.assign({},z);typeof o=="boolean"&&(o&&E.enableAuditing(o),me.audit=o),r&&(me.expiration=+r),n&&(me.eviction=+n),c!==void 0&&(me.sealed=c),g=!0,k(),T.put(j,me)}continue}z?.attribute&&!z.name&&(z.indexed=!0);let J=!z||z.type!==H.type||z.indexed!==H.indexed||z.nullable!==H.nullable||JSON.stringify(z.attributes)!==JSON.stringify(H.attributes)||JSON.stringify(z.elements)!==JSON.stringify(H.elements);if(H.indexed){let me=new vo.default(!0,!1),ce=d.openDB(j,me);(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(g=!0,k(),z=T.get(j),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(g=!0,H.indexNulls===void 0&&(H.indexNulls=!0),E.primaryStore.getStats().entryCount>0&&(H.lastIndexedKey=z?.lastIndexedKey||!1,H.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(H,"dbi",{value:ce}),P.push(H))),T.put(j,H)),z?.indexNulls&&H.indexNulls===void 0&&(H.indexNulls=!0),ce.indexNulls=H.indexNulls,p[H.name]=ce}else J&&(g=!0,k(),T.put(j,H))}}finally{L&&L()}if(g&&(E.schemaVersion++,E.updatedAttributes()),Rn.trace(`${e} table loading, running index`),P.length>0||v.length>0?E.indexingOperation=lie(E,P,v):g&&oh.signalSchemaChange(new ah.SchemaEventMsg(process.pid,"schema-change",E.databaseName,E.tableName)),E.origin=l,g)for(let H of FA)H(E,l!=="cluster");return(r||n||s)&&E.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),Rn.trace(`${e} table loaded`),E;function k(){L||d.transactionSync(()=>({then(H){L=H}}))}a(k,"startTxn")}async function lie(e,t,r){try{let n=e.schemaVersion;await oh.signalSchemaChange(new ah.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,S=(0,oG.getIndexedValues)(l[h]);if(S)for(let p=0,T=S.length;p<T;p++)E.dbi.put(S[p],_)}}),s.then(()=>u--,f=>{u--,Rn.error(f)}),ql.workerData&&ql.workerData.restartNumber!==aG.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>cie?await s:u>uie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await oh.signalSchemaChange(new ah.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){Rn.error("Error in indexing",n)}}function _ie({table:e,database:t}){let r=nu({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function WR(e){FA.push(e)}function _f(){let e=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||cG,n={startingOffset:32};return t&&(n.dictionary=uh.readFileSync(t)),r&&(n.threshold=r),e&&n}var Et,sh,ih,Ze,en,rc,vo,HA,Dt,uh,xA,oG,oh,ah,ql,Rn,aG,GA,lh,cG,vr,nt,tc,FA,ch,Li,nc,cie,uie,Re=ge(()=>{Et=B(re()),sh=B(ct()),ih=require("lmdb"),Ze=require("path"),en=require("fs"),rc=B(Qe());nE();vo=B(Lc()),HA=B(Mc()),Dt=B(U()),uh=B(require("fs-extra")),xA=require("../../index"),oG=B(Pr()),oh=B(Os()),ah=B(Ln()),ql=require("worker_threads"),Rn=B(Y()),aG=B(rt());Zs();Dc();GA="data",lh=Symbol("defined-tables"),cG=((0,Et.get)(Dt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,Et.initSync)();vr=Object.create(null),nt=Object.create(null);(0,xA._assignPackageExport)("databases",nt);(0,xA._assignPackageExport)("tables",vr);tc=Symbol.for("next-table-id"),FA=[],Li=new Map;a(aie,"getTables");a(Er,"getDatabases");a(qu,"resetDatabases");a(Fl,"readMetaDb");a(uG,"ensureDB");a(lG,"setTable");a(nu,"database");a(iS,"dropDatabase");a(ut,"table");cie=1e3,uie=10;a(lie,"runIndexing");a(_ie,"dropTableMeta");a(WR,"onUpdatedTable");a(_f,"getDefaultCompression")});var Q=R((Ype,bG)=>{"use strict";var Mi=require("path"),hG=require("fs-extra"),Cr=Y(),_G=require("fs-extra"),_h=require("os"),die=require("net"),fie=require("recursive-iterator"),at=U(),Eie=IO(),dG=require("papaparse"),dh=require("moment"),{inspect:hie}=require("util"),fG=require("is-number"),$pe=require("lodash"),mie=require("minimist"),pie=require("https"),Sie=require("http"),{hdb_errors:fh}=ne(),Tie=/^((\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)))$/,mG=require("util").promisify(setTimeout),gie=100,Rie=5,Aie="",Oie=4,EG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};bG.exports={isEmpty:tn,isEmptyOrZeroLength:Es,arrayHasEmptyValues:Nie,arrayHasEmptyOrZeroLengthValues:Iie,buildFolderPath:wie,isBoolean:pG,errorizeMessage:bie,stripFileExtension:Die,autoCast:Lie,autoCastJSON:SG,autoCastJSONDeep:kA,removeDir:Mie,compareVersions:Uie,isCompatibleDataVersion:Pie,escapeRawValue:vie,unescapeValue:Bie,stringifyProps:Hie,timeoutPromise:Gie,isClusterOperation:qie,getClusterUser:Vie,checkGlobalSchemaTable:kie,getHomeDir:gG,getPropsFilePath:xie,promisifyPapaParse:$ie,removeBOM:RG,createEventPromise:Yie,checkProcessRunning:Kie,checkSchemaTableExist:Wie,checkSchemaExists:AG,checkTableExists:OG,getStartOfTomorrowInSeconds:Qie,getLimitKey:zie,isObject:Cie,isNotEmptyAndHasValue:yie,autoCasterIsNumberCheck:TG,backtickASTSchemaItems:Jie,isPortTaken:Fie,createForkArgs:jie,autoCastBoolean:Xie,async_set_timeout:mG,getTableHashAttribute:Zie,doesSchemaExist:eoe,doesTableExist:toe,stringifyObj:roe,ms_to_time:noe,changeExtension:soe,getEnvCliRootPath:VA,noBootFile:ioe,httpRequest:ooe,transformReq:aoe,convertToMS:coe,PACKAGE_ROOT:at.PACKAGE_ROOT};function bie(e){return e instanceof Error?e:new Error(e)}a(bie,"errorizeMessage");function tn(e){return e==null}a(tn,"isEmpty");function yie(e){return!tn(e)&&(e||e===0||e===""||pG(e))}a(yie,"isNotEmptyAndHasValue");function Es(e){return tn(e)||e.length===0||e.size===0}a(Es,"isEmptyOrZeroLength");function Nie(e){if(tn(e))return!0;for(let t=0;t<e.length;t++)if(tn(e[t]))return!0;return!1}a(Nie,"arrayHasEmptyValues");function Iie(e){if(Es(e))return!0;for(let t=0;t<e.length;t++)if(Es(e[t]))return!0;return!1}a(Iie,"arrayHasEmptyOrZeroLengthValues");function wie(...e){try{return e.join(Mi.sep)}catch{console.error(e)}}a(wie,"buildFolderPath");function pG(e){return tn(e)?!1:e===!0||e===!1}a(pG,"isBoolean");function Cie(e){return tn(e)?!1:typeof e=="object"}a(Cie,"isObject");function Die(e){return Es(e)?Aie:e.slice(0,-Oie)}a(Die,"stripFileExtension");function Lie(e){return tn(e)||e===""||typeof e!="string"?e:EG[e]!==void 0?EG[e]:TG(e)===!0?Number(e):Tie.test(e)?new Date(e):e}a(Lie,"autoCast");function SG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(SG,"autoCastJSON");function kA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=kA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=kA(r);n!==r&&(e[t]=n)}return e}else return SG(e)}a(kA,"autoCastJSONDeep");function TG(e){if(e.startsWith("0.")&&fG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&fG(e))}a(TG,"autoCasterIsNumberCheck");async function Mie(e){if(Es(e))throw new Error(`Directory path: ${e} does not exist`);try{await _G.emptyDir(e),await _G.remove(e)}catch(t){throw Cr.error(`Error removing files in ${e} -- ${t}`),t}}a(Mie,"removeDir");function Uie(e,t){if(Es(e)){Cr.info("Invalid current version sent as parameter.");return}if(Es(t)){Cr.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(Uie,"compareVersions");function Pie(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Pie,"isCompatibleDataVersion");function vie(e){if(tn(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(vie,"escapeRawValue");function Bie(e){if(tn(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(Bie,"unescapeValue");function Hie(e,t){if(tn(e))return Cr.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+_h.EOL}!Es(n)&&n[0]===";"?r+=" "+n+s+_h.EOL:Es(n)||(r+=n+"="+s+_h.EOL)}catch{Cr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Hie,"stringifyProps");function gG(){let e;try{e=_h.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(gG,"getHomeDir");function xie(){let e=Mi.join(gG(),at.HDB_HOME_DIR_NAME,at.BOOT_PROPS_FILE_NAME);return hG.existsSync(e)||(e=Mi.join(__dirname,"../","hdb_boot_properties.file")),e}a(xie,"getPropsFilePath");function Gie(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Gie,"timeoutPromise");async function Fie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=die.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Fie,"isPortTaken");function qie(e){try{return at.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Cr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(qie,"isClusterOperation");function kie(e,t){let r=(Re(),ie(qe)).getDatabases();if(!r[e])return fh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return fh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(kie,"checkGlobalSchemaTable");function Vie(e,t){if(tn(t)){Cr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(tn(e)||Es(e)){Cr.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Cr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Cr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Vie,"getClusterUser");function $ie(){dG.parsePromise=function(e,t,r){return new Promise(function(n,s){dG.parse(e,{header:!0,transformHeader:RG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a($ie,"promisifyPapaParse");function RG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(RG,"removeBOM");function Yie(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Cr.info(`Got cluster status event response: ${hie(s)}`);try{i.cancel()}catch{Cr.error("Error trying to cancel timeout.")}n(s)})})}a(Yie,"createEventPromise");async function Kie(e){let t=!0,r=0;do await mG(gie*r++),(await Eie.findPs(e)).length>0&&(t=!1);while(t&&r<Rie);if(t)throw new Error(`process ${e} was not started`)}a(Kie,"checkProcessRunning");function Wie(e,t){let r=AG(e);if(r)return r;let n=OG(e,t);if(n)return n}a(Wie,"checkSchemaTableExist");function AG(e){let{getDatabases:t}=(Re(),ie(qe));if(!t()[e])return fh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(AG,"checkSchemaExists");function OG(e,t){let{getDatabases:r}=(Re(),ie(qe));if(!r()[e][t])return fh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(OG,"checkTableExists");function Qie(){let e=dh().utc().add(1,at.MOMENT_DAYS_TAG).startOf(at.MOMENT_DAYS_TAG).unix(),t=dh().utc().unix();return e-t}a(Qie,"getStartOfTomorrowInSeconds");function zie(){return dh().utc().format("DD-MM-YYYY")}a(zie,"getLimitKey");function Jie(e){try{let t=new fie(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){Cr.error("Got an error back ticking items."),Cr.error(t)}}a(Jie,"backtickASTSchemaItems");function jie(e){return[e]}a(jie,"createForkArgs");function Xie(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Xie,"autoCastBoolean");function Zie(e,t){let{getDatabases:r}=(Re(),ie(qe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Zie,"getTableHashAttribute");function eoe(e){let{getDatabases:t}=(Re(),ie(qe));return t()[e]!==void 0}a(eoe,"doesSchemaExist");function toe(e,t){let{getDatabases:r}=(Re(),ie(qe));return r()[e]?.[t]!==void 0}a(toe,"doesTableExist");function roe(e){try{return JSON.stringify(e)}catch{return e}}a(roe,"stringifyObj");function noe(e){let t=dh.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(noe,"ms_to_time");function soe(e,t){let r=Mi.basename(e,Mi.extname(e));return Mi.join(Mi.dirname(e),r+t)}a(soe,"changeExtension");function VA(){if(process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=mie(process.argv);if(e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[at.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(VA,"getEnvCliRootPath");var qA;function ioe(){if(qA)return qA;let e=VA();VA()&&hG.pathExistsSync(Mi.join(e,at.HDB_CONFIG_FILE))&&(qA=!0)}a(ioe,"noBootFile");function ooe(e,t){let r;return e.protocol==="http:"?r=Sie:r=pie,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(ooe,"httpRequest");function aoe(e){if(!e.schema&&!e.database){e.schema=at.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(aoe,"transformReq");function coe(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(coe,"convertToMS")});var $A=U(),yG=Q(),kl=Y(),uoe=As(),loe=Fr(),_oe=yR(),{start:doe}=(KR(),ie(bE)),{closeConnection:foe}=St(),NG=require("moment"),IG=iE(),{cloneDeep:Eoe}=require("lodash"),hoe=process.env[$A.PROCESS_NAME_ENV_PROP],Bo=hoe.substring(4);a(async function(){let t={id:Bo,request:void 0},r=0;try{kl.notify("Starting job:",Bo),doe(),uoe.setSchemaDataToGlobal(),await loe.setUsersToGlobal();let n=await IG.getJobById(Bo);if(yG.isEmptyOrZeroLength(n))throw new Error(`Unable to find a record in hdb_job for job: ${Bo}`);let{request:s}=n[0];if(yG.isEmptyOrZeroLength(s))throw new Error("Did not find job request in hdb_job table, unable to proceed");s=Eoe(s);let i=_oe.getOperationFunction(s);kl.trace("Running operation:",s.operation,"for job",Bo);let o=await i.job_operation_function(s);kl.trace("Result from job:",Bo,o),t.status=$A.JOB_STATUS_ENUM.COMPLETE,t.message=o,t.end_datetime=NG().valueOf(),kl.notify("Successfully completed job:",Bo)}catch(n){r=1,kl.error(n),t.status=$A.JOB_STATUS_ENUM.ERROR,t.message=n.message?n.message:n,t.end_datetime=NG().valueOf()}finally{await IG.updateJob(t),await foe(),setTimeout(()=>{process.exit(r)},3e3).unref()}},"job")();
|