harperdb 4.3.24 → 4.4.0-beta.1

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.
Files changed (86) hide show
  1. package/README.md +12 -3
  2. package/application-template/config.yaml +2 -5
  3. package/bin/harperdb.js +103 -74
  4. package/bin/lite.js +121 -22
  5. package/config/yaml/defaultConfig.yaml +11 -43
  6. package/config/yaml/defaultNatsConfig.yaml +36 -0
  7. package/index.js +3 -12
  8. package/json/hdbConnectorOptions.json +14 -14
  9. package/json/interNodeConnectorOptions.json +15 -15
  10. package/json/systemSchema.json +260 -307
  11. package/launchServiceScripts/launchInstallNATSServer.js +4 -4
  12. package/launchServiceScripts/launchNatsIngestService.js +121 -22
  13. package/launchServiceScripts/launchNatsReplyService.js +121 -22
  14. package/launchServiceScripts/launchUpdateNodes4-0-0.js +121 -22
  15. package/logs/README.md +1 -1
  16. package/npm-shrinkwrap.json +7545 -7228
  17. package/package.json +130 -131
  18. package/resources/DatabaseTransaction.d.ts +1 -0
  19. package/resources/ErrorResource.d.ts +26 -0
  20. package/resources/RecordEncoder.d.ts +3 -1
  21. package/resources/Resource.d.ts +8 -1
  22. package/resources/ResourceInterface.d.ts +7 -3
  23. package/resources/Resources.d.ts +5 -4
  24. package/resources/Table.d.ts +50 -19
  25. package/resources/auditStore.d.ts +45 -1
  26. package/resources/databases.d.ts +54 -17
  27. package/resources/search.d.ts +6 -0
  28. package/resources/transactionBroadcast.d.ts +2 -1
  29. package/server/Server.d.ts +1 -1
  30. package/server/jobs/jobProcess.js +121 -22
  31. package/server/serverHelpers/Headers.d.ts +9 -1
  32. package/server/threads/threadServer.js +121 -22
  33. package/utility/scripts/restartHdb.js +121 -22
  34. package/application-template/routes/index.js +0 -14
  35. package/studio/build-local/asset-manifest.json +0 -53
  36. package/studio/build-local/index.html +0 -1
  37. package/studio/build-local/static/css/main.6c0f1b63.css +0 -13
  38. package/studio/build-local/static/js/110.ca4244a6.chunk.js +0 -2
  39. package/studio/build-local/static/js/110.ca4244a6.chunk.js.LICENSE.txt +0 -1
  40. package/studio/build-local/static/js/228.302d7db9.chunk.js +0 -1
  41. package/studio/build-local/static/js/287.21477cf9.chunk.js +0 -1
  42. package/studio/build-local/static/js/409.17daa4fe.chunk.js +0 -2
  43. package/studio/build-local/static/js/409.17daa4fe.chunk.js.LICENSE.txt +0 -8
  44. package/studio/build-local/static/js/424.ad87c8fd.chunk.js +0 -1
  45. package/studio/build-local/static/js/446.5237e847.chunk.js +0 -2
  46. package/studio/build-local/static/js/446.5237e847.chunk.js.LICENSE.txt +0 -13
  47. package/studio/build-local/static/js/662.92e32ffc.chunk.js +0 -1
  48. package/studio/build-local/static/js/718.74e9355d.chunk.js +0 -1
  49. package/studio/build-local/static/js/723.c58acced.chunk.js +0 -2
  50. package/studio/build-local/static/js/723.c58acced.chunk.js.LICENSE.txt +0 -5
  51. package/studio/build-local/static/js/731.8a941eb3.chunk.js +0 -1
  52. package/studio/build-local/static/js/807.510f66df.chunk.js +0 -2
  53. package/studio/build-local/static/js/807.510f66df.chunk.js.LICENSE.txt +0 -5
  54. package/studio/build-local/static/js/926.88d6f9ce.chunk.js +0 -1
  55. package/studio/build-local/static/js/browse-csvupload.453237f3.chunk.js +0 -1
  56. package/studio/build-local/static/js/browse-datatable.b9ef2d28.chunk.js +0 -1
  57. package/studio/build-local/static/js/browse-entitymanager.50827a5a.chunk.js +0 -1
  58. package/studio/build-local/static/js/browse-jsonviewer.a2534004.chunk.js +0 -1
  59. package/studio/build-local/static/js/custom-functions.dd7e182c.chunk.js +0 -1
  60. package/studio/build-local/static/js/instance-charts.34d15f02.chunk.js +0 -1
  61. package/studio/build-local/static/js/instance-cluster.5bce430c.chunk.js +0 -1
  62. package/studio/build-local/static/js/instance-config.70c17b53.chunk.js +0 -1
  63. package/studio/build-local/static/js/instance-query.4f6eec62.chunk.js +0 -1
  64. package/studio/build-local/static/js/instance-roles.507a4ed0.chunk.js +0 -1
  65. package/studio/build-local/static/js/instance-status.ce9d7f64.chunk.js +0 -1
  66. package/studio/build-local/static/js/instance-users-datatable.190640fd.chunk.js +0 -1
  67. package/studio/build-local/static/js/instance-users-edit.d2444479.chunk.js +0 -1
  68. package/studio/build-local/static/js/instance-users.eabfbbde.chunk.js +0 -1
  69. package/studio/build-local/static/js/instance.a163623f.chunk.js +0 -1
  70. package/studio/build-local/static/js/instances.6b88a87c.chunk.js +0 -1
  71. package/studio/build-local/static/js/main.7106edfd.js +0 -2
  72. package/studio/build-local/static/js/main.7106edfd.js.LICENSE.txt +0 -72
  73. package/studio/build-local/static/js/offline-app.7371216b.chunk.js +0 -1
  74. package/studio/build-local/static/js/online-app.db436eec.chunk.js +0 -1
  75. package/studio/build-local/static/js/organization-billing.b2f260f0.chunk.js +0 -1
  76. package/studio/build-local/static/js/organization-users.b6171b18.chunk.js +0 -1
  77. package/studio/build-local/static/js/organization.7800f16a.chunk.js +0 -1
  78. package/studio/build-local/static/js/organizations.8bb505f2.chunk.js +0 -1
  79. package/studio/build-local/static/js/profile.292bdd86.chunk.js +0 -1
  80. package/studio/build-local/static/js/resetPassword.8fdfba77.chunk.js +0 -1
  81. package/studio/build-local/static/js/roles-jsonviewer.c11f1816.chunk.js +0 -1
  82. package/studio/build-local/static/js/signIn.b11bdc50.chunk.js +0 -1
  83. package/studio/build-local/static/js/signUp.564d4e0b.chunk.js +0 -1
  84. package/studio/build-local/static/js/structure-reloader.b6de4091.chunk.js +0 -1
  85. package/studio/build-local/static/js/topnav.4fd41d60.chunk.js +0 -1
  86. package/studio/build-local/static/js/updatePassword.e23019c7.chunk.js +0 -1
package/bin/harperdb.js CHANGED
@@ -1,124 +1,153 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var cY=Object.create;var Fl=Object.defineProperty;var lY=Object.getOwnPropertyDescriptor;var uY=Object.getOwnPropertyNames;var _Y=Object.getPrototypeOf,dY=Object.prototype.hasOwnProperty;var a=(e,t)=>Fl(e,"name",{value:t,configurable:!0});var be=(e,t)=>()=>(e&&(t=e(e=0)),t);var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ve=(e,t)=>{for(var r in t)Fl(e,r,{get:t[r],enumerable:!0})},hy=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of uY(t))!dY.call(e,s)&&s!==r&&Fl(e,s,{get:()=>t[s],enumerable:!(n=lY(t,s))||n.enumerable});return e};var G=(e,t,r)=>(r=e!=null?cY(_Y(e)):{},hy(t||!e||!e.__esModule?Fl(r,"default",{value:e,enumerable:!0}):r,e)),ae=e=>hy(Fl({},"__esModule",{value:!0}),e);var Sy=R((Fhe,my)=>{var fY=require("fast-glob"),{statSync:tS,existsSync:rS,readFileSync:EY,writeFileSync:hY}=require("fs"),{spawnSync:pY,spawn:mY,execFileSync:qhe}=require("child_process"),{isMainThread:SY}=require("worker_threads"),{join:Zi,relative:py}=require("path"),{PACKAGE_ROOT:es}=D(),{tmpdir:TY,platform:gY}=require("os");require("source-map-support").install();var RY=["resources","server","dataLayer","components"],kl="ts-build",nS,AY=__filename.endsWith("tsBuild.js");if(AY){if(SY){let r;try{tS(Zi(es,kl)),r=!0}catch{}if(r)for(let n of fY.sync(RY.map(s=>s+"/**/*.ts"),{cwd:es})){let s=0,i=0;try{s=tS(Zi(es,n)).mtimeMs-5e3,i=tS(Zi(es,kl,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."),nS=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),nS=!0;if(nS){let n=Zi(es,"node_modules/.bin/tsc");gY()==="win32"&&(n+=".cmd");let s=pY(n,{cwd:es});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Zi(TY(),"harperdb-tsc.pid"),o;if(rS(i))try{process.kill(+EY(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=mY(n,["--watch"],{cwd:es,detached:!0,stdio:"ignore"});hY(i,c.pid.toString()),c.unref()}}}}let e=my.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(es)&&!n[0].includes("node_modules")){let i=py(es,n[0]),o;i.startsWith(kl)?o=Zi(es,py(kl,i)):o=Zi(es,kl,i);let c=Zi(o,r),l=c+".js";if(rS(l))return l;if(c.includes(".")&&rS(c))return c}return t(r,n,s)}}});var D=R(($he,Py)=>{"use strict";var Pn=require("path"),OY=require("fs"),{relative:khe,join:Vhe}=Pn,{existsSync:bY}=OY;function NY(){let e=__dirname;for(;!bY(Pn.join(e,"package.json"));){let t=Pn.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(NY,"getHDBPackageRoot");var eo=NY(),Ty="js",Xd=Ty,yY="harperdb-config.yaml",IY="defaultConfig.yaml",wY="hdb",gy=`harperdb.${Xd}`,Ry=`customFunctionsServer.${Xd}`,CY=`restartHdb.${Xd}`,iS="HarperDB",Jd="Custom Functions",Zd="Clustering Hub",ef="Clustering Leaf",DY="Clustering Ingest Service",LY="Clustering Reply Service",PY="foreground.pid",MY="hdb.pid",UY="data",vY={HDB:iS,CLUSTERING_HUB:Zd,CLUSTERING_LEAF:ef,CLUSTERING_INGEST_SERVICE:DY,CLUSTERING_REPLY_SERVICE:LY,CUSTOM_FUNCTIONS:Jd,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"},BY={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},HY={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},GY={harperdb:iS,"clustering hub":Zd,"clustering leaf":ef,"custom functions":Jd,custom_functions:Jd,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},xY={CLUSTERING_HUB_PROC_DESCRIPTOR:Zd,CLUSTERING_LEAF_PROC_DESCRIPTOR:ef},sS={HDB:Pn.join(eo,"server/harperdb"),CUSTOM_FUNCTIONS:Pn.join(eo,"server/customFunctions"),CLUSTERING_HUB:Pn.join(eo,"server/nats"),CLUSTERING_LEAF:Pn.join(eo,"server/nats")},qY={HDB:Pn.join(sS.HDB,gy),CUSTOM_FUNCTIONS:Pn.join(sS.CUSTOM_FUNCTIONS,Ry)},FY={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Pn.join(eo,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Pn.join(eo,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Pn.join(eo,"launchServiceScripts/launchUpdateNodes4-0-0.js")},kY={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},Ay="support@harperdb.io",VY="customer-success@harperdb.io",Oy=1,$Y=4141,by="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",YY="https://www.harperdb.io/product",KY=`For support, please submit a request at ${by} or contact ${Ay}`,Ny=`For license support, please contact ${VY}`,WY="None of the specified records were found.",QY="hash attribute not found",jY=`Your current license only supports ${Oy} role. ${Ny}`,zY="Your current license only supports 3 connections to a node.",JY="127.0.0.1",XY=1,ZY=/^\.$/,e1=/^\.\.$/,t1="U+002E",r1=/\//g,n1="U+002F",s1=/U\+002F/g,i1=/^U\+002E$/,o1=/^U\+002EU\+002E$/,a1="d",c1=999999,l1="*",u1="--max-old-space-size=",_1="system",d1="__hdb_hash",f1=".harperdb",E1=".hdb",h1="keys",p1="hdb_boot_properties.file",m1=".updateConfig.json",S1="SIGTSTP",T1=24,g1=6e4,R1=448,A1="blob",O1="trash",b1="database",N1="schema",y1="transactions",I1=".count",w1="id",C1="PROCESS_NAME",yy={SETTINGS_PATH_KEY:"settings_path"},Iy=require("lodash"),D1={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"},L1={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},P1={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},M1={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"},U1={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"},tn="hdb_internal:",v1={CREATE_SCHEMA:tn+"create_schema",CREATE_TABLE:tn+"create_table",CREATE_ATTRIBUTE:tn+"create_attribute",ADD_USER:tn+"add_user",ALTER_USER:tn+"alter_user",DROP_USER:tn+"drop_user",HDB_NODES:tn+"hdb_nodes",HDB_USERS:tn+"hdb_users",HDB_WORKERS:tn+"hdb_workers",CATCHUP:tn+"catchup",SCHEMA_CATCHUP:tn+"schema_catchup",WORKER_ROOM:tn+"cluster_workers"},B1={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"},H1="060493.ks",G1=".license",x1={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},te={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"},q1={CSV:".csv",JSON:".json"},F1={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},k1={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Vl={};Vl[te.INSERT]=te.INSERT;Vl[te.UPDATE]=te.UPDATE;Vl[te.UPSERT]=te.UPSERT;Vl[te.DELETE]=te.DELETE;var Fe=Object.create(null);Fe[te.DESCRIBE_ALL]=te.DESCRIBE_ALL;Fe[te.DESCRIBE_TABLE]=te.DESCRIBE_TABLE;Fe[te.DESCRIBE_SCHEMA]=te.DESCRIBE_SCHEMA;Fe[te.READ_LOG]=te.READ_LOG;Fe[te.ADD_NODE]=te.ADD_NODE;Fe[te.LIST_USERS]=te.LIST_USERS;Fe[te.LIST_ROLES]=te.LIST_ROLES;Fe[te.USER_INFO]=te.USER_INFO;Fe[te.SQL]=te.SQL;Fe[te.GET_JOB]=te.GET_JOB;Fe[te.SEARCH_JOBS_BY_START_DATE]=te.SEARCH_JOBS_BY_START_DATE;Fe[te.DELETE_FILES_BEFORE]=te.DELETE_FILES_BEFORE;Fe[te.EXPORT_LOCAL]=te.EXPORT_LOCAL;Fe[te.EXPORT_TO_S3]=te.EXPORT_TO_S3;Fe[te.CLUSTER_STATUS]=te.CLUSTER_STATUS;Fe[te.REMOVE_NODE]=te.REMOVE_NODE;Fe[te.RESTART]=te.RESTART;Fe[te.CUSTOM_FUNCTIONS_STATUS]=te.CUSTOM_FUNCTIONS_STATUS;Fe[te.GET_CUSTOM_FUNCTIONS]=te.GET_CUSTOM_FUNCTIONS;Fe[te.GET_CUSTOM_FUNCTION]=te.GET_CUSTOM_FUNCTION;Fe[te.SET_CUSTOM_FUNCTION]=te.SET_CUSTOM_FUNCTION;Fe[te.DROP_CUSTOM_FUNCTION]=te.DROP_CUSTOM_FUNCTION;Fe[te.ADD_CUSTOM_FUNCTION_PROJECT]=te.ADD_CUSTOM_FUNCTION_PROJECT;Fe[te.DROP_CUSTOM_FUNCTION_PROJECT]=te.DROP_CUSTOM_FUNCTION_PROJECT;Fe[te.PACKAGE_CUSTOM_FUNCTION_PROJECT]=te.PACKAGE_CUSTOM_FUNCTION_PROJECT;Fe[te.DEPLOY_CUSTOM_FUNCTION_PROJECT]=te.DEPLOY_CUSTOM_FUNCTION_PROJECT;var V1={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"},$1={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},wy={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"},Y1=Iy.invert(wy),K1={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",HTTP_THREADRANGE:"http_threadRange",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:"operationsApi_tls",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_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",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",TLS:"tls",CLONED:"cloned"},Cy={settings_path:yy.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,customfunctions_tls:w.TLS,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,http_maxheadersize:w.HTTP_MAXHEADERSIZE,http_threadrange:w.HTTP_THREADRANGE,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:w.OPERATIONSAPI_TLS,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,storage_maxtransactionqueuetime:w.STORAGE_MAXTRANSACTIONQUEUETIME,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:w.TLS,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];Cy[t.toLowerCase()]=t}var W1={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Q1={csv_file_load:"csv_file_load",csv_data_load:te.CSV_DATA_LOAD,csv_url_load:te.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",restart_service:"restart_service"},j1={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"},z1={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},J1={VERSION_DEFAULT:"2.2.0"},X1={DEVELOPMENT:8192,DEFAULT:512},Z1={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"},eK={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"},tK={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},Dy={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},rK=Symbol("metadata"),nK="__clustering__",sK=Object.values(Dy),iK=15984864e5,Ly={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},oK=Iy.invert(Ly),aK={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"},cK=111,lK=`\r
3
- `,uK={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},_K=["*","%"],dK="unauthorized_access",fK="func_val",EK={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},hK={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},pK={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",START_JOB:"start_job",NATS_CONSUMER_UPDATE:"nats_consumer_update"},mK={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},SK={HTTP:"http"},TK={STOPPED:"stopped",ONLINE:"online"},gK="3.x.x",RK={SUCCESS:"success",FAILURE:"failure"},AK={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};Py.exports={LOCAL_HARPERDB_OPERATIONS:Fe,HDB_SUPPORT_ADDRESS:Ay,HDB_SUPPORT_URL:by,HDB_PRICING_URL:YY,SUPPORT_HELP_MSG:KY,LICENSE_HELP_MSG:Ny,HDB_PROC_NAME:gy,HDB_PROC_DESCRIPTOR:iS,CLUSTERING_LEAF_PROC_DESCRIPTOR:ef,CLUSTERING_HUB_PROC_DESCRIPTOR:Zd,SYSTEM_SCHEMA_NAME:_1,HASH_FOLDER_NAME:d1,HDB_HOME_DIR_NAME:f1,UPDATE_FILE_NAME:m1,LICENSE_KEY_DIR_NAME:h1,BOOT_PROPS_FILE_NAME:p1,JOB_TYPE_ENUM:Q1,JOB_STATUS_ENUM:x1,SYSTEM_TABLE_NAMES:M1,SYSTEM_TABLE_HASH_ATTRIBUTES:U1,OPERATIONS_ENUM:te,VALID_S3_FILE_TYPES:q1,S3_BUCKET_AUTH_KEYS:F1,VALID_SQL_OPS_ENUM:k1,GEO_CONVERSION_ENUM:$1,HDB_SETTINGS_NAMES:wy,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:Y1,SERVICE_ACTIONS_ENUM:V1,CLUSTER_MESSAGE_TYPE_ENUM:j1,CLUSTER_CONNECTION_DIRECTION_ENUM:z1,CLUSTER_EVENTS_DEFS_ENUM:Z1,PERIOD_REGEX:ZY,DOUBLE_PERIOD_REGEX:e1,UNICODE_PERIOD:t1,FORWARD_SLASH_REGEX:r1,UNICODE_FORWARD_SLASH:n1,ESCAPED_FORWARD_SLASH_REGEX:s1,ESCAPED_PERIOD_REGEX:i1,ESCAPED_DOUBLE_PERIOD_REGEX:o1,REG_KEY_FILE_NAME:H1,RESTART_TIMEOUT_MS:g1,HDB_FILE_PERMISSIONS:R1,DATABASES_DIR_NAME:b1,LEGACY_DATABASES_DIR_NAME:N1,TRANSACTIONS_DIR_NAME:y1,LIMIT_COUNT_NAME:I1,ID_ATTRIBUTE_STRING:w1,INSERT_MODULE_ENUM:L1,UPGRADE_JSON_FIELD_NAMES_ENUM:P1,RESTART_CODE:S1,RESTART_CODE_NUM:T1,CLUSTER_OPERATIONS:Vl,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:B1,HDB_INTERNAL_SC_CHANNEL_PREFIX:tn,INTERNAL_SC_CHANNELS:v1,CLUSTERING_MESSAGE_TYPES:aK,HDB_FILE_SUFFIX:E1,BLOB_FOLDER_NAME:A1,HDB_TRASH_DIR:O1,ORIGINATOR_SET_VALUE:cK,LICENSE_VALUES:J1,RAM_ALLOCATION_ENUM:X1,TIME_STAMP_NAMES_ENUM:Dy,TIME_STAMP_NAMES:sK,PERMS_UPDATE_RELEASE_TIMESTAMP:iK,SEARCH_NOT_FOUND_MESSAGE:WY,SEARCH_ATTRIBUTE_NOT_FOUND:QY,LICENSE_ROLE_DENIED_RESPONSE:jY,LICENSE_MAX_CONNS_REACHED:zY,BASIC_LICENSE_MAX_NON_CU_ROLES:Oy,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:$Y,VALUE_SEARCH_COMPARATORS:Ly,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:oK,LICENSE_FILE_NAME:G1,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:eK,NEW_LINE:lK,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:XY,MOMENT_DAYS_TAG:a1,API_TURNOVER_SEC:c1,LOOPBACK:JY,CODE_EXTENSION:Xd,WILDCARD_SEARCH_VALUE:l1,NODE_ERROR_CODES:tK,JAVASCRIPT_EXTENSION:Ty,PERMS_CRUD_ENUM:uK,UNAUTHORIZED_PERMISSION_NAME:dK,SEARCH_WILDCARDS:_K,FUNC_VAL:fK,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:EK,JWT_ENUM:hK,CLUSTERING_FLAG:nK,ITC_EVENT_TYPES:pK,CUSTOM_FUNCTION_PROC_NAME:Ry,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Jd,SERVICES:mK,THREAD_TYPES:SK,MEM_SETTING_KEY:u1,HDB_RESTART_SCRIPT:CY,PROCESS_DESCRIPTORS:vY,SERVICE_SERVERS:qY,SERVICE_SERVERS_CWD:sS,PROCESS_DESCRIPTORS_VALIDATE:GY,LAUNCH_SERVICE_SCRIPTS:FY,LOG_LEVELS:HY,PROCESS_NAME_ENV_PROP:C1,LOG_NAMES:BY,PM2_PROCESS_STATUSES:TK,CONFIG_PARAM_MAP:Cy,CONFIG_PARAMS:w,HDB_CONFIG_FILE:yY,HDB_DEFAULT_CONFIG_FILE:IY,ROLE_TYPES_ENUM:kY,BOOT_PROP_PARAMS:yy,INSTALL_PROMPTS:D1,HDB_ROOT_DIR_NAME:wY,CLUSTERING_PROCESSES:xY,FOREGROUND_PID_FILE:PY,PACKAGE_ROOT:eo,PRE_4_0_0_VERSION:gK,DATABASES_PARAM_CONFIG:W1,METADATA_PROPERTY:rK,AUTH_AUDIT_STATUS:RK,AUTH_AUDIT_TYPES:AK,HDB_PID_FILE:MY,DEFAULT_DATABASE_NAME:UY,LEGACY_CONFIG_PARAMS:K1};Sy()});var to=R((Khe,vy)=>{"use strict";var My=require("minimist");vy.exports=OK;function OK(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=Uy(process.env),n=Uy(My(process.argv))):(r=process.env,n=My(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(OK,"assignCMDENVVariables");function Uy(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(Uy,"objKeysToLowerCase")});var k=R((Qhe,dS)=>{"use strict";var Qo=require("fs-extra"),{workerData:bK,threadId:NK}=require("worker_threads"),ci=require("path"),Gy=require("yaml"),xy=require("properties-reader"),Nt=D(),By=to(),yK=require("os"),{PACKAGE_ROOT:aS}=D(),{_assignPackageExport:IK}=require("../index"),Yl={};for(let e in console)Yl[e]||(Yl[e]=console[e]);var Or={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},qy={STDOUT:"stdOut",STDERR:"stdErr"},wK=ci.join(aS,"logs"),CK=ci.join(aS,"config/yaml/",Nt.HDB_DEFAULT_CONFIG_FILE),DK=1e4,ai,ws,Ar,tf,rf,Kl,lc,$l;$l===void 0&&Fy();dS.exports={notify:$y,fatal:Yy,error:Wl,warn:_S,info:nf,debug:uS,trace:lS,setLogLevel:HK,log_level:Ar,loggerWithTag:LK,suppressLogging:PK,initLogSettings:Fy,setupConsoleLogging:ky,logCustomLevel:vK,closeLogFile:cS,getLogFilePath:()=>Kl,OUTPUTS:qy,AuthAuditLog:qK};IK("logger",dS.exports);function Fy(e=!1){try{if($l===void 0||e){cS();let t=BK(),r=By(["ROOTPATH"]);try{$l=xy(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Qo.pathExistsSync(ci.join(r.ROOTPATH,Nt.HDB_CONFIG_FILE)))throw n}({level:Ar,config_log_path:rf,to_file:ai,to_stream:ws}=GK(r.ROOTPATH?ci.join(r.ROOTPATH,Nt.HDB_CONFIG_FILE):$l.get("settings_path"))),tf=Nt.LOG_NAMES.HDB,Kl=ci.join(rf,tf)}}catch(t){if($l=void 0,t.code===Nt.NODE_ERROR_CODES.ENOENT||t.code===Nt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=By(Object.keys(Nt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Nt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let l=r[o];if(c===Nt.CONFIG_PARAMS.LOGGING_LEVEL){Ar=l;continue}if(c===Nt.CONFIG_PARAMS.LOGGING_STDSTREAMS){ws=l;continue}c===Nt.CONFIG_PARAMS.LOGGING_FILE&&(ai=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=xK();ai=ai===void 0?s:ai,ai=Hy(ai),ws=ws===void 0?i:ws,ws=Hy(ws),Ar=Ar===void 0?n:Ar,rf=wK,tf=Nt.LOG_NAMES.INSTALL,Kl=ci.join(rf,tf);return}throw Wl("Error initializing log settings"),Wl(t),t}process.env.DEV_MODE&&(ws=!0),ky()}a(Fy,"initLogSettings");var oS=!0;function ky(){cc("error",Wl),cc("warn",_S),cc("log",nf),cc("info",nf),cc("debug",uS),cc("trace",lS)}a(ky,"setupConsoleLogging");function cc(e,t){console[e]=function(...r){if(oS&&t(...r),!/PM2 log:|App \[/.test(r[0]))return Yl[e](...r)}}a(cc,"logConsole");function LK(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r($y),fatal:r(Yy),error:r(Wl),warn:r(_S),info:r(nf),debug:r(uS),trace:r(lS)};function r(n){return function(...s){return n(t,...s)}}}a(LK,"loggerWithTag");function PK(e){try{oS=!1,e()}finally{oS=!0}}a(PK,"suppressLogging");var MK=bK?.name?.replace(/ /g,"-")||"main";function li(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,l;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(l=t[0]?.serviceName,c++)),o.unshift(l||MK+"/"+NK);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}
4
- `}a(li,"createLogRecord");function Ql(e){ai&&Vy(e),ws&&process.stdout.write(e)}a(Ql,"logStdOut");function sf(e){ai&&Vy(e),ws&&process.stderr.write(e)}a(sf,"logStdErr");function Vy(e){UK(),lc?Qo.appendFileSync(lc,e):Yl.log(e)}a(Vy,"logToFile");function cS(){try{Qo.closeSync(lc)}catch{}lc=null}a(cS,"closeLogFile");function UK(){if(!lc){try{if(!Kl)debugger;lc=Qo.openSync(Kl,"a")}catch(e){Yl.error(e)}setTimeout(()=>{cS()},DK).unref()}}a(UK,"openLogFile");function nf(...e){Or[Ar]<=Or.info&&Ql(li("info",e))}a(nf,"info");function lS(...e){Or[Ar]<=Or.trace&&Ql(li("trace",e))}a(lS,"trace");function Wl(...e){Or[Ar]<=Or.error&&sf(li("error",e))}a(Wl,"error");function uS(...e){Or[Ar]<=Or.debug&&Ql(li("debug",e))}a(uS,"debug");function $y(...e){Or[Ar]<=Or.notify&&Ql(li("notify",e))}a($y,"notify");function Yy(...e){Or[Ar]<=Or.fatal&&sf(li("fatal",e))}a(Yy,"fatal");function _S(...e){Or[Ar]<=Or.warn&&sf(li("warn",e))}a(_S,"warn");function vK(e,t,...r){t===qy.STDERR?sf(li(e,r)):Ql(li(e,r))}a(vK,"logCustomLevel");function BK(){let e;try{e=yK.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ci.join(e,Nt.HDB_HOME_DIR_NAME,Nt.BOOT_PROPS_FILE_NAME);return Qo.existsSync(t)||(t=ci.join(aS,"utility/hdb_boot_properties.file")),t}a(BK,"getPropsFilePath");function HK(e){Ar=e}a(HK,"setLogLevel");function Hy(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Hy,"autoCastBoolean");function GK(e){try{if(e.includes("config/settings.js")){let o=xy(e);return{level:o.get(Nt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ci.dirname(o.get(Nt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Nt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Nt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=Gy.parseDocument(Qo.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===Nt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(GK,"getLogConfig");function xK(){try{let e=Gy.parseDocument(Qo.readFileSync(CK,"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(xK,"getDefaultConfig");function qK(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(qK,"AuthAuditLog")});var fS=R((zhe,Ky)=>{"use strict";var FK=require("util"),kK=require("path"),VK=require("child_process"),$K=FK.promisify(VK.execFile),YK=1e3*1e3*10;Ky.exports={findPs:KK};async function KK(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await $K("ps",["wwxo",`pid,${r}`],{maxBuffer:YK});for(let s of n.trim().split(`
5
- `).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:kK.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(KK,"findPs")});var _t=R((Xhe,Qy)=>{"use strict";var WK="__dbis__",QK="__txns__",jK="__environment_name__",zK="__dbi_defintion__",JK={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"},XK=["__createdtime__","__updatedtime__"],ZK="\uFFFF",Wy={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},eW=Object.values(Wy);Qy.exports={AUDIT_STORE_NAME:QK,INTERNAL_DBIS_NAME:WK,DBI_DEFINITION_NAME:zK,SEARCH_TYPES:JK,TIMESTAMP_NAMES:XK,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:jK,TRANSACTIONS_DBI_NAMES_ENUM:Wy,TRANSACTIONS_DBIS:eW,OVERFLOW_MARKER:ZK}});var rn=R((Zhe,nI)=>{"use strict";var jy=D(),zy=_t(),Jy={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},Xy=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),Zy={500:Xy("There was an error processing your request."),400:"Invalid request"},tW=Zy[Jy.INTERNAL_SERVER_ERROR],rW={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.`},nW={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},sW={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"},iW={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 ${zy.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${zy.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"},oW={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${jy.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 ${jy.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"},eI={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"},aW={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."},cW={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`},lW={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"},uW={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},_W={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`},tI={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.`},rI={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}`},dW={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."},fW={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},EW={...eI,...sW,...rW,...aW,...cW,...lW,...uW,..._W,...oW,...tI,...rI,...dW,...fW,...nW};nI.exports={CHECK_LOGS_WRAPPER:Xy,HDB_ERROR_MSGS:EW,DEFAULT_ERROR_MSGS:Zy,DEFAULT_ERROR_RESP:tW,HTTP_STATUS_CODES:Jy,LMDB_ERRORS_ENUM:iW,AUTHENTICATION_ERROR_MSGS:eI,VALIDATION_ERROR_MSGS:tI,ITC_ERRORS:rI}});var ie=R((tpe,oI)=>{"use strict";var uc=rn(),hW=k(),pW=D(),of=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,sI),this.statusCode=n||uc.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(uc.DEFAULT_ERROR_MSGS[n]?uc.DEFAULT_ERROR_MSGS[n]:uc.DEFAULT_ERROR_MSGS[uc.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&&hW[s](i)}},ES=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}},hS=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function sI(e,t,r,n=pW.LOG_LEVELS.ERROR,s=null,i=!1){if(iI(e))return e;let o=new of(e,t,r,n,s);return i&&delete o.stack,o}a(sI,"handleHDBError");function iI(e){return e.__proto__.constructor.name===of.name}a(iI,"isHDBError");oI.exports={isHDBError:iI,handleHDBError:sI,ClientError:ES,ServerError:hS,hdb_errors:uc}});var ze=R((npe,fI)=>{"use strict";var Zl=D(),mW=Y(),br=X(),eu=require("path"),SW=require("minimist"),aI=require("fs-extra"),cI=require("lodash");br.initSync();var{CONFIG_PARAMS:ro,DATABASES_PARAM_CONFIG:jl,SYSTEM_SCHEMA_NAME:af}=Zl,zl,Jl,Xl;function lI(){if(zl!==void 0)return zl;if(br.getHdbBasePath()!==void 0)return zl=br.get(ro.STORAGE_PATH)||eu.join(br.getHdbBasePath(),Zl.DATABASES_DIR_NAME),zl}a(lI,"getBaseSchemaPath");function uI(){if(Jl!==void 0)return Jl;if(br.getHdbBasePath()!==void 0)return Jl=dI(af),Jl}a(uI,"getSystemSchemaPath");function _I(){if(Xl!==void 0)return Xl;if(br.getHdbBasePath()!==void 0)return Xl=br.get(Zl.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||eu.join(br.getHdbBasePath(),Zl.TRANSACTIONS_DIR_NAME),Xl}a(_I,"getTransactionAuditStoreBasePath");function TW(e,t){let r=br.get(ro.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||eu.join(_I(),e.toString())}a(TW,"getTransactionAuditStorePath");function dI(e,t){e=e.toString(),t=t&&t.toString();let r=br.get(Zl.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||eu.join(lI(),e)}a(dI,"getSchemaPath");function gW(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,SW(process.argv));let n=r[ro.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!mW.isObject(n))throw o;i=n}for(let o of i){let c=o[af];if(!c)continue;let l=br.get(ro.DATABASES);l=l??{};let _=c?.tables?.[t]?.[jl.PATH];if(_)return cI.set(l,[af,jl.TABLES,t,jl.PATH],_),br.setProperty(ro.DATABASES,l),_;let u=c?.[jl.PATH];if(u)return cI.set(l,[af,jl.PATH],u),br.setProperty(ro.DATABASES,l),u}}let s=r[ro.STORAGE_PATH.toUpperCase()];if(s){if(!aI.pathExistsSync(s))throw new Error(s+" does not exist");let i=eu.join(s,e);return aI.mkdirsSync(i),br.setProperty(ro.STORAGE_PATH,s),i}return uI()}a(gW,"initSystemSchemaPaths");function RW(){zl=void 0,Jl=void 0,Xl=void 0}a(RW,"resetPaths");fI.exports={getBaseSchemaPath:lI,getSystemSchemaPath:uI,getTransactionAuditStorePath:TW,getTransactionAuditStoreBasePath:_I,getSchemaPath:dI,initSystemSchemaPaths:gW,resetPaths:RW}});var Nr=R((ape,SI)=>{"use strict";var AW=rn().LMDB_ERRORS_ENUM,ipe=require("lmdb"),OW=_t(),ope=require("buffer").Buffer,{OVERFLOW_MARKER:EI,MAX_SEARCH_KEY_LENGTH:cf}=OW,hI=["number","string","symbol","boolean","bigint"];function bW(e){if(e=e?.primaryStore||e,!e)throw new Error(AW.ENV_REQUIRED)}a(bW,"validateEnv");function NW(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(NW,"stringifyData");function yW(e){return e instanceof Date?e.valueOf():e}a(yW,"convertKeyValueToWrite");function IW(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(hI.includes(typeof e))return e.length>cf?[e.slice(0,cf)+EI]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(hI.includes(typeof i))i.length>cf?r.push(i.slice(0,cf)+EI):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(IW,"getIndexedValues");var lf=0,pI=0;function mI(){pI=Date.now()-performance.now()}a(mI,"adjustStartTime");mI();var wW=6e4;setInterval(mI,wW).unref();function CW(){let e=performance.now()+pI;return e>lf?(lf=e,e):(lf+=488e-6,lf)}a(CW,"getNextMonotonicTime");SI.exports={validateEnv:bW,stringifyData:NW,convertKeyValueToWrite:yW,getNextMonotonicTime:CW,getIndexedValues:IW}});var TI,ts,pS,tu=be(()=>{TI=require("events"),ts=class extends TI.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new pS;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(){let t=this.queue?.shift();return t||this.emit("drained"),t}waitForDrain(){return new Promise(t=>{!this.queue||this.queue.length===0?t(!0):(this.once("drained",()=>t(!0)),this.currentDrainResolver=t,this.drainCloseListener||(this.drainCloseListener=!0,this.on("close",()=>{this.currentDrainResolver?.(!1)})))})}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)}},pS=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 jo={};Ve(jo,{server:()=>dt});var gI,dt,yr=be(()=>{gI=require("../index"),dt={};(0,gI._assignPackageExport)("server",dt)});var TS={};Ve(TS,{loadGQLSchema:()=>PW,start:()=>SS,startOnMainThread:()=>LW});function SS({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:_,StringValueNode:u}=await import("graphql"),d=o(new c(r.toString(),s)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case l.OBJECT_TYPE_DEFINITION:let v=function(U){if(U.kind==="NonNullType"){let W=v(U.type);return W.nullable=!1,W}if(U.kind==="ListType")return{type:"array",elements:v(U.type)};let M={type:U.name?.value};return Object.defineProperty(M,"location",{value:U.loc.startToken}),M};a(v,"getProperty");let g=S.name.value,T=[],b={table:null,database:null,properties:T};E.set(g,b);for(let U of S.directives){if(U.name.value==="table"){for(let F of U.arguments)b[F.name.value]=F.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=g),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,f.push(b)}if(U.name.value==="sealed"&&(b.sealed=!0),U.name.value==="export"){b.export=!0;for(let F of U.arguments)F.name.value==="name"&&(b.export={name:F.value.value})}}let N=!1;for(let U of S.fields){let F=v(U.type);F.name=U.name.value,T.push(F);for(let M of U.directives)if(M.name.value==="primaryKey")N?console.warn("Can not define two attributes as a primary key"):(F.isPrimaryKey=!0,N=!0);else if(M.name.value==="indexed")F.indexed=!0;else if(M.name.value==="relationship"){let W={};for(let z of M.arguments)W[z.name.value]=z.value.value;F.relationship=W}else if(M.name.value==="createdTime")F.assignCreatedTime=!0;else if(M.name.value==="updatedTime")F.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")F.expiresAt=!0;else if(M.name.value==="allow"){let W=F.authorizedRoles=[];for(let z of M.arguments)z.name.value==="role"&&W.push(z.value.value)}}b.type=g,g==="Query"&&(h=b)}function m(S){let g=E.get(S.type);g?(Object.defineProperty(S,"properties",{value:g.properties}),Object.defineProperty(S,"definition",{value:g})):S.type==="array"?m(S.elements):DW.includes(S.type)||(0,RI.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(m,"connectPropertyType");for(let S of E.values())for(let g of S.properties)m(g);for(let S of f)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,mS.dirname)(n),S.tableClass):i.set((0,mS.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var mS,RI,DW,LW,PW,AI=be(()=>{mS=require("path");Re();RI=G(rt()),DW=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(SS,"start");LW=SS,PW=SS({ensureTable:St}).handleFile});async function uf(e){let t=(0,NI.pathToFileURL)(e).toString();return MW?(ru||(ru=UW(BW)),(await(await ru).import(t)).namespace):import(t)}async function UW(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),ru=new Compartment({console,Math,Date,fetch:vW,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,bI.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:er,tables:nn,databases:ft})}};let n=await(0,OI.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),ru}function vW(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 BW(){return{Resource:er,tables:nn}}var OI,bI,NI,MW,ru,gS=be(()=>{Mn();Re();OI=require("fs/promises"),bI=require("path"),NI=require("url"),MW=!1;a(uf,"secureImport");a(UW,"getCompartment");a(vW,"secureOnlyFetch");a(BW,"getGlobalVars")});var AS={};Ve(AS,{handleFile:()=>HW});async function HW(e,t,r,n){let s=new Map,i=await uf(r);c(i.default)&&n.set((0,RS.dirname)(t),i.default),o(i,(0,RS.dirname)(t));function o(l,_){for(let u in l){let d=l[u];c(d)?n.set(_+"/"+u,d):typeof d=="object"&&o(d,_+"/"+u)}}a(o,"recurseForResources");function c(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(c,"isResource"),s}var RS,yI=be(()=>{gS();RS=require("path");a(HW,"handleFile")});var bS={};Ve(bS,{start:()=>GW});function GW({resources:e}){e.set("login",OS),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var OS,II=be(()=>{Mn();a(GW,"start");OS=class extends er{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 UI={};Ve(UI,{parse:()=>yS,streamAsJSON:()=>nu,stringify:()=>zo});function nu(e){return new NS({value:e})}function wI(e){return console.error(e),JSON.stringify(e.toString())}function CI(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function zo(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===PI)return MI(e);if(t.resolution)return t.resolution.then(()=>zo(e));throw t}}function MI(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+=MI(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+zo(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function yS(e){return FW.test(e)?xW.parse(e):JSON.parse(e)}var DI,LI,xW,qW,PI,NS,FW,IS=be(()=>{DI=require("stream"),LI=G(require("json-bigint-fixes")),xW=(0,LI.default)({useNativeBigInt:!0}),qW=1e4,PI={};BigInt.prototype.toJSON=function(){throw PI};a(nu,"streamAsJSON");NS=class extends DI.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),wI)}catch(s){yield wI(s)}else yield zo(t)}else yield zo(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);CI(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>qW?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 CI(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(wI,"handleError");a(CI,"when");a(zo,"stringify");a(MI,"jsStringify");FW=/[[,:]\s*-?\d{16,}/;a(yS,"parse")});var WI=R((Ope,KI)=>{"use strict";var wS=require("recursive-iterator"),kW=require("alasql"),CS=require("clone"),vI=Y(),{handleHDBError:BI,hdb_errors:VW}=ie(),{HDB_ERROR_MSGS:HI,HTTP_STATUS_CODES:GI}=VW,{getDatabases:$W}=(Re(),ae($e)),YW=["DISTINCT_ARRAY"],xI=Symbol("validateTables"),DS=Symbol("validateTable"),Ape=Symbol("getAllColumns"),qI=Symbol("validateAllColumns"),_f=Symbol("findColumn"),FI=Symbol("validateOrderBy"),su=Symbol("validateSegment"),LS=Symbol("validateColumn"),kI=Symbol("setColumnsForTable"),VI=Symbol("checkColumnsForAsterisk"),$I=Symbol("validateGroupBy"),YI=Symbol("hasColumns"),PS=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[xI](),this[VI](),this[qI]()}[xI](){if(this[YI]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[DS](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[DS](t.table)})}}[YI](){let t=!1,r=new wS(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[DS](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=$W();if(!r[t.databaseid])throw BI(new Error,HI.SCHEMA_NOT_FOUND(t.databaseid),GI.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw BI(new Error,HI.TABLE_NOT_FOUND(t.databaseid,t.tableid),GI.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=CS(s);i.table=CS(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)}[VI](){let t=new wS(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[kI](r.tableid)}[kI](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new kW.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[qI](){this[su](this.statement.columns,!1),this[su](this.statement.joins,!1),this[su](this.statement.where,!1),this[$I](this.statement.group,!1),this[su](this.statement.order,!0)}[su](t,r){if(!t)return;let n=new wS(t),s=[];for(let{node:i,path:o}of n)!vI.isEmpty(i)&&!vI.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[FI](i):s.push(this[LS](i)));return s}[$I](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&YW.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=CS(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`}[FI](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[LS](t)}[LS](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]}};KI.exports=PS});var jI=R((Npe,QI)=>{"use strict";var MS=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")}};QI.exports=MS});var JI=R((Ipe,zI)=>{"use strict";var US=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};zI.exports=US});var tw={};Ve(tw,{HAS_EXPIRATION:()=>FS,LAST_TIMESTAMP_PLACEHOLDER:()=>au,LOCAL_TIMESTAMP:()=>KW,METADATA:()=>iu,NO_TIMESTAMP:()=>BS,PENDING_LOCAL_TIME:()=>kS,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>qS,RecordEncoder:()=>xS,TIMESTAMP_ASSIGN_LAST:()=>QW,TIMESTAMP_ASSIGN_NEW:()=>ZI,TIMESTAMP_ASSIGN_PREVIOUS:()=>ew,TIMESTAMP_PLACEHOLDER:()=>df,TIMESTAMP_RECORD_PREVIOUS:()=>HS,getUpdateRecord:()=>VS,handleLocalTimeForGets:()=>pf});function zW(){return ou[0]=ou[0]^64,WW.getFloat64(0)}function pf(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),l=c?.value,_=l?.[iu];return _>=0&&(c.metadataFlags=_,c.localTime=l.localTime,c.value=l.value,l.expiresAt>0&&(c.expiresAt=l.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[iu]>=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 l=c.value,_=l[iu];return _>=0&&(c.metadataFlags=_,c.localTime=l.localTime,c.value=l.value,l.expiresAt>0&&(c.expiresAt=l.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,Jo.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let l=0;l<Jo.length;l++){let _=Jo[l].deref();(!_||_.isDone||_.isCommitted)&&Jo.splice(l--,1)}},i.prototype.done.isTracked=!0}return e}function VS(e,t,r){return function(n,s,i,o,c=-1,l,_,u,d="put",E,f){if(E||l==null?_c=i?.localTime?HS|ew:BS:_c=l?i?.localTime?HS|16384:ZI|16384:BS,u>0&&(c|=FS),Ef=c,GS=u,i?.version===o&&l===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:_c>0},m;try{E&&(h.ifVersion=m=i?.version??null);let S=e.put(n,s,h);if(l){let g=_?.user?.username;if(f&&(ff=e.encoder.encode(f)),E&&i?.localTime){let T=i?.localTime,b=r.get(T);if(b){let N=Yt(b).previousLocalTime;return r.put(T,hf(o,t,n,N,g,d,ff),{ifVersion:m}),S}}r.put(au,hf(o,t,n,i?.localTime?1:0,g,d,ff),{append:d!=="invalidate",instructedWrite:!0,ifVersion:m})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var XI,vS,df,au,qS,KW,iu,ou,WW,BS,ZI,QW,ew,HS,FS,kS,jW,ff,_c,Ef,GS,xS,Jo,cu=be(()=>{XI=require("msgpackr");no();vS=G(k()),df=new Uint8Array([1,1,1,1,4,64,0,0]),au=new Uint8Array([1,1,1,1,1,0,0,0]),qS=new Uint8Array([1,1,1,1,3,64,0,0]),KW=Symbol("local-timestamp"),iu=Symbol("metadata"),ou=new Uint8Array(8),WW=new DataView(ou.buffer,0,8),BS=0,ZI=0,QW=1,ew=3,HS=4,FS=16,kS=1,_c=0,Ef=-1,GS=0,xS=class extends XI.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(_c||Ef>=0){let i=0,o=_c;o&&(i+=8,_c=0);let c=Ef,l=GS;c>=0&&(i+=2,Ef=-1,l&&(i+=8,GS=0));let _=jW=r.call(this,n,s|2048|i);ff=_.subarray((_.start||0)+i,_.end);let u=_.start||0;return o&&(df[4]=o,df[5]=o>>8,_.set(df,u),u+=8),c>=0&&(_[u++]=c,_[u++]=0,l&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(u,l)),_}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,l;if(i===2){if(t.copy)t.copy(ou,0,c),c+=8;else for(let d=0;d<8;d++)ou[d]=t[c++];l=zW(),i=t[c]}let _;i<32&&(o=i,c+=2,o&FS&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let u=super.decode(t.subarray(c,s),s-c);return{localTime:l,value:u,[iu]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(zW,"getTimestamp");a(pf,"handleLocalTimeForGets");Jo=[];setInterval(()=>{for(let e=0;e<Jo.length;e++){let t=Jo[e].deref();!t||t.isDone||t.isCommitted?Jo.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(vS.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):vS.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(VS,"getUpdateRecord")});var lu=R((Ppe,nw)=>{"use strict";var rw=X(),JW=D(),{RecordEncoder:XW}=(cu(),ae(tw)),Lpe=require("fs");rw.initSync();var ZW=rw.get(JW.CONFIG_PARAMS.STORAGE_CACHING)!==!1,$S=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=ZW&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:XW})}};nw.exports=$S});var uu=R((Upe,sw)=>{"use strict";var sn=X(),Un=D();sn.initSync();var mf=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=2048,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=sn.get(Un.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||sn.get(Un.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||sn.get(Un.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",sn.get(Un.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=sn.get(Un.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),sn.get(Un.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=sn.get(Un.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),sn.get(Un.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=sn.get(Un.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),sn.get(Un.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=sn.get(Un.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=sn.get(Un.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};sw.exports=mf;mf.MAX_DBS=1e4});var Ye=R((Bpe,Ew)=>{"use strict";var KS=require("lmdb"),rs=require("fs-extra"),on=require("path"),Sf=Nr(),aw=k(),Ir=rn().LMDB_ERRORS_ENUM,Tf=JI(),WS=lu(),cw=uu(),so=_t(),iw=D(),{table:eQ,resetDatabases:tQ}=(Re(),ae($e)),ow=X(),ns=so.INTERNAL_DBIS_NAME,lw=so.DBI_DEFINITION_NAME,rQ="data.mdb",nQ="lock.mdb",_u=".mdb",sQ="-lock",YS=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=vn(t,r),this.key_type=this.dbi[so.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[so.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new KS.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function gf(e,t){if(e===void 0)throw new Error(Ir.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Ir.ENV_NAME_REQUIRED)}a(gf,"pathEnvNameValidation");async function QS(e,t,r=!0){try{await rs.access(e)}catch(n){throw n.code==="ENOENT"?new Error(Ir.INVALID_BASE_PATH):n}try{let n=on.join(e,t+_u);return await rs.access(n,rs.constants.R_OK|rs.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await rs.access(on.join(e,t,rQ),rs.constants.R_OK|rs.constants.F_OK),on.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(Ir.INVALID_ENVIRONMENT)}else throw new Error(Ir.INVALID_ENVIRONMENT);throw n}}a(QS,"validateEnvironmentPath");function Rf(e,t){if(Sf.validateEnv(e),t===void 0)throw new Error(Ir.DBI_NAME_REQUIRED)}a(Rf,"validateEnvDBIName");async function iQ(e,t,r=!1,n=!1){gf(e,t);let s=on.basename(e);t=t.toString();let i=ow.get(iw.CONFIG_PARAMS.DATABASES);i||ow.setProperty(iw.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await QS(e,t,n),uw(e,t,r)}catch(o){if(o.message===Ir.INVALID_ENVIRONMENT){let c=on.join(e,t);await rs.mkdirp(n?c:e);let l=new cw(n?c:c+_u,!1),_=KS.open(l);_.dbis=Object.create(null);let u=new WS(!1);_.openDB(ns,u),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=jS(e,t,r);return _[so.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(iQ,"createEnvironment");async function oQ(e,t,r,n=!0){gf(e,t),t=t.toString();let s=on.join(e,t);return eQ({table:t,database:on.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(oQ,"copyEnvironment");async function uw(e,t,r=!1){gf(e,t),t=t.toString();let n=jS(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 QS(e,t),i=on.join(e,t+_u),o=s!=i,c=new cw(s,o),l=KS.open(c);l.dbis=Object.create(null);let _=dw(l);for(let u=0;u<_.length;u++)vn(l,_[u]);return l[so.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=l,l}a(uw,"openEnvironment");async function aQ(e,t,r=!1){gf(e,t),t=t.toString();let n=on.join(e,t+_u),s=await QS(e,t);if(global.lmdb_map!==void 0){let i=jS(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await _w(o),delete global.lmdb_map[i]}}await rs.remove(s),await rs.remove(s===n?s+sQ:on.join(on.dirname(s),nQ))}a(aQ,"deleteEnvironment");async function _w(e){Sf.validateEnv(e);let t=e[so.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(_w,"closeEnvironment");function jS(e,t,r=!1){let s=`${on.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(jS,"getCachedEnvironmentName");function cQ(e){Sf.validateEnv(e);let t=Object.create(null),r=vn(e,ns);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==ns)try{t[n]=Object.assign(new Tf,s)}catch{aw.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(cQ,"listDBIDefinitions");function dw(e){Sf.validateEnv(e);let t=[],r=vn(e,ns);for(let{key:n}of r.getRange({start:!1}))n!==ns&&t.push(n);return t}a(dw,"listDBIs");function lQ(e,t){let n=vn(e,ns).getEntry(t),s=new Tf;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{aw.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(lQ,"getDBIDefinition");function fw(e,t,r,n=!r){if(Rf(e,t),t=t.toString(),t===ns)throw new Error(Ir.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return vn(e,t)}catch(s){if(s.message===Ir.DBI_DOES_NOT_EXIST){let i=new WS(r,n===!0),o=e.openDB(t,i),c=new Tf(r===!0,n);return o[lw]=c,vn(e,ns).putSync(t,c),e.dbis[t]=o,o}throw s}}a(fw,"createDBI");function vn(e,t){if(Rf(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==ns?r=lQ(e,t):r=new Tf,r===void 0)throw new Error(Ir.DBI_DOES_NOT_EXIST);let n;try{let s=new WS(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(Ir.DBI_DOES_NOT_EXIST):s}return n[lw]=r,e.dbis[t]=n,n}a(vn,"openDBI");function uQ(e,t){Rf(e,t),t=t.toString();let r=vn(e,t),n=r.getStats();return r[so.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(uQ,"statDBI");async function _Q(e,t){try{let r=on.join(e,t+_u);return(await rs.stat(r)).size}catch{throw new Error(Ir.INVALID_ENVIRONMENT)}}a(_Q,"environmentDataSize");function dQ(e,t){if(Rf(e,t),t=t.toString(),t===ns)throw new Error(Ir.CANNOT_DROP_INTERNAL_DBIS_NAME);vn(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],vn(e,ns).removeSync(t)}a(dQ,"dropDBI");function fQ(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{vn(e,i)}catch(o){if(o.message===Ir.DBI_DOES_NOT_EXIST)fw(e,i,i!==t,i===t),n=!0;else throw o}}n&&tQ()}a(fQ,"initializeDBIs");Ew.exports={openDBI:vn,openEnvironment:uw,createEnvironment:iQ,listDBIs:dw,listDBIDefinitions:cQ,createDBI:fw,dropDBI:dQ,statDBI:uQ,deleteEnvironment:aQ,initializeDBIs:fQ,TransactionCursor:YS,environmentDataSize:_Q,copyEnvironment:oQ,closeEnvironment:_w}});var pw=R((Gpe,hw)=>{"use strict";var zS=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};hw.exports=zS});var Sw=R((qpe,mw)=>{"use strict";var JS=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}};mw.exports=JS});var gw=R((kpe,Tw)=>{"use strict";var XS=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Tw.exports=XS});var Zo=R((Wpe,Ow)=>{"use strict";var EQ=Ye(),hQ=pw(),pQ=Sw(),mQ=gw(),Cs=Nr(),du=rn().LMDB_ERRORS_ENUM,SQ=_t(),ui=D(),TQ=Y(),gQ=require("uuid"),$pe=require("lmdb"),{handleHDBError:RQ,hdb_errors:AQ}=ie(),{OVERFLOW_MARKER:Ype,MAX_SEARCH_KEY_LENGTH:Kpe}=SQ,Rw=X();Rw.initSync();var Af=Rw.get(ui.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),ZS=ui.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Xo=ui.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function OQ(e,t,r,n,s=Cs.getNextMonotonicTime()){nT(e,t,r,n),eT(e,t,r);let i=new hQ,o=[],c=[];for(let l=0;l<n.length;l++){let _=n[l];Aw(_,!0,s);let u=bQ(e,t,r,_),d=_[t];o.push(u),c.push(d)}return tT(o,c,n,i,s)}a(OQ,"insertRecords");function bQ(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 u=c([[{}]]);Array.isArray(u)&&(c=u[0][ui.FUNC_VAL],n[o]=c)}let l=Cs.getIndexedValues(c),_=e.dbis[o];if(l){Af&&_.prefetch(l.map(u=>({key:u,value:s})),Of);for(let u=0,d=l.length;u<d;u++)_.put(l[u],s)}}Af&&e.dbis[t].prefetch([s],Of),e.dbis[t].put(s,n,n[Xo])})}a(bQ,"insertRecord");function NQ(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(NQ,"removeSkippedRecords");function Aw(e,t,r){let n=r>0;(n||!Number.isInteger(e[Xo]))&&(e[Xo]=r||(r=Cs.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[ZS]))&&(e[ZS]=r||Cs.getNextMonotonicTime()):delete e[ZS]}a(Aw,"setTimestamps");function eT(e,t,r){r.indexOf(ui.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(ui.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(ui.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(ui.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),EQ.initializeDBIs(e,t,r)}a(eT,"initializeTransaction");async function yQ(e,t,r,n,s=Cs.getNextMonotonicTime()){nT(e,t,r,n),eT(e,t,r);let i=new pQ,o=[],c=[],l=[];for(let _=0;_<n.length;_++){let u=n[_],d=u[t],E;try{E=rT(e,t,u,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),l.push(d)}return tT(c,l,n,i,s,o)}a(yQ,"updateRecords");async function IQ(e,t,r,n,s=Cs.getNextMonotonicTime()){try{nT(e,t,r,n)}catch(l){throw RQ(l,l.message,AQ.HTTP_STATUS_CODES.BAD_REQUEST)}eT(e,t,r);let i=new mQ,o=[],c=[];for(let l=0;l<n.length;l++){let _=n[l],u;TQ.isEmpty(_[t])?(u=gQ.v4(),_[t]=u):u=_[t];let d=rT(e,t,_,u,i,!1,s);o.push(d),c.push(u)}return tT(o,c,n,i,s)}a(IQ,"upsertRecords");async function tT(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,l=o.length;c<l;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Cs.getNextMonotonicTime(),NQ(r,i),n}a(tT,"finalizeWrite");function rT(e,t,r,n,s,i=!1,o){let c=e.dbis[t],l=c.getEntry(n),_=l?.value,u=_;if(!_){if(i)return!1;_={}}if(Aw(r,!u,o),Number.isInteger(r[Xo])&&_[Xo]>r[Xo])return!1;u&&s.original_records.push(_);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let m=r[h],S=e.dbis[h];if(S===void 0)continue;let g=_[h];if(typeof m=="function"){let b=m([[_]]);Array.isArray(b)&&(m=b[0][ui.FUNC_VAL],r[h]=m)}if(m===g)continue;let T=Cs.getIndexedValues(g);if(T){Af&&S.prefetch(T.map(b=>({key:b,value:n})),Of);for(let b=0,N=T.length;b<N;b++)S.remove(T[b],n)}if(T=Cs.getIndexedValues(m),T){Af&&S.prefetch(T.map(b=>({key:b,value:n})),Of);for(let b=0,N=T.length;b<N;b++)S.put(T[b],n)}}let f=Object.assign({},_,r);c.put(n,f,f[Xo])},"do_put");return l?d=c.ifVersion(n,l.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:rT(e,t,r,n,s,i,o))}a(rT,"updateUpsertRecord");function wQ(e,t,r){if(Cs.validateEnv(e),t===void 0)throw new Error(du.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(du.WRITE_ATTRIBUTES_REQUIRED):new Error(du.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(wQ,"validateBasic");function nT(e,t,r,n){if(wQ(e,t,r),!Array.isArray(n))throw n===void 0?new Error(du.RECORDS_REQUIRED):new Error(du.RECORDS_MUST_BE_ARRAY)}a(nT,"validateWrite");function Of(){}a(Of,"noop");Ow.exports={insertRecords:OQ,updateRecords:yQ,upsertRecords:IQ}});var _i=R((jpe,CQ)=>{CQ.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 Ls=R((zpe,yw)=>{"use strict";var Nw=Y(),bw=D(),dc=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Ds=require("joi"),io={schema_format:{pattern:dc,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},DQ=Ds.alternatives(Ds.string().min(1).max(io.schema_length.maximum).pattern(dc).messages({"string.pattern.base":"{:#label} "+io.schema_format.message}),Ds.number(),Ds.array()).required(),LQ=Ds.alternatives(Ds.string().min(1).max(io.schema_length.maximum).pattern(dc).messages({"string.pattern.base":"{:#label} "+io.schema_format.message}),Ds.number()),PQ=Ds.alternatives(Ds.string().min(1).max(io.schema_length.maximum).pattern(dc).messages({"string.pattern.base":"{:#label} "+io.schema_format.message}),Ds.number()).required();function MQ(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>io.schema_length.maximum?`'${e}' maximum of 250 characters`:dc.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(MQ,"checkValidTable");function UQ(e,t){return Nw.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(UQ,"validateSchemaExists");function vQ(e,t){let r=t.state.ancestors[0].schema;return Nw.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(vQ,"validateTableExists");function BQ(e,t){return e.toLowerCase()===bw.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${bw.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(BQ,"validateSchemaName");yw.exports={common_validators:io,schema_regex:dc,hdb_schema_table:DQ,validateSchemaExists:UQ,validateTableExists:vQ,validateSchemaName:BQ,checkValidTable:MQ,hdb_database:LQ,hdb_table:PQ}});var nt=R((Xpe,Iw)=>{"use strict";var wr=require("validate.js");wr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||wr.validators.type.checks[t](e)?null:` must be a '${t}' value`};wr.validators.type.checks={Object:function(e){return wr.isObject(e)&&!wr.isArray(e)},Array:wr.isArray,Integer:wr.isInteger,Number:wr.isNumber,String:wr.isString,Date:wr.isDate,Boolean:function(e){return typeof e=="boolean"}};wr.validators.hasValidFileExt=function(e,t){return wr.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};Iw.exports={validateObject:HQ,validateObjectAsync:GQ,validateBySchema:xQ};function HQ(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=wr(e,t,{format:"flat"});return r?new Error(r):null}a(HQ,"validateObject");async function GQ(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await wr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(GQ,"validateObjectAsync");function xQ(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(xQ,"validateBySchema")});var bf=R((eme,ww)=>{var{common_validators:Ps}=Ls(),Eu=nt(),fu="is required",yt={database:{presence:!1,format:Ps.schema_format,length:Ps.schema_length},schema:{presence:!1,format:Ps.schema_format,length:Ps.schema_length},table:{presence:!0,format:Ps.schema_format,length:Ps.schema_length},attribute:{presence:!0,format:Ps.schema_format,length:Ps.schema_length},hash_attribute:{presence:!0,format:Ps.schema_format,length:Ps.schema_length}};function hu(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(hu,"makeAttributesStrings");function qQ(e){return e=hu(e),yt.table.presence=!1,yt.attribute.presence=!1,yt.hash_attribute.presence=!1,Eu.validateObject(e,yt)}a(qQ,"schema_object");function FQ(e){return e=hu(e),yt.table.presence={message:fu},yt.attribute.presence=!1,yt.hash_attribute.presence=!1,Eu.validateObject(e,yt)}a(FQ,"table_object");function kQ(e){return e=hu(e),yt.table.presence={message:fu},yt.attribute.presence=!1,Eu.validateObject(e,yt)}a(kQ,"create_table_object");function VQ(e){return e=hu(e),yt.table.presence={message:fu},yt.attribute.presence={message:fu},yt.hash_attribute.presence=!1,Eu.validateObject(e,yt)}a(VQ,"attribute_object");function $Q(e){return e=hu(e),yt.table.presence={message:fu},yt.attribute.presence=!1,yt.hash_attribute.presence=!1,Eu.validateObject(e,yt)}a($Q,"describe_table");function YQ(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(YQ,"validateTableResidence");ww.exports={schema_object:qQ,create_table_object:kQ,table_object:FQ,attribute_object:VQ,describe_table:$Q,validateTableResidence:YQ}});var Dw=R((rme,Cw)=>{"use strict";var KQ=require("uuid"),sT=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||KQ.v4(),this.schema_table=`${this.schema}.${this.table}`}};Cw.exports=sT});var Nf=R((sme,Lw)=>{"use strict";var WQ=Dw(),iT=class extends WQ{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}};Lw.exports=iT});var Mw=R((ome,Pw)=>{"use strict";Pw.exports=jQ;var QQ="inserted";function jQ(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===QQ?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(jQ,"returnObject")});var yf=R((cme,Gw)=>{"use strict";var zQ=D(),oT=Ye(),JQ=Zo(),{getSystemSchemaPath:XQ,getSchemaPath:ZQ}=ze(),ej=_i(),tj=bf(),rj=Nf(),nj=Mw(),{handleHDBError:Uw,hdb_errors:Bw}=ie(),vw=Y(),{HTTP_STATUS_CODES:sj}=Bw,aT=ej.hdb_attribute,Hw=[];for(let e=0;e<aT.attributes.length;e++)Hw.push(aT.attributes[e].attribute);var ij="inserted";Gw.exports=oj;async function oj(e){let t=tj.attribute_object(e);if(t)throw Uw(new Error,t.message,Bw.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&vw.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Uw(new Error,r,sj.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=vw.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 rj(e.schema,e.table,e.attribute,e.id);try{let i=await oT.openEnvironment(ZQ(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}`);oT.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await oT.openEnvironment(XQ(),zQ.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:l}=await JQ.insertRecords(o,aT.hash_attribute,Hw,[s]);return nj(ij,c,{records:[s]},l)}catch(i){throw i}}a(oj,"lmdbCreateAttribute")});var lT=R((ume,qw)=>{var{hdb_table:aj,hdb_database:xw}=Ls(),cj=nt(),cT=require("joi"),lj={undefined:"undefined",null:"null"},uj=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||lj[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"),_j=cT.object({database:xw,schema:xw,table:aj,records:cT.array().items(cT.object().custom(uj)).required()});qw.exports=function(e){return cj.validateBySchema(e,_j)}});var pu=R((fme,kw)=>{"use strict";var di=Y(),Fw=k(),dme=lT(),{getDatabases:dj}=(Re(),ae($e)),{ClientError:ea}=ie();kw.exports=fj;function fj(e){if(di.isEmpty(e))throw new ea("invalid update parameters defined.");if(di.isEmptyOrZeroLength(e.schema))throw new ea("invalid schema specified.");if(di.isEmptyOrZeroLength(e.table))throw new ea("invalid table specified.");if(!Array.isArray(e.records))throw new ea("records must be an array");let t=dj()[e.schema]?.[e.table];if(di.isEmpty(t))throw new ea(`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&&di.isEmptyOrZeroLength(o[r]))throw Fw.error("a valid hash attribute must be provided with update record:",o),new ea("a valid hash attribute must be provided with update record, check log for more info");if(!di.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw Fw.error(`a valid hash value must be provided with ${e.operation} record:`,o),new ea(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!di.isEmpty(o[r])&&o[r]!==""&&n.has(di.autoCast(o[r]))&&(o.skip=!0),n.add(di.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(fj,"insertUpdateValidate")});var mu=R((hme,Vw)=>{"use strict";var Ej=D().OPERATIONS_ENUM,uT=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=Ej.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Vw.exports=uT});var Su=R((Sme,Yw)=>{"use strict";var mme=mu(),If=D(),_T=Y(),$w=k(),hj=require("uuid"),{handleHDBError:wf,hdb_errors:pj}=ie(),{HDB_ERROR_MSGS:Cf,HTTP_STATUS_CODES:Df}=pj;Yw.exports=mj;function mj(e,t,r){for(let s=0;s<t.length;s++)Sj(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];Tj(i,r,e.operation)}}a(mj,"processRows");function Sj(e){if(Buffer.byteLength(String(e))>If.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw wf(new Error,Cf.ATTR_NAME_LENGTH_ERR(e),Df.BAD_REQUEST,void 0,void 0,!0);if(_T.isEmptyOrZeroLength(e)||_T.isEmpty(e.trim()))throw wf(new Error,Cf.ATTR_NAME_NULLISH_ERR,Df.BAD_REQUEST,void 0,void 0,!0)}a(Sj,"validateAttribute");function Tj(e,t,r){if(!e.hasOwnProperty(t)||_T.isEmptyOrZeroLength(e[t])){if(r===If.OPERATIONS_ENUM.INSERT||r===If.OPERATIONS_ENUM.UPSERT){e[t]=hj.v4();return}throw $w.error("Update transaction aborted due to record with no hash value:",e),wf(new Error,Cf.RECORD_MISSING_HASH_ERR,Df.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>If.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw $w.error(e),wf(new Error,Cf.HASH_VAL_LENGTH_ERR,Df.BAD_REQUEST,void 0,void 0,!0)}a(Tj,"validateHash")});var Ww=R((gme,Kw)=>{"use strict";var dT=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Kw.exports=dT});var zw=R((Ame,jw)=>{"use strict";var fT=Ye(),gj=k(),Qw=rn().LMDB_ERRORS_ENUM;jw.exports=Rj;async function Rj(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 fT.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Qw.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await fT.closeEnvironment(global.lmdb_map[n]),await fT.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Qw.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){gj.error(t)}}a(Rj,"cleanLMDBMap")});var fi=R((bme,eC)=>{"use strict";var Tu=require("crypto"),Aj=X(),{CONFIG_PARAMS:Oj}=D(),Xw="aes-256-cbc",bj=32,Nj=16,ET=64,Zw=32,yj=ET+Zw,Jw=new Map;eC.exports={encrypt:Ij,decrypt:wj,createNatsTableStreamName:Cj};function Ij(e){let t=Tu.randomBytes(bj),r=Tu.randomBytes(Nj),n=Tu.createCipheriv(Xw,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(Ij,"encrypt");function wj(e){let t=e.substr(0,ET),r=e.substr(ET,Zw),n=e.substr(yj,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Tu.createDecipheriv(Xw,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(wj,"decrypt");function Cj(e,t){let r=Aj.get(Oj.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Jw.get(r);return n||(n=Tu.createHash("md5").update(r).digest("hex"),Jw.set(r,n)),n}a(Cj,"createNatsTableStreamName")});var Ei=R((Ime,rC)=>{"use strict";var yme=ur(),gu=k(),tC=bf(),Dj=fi(),Lf=Y(),{handleHDBError:Pf,hdb_errors:Lj}=ie(),{HDB_ERROR_MSGS:Mf,HTTP_STATUS_CODES:hT}=Lj,Pj=X();Pj.initSync();var{getDatabases:pT}=(Re(),ae($e)),Mj=require("fs-extra");rC.exports={describeAll:Uj,describeTable:Uf,describeSchema:vj};async function Uj(e){try{let t=Lf.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=pT(),i={},o={},c=[],l=e?.exact_count;for(let u in s){i[u]=!0,!t&&!n&&(o[u]=e.hdb_user.role.permission[u].describe);let d=s[u];for(let E in d)try{let f;if(t||n)f=await Uf({schema:u,table:E,exact_count:l});else if(r&&r[u].describe&&r[u].tables[E].describe){let h=r[u].tables[E].attribute_permissions;f=await Uf({schema:u,table:E,exact_count:l},h)}f&&c.push(f)}catch(f){gu.error(f)}}let _={};for(let u in c)t||n?(_[c[u].schema]==null&&(_[c[u].schema]={}),_[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]):o[c[u].schema]&&(_[c[u].schema]==null&&(_[c[u].schema]={}),_[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]);for(let u in i)t||n?_[u]={}:o[u]&&(_[u]={});return _}catch(t){return gu.error("Got an error in describeAll"),gu.error(t),Pf(new Error,Mf.DESCRIBE_ALL_ERR)}}a(Uj,"describeAll");async function Uf(e,t){Lf.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=tC.describe_table(e);if(i)throw i;let c=pT()[r];if(!c)throw Pf(new Error,Mf.SCHEMA_NOT_FOUND(e.schema),hT.NOT_FOUND);let l=c[n];if(!l)throw Pf(new Error,Mf.TABLE_NOT_FOUND(e.schema,e.table),hT.NOT_FOUND);function _(f){u.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(h=>({type:h.type,name:h.name})):void 0}))}a(_,"pushAtt");let u=[];if(s){let f={};s.forEach(h=>{h.describe&&(f[h.attribute_name]=!0)}),l.attributes.forEach(h=>{f[h.name]&&_(h)})}else l.attributes?.forEach(f=>_(f));let d;try{d=(await Mj.stat(l.primaryStore.env.path)).size}catch(f){gu.warn("unable to get database size",f)}let E={schema:r,name:l.tableName,hash_attribute:l.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:u,db_size:d};E.clustering_stream_name=Dj.createNatsTableStreamName(E.schema,E.name);try{let f=l.getRecordCount({exactCount:e.exact_count==="true"});E.record_count=f.recordCount,E.estimated_record_range=f.estimatedRange;let h=l.auditStore;if(h)for(let m of h.getKeys({reverse:!0,limit:1}))E.last_updated_record=m[0];if(!E.last_updated_record&&l.indices.__updatedtime__)for(let m of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))E.last_updated_record=m}catch(f){gu.warn(`unable to stat table dbi due to ${f}`)}return E}a(Uf,"descTable");async function vj(e){Lf.transformReq(e);let t=tC.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=pT()[n];if(!i)throw Pf(new Error,Mf.SCHEMA_NOT_FOUND(e.schema),hT.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),Lf.isEmpty(l)||l.describe){let _=await Uf({schema:e.schema,table:c,exact_count:e.exact_count},l?l.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(vj,"describeSchema")});var Bn=R((Lme,aC)=>{var Bj=_i(),{callbackify:sC,promisify:Hj}=require("util"),{getDatabases:iC}=(Re(),ae($e));aC.exports={setSchemaDataToGlobal:nC,getTableSchema:Gj,getSystemSchema:xj,setSchemaDataToGlobalAsync:Hj(nC)};var oC=Ei(),Cme=sC(oC.describeAll),Dme=sC(oC.describeTable);function nC(e){global.hdb_schema=iC(),e&&e()}a(nC,"setSchemaDataToGlobal");function Gj(e,t,r){let n=iC()[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(Gj,"getTableSchema");function xj(){return Bj}a(xj,"getSystemSchema")});var Cr=R((Mme,_C)=>{"use strict";var Bf=lT(),tr=Y(),qj=require("util"),Hf=Hn(),Fj=Bn(),cC=k(),{handleHDBError:ta,hdb_errors:kj}=ie(),{HTTP_STATUS_CODES:ra}=kj,Vj=qj.promisify(Fj.getTableSchema),$j="updated",lC="inserted",uC="upserted";_C.exports={insert:Kj,update:Wj,upsert:Qj,validation:Yj,flush:jj};async function Yj(e){if(tr.isEmpty(e))throw new Error("invalid update parameters defined.");if(tr.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(tr.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await Vj(e.schema,e.table),r=Bf(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&&tr.isEmptyOrZeroLength(c[n]))throw cC.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(!tr.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw cC.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!tr.isEmpty(c[n])&&c[n]!==""&&s.has(tr.autoCast(c[n]))&&(c.skip=!0),s.add(tr.autoCast(c[n]));for(let l in c)i[l]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(Yj,"validation");async function Kj(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=Bf(e);if(t)throw ta(new Error,t.message,ra.BAD_REQUEST);tr.transformReq(e);let r=tr.checkSchemaTableExist(e.schema,e.table);if(r)throw ta(new Error,r,ra.BAD_REQUEST);let n=await Hf.createRecords(e);return vf(lC,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(Kj,"insertData");async function Wj(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=Bf(e);if(t)throw ta(new Error,t.message,ra.BAD_REQUEST);tr.transformReq(e);let r=tr.checkSchemaTableExist(e.schema,e.table);if(r)throw ta(new Error,r,ra.BAD_REQUEST);let n=await Hf.updateRecords(e);return tr.isEmpty(n.existing_rows)?vf($j,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):vf(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(Wj,"updateData");async function Qj(e){if(e.operation!=="upsert")throw ta(new Error,"invalid operation, must be upsert",ra.INTERNAL_SERVER_ERROR);let t=Bf(e);if(t)throw ta(new Error,t.message,ra.BAD_REQUEST);tr.transformReq(e);let r=tr.checkSchemaTableExist(e.schema,e.table);if(r)throw ta(new Error,r,ra.BAD_REQUEST);let n=await Hf.upsertRecords(e);return vf(uC,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(Qj,"upsertData");function vf(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===lC?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===uC?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(vf,"returnObject");function jj(e){return tr.transformReq(e),Hf.flush(e.schema,e.table)}a(jj,"flush")});var ST=R((vme,EC)=>{var zj=nt(),mT=require("joi"),{hdb_table:Jj,hdb_database:dC}=Ls(),fC={schema:dC,database:dC,table:Jj},Xj={date:mT.date().iso().required()},Zj={timestamp:mT.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};EC.exports=function(e,t){let r=t==="timestamp"?{...fC,...Zj}:{...fC,...Xj},n=mT.object(r);return zj.validateBySchema(e,n)}});var mC=R((Bme,pC)=>{var ez=nt(),TT=require("joi"),{hdb_table:tz,hdb_database:hC}=Ls(),rz=TT.object({schema:hC,database:hC,table:tz,hash_values:TT.array().required(),ids:TT.array()});pC.exports=function(e){return ez.validateBySchema(e,rz)}});var OT=R((Hme,SC)=>{"use strict";var gT=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}},RT=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}},AT=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};SC.exports={InsertObject:gT,NoSQLSeachObject:RT,DeleteResponseObject:AT}});var ia=R((xme,OC)=>{"use strict";var gC=ST(),nz=mC(),na=Y(),TC=require("moment"),RC=k(),{promisify:sz,callbackify:iz}=require("util"),sa=D(),oz=Bn(),bT=sz(oz.getTableSchema),NT=Hn(),{DeleteResponseObject:az}=OT(),{handleHDBError:oo,hdb_errors:cz}=ie(),{HDB_ERROR_MSGS:Gf,HTTP_STATUS_CODES:ao}=cz,lz="records successfully deleted",uz=iz(AC);OC.exports={delete:uz,deleteRecord:AC,deleteFilesBefore:_z,deleteAuditLogsBefore:dz};async function _z(e){let t=gC(e,"date");if(t)throw oo(t,t.message,ao.BAD_REQUEST,void 0,void 0,!0);if(na.transformReq(e),!TC(e.date,TC.ISO_8601).isValid())throw oo(new Error,Gf.INVALID_DATE,ao.BAD_REQUEST,sa.LOG_LEVELS.ERROR,Gf.INVALID_DATE,!0);let n=na.checkSchemaTableExist(e.schema,e.table);if(n)throw oo(new Error,n,ao.NOT_FOUND,sa.LOG_LEVELS.ERROR,n,!0);let s=await NT.deleteRecordsBefore(e);if(await bT(e.schema,e.table),RC.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(_z,"deleteFilesBefore");async function dz(e){let t=gC(e,"timestamp");if(t)throw oo(t,t.message,ao.BAD_REQUEST,void 0,void 0,!0);if(na.transformReq(e),isNaN(e.timestamp))throw oo(new Error,Gf.INVALID_VALUE("Timestamp"),ao.BAD_REQUEST,sa.LOG_LEVELS.ERROR,Gf.INVALID_VALUE("Timestamp"),!0);let r=na.checkSchemaTableExist(e.schema,e.table);if(r)throw oo(new Error,r,ao.NOT_FOUND,sa.LOG_LEVELS.ERROR,r,!0);let n=await NT.deleteAuditLogsBefore(e);return await bT(e.schema,e.table),RC.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(dz,"deleteAuditLogsBefore");async function AC(e){e.ids&&(e.hash_values=e.ids);let t=nz(e);if(t)throw oo(t,t.message,ao.BAD_REQUEST,void 0,void 0,!0);na.transformReq(e);let r=na.checkSchemaTableExist(e.schema,e.table);if(r)throw oo(new Error,r,ao.NOT_FOUND,sa.LOG_LEVELS.ERROR,r,!0);try{await bT(e.schema,e.table);let n=await NT.deleteRecords(e);return na.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${lz}`),n}catch(n){if(n.message===sa.SEARCH_NOT_FOUND_MESSAGE){let s=new az;return s.message=sa.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(AC,"deleteRecord")});var xf=R((Fme,yC)=>{var fz=require("crypto"),bC=9;function Ez(e){let t=pz(bC),r=NC(e+t);return t+r}a(Ez,"createHash");function hz(e,t){let r=e?.substr(0,bC),n=r+NC(t+r);return e===n}a(hz,"validateHash");function pz(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(pz,"generateSalt");function NC(e){return fz.createHash("md5").update(e).digest("hex")}a(NC,"md5");yC.exports={hash:Ez,validate:hz}});var wC=R((Vme,IC)=>{var yT=nt(),_r={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 mz(e){return _r.password.presence=!0,_r.username.presence=!0,_r.role.presence=!0,_r.active.presence=!0,yT.validateObject(e,_r)}a(mz,"addUserValidation");function Sz(e){return _r.password.presence=!1,_r.username.presence=!0,_r.role.presence=!1,_r.active.presence=!1,yT.validateObject(e,_r)}a(Sz,"alterUserValidation");function Tz(e){return _r.password.presence=!1,_r.username.presence=!0,_r.role.presence=!1,_r.active.presence=!1,yT.validateObject(e,_r)}a(Tz,"dropUserValidation");IC.exports={addUserValidation:mz,alterUserValidation:Sz,dropUserValidation:Tz}});var Ze=R((Kme,DC)=>{"use strict";var{platform:Yme}=require("os"),gz="nats-server.zip",IT="nats-server",Rz=process.platform==="win32"?`${IT}.exe`:IT,Az=/^[^\s.,*>]+$/,CC="__request__",Oz=a(e=>`${e}.${CC}`,"REQUEST_SUBJECT"),bz={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},Nz={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},yz={HUB:"hub.pid",LEAF:"leaf.pid"},Iz={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},wz={SUCCESS:"success",ERROR:"error"},Cz={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},Dz={TXN:"txn",MSGID:"msgid"},fc={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},Lz={[fc.ERR]:1,[fc.WRN]:2,[fc.INF]:3,[fc.DBG]:4,[fc.TRC]:5},Pz={debug:"-D",trace:"-DVV"};DC.exports={NATS_SERVER_ZIP:gz,NATS_SERVER_NAME:IT,NATS_BINARY_NAME:Rz,PID_FILES:yz,NATS_CONFIG_FILES:Nz,SERVER_SUFFIX:Iz,NATS_TERM_CONSTRAINTS_RX:Az,REQUEST_SUFFIX:CC,UPDATE_REMOTE_RESPONSE_STATUSES:wz,CLUSTER_STATUS_STATUSES:Cz,REQUEST_SUBJECT:Oz,SUBJECT_PREFIXES:Dz,MSG_HEADERS:bz,LOG_LEVELS:fc,LOG_LEVEL_FLAGS:Pz,LOG_LEVEL_HIERARCHY:Lz}});var wT=R((Qme,LC)=>{"use strict";var Mz={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
6
- `),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
7
- `)},Uz="certificate.pem",vz="privateKey.pem",Bz="ca.pem";LC.exports={CERTIFICATE_VALUES:Mz,CERTIFICATE_PEM_NAME:Uz,PRIVATEKEY_PEM_NAME:vz,CA_PEM_NAME:Bz}});var CT=R((zme,HC)=>{"use strict";var vC=require("fs-extra"),ce=require("joi"),Hz=require("os"),{boolean:ye,string:dr,number:st,array:qf}=ce.types(),{totalmem:PC}=require("os"),oa=require("path"),Gz=k(),Ff=Y(),jme=wT(),MC=D(),xz=nt(),UC="log",qz="components",Fz="Invalid logging.rotation.maxSize unit. Available units are G, M or K",kz="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Vz="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",$z="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",Yz="rootPath config parameter is undefined",Kz="clustering.enabled config parameter is undefined",aa=st.min(0).required(),kf=qf.items({host:dr.required(),port:aa}).empty(null),Ms,BC=!1;HC.exports={configValidator:Wz,routesValidator:Zz,route_constraints:kf};function Wz(e,t=!1){if(BC=t,Ms=e.rootPath,Ff.isEmpty(Ms))throw Yz;let r=ye.required(),n=st.min(0).max(1e3).empty(null).default(Xz),s=dr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Ru),i=dr.optional().empty(null),o=dr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=ce.string().empty(null).default(Ru),l=ce.custom(jz).empty(null).default(Ru),_=e.clustering?.enabled;if(Ff.isEmpty(_))throw Kz;let u=ce.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=ce.object({enabled:r,hubServer:ce.object({cluster:ce.object({name:ce.required().empty(null),network:ce.object({port:aa,routes:kf}).required()}).required(),leafNodes:ce.object({network:ce.object({port:aa}).required()}).required(),network:ce.object({port:aa}).required()}).required(),leafServer:ce.object({network:ce.object({port:aa,routes:kf}).required(),streams:ce.object({maxAge:st.min(120).allow(null).optional(),maxBytes:st.min(1).allow(null).optional(),maxMsgs:st.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:ce.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:ye.optional(),databaseLevel:ye.optional(),tls:ce.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required(),verify:ye.optional()}),user:dr.optional().empty(null)}).required():d=ce.object({enabled:r,tls:ce.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()})}).required(),ce.object({authentication:ce.object({authorizeLocal:ye,cacheTTL:st.required(),enableSessions:ye}),analytics:ce.object({aggregatePeriod:st}),componentsRoot:s.optional(),clustering:d,localStudio:ce.object({enabled:r}).required(),logging:ce.object({auditAuthEvents:ce.object({logFailed:ye,logSuccessful:ye}),file:ye.required(),level:ce.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ce.object({enabled:ye.optional(),compress:ye.optional(),interval:dr.custom(Jz).optional().empty(null),maxSize:dr.custom(zz).optional().empty(null),path:dr.optional().empty(null).default(Ru)}).required(),root:s,stdStreams:ye.required(),auditLog:ye.required()}).required(),operationsApi:ce.object({network:ce.object({cors:ye.optional(),corsAccessList:qf.optional(),headersTimeout:st.min(1).optional(),keepAliveTimeout:st.min(1).optional(),port:st.optional().empty(null),domainSocket:ce.optional().empty("hdb/operations-server").default(Ru),securePort:st.optional().empty(null),timeout:st.min(1).optional()}).optional(),tls:ce.alternatives([ce.array().items(u),u])}).required(),rootPath:dr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ce.object({network:ce.object({port:aa,securePort:aa,mtls:ce.alternatives([ye.optional(),ce.object({user:dr.optional(),certificateAuthority:i,required:ye.optional()})])}).required(),webSocket:ye.optional(),requireAuthentication:ye.optional()}),http:ce.object({compressionThreshold:st.optional(),cors:ye.optional(),corsAccessList:qf.optional(),headersTimeout:st.min(1).optional(),port:st.min(0).optional().empty(null),securePort:st.min(0).optional().empty(null),maxHeaderSize:st.optional(),mtls:ce.alternatives([ye.optional(),ce.object({user:dr.optional(),certificateAuthority:i,required:ye.optional()})]),threadRange:ce.alternatives([qf.optional(),dr.optional()])}).required(),threads:ce.alternatives(n.optional(),ce.object({count:n.optional(),debug:ce.alternatives(ye.optional(),ce.object({startingPort:st.min(1).optional(),host:dr.optional(),waitForDebugger:ye.optional()})),maxHeapMemory:st.min(0).optional()})),storage:ce.object({writeAsync:ye.required(),overlappingSync:ye.optional(),caching:ye.optional(),compression:ce.alternatives([ye.optional(),ce.object({dictionary:dr.optional(),threshold:st.optional()})]),compactOnStart:ye.optional(),compactOnStartKeepBackup:ye.optional(),noReadAhead:ye.optional(),path:l,prefetchWrites:ye.optional(),maxFreeSpaceToLoad:st.optional(),maxFreeSpaceToRetain:st.optional()}).required(),ignoreScripts:ye.optional(),tls:ce.alternatives([ce.array().items(u),u])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Wz,"configValidator");function Qz(e){return BC||vC.existsSync(e)?null:`Specified path ${e} does not exist.`}a(Qz,"doesPathExist");function jz(e,t){ce.assert(e,dr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=Qz(e);if(r)return t.message(r)}a(jz,"validatePath");function zz(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Fz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Vz):e}a(zz,"validateRotationMaxSize");function Jz(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(kz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message($z):e}a(Jz,"validateRotationInterval");function Xz(e,t){let r=t.state.path.join("."),n=Hz.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||PC();return i=Math.round(Math.min(i,PC())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Gz.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(Xz,"setDefaultThreads");function Ru(e,t){let r=t.state.path.join(".");if(!Ff.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(Ff.isEmpty(Ms))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return oa.join(Ms,qz);case"logging.root":return oa.join(Ms,UC);case"clustering.leafServer.streams.path":return oa.join(Ms,"clustering","leaf");case"storage.path":let n=oa.join(Ms,MC.LEGACY_DATABASES_DIR_NAME);return vC.existsSync(n)?n:oa.join(Ms,MC.DATABASES_DIR_NAME);case"logging.rotation.path":return oa.join(Ms,UC);case"operationsApi.network.domainSocket":return r==null?null:oa.join(Ms,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Ru,"setDefaultRoot");function Zz(e){let t=ce.object({routes:kf});return xz.validateBySchema({routes:e},t)}a(Zz,"routesValidator")});var Et=R((Zme,KC)=>{"use strict";var cn=D(),Kt=Y(),Bt=k(),{configValidator:eJ,routesValidator:GC}=CT(),Dr=require("fs-extra"),tJ=require("yaml"),ss=require("path"),rJ=require("is-number"),qC=require("properties-reader"),nJ=require("lodash"),{handleHDBError:sJ}=ie(),{HTTP_STATUS_CODES:iJ,HDB_ERROR_MSGS:Vf}=rn(),Xme=require("minimist"),{server:oJ}=(yr(),ae(jo)),{DATABASES_PARAM_CONFIG:Au,CONFIG_PARAMS:an,CONFIG_PARAM_MAP:is}=cn,aJ="Unable to get config value because config is uninitialized",cJ="Config successfully initialized",lJ="Error backing up config file",uJ="Empty parameter sent to getConfigValue",FC=ss.join(cn.PACKAGE_ROOT,"config","yaml",cn.HDB_DEFAULT_CONFIG_FILE),_J="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",xC={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"},$f,Ht,Yf;KC.exports={createConfigFile:dJ,getDefaultConfig:fJ,getConfigValue:VC,initConfig:LT,flattenConfig:Ec,updateConfigValue:$C,updateConfigObject:hJ,getConfiguration:SJ,setConfiguration:TJ,readConfigFile:MT,getClusteringRoutes:gJ,initOldConfig:YC,getConfigFromFile:RJ,getConfigFilePath:ca,addConfig:AJ,deleteConfigFromFile:OJ,getConfigObj:bJ};function dJ(e,t=!1){let r=co(FC);$f=Ec(r.toJSON());let n;for(let c in e){let l=is[c.toLowerCase()];if(l===an.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!l&&(c.endsWith("_package")||c.endsWith("_port"))&&(l=c),l!==void 0){let _=l.split("_"),u=DT(l,e[c]);l==="rootPath"&&u?.endsWith("/")&&(u=u.slice(0,-1));try{r.setIn([..._],u)}catch(d){Bt.error(d)}}}n&&kC(r,n),PT(r,t);let s=r.toJSON();Ht=Ec(s);let i=r.getIn(["rootPath"]),o=ss.join(i,cn.HDB_CONFIG_FILE);Dr.createFileSync(o),Dr.writeFileSync(o,String(r)),Bt.trace(`Config file written to ${o}`)}a(dJ,"createConfigFile");function kC(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Kt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Au.TABLES))for(let i in n[s][Au.TABLES])for(let o in n[s][Au.TABLES][i]){let c=n[s][Au.TABLES][i][o],l=[an.DATABASES,s,Au.TABLES,i,o];e.hasIn(l)?e.setIn(l,c):e.addIn(l,c)}else for(let i in n[s]){let o=n[s][i],c=[an.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(kC,"setSchemasConfig");function fJ(e){if($f===void 0){let r=co(FC);$f=Ec(r.toJSON())}let t=is[e.toLowerCase()];if(t!==void 0)return $f[t.toLowerCase()]}a(fJ,"getDefaultConfig");function VC(e){if(e==null){Bt.error(uJ);return}if(Ht===void 0){Bt.trace(aJ);return}let t=is[e.toLowerCase()];if(t!==void 0)return Ht[t.toLowerCase()]}a(VC,"getConfigValue");function ca(e=Kt.getPropsFilePath()){let t=Kt.getEnvCliRootPath();return t?ss.join(t,cn.HDB_CONFIG_FILE):qC(e).get(cn.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(ca,"getConfigFilePath");function LT(e=!1){if(Ht===void 0||e){let t;if(!Kt.noBootFile()){t=Kt.getPropsFilePath();try{Dr.accessSync(t,Dr.constants.F_OK|Dr.constants.R_OK)}catch(i){throw Bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=ca(t),n;if(r.includes("config/settings.js"))try{YC(r);return}catch(i){if(i.code!==cn.NODE_ERROR_CODES.ENOENT)throw i}try{n=co(r)}catch(i){if(i.code===cn.NODE_ERROR_CODES.ENOENT){Bt.trace(`HarperDB config file not found at ${r}.
8
- 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}`)}EJ(n,r),PT(n);let s=n.toJSON();if(oJ.config=s,Ht=Ec(s),Ht.logging_rotation_rotate)for(let i in xC)Ht[i]&&Bt.error(`Config ${xC[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Bt.trace(cJ)}}a(LT,"initConfig");function EJ(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],ss.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],ss.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],ss.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"),Dr.writeFileSync(t,String(e)))}a(EJ,"checkForUpdatedConfig");function PT(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=eJ(r,t);if(n.error)throw Vf.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(PT,"validateConfig");function hJ(e,t){Ht===void 0&&(Ht={});let r=is[e.toLowerCase()];if(r===void 0){Bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Ht[r.toLowerCase()]=t}a(hJ,"updateConfigObject");function $C(e,t,r=void 0,n=!1,s=!1,i=!1){Ht===void 0&&LT();let o=VC(is.hdb_root),c=ss.join(o,cn.HDB_CONFIG_FILE),l=co(c),_;if(r===void 0&&e.toLowerCase()===an.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=is[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=DT(E,t);l.setIn([...f],h)}else for(let E in r){let f=is[E.toLowerCase()];if(f===an.HTTP_SECUREPORT&&r[E]===Ht[an.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),f===an.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===Ht[an.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),f===an.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=l.getIn(["threads"]);h>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),m=cn.LEGACY_CONFIG_PARAMS[E.toUpperCase()];m&&m.startsWith("customFunctions")&&l.hasIn(m.split("_"))&&(f=m,h=m.split("_"));let S=DT(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof l.getIn(h.slice(0,-1))=="boolean"&&l.deleteIn(h.slice(0,-1)),l.setIn([...h],S)}catch(g){Bt.error(g)}}}_&&kC(l,_),PT(l);let u=l.getIn(["rootPath"]),d=ss.join(u,cn.HDB_CONFIG_FILE);n===!0&&pJ(c,u),Dr.writeFileSync(d,String(l)),s&&(Ht=Ec(l.toJSON())),Bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a($C,"updateConfigValue");function pJ(e,t){try{let r=ss.join(t,"backup",`${cn.HDB_CONFIG_FILE}.bak`);Dr.copySync(e,r),Bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Bt.error(lJ),Bt.error(r)}}a(pJ,"backupConfigFile");var mJ=["databases"];function Ec(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)),Yf=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])&&!mJ.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!an[l.toUpperCase()]&&is[l]&&(s[is[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Ec,"flattenConfig");function DT(e,t){if(e===an.CLUSTERING_NODENAME||e===an.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(rJ(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Kt.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 Kt.autoCast(t)}a(DT,"castConfigValue");function SJ(){let e=Kt.getPropsFilePath(),t=ca(e);return co(t).toJSON()}a(SJ,"getConfiguration");async function TJ(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return $C(void 0,void 0,s,!0),_J}catch(i){throw typeof i=="string"||i instanceof String?sJ(i,i,iJ.BAD_REQUEST,void 0,void 0,!0):i}}a(TJ,"setConfiguration");function MT(){let e=Kt.getPropsFilePath();try{Dr.accessSync(e,Dr.constants.F_OK|Dr.constants.R_OK)}catch(n){if(!Kt.noBootFile())throw Bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=ca(e);return co(t).toJSON()}a(MT,"readConfigFile");function co(e){return tJ.parseDocument(Dr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(co,"parseYamlDoc");function gJ(){let e=MT(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Kt.isEmptyOrZeroLength(t)?[]:t;let r=GC(t);if(r)throw Vf.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Kt.isEmptyOrZeroLength(n)?[]:n;let s=GC(n);if(s)throw Vf.CONFIG_VALIDATION(s.message);if(!Kt.isEmptyOrZeroLength(n)&&!Kt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Kt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Vf.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(gJ,"getClusteringRoutes");function YC(e){let t=qC(e);Ht={};for(let r in is){let n=t.get(r.toUpperCase());if(Kt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=is[r].toLowerCase();s===an.LOGGING_ROOT?Ht[s]=ss.dirname(n):Ht[s]=n}return Ht}a(YC,"initOldConfig");function RJ(e){let t=MT();return nJ.get(t,e.replaceAll("_","."))}a(RJ,"getConfigFromFile");async function AJ(e,t){let r=co(ca());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await Dr.writeFile(ca(),String(r))}a(AJ,"addConfig");function OJ(e){let t=ca(Kt.getPropsFilePath()),r=co(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=ss.join(n,cn.HDB_CONFIG_FILE);Dr.writeFileSync(s,String(r))}a(OJ,"deleteConfigFromFile");function bJ(){return Yf||(LT(),Yf)}a(bJ,"getConfigObj")});var QC=R((tSe,WC)=>{"use strict";var Kf=D(),Wf=class{static{a(this,"BaseLicense")}constructor(t=0,r=Kf.RAM_ALLOCATION_ENUM.DEFAULT,n=Kf.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},UT=class extends Wf{static{a(this,"ExtendedLicense")}constructor(t=0,r=Kf.RAM_ALLOCATION_ENUM.DEFAULT,n=Kf.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};WC.exports={BaseLicense:Wf,ExtendedLicense:UT}});var la=R((nSe,eD)=>{"use strict";var pc=require("fs-extra"),zC=xf(),JC=require("crypto"),NJ=require("moment"),yJ=require("uuid").v4,fr=k(),BT=require("path"),IJ=Y(),lo=D(),{totalmem:jC}=require("os"),wJ=QC().ExtendedLicense,hc="invalid license key format",CJ="061183",DJ="mofi25",LJ="aes-256-cbc",PJ=16,MJ=32,XC=X();XC.initSync();var vT;eD.exports={validateLicense:ZC,generateFingerPrint:vJ,licenseSearch:xT,getLicense:GJ,checkMemoryLimit:xJ};function HT(){return BT.join(XC.getHdbBasePath(),lo.LICENSE_KEY_DIR_NAME,lo.LICENSE_FILE_NAME)}a(HT,"getLicenseDirPath");function UJ(){let e=HT();return BT.join(e,lo.LICENSE_FILE_NAME)}a(UJ,"getLicenseFilePath");function GT(){let e=HT();return BT.join(e,lo.REG_KEY_FILE_NAME)}a(GT,"getFingerPrintFilePath");async function vJ(){let e=GT();try{return await pc.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await BJ();throw fr.error(`Error writing fingerprint file to ${e}`),fr.error(t),new Error("There was an error generating the fingerprint")}}a(vJ,"generateFingerPrint");async function BJ(){let e=yJ(),t=zC.hash(e),r=GT();try{await pc.mkdirp(HT()),await pc.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw fr.error(`Error writing fingerprint file to ${r}`),fr.error(n),new Error("There was an error generating the fingerprint")}return t}a(BJ,"writeFingerprint");function ZC(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:lo.RAM_ALLOCATION_ENUM.DEFAULT,version:lo.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return fr.error("empty license key passed to validate."),r;let n=GT(),s=!1;try{s=pc.statSync(n)}catch(i){fr.error(i)}if(s){let i;try{i=pc.readFileSync(n,"utf8")}catch{fr.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(DJ),c=o[1];c=Buffer.concat([Buffer.from(c)],PJ);let l=Buffer.concat([Buffer.from(i)],MJ),_=JC.createDecipheriv(LJ,l,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let u=null;try{u=_.update(o[0],"hex","utf8"),u.trim(),u+=_.final("utf8")}catch{let f=HJ(o[0],i);if(f)u=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(hc),fr.error(hc),new Error(hc)}let d;if(isNaN(u))try{d=JSON.parse(u),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(hc),fr.error(hc),new Error(hc)}else r.exp_date=u;r.exp_date<NJ().valueOf()&&(r.valid_date=!1),zC.validate(o[1],`${CJ}${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||fr.error("Invalid licence"),r}a(ZC,"validateLicense");function HJ(e,t){try{let r=JC.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{fr.warn("Check old license failed")}}a(HJ,"checkOldLicense");function xT(){let e=new wJ,t=[];try{t=pc.readFileSync(UJ(),"utf-8").split(lo.NEW_LINE)}catch(r){r.code==="ENOENT"?fr.info("no license file found"):fr.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(IJ.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=ZC(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){fr.error("There was an error parsing the license string."),fr.error(s),e.ram_allocation=lo.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return vT=e,e}a(xT,"licenseSearch");async function GJ(){return vT||await xT(),vT}a(GJ,"getLicense");function xJ(){let e=xT().ram_allocation,t=process.constrainedMemory?.()||jC();if(t=Math.round(Math.min(t,jC())/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(xJ,"checkMemoryLimit")});var Lr=R((cSe,pD)=>{"use strict";var sD="username is required",iD="nothing to update, must supply active, role or password to update",oD="password cannot be an empty string",aD="If role is specified, it cannot be empty.",cD="active must be true or false";pD.exports={addUser:QJ,alterUser:jJ,dropUser:JJ,getSuperUser:t2,userInfo:XJ,listUsers:jf,listUsersExternal:ZJ,setUsersToGlobal:Sc,findAndValidateUser:ED,getClusterUser:r2,USERNAME_REQUIRED:sD,ALTERUSER_NOTHING_TO_UPDATE:iD,EMPTY_PASSWORD:oD,EMPTY_ROLE:aD,ACTIVE_BOOLEAN:cD};var lD=Cr(),qJ=ia(),kT=xf(),uD=wC(),_D=ur(),VT=hi(),ln=Y(),dD=require("validate.js"),Ne=k(),{promisify:FJ}=require("util"),$T=fi(),tD=D(),rD=Ze(),kJ=Et(),iSe=X(),oSe=la(),VJ=_i(),{table:aSe}=(Re(),ae($e)),{handleHDBError:Us,hdb_errors:$J}=ie(),{HTTP_STATUS_CODES:vs,AUTHENTICATION_ERROR_MSGS:qT,HDB_ERROR_MSGS:mc}=$J,{UserEventMsg:YT}=os(),FT=require("lodash"),{server:KT}=(yr(),ae(jo)),YJ=k();KT.getUser=(e,t)=>ED(e,t,t!=null);var fD={username:!0,active:!0,role:!0,password:!0},nD=new Map,Qf=_D.searchByValue,KJ=_D.searchByHash,WJ=FJ(qJ.delete);async function QJ(e){let t=dD.cleanAttributes(e,fD),r=uD.addUserValidation(t);if(r)throw Us(new Error,r.message,vs.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 Qf(n),s=s&&Array.from(s)}catch(l){throw Ne.error("There was an error searching for a role in add user"),Ne.error(l),l}if(!s||s.length<1)throw Us(new Error,mc.ROLE_NAME_NOT_FOUND(t.role),vs.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Us(new Error,mc.DUP_ROLES_FOUND(t.role),vs.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=$T.encrypt(t.password)),t.password=kT.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await lD.insert(i)}catch(l){throw Ne.error("There was an error searching for a user."),Ne.error(l),l}Ne.debug(o);try{await Sc()}catch(l){throw Ne.error("Got an error setting users to global"),Ne.error(l),l}if(o.skipped_hashes.length===1)throw Us(new Error,mc.USER_ALREADY_EXISTS(t.username),vs.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],VT.signalUserChange(new YT(process.pid)),`${c.username} successfully added`}a(QJ,"addUser");async function jJ(e){let t=dD.cleanAttributes(e,fD);if(ln.isEmptyOrZeroLength(t.username))throw new Error(sD);if(ln.isEmptyOrZeroLength(t.password)&&ln.isEmptyOrZeroLength(t.role)&&ln.isEmptyOrZeroLength(t.active))throw new Error(iD);if(!ln.isEmpty(t.password)&&ln.isEmptyOrZeroLength(t.password.trim()))throw new Error(oD);if(!ln.isEmpty(t.active)&&!ln.isBoolean(t.active))throw new Error(cD);let r=zJ(t.username);if(!ln.isEmpty(t.password)&&!ln.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=$T.encrypt(t.password)),t.password=kT.hash(t.password)),t.role==="")throw new Error(aD);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 Qf(i)||[])}catch(c){throw Ne.error("Got an error searching for a role."),Ne.error(c),c}if(!o||o.length===0){let c=mc.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ne.error(c),Us(new Error,c,vs.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=mc.ALTER_USER_DUP_ROLES(t.role);throw Ne.error(c),Us(new Error,c,vs.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 lD.update(n)}catch(i){throw Ne.error("Error during update."),Ne.error(i),i}try{await Sc()}catch(i){throw Ne.error("Got an error setting users to global"),Ne.error(i),i}return VT.signalUserChange(new YT(process.pid)),s}a(jJ,"alterUser");function zJ(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(zJ,"isClusterUser");async function JJ(e){try{let t=uD.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(ln.isEmpty(global.hdb_users.get(e.username)))throw Us(new Error,mc.USER_NOT_EXIST(e.username),vs.NOT_FOUND,void 0,void 0,!0);let n;try{n=await WJ(r)}catch(s){throw Ne.error("Got an error deleting a user."),Ne.error(s),s}Ne.debug(n);try{await Sc()}catch(s){throw Ne.error("Got an error setting users to global."),Ne.error(s),s}return VT.signalUserChange(new YT(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(JJ,"dropUser");async function XJ(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=FT.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await KJ(r)}catch(s){throw Ne.error("Got an error searching for a role."),Ne.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ne.error(r),r}return t}a(XJ,"userInfo");async function ZJ(){let e;try{e=await jf()}catch(t){throw Ne.error("Got an error listing users."),Ne.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(ZJ,"listUsersExternal");async function jf(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await Qf(e)}catch(o){throw Ne.error("Got an error searching for roles."),Ne.error(o),o}let r={};for(let o of t)r[o.id]=FT.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 Qf(n)}catch(o){throw Ne.error("Got an error searching for users."),Ne.error(o),o}let i=new Map;for(let o of s)o=FT.cloneDeep(o),o.role=r[o.role],e2(o.role),i.set(o.username,o);return i}catch(e){throw Ne.error("got an error listing users"),Ne.error(e),ln.errorizeMessage(e)}return null}a(jf,"listUsers");function e2(e){try{if(!e){Ne.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(VJ)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ne.error("Got an error trying to set system permissions."),Ne.error(t)}}a(e2,"appendSystemTablesToRole");async function Sc(){try{let e=await jf();global.hdb_users=e}catch(e){throw Ne.error(e),e}}a(Sc,"setUsersToGlobal");async function ED(e,t,r=!0){global.hdb_users||await Sc();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Us(new Error,qT.GENERIC_AUTH_FAIL,vs.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Us(new Error,qT.USER_INACTIVE,vs.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(nD.get(t)===n.password)return s;if(kT.validate(n.password,t))nD.set(t,n.password);else throw Us(new Error,qT.GENERIC_AUTH_FAIL,vs.UNAUTHORIZED,void 0,void 0,!0)}return s}a(ED,"findAndValidateUser");async function t2(){global.hdb_users||await Sc();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(t2,"getSuperUser");async function r2(){let e=await jf(),t=kJ.getConfigFromFile(tD.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!ln.isEmpty(r)&&r?.role?.role===tD.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=$T.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+rD.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+rD.SERVER_SUFFIX.ADMIN,r}a(r2,"getClusterUser");var hD=[];KT.invalidateUser=function(e){for(let t of hD)try{t(e)}catch(r){YJ.error("Error invalidating user",r)}};KT.onInvalidatedUser=function(e){hD.push(e)}});var bu=R((dSe,gD)=>{"use strict";var ua=k(),un=D(),n2=zw(),uSe=Bn(),_Se=Ei(),s2=Lr(),{validateEvent:mD}=os(),Ou=Hn(),i2=require("process"),{resetDatabases:o2}=(Re(),ae($e)),a2={[un.ITC_EVENT_TYPES.SCHEMA]:c2,[un.ITC_EVENT_TYPES.USER]:TD};async function c2(e){let t=mD(e);if(t){ua.error(t);return}ua.trace("ITC schemaHandler received schema event:",e),await n2(e.message),await l2(e.message)}a(c2,"schemaHandler");async function l2(e){try{Ou.resetReadTxn(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Ou.resetReadTxn(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Ou.resetReadTxn(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=o2();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ua.error(t)}}a(l2,"syncSchemaMetadata");var SD=[];async function TD(e){try{try{Ou.resetReadTxn(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Ou.resetReadTxn(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ua.warn(r)}let t=mD(e);if(t){ua.error(t);return}ua.trace(`ITC userHandler ${un.HDB_ITC_CLIENT_PREFIX}${i2.pid} received user event:`,e),await s2.setUsersToGlobal();for(let r of SD)r()}catch(t){ua.error(t)}}a(TD,"userHandler");TD.addListener=function(e){SD.push(e)};gD.exports=a2});var os=R((SSe,AD)=>{"use strict";var ESe=k(),WT=Y(),u2=D(),{ITC_ERRORS:Nu}=rn(),{parentPort:hSe,threadId:_2,isMainThread:d2,workerData:pSe}=require("worker_threads"),{onMessageFromWorkers:f2,broadcast:mSe,broadcastWithAcknowledgement:E2}=rt();AD.exports={sendItcEvent:h2,validateEvent:RD,SchemaEventMsg:p2,UserEventMsg:m2};var zf;f2(async(e,t)=>{zf=zf||bu(),RD(e),zf[e.type]&&await zf[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function h2(e){return!d2&&e.message&&(e.message.originator=_2),E2(e)}a(h2,"sendItcEvent");function RD(e){if(typeof e!="object")return Nu.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||WT.isEmpty(e.type))return Nu.MISSING_TYPE;if(!e.hasOwnProperty("message")||WT.isEmpty(e.message))return Nu.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||WT.isEmpty(e.message.originator))return Nu.MISSING_ORIGIN;if(u2.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Nu.INVALID_EVENT(e.type)}a(RD,"validateEvent");function p2(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(p2,"SchemaEventMsg");function m2(e){this.originator=e}a(m2,"UserEventMsg")});var hi=R((RSe,yD)=>{"use strict";var OD=D(),gSe=Y(),Jf=k(),bD=Ww(),Tc,{sendItcEvent:ND}=os();function S2(e){try{Jf.trace("signalSchemaChange called with message:",e),Tc=Tc||bu();let t=new bD(OD.ITC_EVENT_TYPES.SCHEMA,e);return Tc.schema(t),ND(t)}catch(t){Jf.error(t)}}a(S2,"signalSchemaChange");function T2(e){try{Jf.trace("signalUserChange called with message:",e),Tc=Tc||bu();let t=new bD(OD.ITC_EVENT_TYPES.USER,e);return Tc.user(t),ND(t)}catch(t){Jf.error(t)}}a(T2,"signalUserChange");yD.exports={signalSchemaChange:S2,signalUserChange:T2}});var Xf=R((OSe,wD)=>{"use strict";var ID=Y(),g2=D(),R2=k(),A2=yf(),O2=Nf(),b2=hi(),{SchemaEventMsg:N2}=os(),y2="already exists in";wD.exports=I2;async function I2(e,t,r){if(ID.isEmptyOrZeroLength(r))return r;let n=[];ID.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 w2(e,t.schema,t.name,i)})),s}a(I2,"lmdbCheckForNewAttributes");async function w2(e,t,r,n){let s=new O2(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await C2(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(y2))R2.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(w2,"createNewAttribute");async function C2(e){let t;return t=await A2(e),b2.signalSchemaChange(new N2(process.pid,g2.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(C2,"createAttribute")});var gc=R((NSe,CD)=>{"use strict";var QT=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}};CD.exports=QT});var LD=R((ISe,DD)=>{"use strict";var D2=gc(),L2=D().OPERATIONS_ENUM,jT=class extends D2{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(L2.INSERT,r,n,s,i),this.records=t}};DD.exports=jT});var MD=R((CSe,PD)=>{"use strict";var P2=gc(),M2=D().OPERATIONS_ENUM,zT=class extends P2{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(M2.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};PD.exports=zT});var vD=R((LSe,UD)=>{"use strict";var U2=gc(),v2=D().OPERATIONS_ENUM,JT=class extends U2{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(v2.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};UD.exports=JT});var HD=R((MSe,BD)=>{"use strict";var B2=gc(),H2=D().OPERATIONS_ENUM,XT=class extends B2{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(H2.DELETE,n,s,t,i),this.original_records=r}};BD.exports=XT});var yu=R((BSe,FD)=>{"use strict";var vSe=require("path"),GD=Ye(),G2=LD(),x2=MD(),q2=vD(),F2=HD(),Rc=_t(),xD=Y(),{CONFIG_PARAMS:k2}=D(),qD=X();qD.initSync();var Zf=D().OPERATIONS_ENUM,{getTransactionAuditStorePath:V2}=ze();FD.exports=$2;async function $2(e,t){if(qD.get(k2.LOGGING_AUDITLOG)===!1)return;let r=V2(e.schema,e.table),n=await GD.openEnvironment(r,e.table,!0),s=Y2(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){GD.initializeDBIs(n,Rc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Rc.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Rc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Rc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),xD.isEmpty(s.user_name)||n.dbis[Rc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Rc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a($2,"writeTransaction");function Y2(e,t){let r=xD.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===Zf.INSERT)return new G2(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Zf.UPDATE)return new x2(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Zf.UPSERT)return new q2(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Zf.DELETE)return new F2(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(Y2,"createTransactionObject")});var ZT=R((xSe,kD)=>{"use strict";var K2=pu(),GSe=mu(),Iu=D(),W2=Su(),Q2=Zo().insertRecords,j2=Ye(),z2=k(),J2=Xf(),{getSchemaPath:X2}=ze(),Z2=yu();kD.exports=e4;async function e4(e){try{let{schema_table:t,attributes:r}=K2(e);W2(e,r,t.hash_attribute),e.schema!==Iu.SYSTEM_SCHEMA_NAME&&(r.includes(Iu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Iu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Iu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Iu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await J2(e.hdb_auth_header,t,r),s=X2(e.schema,e.table),i=await j2.openEnvironment(s,e.table),o=await Q2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await Z2(e,o)}catch(c){z2.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(e4,"lmdbCreateRecords")});var YD=R((FSe,$D)=>{"use strict";var VD=D(),t4=ZT(),r4=mu(),n4=require("fs-extra"),{getSchemaPath:s4}=ze();$D.exports=i4;async function i4(e){let t=[{name:e.schema,createddate:Date.now()}],r=new r4(VD.SYSTEM_SCHEMA_NAME,VD.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await t4(r),await n4.mkdirp(s4(e.schema))}a(i4,"lmdbCreateSchema")});var WD=R((VSe,KD)=>{"use strict";var eg=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}};KD.exports=eg});var JD=R((QSe,zD)=>{"use strict";var QD=Ye(),tg=Nr(),rg=rn().LMDB_ERRORS_ENUM,o4=_t(),jD=k(),YSe=Y(),a4=require("lmdb"),c4=WD(),l4=D(),{OVERFLOW_MARKER:KSe,MAX_SEARCH_KEY_LENGTH:WSe}=o4,u4=l4.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function _4(e,t,r,n){if(tg.validateEnv(e),t===void 0)throw new Error(rg.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(rg.IDS_REQUIRED):new Error(rg.IDS_MUST_BE_ITERABLE);try{let s=QD.listDBIs(e);QD.initializeDBIs(e,t,s);let i=new c4,o,c=[],l=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[u4]>n){i.skipped.push(o);continue}let m=e.dbis[t].ifVersion(o,a4.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let g=s[S];if(!h.hasOwnProperty(g)||g===t)continue;let T=e.dbis[g],b=h[g];if(b!=null)try{let N=tg.getIndexedValues(b);if(N)for(let v=0,U=N.length;v<U;v++)T.remove(N[v],o)}catch{jD.warn(`cannot delete from attribute: ${g}, ${b}:${o}`)}}});c.push(m),l.push(o),i.original_records.push(h)}catch(h){jD.warn(h),i.skipped.push(o)}let _=[],u=await Promise.all(c);for(let E=0,f=u.length;E<f;E++)u[E]===!0?i.deleted.push(l[E]):(i.skipped.push(l[E]),_.push(E));let d=0;for(let E=0;E<_.length;E++){let f=_[E];i.original_records.splice(f-d,1),d++}return i.txn_time=tg.getNextMonotonicTime(),i}catch(s){throw s}}a(_4,"deleteRecords");zD.exports={deleteRecords:_4}});var wu=R((zSe,ZD)=>{"use strict";var Ac=Y(),d4=JD(),f4=Ye(),{getSchemaPath:E4}=ze(),h4=yu(),p4=k();ZD.exports=m4;async function m4(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(Ac.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Ac.isEmptyOrZeroLength(e.hash_values)&&!Ac.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let l=e.records[c][n];Ac.isEmpty(l)||e.hash_values.push(l)}}if(Ac.isEmptyOrZeroLength(e.hash_values))return XD([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Ac.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=E4(e.schema,e.table),i=await f4.openEnvironment(s,e.table),o=await d4.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await h4(e,o)}catch(c){p4.error(`unable to write transaction due to ${c.message}`)}return XD(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(m4,"lmdbDeleteRecords");function XD(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(XD,"createDeleteResponse")});var sg=R((ZSe,eL)=>{"use strict";var S4=D(),XSe=Nr();function ng(e,t){let r=Object.create(null);if(t.length===1&&S4.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(ng,"parseRow");function T4(e,t,r,n){let s=ng(r,e);n.push(s)}a(T4,"searchAll");function g4(e,t,r,n){let s=ng(r,e);n[t]=s}a(g4,"searchAllToMap");function R4(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(R4,"iterateDBI");function _a(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(_a,"pushResults");function A4(e,t,r,n,s,i){t.toString().endsWith(e)&&_a(t,r,n,s,i)}a(A4,"endsWith");function O4(e,t,r,n,s,i){t.toString().includes(e)&&_a(t,r,n,s,i)}a(O4,"contains");function b4(e,t,r,n,s,i){t>e&&_a(t,r,n,s,i)}a(b4,"greaterThanCompare");function N4(e,t,r,n,s,i){t>=e&&_a(t,r,n,s,i)}a(N4,"greaterThanEqualCompare");function y4(e,t,r,n,s,i){t<e&&_a(t,r,n,s,i)}a(y4,"lessThanCompare");function I4(e,t,r,n,s,i){t<=e&&_a(t,r,n,s,i)}a(I4,"lessThanEqualCompare");eL.exports={parseRow:ng,searchAll:T4,searchAllToMap:g4,iterateDBI:R4,endsWith:A4,contains:O4,greaterThanCompare:b4,greaterThanEqualCompare:N4,lessThanCompare:y4,lessThanEqualCompare:I4,pushResults:_a}});var Oc=R((sTe,aL)=>{"use strict";var uo=Ye(),tTe=k(),_n=Nr(),eE=_t(),Tt=rn().LMDB_ERRORS_ENUM,rTe=Y(),w4=D(),tE=sg(),{parseRow:C4}=tE,nTe=require("lmdb"),{OVERFLOW_MARKER:tL,MAX_SEARCH_KEY_LENGTH:D4}=eE;function rL(e,t,r,n=!1,s=void 0,i=void 0){return da(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(rL,"iterateFullIndex");function Cu(e,t,r,n,s,i=!1,o=void 0,c=void 0,l=!1,_=!1){return da(e,t,r,(u,d,E,f)=>{let T={transaction:u,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!l:!_,exclusiveStart:i===!0?_:l};return f===r?(T.values=!1,d.getRange(T).map(b=>({value:b}))):d.getRange(T)})}a(Cu,"iterateRangeBetween");function da(e,t,r,n){let s=e.database||e,i=uo.openDBI(s,r);i[eE.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&uo.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(da,"setupTransaction");function nL(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(tL)){if(!s)if(r)s=uo.openDBI(e,r);else{let l=uo.listDBIs(e);for(let _=0,u=l.length;_<u&&(s=uo.openDBI(e,l[_]),!s[eE.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(nL,"getOverflowCheck");function L4(e,t,r,n=!1,s=void 0,i=void 0){if(_n.validateEnv(e),t===void 0)throw new Error(Tt.HASH_ATTRIBUTE_REQUIRED);return da(e,t,t,(o,c,l)=>(rE(r),r=Du(l,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>C4(_.value,r))))}a(L4,"searchAll");function P4(e,t,r,n=!1,s=void 0,i=void 0){if(_n.validateEnv(e),t===void 0)throw new Error(Tt.HASH_ATTRIBUTE_REQUIRED);rE(r),r=Du(e.database||e,r);let o=new Map;for(let{key:c,value:l}of rL(e,t,t,n,s,i))o.set(c,tE.parseRow(l,r));return o}a(P4,"searchAllToMap");function M4(e,t,r=!1,n=void 0,s=void 0){if(_n.validateEnv(e),t===void 0)throw new Error(Tt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=rL(e,void 0,t,r,n,s),c=o.transaction,l=nL(c.database,c,void 0,t);for(let{key:_,value:u}of o){let d=l(_,u);i[d]===void 0&&(i[d]=[]),i[d].push(u)}return i}a(M4,"iterateDBI");function U4(e,t){if(_n.validateEnv(e),t===void 0)throw new Error(Tt.HASH_ATTRIBUTE_REQUIRED);return uo.statDBI(e,t).entryCount}a(U4,"countAll");function v4(e,t,r,n,s=!1,i=void 0,o=void 0){return _o(e,r,n),da(e,t,r,(c,l,_,u)=>(n=_n.convertKeyValueToWrite(n),u===r?l.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:l.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(v4,"equals");function B4(e,t,r){return _o(e,t,r),uo.openDBI(e,t).getValuesCount(r)}a(B4,"count");function H4(e,t,r,n,s=!1,i=void 0,o=void 0){return _o(e,r,n),da(e,null,r,(c,l)=>{n=_n.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let u;if(s===!0){let d;for(let E of l.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),u=l.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(n))return E;if(_===!0)return u.DONE}}),u.filter(E=>E)}else return u=l.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return u.DONE}),_?u:u.filter(d=>d)})}a(H4,"startsWith");function G4(e,t,r,n,s=!1,i=void 0,o=void 0){return sL(e,t,r,n,s,i,o,!0)}a(G4,"endsWith");function sL(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return _o(e,r,n),da(e,null,r,(l,_,u,d)=>{let E=nL(u,l,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:l,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(tL)?_.getValues(f,{transaction:l}).map(m=>{let S=E(f,m);if(c?S.endsWith(n):S.includes(n))return{key:S,value:m}}).filter(m=>m):(c?h.endsWith(n):h.includes(n))?_[eE.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:l}).map(m=>({key:f,value:m})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(sL,"contains");function x4(e,t,r,n,s=!1,i=void 0,o=void 0){_o(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),Cu(e,t,r,n,l,s,i,o,!0,!1)}a(x4,"greaterThan");function q4(e,t,r,n,s=!1,i=void 0,o=void 0){_o(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),Cu(e,t,r,n,l,s,i,o,!1,!1)}a(q4,"greaterThanEqual");function F4(e,t,r,n,s=!1,i=void 0,o=void 0){_o(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),Cu(e,t,r,l,n,s,i,o,!1,!0)}a(F4,"lessThan");function k4(e,t,r,n,s=!1,i=void 0,o=void 0){_o(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),Cu(e,t,r,l,n,s,i,o,!1,!1)}a(k4,"lessThanEqual");function V4(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(_n.validateEnv(e),r===void 0)throw new Error(Tt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(Tt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(Tt.END_VALUE_REQUIRED);if(n=_n.convertKeyValueToWrite(n),s=_n.convertKeyValueToWrite(s),n>s)throw new Error(Tt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Cu(e,t,r,n,s,i,o,c)}a(V4,"between");function $4(e,t,r,n){_n.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(Tt.HASH_ATTRIBUTE_REQUIRED);if(rE(r),r=Du(s,r),n===void 0)throw new Error(Tt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=tE.parseRow(c,r)),o}a($4,"searchByHash");function Y4(e,t,r){_n.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(Tt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(Tt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(Y4,"checkHashExists");function K4(e,t,r,n,s=[]){return oL(e,t,r,n,s),iL(e,t,r,n,s).map(i=>i[1])}a(K4,"batchSearchByHash");function W4(e,t,r,n,s=[]){oL(e,t,r,n,s);let i=new Map;for(let[o,c]of iL(e,t,r,n,s))i.set(o,c);return i}a(W4,"batchSearchByHashToMap");function iL(e,t,r,n,s=[]){return da(e,t,t,(i,o,c)=>{r=Du(c,r);let l=r.length<3;return n.map(_=>{let u=c.dbis[t].get(_,{transaction:i,lazy:l});if(u)return[_,tE.parseRow(u,r)];s.push(_)}).filter(_=>_)})}a(iL,"batchHashSearch");function oL(e,t,r,n,s){if(_n.validateEnv(e),t===void 0)throw new Error(Tt.HASH_ATTRIBUTE_REQUIRED);if(rE(r),n==null)throw new Error(Tt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(Tt.IDS_MUST_BE_ITERABLE)}a(oL,"initializeBatchSearchByHash");function rE(e){if(!Array.isArray(e))throw e===void 0?new Error(Tt.FETCH_ATTRIBUTES_REQUIRED):new Error(Tt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(rE,"validateFetchAttributes");function _o(e,t,r){if(_n.validateEnv(e),t===void 0)throw new Error(Tt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(Tt.SEARCH_VALUE_REQUIRED);if(r?.length>D4)throw new Error(Tt.SEARCH_VALUE_TOO_LARGE)}a(_o,"validateComparisonFunctions");function Du(e,t){return t.length===1&&w4.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=uo.listDBIs(e)),t}a(Du,"setGetWholeRowAttributes");aL.exports={searchAll:L4,searchAllToMap:P4,count:B4,countAll:U4,equals:v4,startsWith:H4,endsWith:G4,contains:sL,searchByHash:$4,setGetWholeRowAttributes:Du,batchSearchByHash:K4,batchSearchByHashToMap:W4,checkHashExists:Y4,iterateDBI:M4,greaterThan:x4,greaterThanEqual:q4,lessThan:F4,lessThanEqual:k4,between:V4}});var bc=R((oTe,dL)=>{var cL=require("lodash"),lL=nt(),me=require("joi"),Q4=Y(),{hdb_schema_table:Lu,checkValidTable:uL,hdb_table:_L,hdb_database:nE}=Ls(),{handleHDBError:j4,hdb_errors:z4}=ie(),{getDatabases:J4}=(Re(),ae($e)),{HTTP_STATUS_CODES:X4}=z4,Z4=me.object({database:nE,schema:nE,table:_L,search_attribute:Lu,search_value:me.any().required(),get_attributes:me.array().min(1).items(me.alternatives(Lu,me.object())).optional(),desc:me.bool(),limit:me.number().integer().min(1),offset:me.number().integer().min(0)}),e3=me.object({database:nE,schema:nE,table:_L,operator:me.string().valid("and","or").default("and").lowercase(),offset:me.number().integer().min(0),limit:me.number().integer().min(1),get_attributes:me.array().min(1).items(me.alternatives(Lu,me.object())).optional(),sort:me.object({attribute:me.alternatives(Lu,me.array().min(1)),descending:me.bool().optional()}).optional(),conditions:me.array().min(1).items(me.alternatives(me.object({operator:me.string().valid("and","or").default("and").lowercase(),conditions:me.array()}),me.object({search_attribute:me.alternatives(Lu,me.array().min(1)),search_type:me.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:me.when("search_type",{switch:[{is:"equals",then:me.any()},{is:"between",then:me.array().items(me.alternatives([me.string(),me.number()])).length(2)}],otherwise:me.alternatives(me.string(),me.number())}).required()}))).required()});dL.exports=function(e,t){let r=null;switch(t){case"value":r=lL.validateBySchema(e,Z4);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(uL("database",e.schema)),i(uL("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=lL.validateBySchema(e,e3);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=Q4.checkGlobalSchemaTable(e.schema,e.table);if(s)return j4(new Error,s,X4.NOT_FOUND);let o=J4()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let l=a(u=>{for(let d=0,E=u.conditions.length;d<E;d++){let f=u.conditions[d];f.conditions?l(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&l(e);let _=cL.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!Array.isArray(u)&&!u.name&&!cL.some(o,d=>d===u||d.attribute===u||d.attribute===u.attribute));if(_&&_.length>0){let u=_.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var ig=R((cTe,fL)=>{"use strict";var t3=Ye(),r3=bc(),{getSchemaPath:n3}=ze();fL.exports=s3;function s3(e){let t=r3(e,"hashes");if(t)throw t;let r=n3(e.schema,e.table);return t3.openEnvironment(r,e.table)}a(s3,"initialize")});var og=R((uTe,EL)=>{"use strict";var i3=Oc(),o3=ig();EL.exports=a3;async function a3(e){let t=await o3(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return i3.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(a3,"lmdbGetDataByHash")});var Nc=R((dTe,hL)=>{"use strict";var ag=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};hL.exports=ag});var mL=R((hTe,pL)=>{"use strict";var ETe=Nc(),c3=Oc(),l3=ig();pL.exports=u3;async function u3(e){let t=await l3(e),r=global.hdb_schema[e.schema][e.table];return c3.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(u3,"lmdbSearchByHash")});var as=R((mTe,SL)=>{"use strict";var cg=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,l=!1,_=void 0,u=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=l,this.limit=_,this.offset=u}};SL.exports=cg});var sE=R((TTe,bL)=>{"use strict";var Er=Oc(),_3=Ye(),d3=Y(),Se=_t(),fa=D(),f3=_i(),TL=rn().LMDB_ERRORS_ENUM,{getSchemaPath:E3}=ze(),pi=fa.SEARCH_WILDCARDS;async function h3(e,t,r){let n;e.schema===fa.SYSTEM_SCHEMA_NAME?n=f3[e.table]:n=global.hdb_schema[e.schema][e.table];let s=OL(e,n.hash_attribute,r,t);return RL(e,s,n.hash_attribute,r)}a(h3,"prepSearch");async function RL(e,t,r,n){let s=E3(e.schema,e.table),i=await _3.openEnvironment(s,e.table),o=AL(i,e,t,r),c=o.transaction||i;if([Se.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Se.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Se.SEARCH_TYPES.SEARCH_ALL,Se.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(p3(e,r)===!1){let u=e.search_attribute;if(u===r)return n?gL(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[u]:E.key}),"toObject");return n?gL(o,d):o.map(d)}let _=e.search_attribute===r?o.map(u=>u.key):o.map(u=>u.value);return n===!0?Er.batchSearchByHashToMap(c,r,e.get_attributes,_):Er.batchSearchByHash(c,r,e.get_attributes,_)}a(RL,"executeSearch");function AL(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:l}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,l=Number.isInteger(l)?l:void 0,r){case Se.SEARCH_TYPES.EQUALS:s=Er.equals(e,i,t.search_attribute,t.search_value,o,c,l);break;case Se.SEARCH_TYPES.CONTAINS:s=Er.contains(e,i,t.search_attribute,t.search_value,o,c,l);break;case Se.SEARCH_TYPES.ENDS_WITH:case Se.SEARCH_TYPES._ENDS_WITH:s=Er.endsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case Se.SEARCH_TYPES.STARTS_WITH:case Se.SEARCH_TYPES._STARTS_WITH:s=Er.startsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case Se.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Er.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Se.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Er.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Se.SEARCH_TYPES.SEARCH_ALL:return Er.searchAll(e,n,t.get_attributes,o,c,l);case Se.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Er.searchAllToMap(e,n,t.get_attributes,o,c,l);case Se.SEARCH_TYPES.BETWEEN:s=Er.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,l);break;case Se.SEARCH_TYPES.GREATER_THAN:case Se.SEARCH_TYPES._GREATER_THAN:s=Er.greaterThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case Se.SEARCH_TYPES.GREATER_THAN_EQUAL:case Se.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Er.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;case Se.SEARCH_TYPES.LESS_THAN:case Se.SEARCH_TYPES._LESS_THAN:s=Er.lessThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case Se.SEARCH_TYPES.LESS_THAN_EQUAL:case Se.SEARCH_TYPES._LESS_THAN_EQUAL:s=Er.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;default:return Object.create(null)}return s}a(AL,"searchByType");function gL(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(gL,"createMapFromIterable");function p3(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(p3,"checkToFetchMore");function OL(e,t,r,n){if(d3.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),pi.indexOf(s)>-1)return r===!0?Se.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Se.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(pi[0])<0&&s.indexOf(pi[1])<0)return c===!0?r===!0?Se.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Se.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Se.SEARCH_TYPES.EQUALS;if(pi.indexOf(i)>=0&&pi.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Se.SEARCH_TYPES.CONTAINS;if(pi.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Se.SEARCH_TYPES.ENDS_WITH;if(pi.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Se.SEARCH_TYPES.STARTS_WITH;if(s.includes(pi[0])||s.includes(pi[1]))return Se.SEARCH_TYPES.EQUALS;throw new Error(TL.UNKNOWN_SEARCH_TYPE)}else switch(n){case fa.VALUE_SEARCH_COMPARATORS.BETWEEN:return Se.SEARCH_TYPES.BETWEEN;case fa.VALUE_SEARCH_COMPARATORS.GREATER:return Se.SEARCH_TYPES.GREATER_THAN;case fa.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Se.SEARCH_TYPES.GREATER_THAN_EQUAL;case fa.VALUE_SEARCH_COMPARATORS.LESS:return Se.SEARCH_TYPES.LESS_THAN;case fa.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Se.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(TL.UNKNOWN_SEARCH_TYPE)}}a(OL,"createSearchTypeFromSearchObject");bL.exports={executeSearch:RL,createSearchTypeFromSearchObject:OL,prepSearch:h3,searchByType:AL}});var yL=R((ATe,NL)=>{"use strict";var RTe=as(),m3=bc(),S3=Y(),T3=D(),g3=sE();NL.exports=R3;function R3(e,t){if(!S3.isEmpty(t)&&T3.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=m3(e,"value");if(n)throw n;return g3.prepSearch(e,t,!0)}a(R3,"lmdbGetDataByValue")});var Pu=R((NTe,IL)=>{"use strict";var bTe=as(),A3=bc(),O3=Y(),b3=D(),N3=sE();IL.exports=y3;async function y3(e,t){if(!O3.isEmpty(t)&&b3.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=A3(e,"value");if(n)throw n;return N3.prepSearch(e,t,!1)}a(y3,"lmdbSearchByValue")});var CL=R((wTe,wL)=>{"use strict";var ITe=_t(),lg=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}},ug=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},_g=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};wL.exports={SearchByConditionsObject:lg,SearchCondition:ug,SortAttribute:_g}});var UL=R((PTe,ML)=>{"use strict";var DTe=CL().SearchByConditionsObject,I3=as(),w3=bc(),dg=Oc(),iE=_t(),{Resource:LTe}=(Mn(),ae(fg)),PL=sE(),C3=sg(),D3=require("lodash"),{getSchemaPath:L3}=ze(),DL=Ye(),{handleHDBError:P3,hdb_errors:M3}=ie(),{HTTP_STATUS_CODES:U3}=M3,v3=1e8;ML.exports=B3;async function B3(e){let t=w3(e,"conditions");if(t)throw P3(t,t.message,U3.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=L3(e.schema,e.table),n=await DL.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)DL.openDBI(n,_.search_attribute);let i=D3.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let u=_.search_type;u===iE.SEARCH_TYPES.EQUALS?_.estimated_count=dg.count(n,_.search_attribute,_.search_value):u===iE.SEARCH_TYPES.CONTAINS||u===iE.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=v3}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await LL(o,e,i[0],s.hash_attribute),l;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],u=i.slice(1).map(PL.filterByType),d=u.length,E=dg.setGetWholeRowAttributes(n,e.get_attributes);l=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(l=l.filter(f=>{for(let h=0;h<d;h++)if(!u[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(l=l.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),l=l.map(f=>C3.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await LL(o,e,E,s.hash_attribute);c=c.concat(f)}let _=new Set,u=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(u,e.limit&&e.limit+u),l=dg.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return l.onDone=()=>{o.done()},l}a(B3,"lmdbSearchByConditions");async function LL(e,t,r,n){let s=new I3(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===iE.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,PL.searchByType(e,s,i,n).map(o=>o.value)}a(LL,"executeConditionSearch")});var Mu=R((UTe,vL)=>{"use strict";var H3=D().OPERATIONS_ENUM,Eg=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=H3.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};vL.exports=Eg});var hg=R((BTe,VL)=>{"use strict";var xL=as(),qL=Mu(),FL=Pu(),kL=wu(),Pr=D(),BL=Y(),HL=Ye(),{getTransactionAuditStorePath:G3,getSchemaPath:x3}=ze(),GL=k();VL.exports=q3;async function q3(e){try{if(BL.isEmpty(global.hdb_schema[e.schema])||BL.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await F3(e),await k3(e);let t=x3(e.schema,e.table);try{await HL.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")GL.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=G3(e.schema,e.table);await HL.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")GL.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(q3,"lmdbDropTable");async function F3(e){let t=new xL(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Pr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Pr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await FL(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 qL(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await kL(s)}a(F3,"deleteAttributesFromSystem");async function k3(e){let t=new xL(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Pr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[Pr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,Pr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,Pr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await FL(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 qL(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await kL(s)}catch(i){throw i}}a(k3,"dropTableFromSystem")});var YL=R((GTe,$L)=>{"use strict";var V3=require("fs-extra"),$3=as(),Y3=Nc(),K3=Mu(),W3=hg(),Q3=wu(),j3=og(),z3=Pu(),mi=D(),{getSchemaPath:J3}=ze(),{handleHDBError:X3,hdb_errors:Z3}=ie(),{HDB_ERROR_MSGS:eX,HTTP_STATUS_CODES:tX}=Z3;$L.exports=rX;async function rX(e){let t;try{t=await nX(e.schema);let r=new $3(mi.SYSTEM_SCHEMA_NAME,mi.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,mi.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[mi.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await z3(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await W3(c)}catch(l){if(l.message!=="invalid environment")throw l}}let s=new K3(mi.SYSTEM_SCHEMA_NAME,mi.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Q3(s);let i=J3(t);await V3.remove(i)}catch(r){throw r}}a(rX,"lmdbDropSchema");async function nX(e){let t=new Y3(mi.SYSTEM_SCHEMA_NAME,mi.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[mi.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await j3(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw X3(new Error,eX.SCHEMA_NOT_FOUND(e),tX.NOT_FOUND,void 0,void 0,!0);return n}a(nX,"validateDropSchema")});var Uu=R((qTe,KL)=>{"use strict";var pg=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};KL.exports=pg});var Sg=R((VTe,WL)=>{"use strict";var sX=require("fs-extra"),oE=Ye(),{getTransactionAuditStorePath:iX}=ze(),mg=_t(),kTe=Uu();WL.exports=oX;async function oX(e){let t;try{let r=iX(e.schema,e.table);await sX.mkdirp(r),t=await oE.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{oE.createDBI(t,mg.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),oE.createDBI(t,mg.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),oE.createDBI(t,mg.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(oX,"createTransactionsAuditEnvironment")});var JL=R((YTe,zL)=>{"use strict";var Tg=D(),QL=Ye(),aX=Zo(),{getSystemSchemaPath:cX,getSchemaPath:lX}=ze(),uX=_i(),_X=yf(),gg=Nf(),dX=k(),fX=Sg(),Ag=uX.hdb_table,jL=[];for(let e=0;e<Ag.attributes.length;e++)jL.push(Ag.attributes[e].attribute);zL.exports=EX;async function EX(e,t){let r=lX(t.schema,t.table),n=new gg(t.schema,t.table,Tg.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new gg(t.schema,t.table,Tg.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new gg(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await QL.createEnvironment(r,t.table),e!==void 0){let o=await QL.openEnvironment(cX(),Tg.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await aX.insertRecords(o,Ag.hash_attribute,jL,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Rg(n),await Rg(s),await Rg(i)}await fX(t)}catch(o){throw o}}a(EX,"lmdbCreateTable");async function Rg(e){try{await _X(e)}catch(t){dX.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Rg,"createAttribute")});var ZL=R((WTe,XL)=>{"use strict";var hX=pu(),pX=Su(),mX=Xf(),vu=D(),SX=Zo().updateRecords,TX=Ye(),{getSchemaPath:gX}=ze(),RX=yu(),AX=k();XL.exports=OX;async function OX(e){try{let{schema_table:t,attributes:r}=hX(e);pX(e,r,t.hash_attribute),e.schema!==vu.SYSTEM_SCHEMA_NAME&&(r.includes(vu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(vu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(vu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(vu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await mX(e.hdb_auth_header,t,r),s=gX(e.schema,e.table),i=await TX.openEnvironment(s,e.table),o=await SX(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await RX(e,o)}catch(c){AX.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(OX,"lmdbUpdateRecords")});var tP=R((jTe,eP)=>{"use strict";var bX=D().OPERATIONS_ENUM,Og=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=bX.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};eP.exports=Og});var nP=R((XTe,rP)=>{"use strict";var JTe=tP(),NX=pu(),yX=Su(),IX=Xf(),Bu=D(),wX=Zo().upsertRecords,CX=Ye(),{getSchemaPath:DX}=ze(),LX=yu(),PX=k(),{handleHDBError:MX,hdb_errors:UX}=ie();rP.exports=vX;async function vX(e){let t;try{t=NX(e)}catch(l){throw MX(l,l.message,UX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;yX(e,n,r.hash_attribute),e.schema!==Bu.SYSTEM_SCHEMA_NAME&&(n.includes(Bu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(Bu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(Bu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(Bu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await IX(e.hdb_auth_header,r,n),i=DX(e.schema,e.table),o=await CX.openEnvironment(i,e.table),c=await wX(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await LX(e,c)}catch(l){PX.error(`unable to write transaction due to ${l.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(vX,"lmdbUpsertRecords")});var iP=R((ege,sP)=>{"use strict";var bg=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};sP.exports=bg});var aP=R((rge,oP)=>{"use strict";var Ng=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}};oP.exports=Ng});var uP=R((ige,lP)=>{"use strict";var yg=Ye(),{getTransactionAuditStorePath:BX}=ze(),sge=iP(),Hu=_t(),HX=Y(),cP=aP(),GX=require("util").promisify,xX=GX(setTimeout),qX=1e4,FX=100;lP.exports=kX;async function kX(e){let t=BX(e.schema,e.table),r=await yg.openEnvironment(t,e.table,!0),n=yg.listDBIs(r);yg.initializeDBIs(r,Hu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new cP;do s=await VX(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 xX(FX);while(s.transactions_deleted>0);return i}a(kX,"deleteAuditLogsBefore");async function VX(e,t){let r=new cP;try{let n=e.dbis[Hu.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[Hu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];HX.isEmpty(c)||(s=e.dbis[Hu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let l=0;l<o.hash_values.length;l++)s=e.dbis[Hu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[l],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>qX)break}return await s,r}catch(n){throw n}}a(VX,"deleteTransactions")});var dP=R((age,_P)=>{"use strict";var Ig=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};_P.exports=Ig});var EP=R((uge,fP)=>{"use strict";var $X=as(),YX=Mu(),lge=dP(),Bs=D(),KX=Y(),wg=Ye(),WX=_i(),QX=Pu(),jX=wu(),{getSchemaPath:zX}=ze();fP.exports=JX;async function JX(e,t=!0){let r;e.schema===Bs.SYSTEM_SCHEMA_NAME?r=WX[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await ZX(e),s=zX(e.schema,e.table),i=await wg.openEnvironment(s,e.table);return t===!0&&await XX(e,i,r.hash_attribute),wg.dropDBI(i,e.attribute),n}a(JX,"lmdbDropAttribute");async function XX(e,t,r){let n=wg.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:l}of n.getRange({start:!1,versions:!0})){let _={};for(let u in c)u!==i&&(_[u]=c[u]);s=t.dbis[r].put(o,_,l)}await s}a(XX,"removeAttributeFromAllObjects");async function ZX(e){let t=new $X(Bs.SYSTEM_SCHEMA_NAME,Bs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await QX(t)).filter(o=>o[Bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(KX.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[Bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new YX(Bs.SYSTEM_SCHEMA_NAME,Bs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return jX(i)}a(ZX,"dropAttributeFromSystem")});var gP=R((fge,TP)=>{"use strict";var Cg=Ye(),yc=_t(),dge=Nr(),Dg=D(),hP=Y(),{getTransactionAuditStorePath:eZ}=ze(),tZ=Oc(),aE=gc(),rZ=k();TP.exports=nZ;async function nZ(e){let t=eZ(e.schema,e.table),r=await Cg.openEnvironment(t,e.table,!0),n=Cg.listDBIs(r);Cg.initializeDBIs(r,yc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case Dg.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return pP(r,e.search_values);case Dg.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,iZ(r,e.search_values,s);case Dg.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return sZ(r,e.search_values);default:return pP(r)}}a(nZ,"readAuditLog");function pP(e,t=[0,Date.now()]){hP.isEmpty(t[0])&&(t[0]=0),hP.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[yc.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 aE,s))}a(pP,"searchTransactionsByTimestamp");function sZ(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[yc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,SP(e,i))}return Object.fromEntries(r)}a(sZ,"searchTransactionsByUsername");function iZ(e,t,r){let n=new Map;for(let c=0,l=t.length;c<l;c++){let _=t[c],u=tZ.equals(e,yc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,yc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of u){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=SP(e,s),o=new Map;for(let c=0;c<i.length;c++){let l=i[c],_=l.timestamp,u=n.get(_);mP(l,"records",r,u,o),mP(l,"original_records",r,u,o)}return Object.fromEntries(o)}a(iZ,"searchTransactionsByHashValues");function mP(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],l=c[r].toString();if(n.indexOf(l)>=0)if(s.has(l)){let _=s.get(l),u=_[_.length-1];if(u.timestamp===i)u[t]=[c];else{let d=new aE(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new aE(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(l,[_])}}}a(mP,"loopRecords");function SP(e,t){let r=[];try{let n=e.dbis[yc.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 aE,i);r.push(o)}}catch(i){rZ.warn(i)}return r}catch(n){throw n}}a(SP,"batchSearchTransactions")});var AP=R((mge,RP)=>{"use strict";var{getSchemaPath:hge}=ze(),pge=Ye(),{database:oZ}=(Re(),ae($e));RP.exports={writeTransaction:aZ};async function aZ(e,t,r){return oZ({database:e,table:t}).transaction(r)}a(aZ,"writeTransaction")});var yP=R((Tge,NP)=>{"use strict";var{getSchemaPath:OP}=ze(),bP=Ye();NP.exports={flush:cZ,resetReadTxn:lZ};async function cZ(e,t){return(await bP.openEnvironment(OP(e,t),t.toString())).flushed}a(cZ,"flush");async function lZ(e,t){try{(await bP.openEnvironment(OP(e,t),t.toString())).resetReadTxn()}catch{}}a(lZ,"resetReadTxn")});var DP=R((Rge,CP)=>{"use strict";var{Readable:uZ}=require("stream"),{getDatabases:_Z}=(Re(),ae($e)),{readSync:dZ,openSync:fZ,createReadStream:IP}=require("fs"),{open:EZ}=require("lmdb"),wP=lu(),hZ=uu(),{AUDIT_STORE_OPTIONS:pZ}=(no(),ae(LP)),{INTERNAL_DBIS_NAME:mZ,AUDIT_STORE_NAME:SZ}=_t();CP.exports=gZ;var Lg=32768,TZ=100;async function gZ(e){let t=e.database||e.schema||"data",r=_Z()[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 u=_.dbisDB,d=EZ({noSync:!0,maxDbs:hZ.MAX_DBS}),E,f=d.openDB(mZ,new wP(!1)),h=u.useReadTransaction(),m=0,S=a(async function(T,b){b.encoding="binary",b.encoder=void 0;let N=d.openDB(T,b),v=u.openDB(T,b);for(let{key:U,version:F,value:M}of v.getRange({start:null,transaction:h,versions:v.useVersions}))E=N.put(U,M,F),m++%TZ===0&&(await new Promise(W=>setTimeout(W,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:T,value:b}of u.getRange({transaction:h,start:!1}))if(s.some(N=>T.startsWith?.(N+"/"))){f.put(T,b);let[,N]=T.split("/"),v=!N,U=new wP(!v,v);await S(T,U)}e.include_audit&&await S(SZ,Object.assign({},pZ)),await E;let g=IP(d.path);return g.headers=l(),g.on("close",()=>{h.done(),d.close()}),g}let o=r[Object.keys(r)[0]].primaryStore,c=fZ(o.path);return o.transaction(()=>{let _=Buffer.alloc(Lg);dZ(c,_,0,Lg),o.resetReadTxn();let u=o.useReadTransaction();u.renew();let d=IP(null,{fd:c,start:Lg}),E=new uZ.from(async function*(){yield _;for await(let f of d)u.openTimer&&(u.openTimer=0),yield f;u.done()}());return E.headers=l(),E});function l(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(gZ,"getBackup")});var UP=R((Oge,MP)=>{"use strict";var RZ=k(),{handleHDBError:AZ}=ie(),OZ=jI(),bZ=yf(),NZ=ZT(),yZ=YD(),IZ=wu(),wZ=og(),CZ=mL(),DZ=yL(),LZ=Pu(),PZ=UL(),MZ=YL(),UZ=JL(),vZ=ZL(),BZ=nP(),HZ=uP(),GZ=hg(),xZ=EP(),qZ=gP(),FZ=AP(),PP=yP(),kZ=DP(),Pg=class extends OZ{static{a(this,"LMDBBridge")}async searchByConditions(t){return PZ(t)}async getDataByHash(t){return await wZ(t)}async searchByHash(t){return await CZ(t)}async getDataByValue(t,r){return await DZ(t,r)}async searchByValue(t){return await LZ(t)}async createSchema(t){return await yZ(t)}async dropSchema(t){return await MZ(t)}async createTable(t,r){return await UZ(t,r)}async dropTable(t){return await GZ(t)}async createAttribute(t){return await bZ(t)}async createRecords(t){return await NZ(t)}async updateRecords(t){return await vZ(t)}async upsertRecords(t){try{return await BZ(t)}catch(r){throw AZ(r,null,null,RZ.ERR,r)}}async deleteRecords(t){return await IZ(t)}async dropAttribute(t){return await xZ(t)}async deleteAuditLogsBefore(t){return await HZ(t)}async readAuditLog(t){return await qZ(t)}writeTransaction(t,r,n){return FZ.writeTransaction(t,r,n)}flush(t,r){return PP.flush(t,r)}resetReadTxn(t,r){return PP.resetReadTxn(t,r)}getBackup(t){return kZ(t)}};MP.exports=Pg});function KZ(){YZ=setInterval(function(){for(let e of Mg)if(e.stale){let t=e[Ie]?.url;GP.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},$Z).unref()}var Ug,HP,GP,xP,qP,FP,vP,Mg,VZ,Gu,BP,Ea,cE,$Z,YZ,vg=be(()=>{Ug=G(Nr()),HP=G(ie()),GP=G(k());Mn();xP=G(X()),qP=G(D()),FP=G(Y()),vP=100,Mg=new Set,VZ=(0,FP.convertToMS)(xP.get(qP.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,Ea=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;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.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),Mg.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Mg.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Gu&&!this.overloadChecked&&performance.now()-BP>VZ)throw new HP.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}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,Ug.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let f=d;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=d;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let m=d;m<this.validated;m++){let S=this.writes[m];if(!S)continue;let g=S[f===0?"before":"beforeIntermediate"];if(g){let T=g();h?h.push?h.push(T):h=[h,T]:h=T}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),l=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let E=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||E}else l();else for(let E of this.writes)c(E)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<vP>>n?l():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return Gu||(Gu=s,BP=performance.now(),Gu.then(()=>{Gu=null})),s.then(d=>d?(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}))):(_&&(_.retryRisk=(_.retryRisk||0)+vP/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let u={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));u.next=d}return u}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},cE=class extends Ea{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Ug.getNextMonotonicTime)())}getReadTxn(){}},$Z=3e4;a(KZ,"startMonitoringTxns");KZ()});function it(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 Ea;e.timestamp&&(n.timestamp=e.timestamp),n[Ie]=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 l=n.commit({letItLinger:r?.letItLinger});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var kP,ha=be(()=>{kP=require("../index");Mn();vg();a(it,"transaction");(0,kP._assignPackageExport)("transaction",it);it.commit=function(e){let t=(e[Ie]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};it.abort=function(e){let t=(e[Ie]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var JP={};Ve(JP,{ResourceBridge:()=>Gg});function xg({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 $P(e,t){let r=Hs(e),n=xg(e,r);if(!r)throw new cs.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;it(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,l=0;return{[Symbol.asyncIterator](){return{async next(){if(l<c.length){let _=c[l++],u=await r.get({id:_,lazy:s,select:n},i);return u=u&&uE(u),t?{value:{key:_,value:u}}:{value:u}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function Hs(e){let t=e.database||e.schema||QZ,r=Mr()[t];if(!r)throw(0,cs.handleHDBError)(new Error,WZ.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function YP(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*KP(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:l}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(l)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[l]})}n&&(yield n)}var WP,lE,cs,QP,jP,ls,Bg,Hg,zP,WZ,QZ,jZ,zZ,VP,Gg,XP=be(()=>{"use strict";WP=G(UP()),lE=G(bc()),cs=G(ie());Re();QP=G(pu()),jP=G(Su()),ls=G(D()),Bg=G(hi()),Hg=G(os()),zP=G(Y());ha();_E();({HDB_ERROR_MSGS:WZ}=cs.hdb_errors),QZ="data",jZ=1e4,zZ=10,Gg=class extends WP.default{static{a(this,"ResourceBridge")}constructor(t){super(t),VP=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,lE.default)(t,"conditions");if(r)throw(0,cs.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=Hs(t);if(!n)throw new cs.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:xg(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 cs.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}]}St({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await Hs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Hs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,l)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,l,()=>r.primaryStore.put(o,c,l)).then(_=>{if(!_){let{value:u,version:d}=r.primaryStore.getEntry(o);return i(o,u,d)}})),"deleteRecord");for(let{key:o,value:c,version:l}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,l),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Hs(t).dropTable()}createSchema(t){return Ic({database:t.schema,table:null}),Bg.signalSchemaChange(new Hg.SchemaEventMsg(process.pid,ls.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await qg(t.schema),Bg.signalSchemaChange(new Hg.SchemaEventMsg(process.pid,ls.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,VP.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,QP.default)(t);(0,jP.default)(t,n,r.primaryKey);let s,i=Mr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return it(o,async c=>{if(!i.schemaDefined){s=[];for(let u of n)i.attributes.find(E=>E.name==u)||s.push(u);s.length>0&&await i.addAttributes(s.map(u=>({name:u,indexed:!0})))}let l=[],_=[];for(let u of t.records){let d=await i.get(u[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(u[i.primaryKey]);continue}d&&(d=uE(d));for(let E in u)if(Object.prototype.hasOwnProperty.call(u,E)){let f=u[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,u[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(u),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(u,E)||(u[E]=d[E]);await i.put(u,o),l.push(u[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:l,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=Mr()[t.schema][t.table],n={user:t.hdb_user};return it(n,async s=>{let i=t.hash_values||t.records.map(l=>l[r.primaryKey]),o=[],c=[];for(let l of i)await r.delete(l,n)?o.push(l):c.push(l);return YP(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=Mr()[t.schema][t.table];if(!r.createdTimeProperty)throw new cs.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:ls.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,l=[],_=a(async()=>{let u=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:l});i.push(...u.deleted_hashes),o.push(...u.skipped_hashes),await(0,zP.async_set_timeout)(zZ),l=[],s=!0},"chunkDelete");for await(let u of n)l.push(u[r.primaryKey]),c++,c%jZ===0&&await _();return l.length>0&&await _(),s?YP(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,lE.default)(t,"hashes");if(r)throw r;return $P(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of $P(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&ls.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,lE.default)(t,"value");if(n)throw n;let s=Hs(t);if(!s)throw new cs.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===ls.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:xg(t,s)})}async getDataByValue(t,r){let n=new Map,s=Hs(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){Hs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Hs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Hs(t),n={};switch(t.search_type){case ls.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 ls.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of KP(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return KP(r,t.search_values?.[0],t.search_values?.[1])}}};a(xg,"getSelect");a($P,"getRecords");a(Hs,"getTable");a(YP,"createDeleteResponse");a(KP,"groupRecordsInHistory")});var Hn=R((Gge,ZP)=>{"use strict";var{ResourceBridge:JZ}=(XP(),ae(JP)),XZ=X();XZ.initSync();var dE;function ZZ(){return dE||(dE=new JZ,dE)}a(ZZ,"getBridge");ZP.exports=ZZ()});var nM=R((qge,rM)=>{"use strict";var eM=require("lodash"),xu=require("mathjs"),e5=require("jsonata"),tM=Y();rM.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?eM.uniqWith(e,eM.isEqual):e,searchJSON:t5,mad:qu.bind(null,xu.mad),mean:qu.bind(null,xu.mean),mode:qu.bind(null,xu.mode),prod:qu.bind(null,xu.prod),median:qu.bind(null,xu.median)};function qu(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(qu,"aggregateFunction");function t5(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(tM.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),tM.isEmpty(this.__ala__.res[r])){let n=e5(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(t5,"searchJSON")});var iM=R((kge,sM)=>{"use strict";var It=require("moment"),Fg="YYYY-MM-DDTHH:mm:ss.SSSZZ";It.suppressDeprecationWarnings=!0;sM.exports={current_date:()=>It().utc().format("YYYY-MM-DD"),current_time:()=>It().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return It(e).utc().format("YYYY");case"month":return It(e).utc().format("MM");case"day":return It(e).utc().format("DD");case"hour":return It(e).utc().format("HH");case"minute":return It(e).utc().format("mm");case"second":return It(e).utc().format("ss");case"millisecond":return It(e).utc().format("SSS");default:break}},date:e=>It(e).utc().format(Fg),date_format:(e,t)=>It(e).utc().format(t),date_add:(e,t,r)=>It(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>It(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=It(e).utc(),s=It(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>It().utc().valueOf(),get_server_time:()=>It().format(Fg),offset_utc:(e,t)=>It(e).utc().utcOffset(t).format(Fg)}});var lM=R((Vge,cM)=>{"use strict";var r5=require("@turf/area"),n5=require("@turf/length"),s5=require("@turf/circle"),i5=require("@turf/difference"),o5=require("@turf/distance"),a5=require("@turf/boolean-contains"),c5=require("@turf/boolean-equal"),l5=require("@turf/boolean-disjoint"),u5=require("@turf/helpers"),oM=D(),Ae=Y(),Si=k();cM.exports={geoArea:_5,geoLength:d5,geoCircle:f5,geoDifference:E5,geoDistance:aM,geoNear:h5,geoContains:p5,geoEqual:m5,geoCrosses:S5,geoConvert:T5};function _5(e){if(Ae.isEmpty(e))return NaN;typeof e=="string"&&(e=Ae.autoCastJSON(e));try{return r5.default(e)}catch(t){return Si.trace(t,e),NaN}}a(_5,"geoArea");function d5(e,t){if(Ae.isEmpty(e))return NaN;typeof e=="string"&&(e=Ae.autoCastJSON(e));try{return n5.default(e,{units:t||"kilometers"})}catch(r){return Si.trace(r,e),NaN}}a(d5,"geoLength");function f5(e,t,r){if(Ae.isEmpty(e))return NaN;if(Ae.isEmpty(t))return NaN;typeof e=="string"&&(e=Ae.autoCastJSON(e));try{return s5.default(e,t,{units:r||"kilometers"})}catch(n){return Si.trace(n,e,t),NaN}}a(f5,"geoCircle");function E5(e,t){if(Ae.isEmpty(e))return NaN;if(Ae.isEmpty(t))return NaN;typeof e=="string"&&(e=Ae.autoCastJSON(e)),typeof t=="string"&&(t=Ae.autoCastJSON(t));try{return i5(e,t)}catch(r){return Si.trace(r,e,t),NaN}}a(E5,"geoDifference");function aM(e,t,r){if(Ae.isEmpty(e))return NaN;if(Ae.isEmpty(t))return NaN;typeof e=="string"&&(e=Ae.autoCastJSON(e)),typeof t=="string"&&(t=Ae.autoCastJSON(t));try{return o5.default(e,t,{units:r||"kilometers"})}catch(n){return Si.trace(n,e,t),NaN}}a(aM,"geoDistance");function h5(e,t,r,n){if(Ae.isEmpty(e)||Ae.isEmpty(t))return!1;if(Ae.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Ae.autoCastJSON(e)),typeof t=="string"&&(t=Ae.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return aM(e,t,n)<=r}catch(s){return Si.trace(s,e,t),!1}}a(h5,"geoNear");function p5(e,t){if(Ae.isEmpty(e)||Ae.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Ae.autoCastJSON(e)),typeof t=="string"&&(t=Ae.autoCastJSON(t));try{return a5.default(e,t)}catch(r){return Si.trace(r,e,t),!1}}a(p5,"geoContains");function m5(e,t){if(Ae.isEmpty(e)||Ae.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Ae.autoCastJSON(e)),typeof t=="string"&&(t=Ae.autoCastJSON(t));try{return c5.default(e,t)}catch(r){return Si.trace(r,e,t),!1}}a(m5,"geoEqual");function S5(e,t){if(Ae.isEmpty(e)||Ae.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Ae.autoCastJSON(e)),typeof t=="string"&&(t=Ae.autoCastJSON(t));try{return!l5.default(e,t)}catch(r){return Si.trace(r,e,t),!1}}a(S5,"geoCrosses");function T5(e,t,r){if(Ae.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Ae.isEmpty(t))throw new Error("geo_type is required");if(Ae.isEmpty(oM.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(oM.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Ae.autoCastJSON(e)),u5[t](e,r)}a(T5,"geoConvert")});var fE=R((Yge,uM)=>{var pa=nM(),dn=iM(),Gs=lM();uM.exports=e=>{e.aggr.mad=e.aggr.MAD=pa.mad,e.aggr.mean=e.aggr.MEAN=pa.mean,e.aggr.mode=e.aggr.MODE=pa.mode,e.aggr.prod=e.aggr.PROD=pa.prod,e.aggr.median=e.aggr.MEDIAN=pa.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=pa.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=pa.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=dn.current_date,e.fn.current_time=e.fn.CURRENT_TIME=dn.current_time,e.fn.extract=e.fn.EXTRACT=dn.extract,e.fn.date=e.fn.DATE=dn.date,e.fn.date_format=e.fn.DATE_FORMAT=dn.date_format,e.fn.date_add=e.fn.DATE_ADD=dn.date_add,e.fn.date_sub=e.fn.DATE_SUB=dn.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=dn.date_diff,e.fn.now=e.fn.NOW=dn.now,e.fn.offset_utc=e.fn.OFFSET_UTC=dn.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=dn.get_server_time,e.fn.getdate=e.fn.GETDATE=dn.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=dn.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=Gs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Gs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Gs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Gs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Gs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Gs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Gs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Gs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Gs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Gs.geoNear}});var EM=R((Kge,fM)=>{"use strict";var Fu=require("lodash"),Ur=require("alasql");Ur.options.cache=!1;var g5=fE(),_M=require("clone"),EE=require("recursive-iterator"),he=k(),Me=Y(),wc=Hn(),R5=D(),{hdb_errors:A5}=ie(),{getDatabases:dM}=(Re(),ae($e)),O5="IS NULL",us="There was a problem performing this search. Please check the logs and try again.";g5(Ur);var kg=class{static{a(this,"SQLSearch")}constructor(t,r){if(Me.isEmpty(t))throw he.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(),Me.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Me.isEmptyOrZeroLength(n))return he.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw he.error("Error thrown from checkEmptySQL in SQLSearch class method search."),he.error(n),new Error(us)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw he.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),he.error(n),new Error(us)}if(Object.keys(this.data).length===0)return he.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw he.error("Error thrown from processJoins in SQLSearch class method search."),he.error(n),new Error(us)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw he.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),he.error(n),new Error(us)}try{return t=await this._finalSQL(),t}catch(n){throw he.error("Error thrown from finalSQL in SQLSearch class method search."),he.error(n),new Error(us)}}_getColumns(){let t=new EE(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(_M(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Fu.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=dM()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Me.isEmpty(this.statement.where)){he.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new EE(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Me.isEmpty(r)&&r.right)if(Me.isNotEmptyAndHasValue(r.right.value)){let n=Me.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new Ur.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Me.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new Ur.yy.LogicValue({value:i}):n instanceof Ur.yy.StringValue&&Me.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new Ur.yy.NumValue({value:i}))});if(t){he.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new EE(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(!Me.isEmpty(R5.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Me.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Me.isEmptyOrZeroLength(r.left.columnid)||Me.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(Me.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"=":!Me.isEmpty(r.right.value)||!Me.isEmpty(r.left.value)?n.add(Me.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let l=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<l.length;_++)if(l[_].value)n.add(l[_].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(Me.isEmptyOrZeroLength(this.all_table_attributes)&&Me.isEmptyOrZeroLength(this.statement.from)&&Me.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&&Fu.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(Me.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Me.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(Me.isEmptyOrZeroLength(this.all_table_attributes)&&!Me.isEmptyOrZeroLength(this.columns.columns))return t;if(Me.isEmptyOrZeroLength(this.all_table_attributes)&&Me.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await Ur.promise(r)}catch(r){throw he.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),he.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(_M(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(Me.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(O5)>-1&&this.tables.forEach(s=>{let i={columnid:dM()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Fu.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]},l=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(l=!0),!Me.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Me.isEmptyOrZeroLength(this.exact_search_values[_].values))if(l)try{c.hash_values=Array.from(this.exact_search_values[_].values);let u=await wc.getDataByHash(c);for(let d of c.hash_values)u.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(u){throw he.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),he.error(u),new Error(us)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async u=>{let d=Object.assign({},c);d.search_value=u;let E=await wc.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(u){throw he.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),he.error(u),new Error(us)}else if(!Me.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Me.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let u=this.comparator_search_values[_].comparators;for(let d=0,E=u.length;d<E;d++){let f=u[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await wc.getDataByValue(c,f.operation);if(l)for(let[m]of h)this.data[i].__merged_data[m]||(this.data[i].__merged_data[m]=[...n[i]],this._setMergedHashAttribute(i,m));else for(let[m,S]of h)this.data[i].__merged_data[m]?this._updateMergedAttribute(i,m,s.attribute,S[s.attribute]):(this.data[i].__merged_data[m]=[...n[i]],this._updateMergedAttribute(i,m,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,m))}}catch(u){throw he.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),he.error(u),new Error(us)}else try{c.search_attribute=s.attribute,c.search_value="*";let u=await wc.getDataByValue(c);if(l)for(let[d]of u)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of u)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,d))}catch(u){throw he.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),he.error(u),new Error(us)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof Ur.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 Ur.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new Ur.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 Ur.yy.FuncValue:new Ur.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(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,m=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${m}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${m}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let l=this.statement.where?"WHERE "+this.statement.where:"";l=l.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(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let u="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(u=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${l} ${_} ${u} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await Ur.promise(h,t),t=null}catch(f){throw he.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),he.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let m=E[f];o.forEach(S=>{m[S.key]!==null&&m[S.key]!==void 0&&S.keys.add(m[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),m=Fu.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,g=m.length;S<g;S++){let T=m[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[T]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new EE(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=Fu.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 he.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),he.error(i),new Error(us)}}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 u in i)o.push(i[u][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},l=await wc.getDataByHash(c),_=s.columns.length;for(let u=0,d=o.length;u<d;u++){let E=o[u],f=l.get(E);for(let h=0;h<_;h++){let m=s.columns[h],S=f[m]===void 0?null:f[m];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw he.error("Error thrown from getDataByHash function in SQLSearch class method getData."),he.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,l=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===l}).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();he.trace(`Final SQL: ${s}`),n=await Ur.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),he.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw he.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),he.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 he.error(A5.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),he.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 l=s[i],_=new RegExp(`${l}.\`${o}\``,"g"),u=`${l}.[${c}]`;n=n.replace(_,u)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let l=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(l,_)});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 wc.getDataByValue(i);for(let[c,l]of o)this.data[s].__merged_data[c]||(l[n.attribute]===void 0&&(l[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=l[n.attribute]??null}catch(o){throw he.error("There was an error when processing this SQL operation. Check your logs"),he.error(o),new Error(us)}}return Object.values(Object.values(this.data)[0].__merged_data)}};fM.exports=kg});var ur=R((Qge,hM)=>{"use strict";var b5=WI();hM.exports={searchByConditions:y5,searchByHash:I5,searchByValue:w5,search:C5};var Vg=Hn(),{transformReq:$g}=Y(),N5=EM();async function y5(e){return $g(e),Vg.searchByConditions(e)}a(y5,"searchByConditions");async function I5(e){$g(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Vg.searchByHash(e))r&&t.push(r);return t}a(I5,"searchByHash");async function w5(e){$g(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Vg.searchByValue(e))t.push(r);return t}a(w5,"searchByValue");function C5(e,t){try{let r=new b5(e);r.validate(),new N5(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(C5,"search")});var hE=R((zge,pM)=>{"use strict";var D5=Hn();pM.exports={writeTransaction:L5};function L5(e,t,r){return D5.writeTransaction(e,t,r)}a(L5,"writeTransaction")});var gM=R((Zge,TM)=>{"use strict";var P5=ur(),M5=Bn(),mM=k(),U5=Cr(),Xge=hE(),v5=require("clone"),Kg=require("alasql"),B5=fE(),SM=require("util"),H5=SM.promisify(M5.getTableSchema),G5=SM.promisify(P5.search),x5=D(),Yg=Y();B5(Kg);TM.exports={update:F5};var q5="There was a problem performing this update. Please check the logs and try again.";async function F5({statement:e,hdb_user:t}){let r=await H5(e.table.databaseid,e.table.tableid),n=k5(e.columns);Yg.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=v5(s),c=Yg.isEmpty(i)?"":` WHERE ${i.toString()}`,l=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=Kg.parse(l).statements[0],u=await G5(_),d=V5(n,u);return $5(o,d,t)}a(F5,"update");function k5(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=Kg.compile(`SELECT ${r.expression.toString()} AS [${x5.FUNC_VAL}] FROM ?`)}),t}catch(t){throw mM.error(t),new Error(q5)}}a(k5,"createUpdateRecord");function V5(e,t){return Yg.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(V5,"buildUpdateRecords");async function $5(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await U5.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){mM.error(`Error delete new_attributes from update response: ${i}`)}return s}a($5,"updateRecords")});var AM=R((nRe,RM)=>{var Y5=require("alasql"),K5=ur(),W5=k(),Q5=Hn(),Qg=require("util"),Wg=Y(),j5=D(),z5=Bn(),tRe=hE(),rRe=Cr(),J5="record",X5="successfully deleted",Z5=Qg.callbackify(n8),e8=Qg.promisify(K5.search),t8=Qg.promisify(z5.getTableSchema);RM.exports={convertDelete:Z5};function r8(e){return`${e.deleted_hashes.length} ${J5}${e.deleted_hashes.length===1?"":"s"} ${X5}`}a(r8,"generateReturnMessage");async function n8({statement:e,hdb_user:t}){let r=await t8(e.table.databaseid,e.table.tableid);Wg.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=Wg.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=Y5.parse(o).statements[0],l={operation:j5.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{l.records=await e8(c);let _=await Q5.deleteRecords(l);return Wg.isEmptyOrZeroLength(_.message)&&(_.message=r8(_)),delete _.txn_time,_}catch(_){throw W5.error(_),_.hdb_code?_.message:_}}a(n8,"convertDelete")});var IM=R((iRe,yM)=>{"use strict";var s8=Ei(),{hdb_errors:OM}=ie(),{getDatabases:bM}=(Re(),ae($e));yM.exports={checkSchemaExists:NM,checkSchemaTableExists:i8,schema_describe:s8};async function NM(e){if(!bM()[e])return OM.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(NM,"checkSchemaExists");async function i8(e,t){let r=await NM(e);if(r)return r;if(!bM()[e][t])return OM.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(i8,"checkSchemaTableExists")});var ma=R((aRe,o8)=>{o8.exports={name:"harperdb",version:"4.3.24",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","enterprise","Fastify","NATS","HarperDB","Harper","clustering","replication","REST","WebSockets","decentralized","server-sent events","document store"],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.635.0","@aws-sdk/lib-storage":"3.635.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.14",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.4.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.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.17.1",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 Ku={};Ve(Ku,{addAnalyticsListener:()=>Yu,recordAction:()=>vr,recordActionBinary:()=>fn,setAnalyticsEnabled:()=>a8});function a8(e){BM=e}function vr(e,t,r,n,s){if(!BM)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=SE.get(i);if(o)if(typeof e=="number"){let c=o.values,l=c.index++;if(l>=c.length){let _=c;o.values=c=new Float32Array(l*2),c.set(_),c.index=l+1}c[l]=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},SE.set(i,o)}pE||c8()}function fn(e,t,r,n,s){vr(!!e,t,r,n,s)}function Yu(e){xM.push(e)}function c8(){pE=performance.now(),setTimeout(async()=>{let e=performance.now()-pE;pE=0;let t=[],r={time:Date.now(),period:e,threadId:Sa.threadId,metrics:t};for(let[s,i]of SE){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,l=0,_=[],u;for(let d of qM){let E=Math.floor(c*d),f=o[E-1];if(E>l){let h=E-l;if(f===u){let m=_[_.length-1];typeof m=="number"?_[_.length-1]={value:m,count:1+h}:m.count+=h}else _.push(h>1?{value:f,count:h}:f),u=f;l=E}}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 FM()}let n=process.memoryUsage();t.push({metric:"memory",threadId:Sa.threadId,byThread:!0,...n});for(let s of xM)s(t);SE=new Map,Sa.parentPort?Sa.parentPort.postMessage({type:GM,report:r}):$M({report:r})},HM).unref()}async function l8(e,t=6e4){let r=Jg(),n=kM(),s=new Promise(m=>{let S=performance.now();setImmediate(()=>{let g=performance.now();g-S>5e3&&(0,ku.warn)("Unusually high event queue latency on the main thread of "+Math.round(g-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let g=performance.now();g-S>5e3&&(0,ku.warn)("Unusually high task queue latency on the main thread of "+Math.round(g-S)+"ms"),m(g-S)})}),i;for(let m of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(m.value?.time){i=m.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,l=new Map,_=[],u;for(let{key:m,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(m>o+t)break}else o=m;u=m;let{metrics:g,threadId:T}=S;for(let b of g||[]){let{path:N,method:v,type:U,metric:F,count:M,total:W,distribution:z,threads:J,...le}=b;M||(M=1);let ue=F+(N?"-"+N:"");v!==void 0&&(ue+="-"+v),U!==void 0&&(ue+="-"+U);let Ee=c.get(ue);if(Ee){if(Ee.threads){let we=Ee.threads[T];if(we)Ee=we;else{Ee.threads[T]=Object.assign({},le);continue}}Ee.count||(Ee.count=1);let Ge=Ee.count;for(let we in le){let xe=le[we];typeof xe=="number"&&(Ee[we]=(Ee[we]*Ge+xe*M)/(Ge+M))}Ee.count+=M,W>=0&&(Ee.total+=W,Ee.ratio=Ee.total/Ee.count)}else Ee=Object.assign({period:t},b),delete Ee.distribution,c.set(ue,Ee),Ee.byThread&&(Ee.threads=[],Ee.threads[T]=Object.assign({},le),_.push(Ee));if(z){z=z.map(we=>typeof we=="number"?{value:we,count:1}:we);let Ge=l.get(ue);Ge?Ge.push(...z):l.set(ue,z)}}await FM()}for(let m of _){let{path:S,method:g,type:T,metric:b,count:N,total:v,distribution:U,threads:F,...M}=m;F=F.filter(W=>W);for(let W in M){if(typeof m[W]!="number")continue;let z=0;for(let J of F){let le=J[W];typeof le=="number"&&(z+=le)}m[W]=z}m.count=F.length,delete m.threads,delete m.byThread}for(let[m,S]of l){let g=c.get(m);S.sort((we,xe)=>we.value>xe.value?1:-1);let T=g.count-1,b=[],N=0,v=0,U;for(let we of qM){let xe=T*we;for(;N<xe;)U=S[v++],N+=U.count,v===1&&N--;let Wd=S[v>1?v-2:0];U||(U=S[0]),b.push(U.value-(U.value-Wd.value)*(N-xe)/U.count)}let[F,M,W,z,J,le,ue,Ee,Ge]=b;Object.assign(g,{p1:F,p10:M,p25:W,median:z,p75:J,p90:le,p95:ue,p99:Ee,p999:Ge})}let d;for(let[m,S]of c)S.id=(0,mE.getNextMonotonicTime)(),S.time=u,n.primaryStore.put(S.id,S,{append:!0}).then(g=>{g||n.primaryStore.put(S.id,S)}),d=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(d||h*10>f){let m=(0,mE.getNextMonotonicTime)(),S={id:m,metric:"main-thread-utilization",idle:f-wM,active:h-CM,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(m,S,{append:!0}).then(g=>{g||n.primaryStore.put(m,S)})}wM=f,CM=h}async function DM(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function Jg(){return LM||(LM=St({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function kM(){return PM||(PM=St({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function d8(){VM=!0;let e=(0,$u.get)(zg.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await l8(HM,e),await DM(Jg(),u8),await DM(kM(),_8)},Math.min(e/2,2147483647)).unref()}function $M(e,t){let r=e.report;r.threadId=t?.threadId||Sa.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(MM+=n.mean*n.count);r.totalBytesProcessed=MM,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(UM.get(t))}),UM.set(t,t.performance.eventLoopUtilization())),r.id=(0,mE.getNextMonotonicTime)(),Jg().primaryStore.put(r.id,r),VM||d8(),f8&&(YM=h8(r))}async function h8(e){if(await YM,!fo){let r=(0,Vu.dirname)((0,ku.getLogFilePath)());try{fo=await(0,jg.open)((0,Vu.join)(r,"analytics.log"),"r+")}catch{fo=await(0,jg.open)((0,Vu.join)(r,"analytics.log"),"w+")}}let t=(await fo.stat()).size;if(t>E8){let r=Buffer.alloc(t);await fo.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await fo.write(r,{position:0}),await fo.truncate(r.length),t=r.length}await fo.write(JSON.stringify(e)+`
9
- `,t)}var Sa,vM,ku,Vu,jg,mE,$u,zg,SE,BM,pE,HM,GM,xM,qM,wM,CM,FM,u8,_8,LM,PM,VM,MM,UM,f8,YM,fo,E8,Ti=be(()=>{Sa=require("worker_threads"),vM=G(rt());Re();ku=G(k()),Vu=require("path"),jg=require("fs/promises"),mE=G(Nr()),$u=G(X()),zg=G(D());yr();(0,$u.initSync)();SE=new Map,BM=(0,$u.get)(zg.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(a8,"setAnalyticsEnabled");a(vr,"recordAction");dt.recordAnalytics=vr;a(fn,"recordActionBinary");pE=0,HM=1e3,GM="analytics-report",xM=[];a(Yu,"addAnalyticsListener");qM=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(c8,"sendAnalytics");a(l8,"aggregation");wM=0,CM=0,FM=a(()=>new Promise(setImmediate),"rest");a(DM,"cleanup");u8=36e5,_8=31536e6;a(Jg,"getRawAnalyticsTable");a(kM,"getAnalyticsTable");(0,vM.setChildListenerByType)(GM,$M);a(d8,"startScheduledTasks");MM=0,UM=new Map,f8=!1;a($M,"recordAnalytics");E8=1e6;a(h8,"logAnalytics")});var rR=R((gRe,rU)=>{"use strict";var{decode:p8}=require("msgpackr"),{isMainThread:mRe,parentPort:SRe,threadId:TRe}=require("worker_threads"),RE=gt(),Cc=Ze(),eR=D(),hr=k(),Zg=X(),m8=D(),{onMessageByType:S8}=rt(),QM=fi(),{recordAction:T8,recordActionBinary:g8}=(Ti(),ae(Ku)),{publishToStream:R8}=RE,{ConsumerEvents:KM}=require("nats"),A8=ur(),{promisify:O8}=require("util"),jM=O8(setTimeout),AE=1e4,OE,gE,b8,N8,zM,Wu=new Map,Dc=new Map;rU.exports={initialize:JM,ingestConsumer:tR,setSubscription:y8,setIgnoreOrigin:C8,getDatabaseSubscriptions:w8,updateConsumer:XM};async function JM(){S8(eR.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await XM(n)}),zM=!0,hr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await RE.getNATSReferences();OE=e,gE=e.info.server_name,b8=t,N8=r}a(JM,"initialize");async function XM(e){if(e.status==="start"){let{js:t,jsm:r}=await ZM(e.node_domain_name);tR(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=Wu.get(e.stream_name+e.node_domain_name);t&&(hr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),Wu.set(e.stream_name+e.node_domain_name,"close")),Dc.get(e.node_domain_name)==="failed"&&Dc.set(e.node_domain_name,"close")}}a(XM,"updateConsumer");var bE=new Map;function y8(e,t,r){let n=bE.get(e);n||bE.set(e,n=new Map),n.set(t,r),zM||JM().then(I8)}a(y8,"setSubscription");async function I8(){let e=await A8.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+Cc.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await ZM(r),!n))break;let{schema:o,table:c}=i,l=QM.createNatsTableStreamName(o,c);tR(l,n,s,r)}}}a(I8,"accessConsumers");async function ZM(e){let t,r,n=1;for(;!r;)try{t=await OE.jetstream({domain:e}),r=await OE.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(Dc.get(e)==="close")break;Dc.set(e,"failed"),n%10===1&&hr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<AE?n++*100:AE;await jM(i)}return{js:t,jsm:r}}a(ZM,"connectToRemoteJS");function w8(){return bE}a(w8,"getDatabaseSubscriptions");var eU;function C8(e){eU=e}a(C8,"setIgnoreOrigin");var tU=100,WM=new Array(tU),TE=0;async function tR(e,t,r,n){let{connection:s}=await RE.getNATSReferences();OE=s,gE=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,gE),hr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(Dc.get(n)==="close")break;o%10===1&&hr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(hr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await RE.createConsumer(r,e,gE,new Date(Date.now()).toISOString()));let u=o++*100<AE?o++*100:AE;await jM(u)}let c=!1,l;for(;!c;){if(Wu.get(e+n)==="close"||Dc.get(n)==="close"){Wu.delete(e+n),c=!0;continue}l=await i.consume({max_messages:Zg.get(eR.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),Wu.set(e+n,l);let _=!1;(async()=>{for await(let u of await l.status())if(u.type===KM.ConsumerDeleted&&(await l.close(),c=!0),u.type===KM.HeartbeatsMissed){let d=u.data;hr.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${l.consumer.stream}`),d===100&&(hr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${l.consumer.stream}`),l.stop(),_=!0)}})();try{for await(let u of l)await WM[TE],WM[TE]=D8(u).catch(d=>{hr.error(d)}),++TE>=tU&&(TE=0)}catch(u){u.message==="consumer deleted"?(hr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",l.consumer.stream),await l.close(),c=!0):hr.error("Error consuming clustering ingest, restarting consumer",u)}}}a(tR,"ingestConsumer");async function D8(e){let t=p8(e.data);T8(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),hr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=Zg.get(eR.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Cc.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Cc.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(Cc.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!eU),g8(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(Cc.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:l,table:_,records:u,hash_values:d,__origin:E,expiresAt:f}=t;hr.trace("processing message:",o,c,_,(u?"records: "+u.map(N=>N?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),hr.trace(`messageProcessor nats msg id: ${e.headers.get(Cc.MSG_HEADERS.NATS_MSG_ID)}`);let h;u||(u=d);let m=new Promise(N=>h=N),{timestamp:S,user:g,node_name:T}=E||{},b=bE.get(c)?.get(_);if(!b)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,b.send(t);else if(u.length===1&&!l)b.send({type:Xg(o),value:u[0],id:d?.[0],expiresAt:f,timestamp:S,table:_,onCommit:h,user:g,nodeName:T});else{let N=u.map((v,U)=>({type:Xg(o),value:v,expiresAt:f,id:d?.[U],table:_}));for(;l;)N.push({type:Xg(l.operation),value:l.record,expiresAt:l.expiresAt,id:l.id,table:l.table}),l=l.next;b.send({type:"transaction",writes:N,table:_,timestamp:S,onCommit:h,user:g,nodeName:T})}Zg.get(m8.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&R8(e.subject.split(".").slice(0,-1).join("."),QM.createNatsTableStreamName(c,_),e.headers,e.data),await m}catch(o){hr.error(o)}e.ack()}a(D8,"messageProcessor");function Xg(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(Xg,"convertOperation")});var gt=R((IRe,TU)=>{"use strict";var Wt=X();Wt.initSync();var L8=require("fs-extra"),P8=require("semver"),zu=require("path"),{monotonicFactory:M8}=require("ulidx"),sU=M8(),U8=require("util"),iU=require("child_process"),v8=U8.promisify(iU.exec),B8=iU.spawn,rr=Ze(),Ce=D(),NE=Y(),_s=k(),yE=fi(),H8=hE(),Qu=Et(),{broadcast:G8,onMessageByType:x8,getWorkerIndex:q8}=rt(),{isMainThread:oU}=require("worker_threads"),{Encoder:F8,decode:oR}=require("msgpackr"),aU=new F8,{isEmpty:Aa}=NE,cU=Lr(),ARe=48*36e11;oU&&x8(Ce.ITC_EVENT_TYPES.RESTART,()=>{Br=void 0,Ra=void 0});var{connect:k8,StorageType:V8,RetentionPolicy:$8,AckPolicy:aR,DeliverPolicy:cR,DiscardPolicy:Y8,NatsConnection:ORe,JetStreamManager:bRe,JetStreamClient:NRe,StringCodec:yRe,JSONCodec:K8,createInbox:lR,headers:W8,ErrorCode:nU}=require("nats"),{PACKAGE_ROOT:Q8}=D(),j8=ma(),{recordAction:z8}=(Ti(),ae(Ku)),lU=K8(),J8="clustering",X8=j8.engines[rr.NATS_SERVER_NAME],Z8=zu.join(Q8,"dependencies"),iR=zu.join(Z8,`${process.platform}-${process.arch}`,rr.NATS_BINARY_NAME),nR,sR,ju,Ta,ga;TU.exports={runCommand:uU,checkNATSServerInstalled:e6,createConnection:uR,getConnection:Ju,getJetStreamManager:Xu,getJetStream:dU,getNATSReferences:xs,getServerList:r6,createLocalStream:_R,listStreams:fU,deleteLocalStream:n6,getServerConfig:Lc,listRemoteStreams:s6,viewStream:i6,viewStreamIterator:o6,publishToStream:a6,request:u6,reloadNATS:dR,reloadNATSHub:_6,reloadNATSLeaf:d6,extractServerName:l6,requestErrorHandler:f6,createLocalTableStream:mU,createTableStreams:p6,purgeTableStream:SU,purgeSchemaTableStreams:m6,getStreamInfo:S6,updateLocalStreams:g6,closeConnection:t6,getJsmServerName:IE,addNatsMsgHeader:EU,clearClientCache:_U,updateRemoteConsumer:E6,createConsumer:hU,updateConsumerIterator:h6};async function uU(e,t=void 0){let{stdout:r,stderr:n}=await v8(e,{cwd:t});if(n)throw new Error(n.replace(`
2
+ "use strict";var Fj=Object.create;var Qd=Object.defineProperty;var kj=Object.getOwnPropertyDescriptor;var Gj=Object.getOwnPropertyNames;var qj=Object.getPrototypeOf,$j=Object.prototype.hasOwnProperty;var a=(e,t)=>Qd(e,"name",{value:t,configurable:!0});var Ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var y=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tt=(e,t)=>{for(var r in t)Qd(e,r,{get:t[r],enumerable:!0})},gC=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Gj(t))!$j.call(e,s)&&s!==r&&Qd(e,s,{get:()=>t[s],enumerable:!(n=kj(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Fj(qj(e)):{},gC(t||!e||!e.__esModule?Qd(r,"default",{value:e,enumerable:!0}):r,e)),ne=e=>gC(Qd({},"__esModule",{value:!0}),e);var bC=y((LRe,AC)=>{var Vj=require("fast-glob"),{statSync:Fg,existsSync:kg,readFileSync:Yj,writeFileSync:Kj}=require("fs"),{spawnSync:Wj,spawn:jj,execFileSync:PRe}=require("child_process"),{isMainThread:Qj}=require("worker_threads"),{join:Qo,relative:RC}=require("path"),{PACKAGE_ROOT:Vs}=M(),{tmpdir:zj,platform:Jj}=require("os");require("source-map-support").install();var Xj=["resources","server","dataLayer","components"],zd="ts-build",Gg,Zj=__filename.endsWith("tsBuild.js");if(Zj){if(Qj){let r;try{Fg(Qo(Vs,zd)),r=!0}catch{}if(r)for(let n of Vj.sync(Xj.map(s=>s+"/**/*.ts"),{cwd:Vs})){let s=0,i=0;try{s=Fg(Qo(Vs,n)).mtimeMs-5e3,i=Fg(Qo(Vs,zd,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."),Gg=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Gg=!0;if(Gg){let n=Qo(Vs,"node_modules/.bin/tsc");Jj()==="win32"&&(n+=".cmd");let s=Wj(n,{cwd:Vs});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Qo(zj(),"harperdb-tsc.pid"),o;if(kg(i))try{process.kill(+Yj(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=jj(n,["--watch"],{cwd:Vs,detached:!0,stdio:"ignore"});Kj(i,c.pid.toString()),c.unref()}}}}let e=AC.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(Vs)&&!n[0].includes("node_modules")){let i=RC(Vs,n[0]),o;i.startsWith(zd)?o=Qo(Vs,RC(zd,i)):o=Qo(Vs,zd,i);let c=Qo(o,r),l=c+".js";if(kg(l))return l;if(c.includes(".")&&kg(c))return c}return t(r,n,s)}}});var M=y((vRe,HC)=>{"use strict";var as=require("path"),eQ=require("fs"),{relative:MRe,join:URe}=as,{existsSync:tQ}=eQ;function rQ(){let e=__dirname;for(;!tQ(as.join(e,"package.json"));){let t=as.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(rQ,"getHDBPackageRoot");var zo=rQ(),yC="js",bh=yC,nQ="harperdb-config.yaml",sQ="defaultConfig.yaml",iQ="hdb",OC=`harperdb.${bh}`,NC=`customFunctionsServer.${bh}`,oQ=`restartHdb.${bh}`,$g="HarperDB",Ah="Custom Functions",yh="Clustering Hub",Oh="Clustering Leaf",aQ="Clustering Ingest Service",cQ="Clustering Reply Service",lQ="foreground.pid",uQ="hdb.pid",dQ="data",_Q={HDB:$g,CLUSTERING_HUB:yh,CLUSTERING_LEAF:Oh,CLUSTERING_INGEST_SERVICE:aQ,CLUSTERING_REPLY_SERVICE:cQ,CUSTOM_FUNCTIONS:Ah,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"},fQ={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},EQ={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},hQ={harperdb:$g,"clustering hub":yh,"clustering leaf":Oh,"custom functions":Ah,custom_functions:Ah,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers",http:"http"},pQ={CLUSTERING_HUB_PROC_DESCRIPTOR:yh,CLUSTERING_LEAF_PROC_DESCRIPTOR:Oh},qg={HDB:as.join(zo,"server/harperdb"),CUSTOM_FUNCTIONS:as.join(zo,"server/customFunctions"),CLUSTERING_HUB:as.join(zo,"server/nats"),CLUSTERING_LEAF:as.join(zo,"server/nats")},mQ={HDB:as.join(qg.HDB,OC),CUSTOM_FUNCTIONS:as.join(qg.CUSTOM_FUNCTIONS,NC)},SQ={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:as.join(zo,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:as.join(zo,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:as.join(zo,"launchServiceScripts/launchUpdateNodes4-0-0.js")},TQ={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},IC="support@harperdb.io",gQ="customer-success@harperdb.io",wC=1,RQ=4141,CC="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",AQ="https://www.harperdb.io/product",bQ=`For support, please submit a request at ${CC} or contact ${IC}`,DC=`For license support, please contact ${gQ}`,yQ="None of the specified records were found.",OQ="hash attribute not found",NQ=`Your current license only supports ${wC} role. ${DC}`,IQ="Your current license only supports 3 connections to a node.",wQ="127.0.0.1",CQ=1,DQ=/^\.$/,PQ=/^\.\.$/,LQ="U+002E",MQ=/\//g,UQ="U+002F",vQ=/U\+002F/g,BQ=/^U\+002E$/,HQ=/^U\+002EU\+002E$/,xQ="d",FQ=999999,kQ="*",GQ="--max-old-space-size=",qQ="system",$Q="__hdb_hash",VQ=".harperdb",YQ=".hdb",KQ="keys",WQ="hdb_boot_properties.file",jQ=".updateConfig.json",QQ="SIGTSTP",zQ=24,JQ=6e4,XQ=448,ZQ="blob",ez="trash",tz="database",rz="schema",nz="transactions",sz=".count",iz="id",oz="PROCESS_NAME",PC={SETTINGS_PATH_KEY:"settings_path"},LC=require("lodash"),az={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",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",DEFAULTS_MODE:"DEFAULTS_MODE",REPLICATION_HOSTNAME:"REPLICATION_HOSTNAME",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},cz={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},lz={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},uz={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"},dz={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"},Pn="hdb_internal:",_z={CREATE_SCHEMA:Pn+"create_schema",CREATE_TABLE:Pn+"create_table",CREATE_ATTRIBUTE:Pn+"create_attribute",ADD_USER:Pn+"add_user",ALTER_USER:Pn+"alter_user",DROP_USER:Pn+"drop_user",HDB_NODES:Pn+"hdb_nodes",HDB_USERS:Pn+"hdb_users",HDB_WORKERS:Pn+"hdb_workers",CATCHUP:Pn+"catchup",SCHEMA_CATCHUP:Pn+"schema_catchup",WORKER_ROOM:Pn+"cluster_workers"},fz={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"},Ez="060493.ks",hz=".license",pz={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},oe={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",SIGN_CERTIFICATE:"sign_certificate",CREATE_CSR:"create_csr",LIST_CERTIFICATES:"list_certificates",ADD_CERTIFICATES:"add_certificate",REMOVE_CERTIFICATE:"remove_certificate",ADD_NODE_BACK:"add_node_back",REMOVE_NODE_BACK:"remove_node_back",ADD_SSH_KEY:"add_ssh_key",UPDATE_SSH_KEY:"update_ssh_key",DELETE_SSH_KEY:"delete_ssh_key",LIST_SSH_KEYS:"list_ssh_keys",SET_SSH_KNOWN_HOSTS:"set_ssh_known_hosts",GET_SSH_KNOWN_HOSTS:"get_ssh_known_hosts"},mz={CSV:".csv",JSON:".json"},Sz={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},Tz={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Jd={};Jd[oe.INSERT]=oe.INSERT;Jd[oe.UPDATE]=oe.UPDATE;Jd[oe.UPSERT]=oe.UPSERT;Jd[oe.DELETE]=oe.DELETE;var rt=Object.create(null);rt[oe.DESCRIBE_ALL]=oe.DESCRIBE_ALL;rt[oe.DESCRIBE_TABLE]=oe.DESCRIBE_TABLE;rt[oe.DESCRIBE_SCHEMA]=oe.DESCRIBE_SCHEMA;rt[oe.READ_LOG]=oe.READ_LOG;rt[oe.ADD_NODE]=oe.ADD_NODE;rt[oe.LIST_USERS]=oe.LIST_USERS;rt[oe.LIST_ROLES]=oe.LIST_ROLES;rt[oe.USER_INFO]=oe.USER_INFO;rt[oe.SQL]=oe.SQL;rt[oe.GET_JOB]=oe.GET_JOB;rt[oe.SEARCH_JOBS_BY_START_DATE]=oe.SEARCH_JOBS_BY_START_DATE;rt[oe.DELETE_FILES_BEFORE]=oe.DELETE_FILES_BEFORE;rt[oe.EXPORT_LOCAL]=oe.EXPORT_LOCAL;rt[oe.EXPORT_TO_S3]=oe.EXPORT_TO_S3;rt[oe.CLUSTER_STATUS]=oe.CLUSTER_STATUS;rt[oe.REMOVE_NODE]=oe.REMOVE_NODE;rt[oe.RESTART]=oe.RESTART;rt[oe.CUSTOM_FUNCTIONS_STATUS]=oe.CUSTOM_FUNCTIONS_STATUS;rt[oe.GET_CUSTOM_FUNCTIONS]=oe.GET_CUSTOM_FUNCTIONS;rt[oe.GET_CUSTOM_FUNCTION]=oe.GET_CUSTOM_FUNCTION;rt[oe.SET_CUSTOM_FUNCTION]=oe.SET_CUSTOM_FUNCTION;rt[oe.DROP_CUSTOM_FUNCTION]=oe.DROP_CUSTOM_FUNCTION;rt[oe.ADD_CUSTOM_FUNCTION_PROJECT]=oe.ADD_CUSTOM_FUNCTION_PROJECT;rt[oe.DROP_CUSTOM_FUNCTION_PROJECT]=oe.DROP_CUSTOM_FUNCTION_PROJECT;rt[oe.PACKAGE_CUSTOM_FUNCTION_PROJECT]=oe.PACKAGE_CUSTOM_FUNCTION_PROJECT;rt[oe.DEPLOY_CUSTOM_FUNCTION_PROJECT]=oe.DEPLOY_CUSTOM_FUNCTION_PROJECT;rt[oe.ADD_SSH_KEY]=oe.ADD_SSH_KEY;rt[oe.UPDATE_SSH_KEY]=oe.UPDATE_SSH_KEY;rt[oe.DELETE_SSH_KEY]=oe.DELETE_SSH_KEY;var gz={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"},Rz={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},MC={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"},Az=LC.invert(MC),bz={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"},D={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",HTTP_THREADRANGE:"http_threadRange",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_CONSOLE:"logging_console",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:"operationsApi_tls",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_SYSINFO_NETWORK:"operationsApi_sysInfo_network",OPERATIONSAPI_SYSINFO_DISK:"operationsApi_sysInfo_disk",REPLICATION:"replication",REPLICATION_HOSTNAME:"replication_hostname",REPLICATION_URL:"replication_url",REPLICATION_PORT:"replication_port",REPLICATION_SECUREPORT:"replication_securePort",REPLICATION_ROUTES:"replication_routes",REPLICATION_DATABASES:"replication_databases",REPLICATION_ENABLEROOTCAS:"replication_enableRootCAs",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_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",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",TLS:"tls",CLONED:"cloned"},UC={settings_path:PC.SETTINGS_PATH_KEY,hdb_root_key:D.ROOTPATH,hdb_root:D.ROOTPATH,rootpath:D.ROOTPATH,server_port_key:D.OPERATIONSAPI_NETWORK_PORT,server_port:D.OPERATIONSAPI_NETWORK_PORT,cert_key:D.TLS_CERTIFICATE,certificate:D.TLS_CERTIFICATE,private_key_key:D.TLS_PRIVATEKEY,private_key:D.TLS_PRIVATEKEY,http_secure_enabled_key:D.OPERATIONSAPI_NETWORK_HTTPS,https_on:D.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:D.OPERATIONSAPI_NETWORK_CORS,cors_on:D.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:D.LOGGING_LEVEL,log_level:D.LOGGING_LEVEL,log_path_key:D.LOGGING_ROOT,log_path:D.LOGGING_ROOT,clustering_node_name_key:D.CLUSTERING_NODENAME,node_name:D.CLUSTERING_NODENAME,clustering_enabled_key:D.CLUSTERING_ENABLED,clustering:D.CLUSTERING_ENABLED,max_http_threads:D.THREADS_COUNT,max_hdb_processes:D.THREADS_COUNT,server_timeout_key:D.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:D.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:D.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:D.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:D.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:D.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:D.LOGGING_AUDITLOG,disable_transaction_log:D.LOGGING_AUDITLOG,operation_token_timeout_key:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:D.HTTP_PORT,custom_functions_port:D.HTTP_PORT,custom_functions_directory_key:D.COMPONENTSROOT,custom_functions_directory:D.COMPONENTSROOT,max_custom_function_processes:D.THREADS_COUNT,logging_console:D.LOGGING_CONSOLE,log_to_file:D.LOGGING_FILE,log_to_stdstreams:D.LOGGING_STDSTREAMS,local_studio_on:D.LOCALSTUDIO_ENABLED,clustering_port:D.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:D.CLUSTERING_USER,clustering_enabled:D.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:D.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:D.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:D.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:D.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:D.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:D.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:D.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:D.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:D.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:D.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:D.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:D.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:D.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:D.CLUSTERING_NODENAME,clustering_tls_certificate:D.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:D.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:D.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:D.CLUSTERING_TLS_INSECURE,clustering_tls_verify:D.CLUSTERING_TLS_VERIFY,clustering_loglevel:D.CLUSTERING_LOGLEVEL,clustering_republishmessages:D.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:D.CLUSTERING_DATABASELEVEL,customfunctions_network_port:D.HTTP_PORT,customfunctions_tls_certificate:D.TLS_CERTIFICATE,customfunctions_network_cors:D.HTTP_CORS,customfunctions_network_corsaccesslist:D.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:D.HTTP_HEADERSTIMEOUT,customfunctions_network_https:D.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:D.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:D.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:D.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:D.HTTP_TIMEOUT,customfunctions_tls:D.TLS,http_threads:D.THREADS_COUNT,threads:D.THREADS_COUNT,threads_count:D.THREADS_COUNT,threads_debug:D.THREADS_DEBUG,threads_debug_startingport:D.THREADS_DEBUG_STARTINGPORT,threads_debug_port:D.THREADS_DEBUG_PORT,threads_debug_host:D.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:D.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:D.THREADS_MAXHEAPMEMORY,http_session_affinity:D.HTTP_SESSIONAFFINITY,http_compressionthreshold:D.HTTP_COMPRESSIONTHRESHOLD,http_cors:D.HTTP_CORS,http_corsaccesslist:D.HTTP_CORSACCESSLIST,http_headerstimeout:D.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:D.HTTP_KEEPALIVETIMEOUT,http_timeout:D.HTTP_TIMEOUT,http_port:D.HTTP_PORT,http_secureport:D.HTTP_SECUREPORT,http_mtls:D.HTTP_MTLS,http_mtls_user:D.HTTP_MTLS_USER,http_mtls_required:D.HTTP_MTLS_REQUIRED,http_maxheadersize:D.HTTP_MAXHEADERSIZE,http_threadrange:D.HTTP_THREADRANGE,customfunctions_processes:D.THREADS_COUNT,customfunctions_root:D.COMPONENTSROOT,localstudio_enabled:D.LOCALSTUDIO_ENABLED,logging_file:D.LOGGING_FILE,logging_level:D.LOGGING_LEVEL,logging_root:D.LOGGING_ROOT,logging_rotation_enabled:D.LOGGING_ROTATION_ENABLED,logging_rotation_compress:D.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:D.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:D.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:D.LOGGING_ROTATION_PATH,logging_stdstreams:D.LOGGING_STDSTREAMS,logging_auditlog:D.LOGGING_AUDITLOG,logging_auditretention:D.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:D.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:D.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:D.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:D.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:D.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:D.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:D.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:D.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:D.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:D.OPERATIONSAPI_TLS,operationsapi_tls_certificate:D.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:D.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:D.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:D.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:D.ROOTPATH,operationsapi_sysinfo_network:D.OPERATIONSAPI_SYSINFO_NETWORK,operationsapi_sysinfo_disk:D.OPERATIONSAPI_SYSINFO_DISK,databases:D.DATABASES,storage_path:D.STORAGE_PATH,storage_maxtransactionqueuetime:D.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:D.IGNORE_SCRIPTS,mqtt_network_port:D.MQTT_NETWORK_PORT,mqtt_websocket:D.MQTT_WEBSOCKET,mqtt_network_secureport:D.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:D.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:D.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:D.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:D.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:D.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:D.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:D.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:D.AUTHENTICATION_CACHETTL,authentication_enablesessions:D.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:D.COMPONENTSROOT,replication:D.REPLICATION,replication_port:D.REPLICATION_PORT,replication_secureport:D.REPLICATION_SECUREPORT,replication_hostname:D.REPLICATION_HOSTNAME,replication_url:D.REPLICATION_URL,replication_routes:D.REPLICATION_ROUTES,tls:D.TLS,tls_certificate:D.TLS_CERTIFICATE,tls_privatekey:D.TLS_PRIVATEKEY,tls_certificateauthority:D.TLS_CERTIFICATEAUTHORITY,tls_ciphers:D.TLS_CIPHERS};for(let e in D){let t=D[e];UC[t.toLowerCase()]=t}var yz={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Oz={csv_file_load:"csv_file_load",csv_data_load:oe.CSV_DATA_LOAD,csv_url_load:oe.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",restart_service:"restart_service"},Nz={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"},Iz={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},wz={VERSION_DEFAULT:"2.2.0"},Cz={DEVELOPMENT:8192,DEFAULT:512},Dz={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"},Pz={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"},Lz={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},vC={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Mz=Symbol("metadata"),Uz="__clustering__",vz=Object.values(vC),Bz=15984864e5,BC={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Hz=LC.invert(BC),xz={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"},Fz=111,kz=`\r
3
+ `,Gz={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},qz=["*","%"],$z="unauthorized_access",Vz="func_val",Yz={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Kz={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Wz={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",START_JOB:"start_job",NATS_CONSUMER_UPDATE:"nats_consumer_update"},jz={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Qz={HTTP:"http"},zz={STOPPED:"stopped",ONLINE:"online"},Jz="3.x.x",Xz={SUCCESS:"success",FAILURE:"failure"},Zz={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};HC.exports={LOCAL_HARPERDB_OPERATIONS:rt,HDB_SUPPORT_ADDRESS:IC,HDB_SUPPORT_URL:CC,HDB_PRICING_URL:AQ,SUPPORT_HELP_MSG:bQ,LICENSE_HELP_MSG:DC,HDB_PROC_NAME:OC,HDB_PROC_DESCRIPTOR:$g,CLUSTERING_LEAF_PROC_DESCRIPTOR:Oh,CLUSTERING_HUB_PROC_DESCRIPTOR:yh,SYSTEM_SCHEMA_NAME:qQ,HASH_FOLDER_NAME:$Q,HDB_HOME_DIR_NAME:VQ,UPDATE_FILE_NAME:jQ,LICENSE_KEY_DIR_NAME:KQ,BOOT_PROPS_FILE_NAME:WQ,JOB_TYPE_ENUM:Oz,JOB_STATUS_ENUM:pz,SYSTEM_TABLE_NAMES:uz,SYSTEM_TABLE_HASH_ATTRIBUTES:dz,OPERATIONS_ENUM:oe,VALID_S3_FILE_TYPES:mz,S3_BUCKET_AUTH_KEYS:Sz,VALID_SQL_OPS_ENUM:Tz,GEO_CONVERSION_ENUM:Rz,HDB_SETTINGS_NAMES:MC,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:Az,SERVICE_ACTIONS_ENUM:gz,CLUSTER_MESSAGE_TYPE_ENUM:Nz,CLUSTER_CONNECTION_DIRECTION_ENUM:Iz,CLUSTER_EVENTS_DEFS_ENUM:Dz,PERIOD_REGEX:DQ,DOUBLE_PERIOD_REGEX:PQ,UNICODE_PERIOD:LQ,FORWARD_SLASH_REGEX:MQ,UNICODE_FORWARD_SLASH:UQ,ESCAPED_FORWARD_SLASH_REGEX:vQ,ESCAPED_PERIOD_REGEX:BQ,ESCAPED_DOUBLE_PERIOD_REGEX:HQ,REG_KEY_FILE_NAME:Ez,RESTART_TIMEOUT_MS:JQ,HDB_FILE_PERMISSIONS:XQ,DATABASES_DIR_NAME:tz,LEGACY_DATABASES_DIR_NAME:rz,TRANSACTIONS_DIR_NAME:nz,LIMIT_COUNT_NAME:sz,ID_ATTRIBUTE_STRING:iz,INSERT_MODULE_ENUM:cz,UPGRADE_JSON_FIELD_NAMES_ENUM:lz,RESTART_CODE:QQ,RESTART_CODE_NUM:zQ,CLUSTER_OPERATIONS:Jd,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:fz,HDB_INTERNAL_SC_CHANNEL_PREFIX:Pn,INTERNAL_SC_CHANNELS:_z,CLUSTERING_MESSAGE_TYPES:xz,HDB_FILE_SUFFIX:YQ,BLOB_FOLDER_NAME:ZQ,HDB_TRASH_DIR:ez,ORIGINATOR_SET_VALUE:Fz,LICENSE_VALUES:wz,RAM_ALLOCATION_ENUM:Cz,TIME_STAMP_NAMES_ENUM:vC,TIME_STAMP_NAMES:vz,PERMS_UPDATE_RELEASE_TIMESTAMP:Bz,SEARCH_NOT_FOUND_MESSAGE:yQ,SEARCH_ATTRIBUTE_NOT_FOUND:OQ,LICENSE_ROLE_DENIED_RESPONSE:NQ,LICENSE_MAX_CONNS_REACHED:IQ,BASIC_LICENSE_MAX_NON_CU_ROLES:wC,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:RQ,VALUE_SEARCH_COMPARATORS:BC,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Hz,LICENSE_FILE_NAME:hz,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:Pz,NEW_LINE:kz,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:CQ,MOMENT_DAYS_TAG:xQ,API_TURNOVER_SEC:FQ,LOOPBACK:wQ,CODE_EXTENSION:bh,WILDCARD_SEARCH_VALUE:kQ,NODE_ERROR_CODES:Lz,JAVASCRIPT_EXTENSION:yC,PERMS_CRUD_ENUM:Gz,UNAUTHORIZED_PERMISSION_NAME:$z,SEARCH_WILDCARDS:qz,FUNC_VAL:Vz,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Yz,JWT_ENUM:Kz,CLUSTERING_FLAG:Uz,ITC_EVENT_TYPES:Wz,CUSTOM_FUNCTION_PROC_NAME:NC,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Ah,SERVICES:jz,THREAD_TYPES:Qz,MEM_SETTING_KEY:GQ,HDB_RESTART_SCRIPT:oQ,PROCESS_DESCRIPTORS:_Q,SERVICE_SERVERS:mQ,SERVICE_SERVERS_CWD:qg,PROCESS_DESCRIPTORS_VALIDATE:hQ,LAUNCH_SERVICE_SCRIPTS:SQ,LOG_LEVELS:EQ,PROCESS_NAME_ENV_PROP:oz,LOG_NAMES:fQ,PM2_PROCESS_STATUSES:zz,CONFIG_PARAM_MAP:UC,CONFIG_PARAMS:D,HDB_CONFIG_FILE:nQ,HDB_DEFAULT_CONFIG_FILE:sQ,ROLE_TYPES_ENUM:TQ,BOOT_PROP_PARAMS:PC,INSTALL_PROMPTS:az,HDB_ROOT_DIR_NAME:iQ,CLUSTERING_PROCESSES:pQ,FOREGROUND_PID_FILE:lQ,PACKAGE_ROOT:zo,PRE_4_0_0_VERSION:Jz,DATABASES_PARAM_CONFIG:yz,METADATA_PROPERTY:Mz,AUTH_AUDIT_STATUS:Xz,AUTH_AUDIT_TYPES:Zz,HDB_PID_FILE:uQ,DEFAULT_DATABASE_NAME:dQ,LEGACY_CONFIG_PARAMS:bz};bC()});var Jo=y((HRe,kC)=>{"use strict";var xC=require("minimist");kC.exports=e2;function e2(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=FC(process.env),n=FC(xC(process.argv))):(r=process.env,n=xC(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(e2,"assignCMDENVVariables");function FC(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(FC,"objKeysToLowerCase")});var no=y(pi=>{"use strict";global.Resource=pi.Resource=void 0;global.tables=pi.tables={};global.databases=pi.databases={};global.getUser=pi.getUser=void 0;global.server=pi.server={};global.contentTypes=pi.contentTypes=null;global.threads=pi.threads=[];global.logger={};pi._assignPackageExport=(e,t)=>{global[e]=pi[e]=t}});var V=y((tD,rD)=>{"use strict";var so=require("fs-extra"),{workerData:t2,threadId:r2,isMainThread:n2}=require("worker_threads"),Si=require("path"),VC=require("yaml"),YC=require("properties-reader"),Kt=M(),GC=Jo(),s2=require("os"),{PACKAGE_ROOT:Wg}=M(),{_assignPackageExport:i2}=no(),qC=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),fr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},KC={STDOUT:"stdOut",STDERR:"stdErr"},o2=Si.join(Wg,"logs"),a2=Si.join(Wg,"config/yaml/",Kt.HDB_DEFAULT_CONFIG_FILE),c2=1e4,Vg,mi,cs,Ir,Nh,Xd,Ih,Xo,Zd;Zd===void 0&&WC();Object.assign(tD,{notify:XC,fatal:ZC,error:wh,warn:eD,info:QC,debug:JC,trace:zC,setLogLevel:p2,log_level:Ir,loggerWithTag:d2,suppressLogging:_2,initLogSettings:WC,logCustomLevel:E2,closeLogFile:jg,logsAtLevel:l2,getLogFilePath:()=>Ih,OUTPUTS:KC,AuthAuditLog:T2});i2("logger",rD.exports);var Yg;function l2(e){return fr[Ir]<=fr[e]}a(l2,"logsAtLevel");function WC(e=!1){try{if(Zd===void 0||e){jg();let t=h2(),r=GC(["ROOTPATH"]);try{Zd=YC(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!so.pathExistsSync(Si.join(r.ROOTPATH,Kt.HDB_CONFIG_FILE)))throw n}if({level:Ir,config_log_path:Xd,to_file:mi,to_stream:cs}=m2(r.ROOTPATH?Si.join(r.ROOTPATH,Kt.HDB_CONFIG_FILE):Zd.get("settings_path")),Nh=Kt.LOG_NAMES.HDB,Ih=Si.join(Xd,Nh),n2)try{require("segfault-handler").registerHandler(Si.join(Xd,"crash.log"))}catch{}}}catch(t){if(Zd=void 0,t.code===Kt.NODE_ERROR_CODES.ENOENT||t.code===Kt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=GC(Object.keys(Kt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Kt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let l=r[o];if(c===Kt.CONFIG_PARAMS.LOGGING_LEVEL){Ir=l;continue}if(c===Kt.CONFIG_PARAMS.LOGGING_STDSTREAMS){cs=l;continue}c===Kt.CONFIG_PARAMS.LOGGING_FILE&&(mi=c),c===Kt.CONFIG_PARAMS.LOGGING_CONSOLE&&(Vg=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=S2();mi=mi===void 0?s:mi,mi=$C(mi),cs=cs===void 0?i:cs,cs=$C(cs),Ir=Ir===void 0?n:Ir,Xd=o2,Nh=Kt.LOG_NAMES.INSTALL,Ih=Si.join(Xd,Nh);return}throw wh("Error initializing log settings"),wh(t),t}process.env.DEV_MODE&&(cs=!0),u2()}a(WC,"initLogSettings");var Zo=!0;function u2(){mi&&(process.stdout.write=function(e){return typeof e=="string"&&Zo&&Vg!==!1&&(Kg(),e=e.toString(),e[e.length-1]===`
4
+ `&&(e=e.slice(0,-1)),so.appendFileSync(Xo,Ys("stdout",[e]))),qC.apply(process.stdout,arguments)},process.stderr.write=function(e){return typeof e=="string"&&Zo&&Vg!==!1&&(Kg(),e[e.length-1]===`
5
+ `&&(e=e.slice(0,-1)),so.appendFileSync(Xo,Ys("stderr",[e]))),qC.apply(process.stderr,arguments)})}a(u2,"stdioLogging");function d2(e,t){let r={tagName:e.replace(/ /g,"-")};return{notify:n(XC,"notify"),fatal:n(ZC,"fatal"),error:n(wh,"error"),warn:n(eD,"warn"),info:n(QC,"info"),debug:n(JC,"debug"),trace:n(zC,"trace")};function n(s,i){return!t||fr[Ir]<=fr[i]?function(...o){return s(r,...o)}:null}}a(d2,"loggerWithTag");function _2(e){try{Zo=!1,e()}finally{Zo=!0}}a(_2,"suppressLogging");var f2=t2?.name?.replace(/ /g,"-")||"main";function Ys(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,l;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(l=t[0]?.serviceName,c++)),o.unshift(l||f2+"/"+r2);c<s;c++){let d=t[c];d instanceof Error&&d.stack?n+=d.stack:typeof d=="object"?n+=JSON.stringify(d):n+=d,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
6
+ `}a(Ys,"createLogRecord");function e_(e){if(mi){if(jC(e),cs){Zo=!1;try{process.stdout.write(e)}finally{Zo=!0}}}else cs&&process.stdout.write(e)}a(e_,"logStdOut");function Ch(e){if(mi){if(jC(e),cs){Zo=!1;try{process.stderr.write(e)}finally{Zo=!0}}}else cs&&process.stderr.write(e)}a(Ch,"logStdErr");function jC(e){Kg(),Xo?so.appendFileSync(Xo,e):Yg||console.log(e)}a(jC,"logToFile");function jg(){try{so.closeSync(Xo)}catch{}Xo=null}a(jg,"closeLogFile");function Kg(){if(!Xo){try{Xo=so.openSync(Ih,"a")}catch(e){Yg||(Yg=!0,console.error(e))}setTimeout(()=>{jg()},c2).unref()}}a(Kg,"openLogFile");function QC(...e){fr[Ir]<=fr.info&&e_(Ys("info",e))}a(QC,"info");function zC(...e){fr[Ir]<=fr.trace&&e_(Ys("trace",e))}a(zC,"trace");function wh(...e){fr[Ir]<=fr.error&&Ch(Ys("error",e))}a(wh,"error");function JC(...e){fr[Ir]<=fr.debug&&e_(Ys("debug",e))}a(JC,"debug");function XC(...e){fr[Ir]<=fr.notify&&e_(Ys("notify",e))}a(XC,"notify");function ZC(...e){fr[Ir]<=fr.fatal&&Ch(Ys("fatal",e))}a(ZC,"fatal");function eD(...e){fr[Ir]<=fr.warn&&Ch(Ys("warn",e))}a(eD,"warn");function E2(e,t,...r){t===KC.STDERR?Ch(Ys(e,r)):e_(Ys(e,r))}a(E2,"logCustomLevel");function h2(){let e;try{e=s2.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Si.join(e,Kt.HDB_HOME_DIR_NAME,Kt.BOOT_PROPS_FILE_NAME);return so.existsSync(t)||(t=Si.join(Wg,"utility/hdb_boot_properties.file")),t}a(h2,"getPropsFilePath");function p2(e){Ir=e}a(p2,"setLogLevel");function $C(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a($C,"autoCastBoolean");function m2(e){try{if(e.includes("config/settings.js")){let o=YC(e);return{level:o.get(Kt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Si.dirname(o.get(Kt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Kt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Kt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=VC.parseDocument(so.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===Kt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(m2,"getLogConfig");function S2(){try{let e=VC.parseDocument(so.readFileSync(a2,"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(S2,"getDefaultConfig");function T2(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(T2,"AuthAuditLog")});var Qg=y((GRe,nD)=>{"use strict";var g2=require("util"),R2=require("path"),A2=require("child_process"),b2=g2.promisify(A2.execFile),y2=1e3*1e3*10;nD.exports={findPs:O2};async function O2(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await b2("ps",["wwxo",`pid,${r}`],{maxBuffer:y2});for(let s of n.trim().split(`
7
+ `).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:R2.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(O2,"findPs")});var Bt=y(($Re,iD)=>{"use strict";var N2="__dbis__",I2="__txns__",w2="__environment_name__",C2="__dbi_defintion__",D2={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"},P2=["__createdtime__","__updatedtime__"],L2="\uFFFF",sD={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},M2=Object.values(sD);iD.exports={AUDIT_STORE_NAME:I2,INTERNAL_DBIS_NAME:N2,DBI_DEFINITION_NAME:C2,SEARCH_TYPES:D2,TIMESTAMP_NAMES:P2,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:w2,TRANSACTIONS_DBI_NAMES_ENUM:sD,TRANSACTIONS_DBIS:M2,OVERFLOW_MARKER:L2}});var Ln=y((VRe,ED)=>{"use strict";var oD=M(),aD=Bt(),cD={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},lD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),uD={500:lD("There was an error processing your request."),400:"Invalid request"},U2=uD[cD.INTERNAL_SERVER_ERROR],v2={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.`},B2={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},H2={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"},x2={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 ${aD.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${aD.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"},F2={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${oD.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 ${oD.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"},dD={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"},k2={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."},G2={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`},q2={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"},$2={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},V2={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`},_D={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.`},fD={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}`},Y2={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.",BAD_SSH_KEY_NAME:"SSH key name can only contain alphanumeric, dash and underscore characters"},K2={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},W2={...dD,...H2,...v2,...k2,...G2,...q2,...$2,...V2,...F2,..._D,...fD,...Y2,...K2,...B2};ED.exports={CHECK_LOGS_WRAPPER:lD,HDB_ERROR_MSGS:W2,DEFAULT_ERROR_MSGS:uD,DEFAULT_ERROR_RESP:U2,HTTP_STATUS_CODES:cD,LMDB_ERRORS_ENUM:x2,AUTHENTICATION_ERROR_MSGS:dD,VALIDATION_ERROR_MSGS:_D,ITC_ERRORS:fD}});var ce=y((KRe,mD)=>{"use strict";var Fl=Ln(),j2=V(),Q2=M(),Dh=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,hD),this.statusCode=n||Fl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Fl.DEFAULT_ERROR_MSGS[n]?Fl.DEFAULT_ERROR_MSGS[n]:Fl.DEFAULT_ERROR_MSGS[Fl.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&&j2[s](i)}},zg=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}},Jg=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function hD(e,t,r,n=Q2.LOG_LEVELS.ERROR,s=null,i=!1){if(pD(e))return e;let o=new Dh(e,t,r,n,s);return i&&delete o.stack,o}a(hD,"handleHDBError");function pD(e){return e.__proto__.constructor.name===Dh.name}a(pD,"isHDBError");mD.exports={isHDBError:pD,handleHDBError:hD,ClientError:zg,ServerError:Jg,hdb_errors:Fl}});var mt=y((jRe,yD)=>{"use strict";var i_=M(),z2=ee(),on=te(),o_=require("path"),J2=require("minimist"),SD=require("fs-extra"),TD=require("lodash");on.initSync();var{CONFIG_PARAMS:ea,DATABASES_PARAM_CONFIG:t_,SYSTEM_SCHEMA_NAME:Ph}=i_,r_,n_,s_;function gD(){if(r_!==void 0)return r_;if(on.getHdbBasePath()!==void 0)return r_=on.get(ea.STORAGE_PATH)||o_.join(on.getHdbBasePath(),i_.DATABASES_DIR_NAME),r_}a(gD,"getBaseSchemaPath");function RD(){if(n_!==void 0)return n_;if(on.getHdbBasePath()!==void 0)return n_=bD(Ph),n_}a(RD,"getSystemSchemaPath");function AD(){if(s_!==void 0)return s_;if(on.getHdbBasePath()!==void 0)return s_=on.get(i_.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||o_.join(on.getHdbBasePath(),i_.TRANSACTIONS_DIR_NAME),s_}a(AD,"getTransactionAuditStoreBasePath");function X2(e,t){let r=on.get(ea.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||o_.join(AD(),e.toString())}a(X2,"getTransactionAuditStorePath");function bD(e,t){e=e.toString(),t=t&&t.toString();let r=on.get(i_.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||o_.join(gD(),e)}a(bD,"getSchemaPath");function Z2(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,J2(process.argv));let n=r[ea.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!z2.isObject(n))throw o;i=n}for(let o of i){let c=o[Ph];if(!c)continue;let l=on.get(ea.DATABASES);l=l??{};let d=c?.tables?.[t]?.[t_.PATH];if(d)return TD.set(l,[Ph,t_.TABLES,t,t_.PATH],d),on.setProperty(ea.DATABASES,l),d;let u=c?.[t_.PATH];if(u)return TD.set(l,[Ph,t_.PATH],u),on.setProperty(ea.DATABASES,l),u}}let s=r[ea.STORAGE_PATH.toUpperCase()];if(s){if(!SD.pathExistsSync(s))throw new Error(s+" does not exist");let i=o_.join(s,e);return SD.mkdirsSync(i),on.setProperty(ea.STORAGE_PATH,s),i}return RD()}a(Z2,"initSystemSchemaPaths");function e4(){r_=void 0,n_=void 0,s_=void 0}a(e4,"resetPaths");yD.exports={getBaseSchemaPath:gD,getSystemSchemaPath:RD,getTransactionAuditStorePath:X2,getTransactionAuditStoreBasePath:AD,getSchemaPath:bD,initSystemSchemaPaths:Z2,resetPaths:e4}});var an=y((XRe,CD)=>{"use strict";var t4=Ln().LMDB_ERRORS_ENUM,zRe=require("lmdb"),r4=Bt(),JRe=require("buffer").Buffer,{OVERFLOW_MARKER:OD,MAX_SEARCH_KEY_LENGTH:Lh}=r4,ND=["number","string","symbol","boolean","bigint"];function n4(e){if(e=e?.primaryStore||e,!e)throw new Error(t4.ENV_REQUIRED)}a(n4,"validateEnv");function s4(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(s4,"stringifyData");function i4(e){return e instanceof Date?e.valueOf():e}a(i4,"convertKeyValueToWrite");function o4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(ND.includes(typeof e))return e.length>Lh?[e.slice(0,Lh)+OD]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(ND.includes(typeof i))i.length>Lh?r.push(i.slice(0,Lh)+OD):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(o4,"getIndexedValues");var Mh=0,ID=0;function wD(){ID=Date.now()-performance.now()}a(wD,"adjustStartTime");wD();var a4=6e4;setInterval(wD,a4).unref();function c4(){let e=performance.now()+ID;return e>Mh?(Mh=e,e):(Mh+=488e-6,Mh)}a(c4,"getNextMonotonicTime");CD.exports={validateEnv:n4,stringifyData:s4,convertKeyValueToWrite:i4,getNextMonotonicTime:c4,getIndexedValues:o4}});var DD,Mn,Xg,kl=Ce(()=>{DD=require("events"),Mn=class extends DD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new Xg;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(){let t=this.queue?.shift();return t||this.emit("drained"),t}waitForDrain(){return new Promise(t=>{!this.queue||this.queue.length===0?t(!0):(this.once("drained",()=>t(!0)),this.currentDrainResolver=t,this.drainCloseListener||(this.drainCloseListener=!0,this.on("close",()=>{this.currentDrainResolver?.(!1)})))})}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)}},Xg=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 ic={};tt(ic,{server:()=>nt});var PD,nt,Wr=Ce(()=>{PD=B(no()),nt={};(0,PD._assignPackageExport)("server",nt)});var tR={};tt(tR,{loadGQLSchema:()=>d4,start:()=>eR,startOnMainThread:()=>u4});function eR({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:d,StringValueNode:u}=await import("graphql"),_=o(new c(r.toString(),s)),E=new Map,f=[],h;for(let g of _.definitions)switch(g.kind){case l.OBJECT_TYPE_DEFINITION:let F=function($){if($.kind==="NonNullType"){let _e=F($.type);return _e.nullable=!1,_e}if($.kind==="ListType")return{type:"array",elements:F($.type)};let Q={type:$.name?.value};return Object.defineProperty(Q,"location",{value:$.loc.startToken}),Q};a(F,"getProperty");let m=g.name.value,C=[],O={table:null,database:null,properties:C};E.set(m,O);for(let $ of g.directives){if($.name.value==="table"){for(let Q of $.arguments)O[Q.name.value]=Q.value.value;O.schema&&(O.database=O.schema),O.table||(O.table=m),O.audit&&(O.audit=O.audit!=="false"),O.attributes=O.properties,f.push(O)}if($.name.value==="sealed"&&(O.sealed=!0),$.name.value==="replicate"&&(O.replicate=!0),$.name.value==="export"){O.export=!0;for(let Q of $.arguments)typeof O.export!="object"&&(O.export={}),O.export[Q.name.value]=Q.value.value}}let x=!1,Y={};for(let $ of g.fields){let Z=F($.type);Z.name=$.name.value,C.push(Z),Y[Z.name]=void 0;for(let Q of $.directives){let _e=Q.name.value;if(_e==="primaryKey")x?console.warn("Can not define two attributes as a primary key at",Q.loc):(Z.isPrimaryKey=!0,x=!0);else if(_e==="indexed")Z.indexed=!0;else if(_e==="computed"){for(let K of Q.arguments||[])if(K.name.value==="from"){let ie=K.value.value;Z.computed={from:T(ie,K,Y)},Z.version==null&&(Z.version=ie)}else K.name.value==="version"&&(Z.version=K.value.value);Z.computed=Z.computed||!0}else if(_e==="relationship"){let K={};for(let ie of Q.arguments)K[ie.name.value]=ie.value.value;Z.relationship=K}else if(_e==="createdTime")Z.assignCreatedTime=!0;else if(_e==="updatedTime")Z.assignUpdatedTime=!0;else if(_e==="expiresAt")Z.expiresAt=!0;else if(_e==="allow"){let K=Z.authorizedRoles=[];for(let ie of Q.arguments)ie.name.value==="role"&&K.push(ie.value.value)}else server.knownGraphQLDirectives.includes(_e)&&console.warn(`@${_e} is an unknown directive, at`,Q.loc)}}O.type=m,m==="Query"&&(h=O)}function S(g){let m=E.get(g.type);m?(Object.defineProperty(g,"properties",{value:m.properties}),Object.defineProperty(g,"definition",{value:m})):g.type==="array"?S(g.elements):l4.includes(g.type)||(0,MD.getWorkerIndex)()===0&&console.error(`The type ${g.type} is unknown at line ${g.location.line}, column ${g.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let g of E.values())for(let m of g.properties)S(m);for(let g of f)g.tableClass=e(g),g.export&&(g.export.name===""?i.set((0,Zg.dirname)(n),g.tableClass):i.set((0,Zg.dirname)(n)+"/"+(g.export.name||g.type),g.tableClass,g.export));function T(g,m,C){return new LD.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${g}; } } } } computed;`,{filename:s,lineOffset:m.loc.startToken.line-1,columnOffset:m.loc.startToken.column}).runInThisContext()(C)}a(T,"createComputedFrom")}}var Zg,LD,MD,l4,u4,d4,UD=Ce(()=>{Zg=require("path"),LD=require("node:vm");De();MD=B(ut()),l4=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(eR,"start");u4=eR,d4=eR({ensureTable:dt}).handleFile});async function Uh(e){let t=(0,HD.pathToFileURL)(e).toString();return _4?(a_||(a_=f4(h4)),(await(await a_).import(t)).namespace):import(t)}async function f4(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),a_=new Compartment({console,Math,Date,fetch:E4,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,BD.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:wr,tables:Un,databases:Ve})}};let n=await(0,vD.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),a_}function E4(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 h4(){return{Resource:wr,tables:Un}}var vD,BD,HD,_4,a_,rR=Ce(()=>{ls();De();vD=require("fs/promises"),BD=require("path"),HD=require("url"),_4=!1;a(Uh,"secureImport");a(f4,"getCompartment");a(E4,"secureOnlyFetch");a(h4,"getGlobalVars")});var sR={};tt(sR,{handleFile:()=>p4});async function p4(e,t,r,n){let s=new Map,i=await Uh(r);c(i.default)&&n.set((0,nR.dirname)(t),i.default),o(i,(0,nR.dirname)(t));function o(l,d){for(let u in l){let _=l[u];c(_)?n.set(d+"/"+u,_):typeof _=="object"&&o(_,d+"/"+u)}}a(o,"recurseForResources");function c(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(c,"isResource"),s}var nR,xD=Ce(()=>{rR();nR=require("path");a(p4,"handleFile")});var oR={};tt(oR,{start:()=>m4});function m4({resources:e}){e.set("login",iR),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var iR,FD=Ce(()=>{ls();a(m4,"start");iR=class extends wr{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 KD={};tt(KD,{parse:()=>cR,streamAsJSON:()=>c_,stringify:()=>oc});function c_(e){return new aR({value:e})}function kD(e){return console.error(e),JSON.stringify(e.toString())}function GD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function oc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===VD)return YD(e);if(t.resolution)return t.resolution.then(()=>oc(e));throw t}}function YD(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+=YD(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+oc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function cR(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),g4.test(e)?S4.parse(e):JSON.parse(e)):null}var qD,$D,S4,T4,VD,aR,g4,lR=Ce(()=>{qD=require("stream"),$D=B(require("json-bigint-fixes")),S4=(0,$D.default)({useNativeBigInt:!0}),T4=1e4,VD={};BigInt.prototype.toJSON=function(){throw VD};a(c_,"streamAsJSON");aR=class extends qD.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(;;){try{o=i.next(),o.then&&(yield o.then(c=>(o=c,""),c=>(o={done:!1,value:{error:c.toString()}},i={next:()=>({done:!0})},"")))}catch(c){o={done:!1,value:{error:c.toString()}},i={next:()=>({done:!0})}}if(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),kD)}catch(s){yield kD(s)}else yield oc(t)}else yield oc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);GD(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>T4?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 GD(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(kD,"handleError");a(GD,"when");a(oc,"stringify");a(YD,"jsStringify");g4=/[[,:]\s*-?\d{16,}/;a(cR,"parse")});var iP=y((EAe,sP)=>{"use strict";var uR=require("recursive-iterator"),R4=require("alasql"),dR=require("clone"),WD=ee(),{handleHDBError:jD,hdb_errors:A4}=ce(),{HDB_ERROR_MSGS:QD,HTTP_STATUS_CODES:zD}=A4,{getDatabases:b4}=(De(),ne(at)),y4=["DISTINCT_ARRAY"],JD=Symbol("validateTables"),_R=Symbol("validateTable"),fAe=Symbol("getAllColumns"),XD=Symbol("validateAllColumns"),vh=Symbol("findColumn"),ZD=Symbol("validateOrderBy"),l_=Symbol("validateSegment"),fR=Symbol("validateColumn"),eP=Symbol("setColumnsForTable"),tP=Symbol("checkColumnsForAsterisk"),rP=Symbol("validateGroupBy"),nP=Symbol("hasColumns"),ER=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[JD](),this[tP](),this[XD]()}[JD](){if(this[nP]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[_R](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[_R](t.table)})}}[nP](){let t=!1,r=new uR(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[_R](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=b4();if(!r[t.databaseid])throw jD(new Error,QD.SCHEMA_NOT_FOUND(t.databaseid),zD.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw jD(new Error,QD.TABLE_NOT_FOUND(t.databaseid,t.tableid),zD.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=dR(s);i.table=dR(t),this.attributes.push(i)})}[vh](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)}[tP](){let t=new uR(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[eP](r.tableid)}[eP](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new R4.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[XD](){this[l_](this.statement.columns,!1),this[l_](this.statement.joins,!1),this[l_](this.statement.where,!1),this[rP](this.statement.group,!1),this[l_](this.statement.order,!0)}[l_](t,r){if(!t)return;let n=new uR(t),s=[];for(let{node:i,path:o}of n)!WD.isEmpty(i)&&!WD.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[ZD](i):s.push(this[fR](i)));return s}[rP](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&y4.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=dR(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[vh](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[vh](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`}[ZD](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[fR](t)}[fR](t){let r=this[vh](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]}};sP.exports=ER});var aP=y((pAe,oP)=>{"use strict";var hR=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")}};oP.exports=hR});var lP=y((SAe,cP)=>{"use strict";var pR=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};cP.exports=pR});var fP={};tt(fP,{HAS_EXPIRATION:()=>xh,HAS_RESIDENCY_ID:()=>yR,HAS_STRUCTURE_UPDATE:()=>Fh,LAST_TIMESTAMP_PLACEHOLDER:()=>f_,LOCAL_TIMESTAMP:()=>O4,METADATA:()=>u_,NO_TIMESTAMP:()=>SR,PENDING_LOCAL_TIME:()=>OR,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>bR,RecordEncoder:()=>AR,TIMESTAMP_ASSIGN_LAST:()=>I4,TIMESTAMP_ASSIGN_NEW:()=>dP,TIMESTAMP_ASSIGN_PREVIOUS:()=>_P,TIMESTAMP_PLACEHOLDER:()=>Bh,TIMESTAMP_RECORD_PREVIOUS:()=>TR,getUpdateRecord:()=>NR,handleLocalTimeForGets:()=>kh});function C4(){return __[0]=__[0]^64,N4.getFloat64(0)}function kh(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),l=c?.value,d=l?.[u_];return d>=0&&(c.metadataFlags=d,c.localTime=l.localTime,c.value=l.value,c.residencyId=l.residencyId,l.expiresAt>=0&&(c.expiresAt=l.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[u_]>=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 l=c.value,d=l[u_];return d>=0&&(c.metadataFlags=d,c.localTime=l.localTime,c.value=l.value,l.expiresAt>=0&&(c.expiresAt=l.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,ac.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let l=0;l<ac.length;l++){let d=ac[l].deref();(!d||d.isDone||d.isCommitted)&&ac.splice(l--,1)}},i.prototype.done.isTracked=!0}return e}function NR(e,t,r){return function(n,s,i,o,c=-1,l,d,u="put",_,E){_||l==null?Gl=i?.localTime?TR|_P:SR:Gl=l?i?.localTime?TR|16384:dP|16384:SR;let f=d?.expiresAt;if(f>=0&&(c|=xh),d_=c,gR=f,i?.version===o&&l===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Gl>0},S,T=0;try{let g=i?.residencyId,m=d?.residencyId;m&&(RR=m,d_|=yR,T|=cc),g!==m&&(T|=lc,g||(g=0)),c&xh&&(T|=h_),d?.originatingOperation&&(T|=E_),_&&(h.ifVersion=S=i?.version??null);let C=e.put(n,s,h);if(l){let O=d?.user?.username;if(E&&(Hh=e.encoder.encode(E)),e.encoder.hasStructureUpdate&&(T|=Fh,e.encoder.hasStructureUpdate=!1),_&&i?.localTime){let x=i?.localTime,F=r.get(x);if(F){let Y=Ht(F).previousLocalTime;return r.put(x,ql(o,t,n,Y,d?.nodeId??server.replication.getThisNodeId(r)??0,O,u,Hh,T,m,g,f),{ifVersion:S}),C}}r.put(f_,ql(o,t,n,i?.localTime?1:0,d?.nodeId??server.replication?.getThisNodeId(r)??0,O,u,Hh,T,m,g,f,d?.originatingOperation),{append:u!=="invalidate",instructedWrite:!0,ifVersion:S})}return C}catch(g){throw g.message+=" id: "+n+" options: "+h,g}}}var uP,mR,Bh,f_,bR,O4,u_,__,N4,SR,dP,I4,_P,TR,xh,yR,OR,Fh,w4,Hh,Gl,d_,gR,RR,AR,ac,$l=Ce(()=>{uP=require("msgpackr");io();mR=B(V()),Bh=new Uint8Array([1,1,1,1,4,64,0,0]),f_=new Uint8Array([1,1,1,1,1,0,0,0]),bR=new Uint8Array([1,1,1,1,3,64,0,0]),O4=Symbol("local-timestamp"),u_=Symbol("metadata"),__=new Uint8Array(8),N4=new DataView(__.buffer,0,8),SR=0,dP=0,I4=1,_P=3,TR=4,xh=16,yR=32,OR=1,Fh=256,Gl=0,d_=-1,gR=-1,RR=0,AR=class extends uP.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,i){if(Gl||d_>=0){let o=0,c=Gl;c&&(o+=8,Gl=0);let l=d_,d=gR,u=RR;l>=0&&(o+=2,d_=-1,d>=0&&(o+=8,gR=-1),u&&(o+=4,RR=0));let _=w4=r.call(this,s,i|2048|o);Hh=_.subarray((_.start||0)+o,_.end);let E=_.start||0;return c&&(Bh[4]=c,Bh[5]=c>>8,_.set(Bh,E),E+=8),l>=0&&(_[E++]=l&31,_[E++]=l>>5,d>=0&&((_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(E,d),E+=8),u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setUint32(E,u)),_}else return r.call(this,s,i)};let n=this.saveStructures;this.saveStructures=function(s,i){let o=n.call(this,s,i);return this.hasStructureUpdate=!0,o}}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,l;if(i===2){if(t.copy)t.copy(__,0,c),c+=8;else for(let E=0;E<8;E++)__[E]=t[c++];l=C4(),i=t[c]}let d,u;i<32&&(o=i|t[c+1]<<5,c+=2,o&xh&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),o&yR&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let _=r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c);return{localTime:l,value:_,[u_]:o,expiresAt:d,residencyId:u}}return r?.valueAsBuffer?t:super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(C4,"getTimestamp");a(kh,"handleLocalTimeForGets");ac=[];setInterval(()=>{for(let e=0;e<ac.length;e++){let t=ac[e].deref();!t||t.isDone||t.isCommitted?ac.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(mR.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):mR.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(NR,"getUpdateRecord")});var p_=y((bAe,hP)=>{"use strict";var EP=te(),D4=M(),{RecordEncoder:P4}=($l(),ne(fP)),AAe=require("fs");EP.initSync();var L4=EP.get(D4.CONFIG_PARAMS.STORAGE_CACHING)!==!1,IR=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=L4&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:P4})}};hP.exports=IR});var m_=y((OAe,pP)=>{"use strict";var vn=te(),us=M();vn.initSync();var Gh=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=2048,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=vn.get(us.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||vn.get(us.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||vn.get(us.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",vn.get(us.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=vn.get(us.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),vn.get(us.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=vn.get(us.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),vn.get(us.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=vn.get(us.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),vn.get(us.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=vn.get(us.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=vn.get(us.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};pP.exports=Gh;Gh.MAX_DBS=1e4});var _t=y((IAe,NP)=>{"use strict";var CR=require("lmdb"),Ks=require("fs-extra"),Bn=require("path"),qh=an(),TP=V(),cn=Ln().LMDB_ERRORS_ENUM,$h=lP(),DR=p_(),gP=m_(),ta=Bt(),mP=M(),{table:M4,resetDatabases:U4}=(De(),ne(at)),SP=te(),Ws=ta.INTERNAL_DBIS_NAME,RP=ta.DBI_DEFINITION_NAME,v4="data.mdb",B4="lock.mdb",S_=".mdb",H4="-lock",wR=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=ds(t,r),this.key_type=this.dbi[ta.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ta.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new CR.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function Vh(e,t){if(e===void 0)throw new Error(cn.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(cn.ENV_NAME_REQUIRED)}a(Vh,"pathEnvNameValidation");async function PR(e,t,r=!0){try{await Ks.access(e)}catch(n){throw n.code==="ENOENT"?new Error(cn.INVALID_BASE_PATH):n}try{let n=Bn.join(e,t+S_);return await Ks.access(n,Ks.constants.R_OK|Ks.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await Ks.access(Bn.join(e,t,v4),Ks.constants.R_OK|Ks.constants.F_OK),Bn.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(cn.INVALID_ENVIRONMENT)}else throw new Error(cn.INVALID_ENVIRONMENT);throw n}}a(PR,"validateEnvironmentPath");function Yh(e,t){if(qh.validateEnv(e),t===void 0)throw new Error(cn.DBI_NAME_REQUIRED)}a(Yh,"validateEnvDBIName");async function x4(e,t,r=!1,n=!1){Vh(e,t);let s=Bn.basename(e);t=t.toString();let i=SP.get(mP.CONFIG_PARAMS.DATABASES);i||SP.setProperty(mP.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await PR(e,t,n),AP(e,t,r)}catch(o){if(o.message===cn.INVALID_ENVIRONMENT){let c=Bn.join(e,t);await Ks.mkdirp(n?c:e);let l=new gP(n?c:c+S_,!1),d=CR.open(l);d.dbis=Object.create(null);let u=new DR(!1);d.openDB(Ws,u),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let _=LR(e,t,r);return d[ta.ENVIRONMENT_NAME_KEY]=_,global.lmdb_map[_]=d,d}throw o}}a(x4,"createEnvironment");async function F4(e,t,r,n=!0){Vh(e,t),t=t.toString();let s=Bn.join(e,t);return M4({table:t,database:Bn.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(F4,"copyEnvironment");async function AP(e,t,r=!1){Vh(e,t),t=t.toString();let n=LR(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 PR(e,t),i=Bn.join(e,t+S_),o=s!=i,c=new gP(s,o),l=CR.open(c);l.dbis=Object.create(null);let d=yP(l);for(let u=0;u<d.length;u++)ds(l,d[u]);return l[ta.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=l,l}a(AP,"openEnvironment");async function k4(e,t,r=!1){Vh(e,t),t=t.toString();let n=Bn.join(e,t+S_),s=await PR(e,t);if(global.lmdb_map!==void 0){let i=LR(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await bP(o),delete global.lmdb_map[i]}}await Ks.remove(s),await Ks.remove(s===n?s+H4:Bn.join(Bn.dirname(s),B4))}a(k4,"deleteEnvironment");async function bP(e){qh.validateEnv(e);let t=e[ta.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(bP,"closeEnvironment");function LR(e,t,r=!1){let s=`${Bn.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(LR,"getCachedEnvironmentName");function G4(e){qh.validateEnv(e);let t=Object.create(null),r=ds(e,Ws);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==Ws)try{t[n]=Object.assign(new $h,s)}catch{TP.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(G4,"listDBIDefinitions");function yP(e){qh.validateEnv(e);let t=[],r=ds(e,Ws);for(let{key:n}of r.getRange({start:!1}))n!==Ws&&t.push(n);return t}a(yP,"listDBIs");function q4(e,t){let n=ds(e,Ws).getEntry(t),s=new $h;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{TP.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(q4,"getDBIDefinition");function OP(e,t,r,n=!r){if(Yh(e,t),t=t.toString(),t===Ws)throw new Error(cn.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return ds(e,t)}catch(s){if(s.message===cn.DBI_DOES_NOT_EXIST){let i=new DR(r,n===!0),o=e.openDB(t,i),c=new $h(r===!0,n);return o[RP]=c,ds(e,Ws).putSync(t,c),e.dbis[t]=o,o}throw s}}a(OP,"createDBI");function ds(e,t){if(Yh(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Ws?r=q4(e,t):r=new $h,r===void 0)throw new Error(cn.DBI_DOES_NOT_EXIST);let n;try{let s=new DR(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(cn.DBI_DOES_NOT_EXIST):s}return n[RP]=r,e.dbis[t]=n,n}a(ds,"openDBI");function $4(e,t){Yh(e,t),t=t.toString();let r=ds(e,t),n=r.getStats();return r[ta.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a($4,"statDBI");async function V4(e,t){try{let r=Bn.join(e,t+S_);return(await Ks.stat(r)).size}catch{throw new Error(cn.INVALID_ENVIRONMENT)}}a(V4,"environmentDataSize");function Y4(e,t){if(Yh(e,t),t=t.toString(),t===Ws)throw new Error(cn.CANNOT_DROP_INTERNAL_DBIS_NAME);ds(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],ds(e,Ws).removeSync(t)}a(Y4,"dropDBI");function K4(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{ds(e,i)}catch(o){if(o.message===cn.DBI_DOES_NOT_EXIST)OP(e,i,i!==t,i===t),n=!0;else throw o}}n&&U4()}a(K4,"initializeDBIs");NP.exports={openDBI:ds,openEnvironment:AP,createEnvironment:x4,listDBIs:yP,listDBIDefinitions:G4,createDBI:OP,dropDBI:Y4,statDBI:$4,deleteEnvironment:k4,initializeDBIs:K4,TransactionCursor:wR,environmentDataSize:V4,copyEnvironment:F4,closeEnvironment:bP}});var wP=y((CAe,IP)=>{"use strict";var MR=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};IP.exports=MR});var DP=y((PAe,CP)=>{"use strict";var UR=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}};CP.exports=UR});var LP=y((MAe,PP)=>{"use strict";var vR=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};PP.exports=vR});var dc=y((xAe,vP)=>{"use strict";var W4=_t(),j4=wP(),Q4=DP(),z4=LP(),Ti=an(),T_=Ln().LMDB_ERRORS_ENUM,J4=Bt(),oo=M(),X4=ee(),Z4=require("uuid"),vAe=require("lmdb"),{handleHDBError:eJ,hdb_errors:tJ}=ce(),{OVERFLOW_MARKER:BAe,MAX_SEARCH_KEY_LENGTH:HAe}=J4,MP=te();MP.initSync();var Kh=MP.get(oo.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),BR=oo.TIME_STAMP_NAMES_ENUM.CREATED_TIME,uc=oo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function rJ(e,t,r,n,s=Ti.getNextMonotonicTime()){kR(e,t,r,n),HR(e,t,r);let i=new j4,o=[],c=[];for(let l=0;l<n.length;l++){let d=n[l];UP(d,!0,s);let u=nJ(e,t,r,d),_=d[t];o.push(u),c.push(_)}return xR(o,c,n,i,s)}a(rJ,"insertRecords");function nJ(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 u=c([[{}]]);Array.isArray(u)&&(c=u[0][oo.FUNC_VAL],n[o]=c)}let l=Ti.getIndexedValues(c),d=e.dbis[o];if(l){Kh&&d.prefetch(l.map(u=>({key:u,value:s})),Wh);for(let u=0,_=l.length;u<_;u++)d.put(l[u],s)}}Kh&&e.dbis[t].prefetch([s],Wh),e.dbis[t].put(s,n,n[uc])})}a(nJ,"insertRecord");function sJ(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(sJ,"removeSkippedRecords");function UP(e,t,r){let n=r>0;(n||!Number.isInteger(e[uc]))&&(e[uc]=r||(r=Ti.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[BR]))&&(e[BR]=r||Ti.getNextMonotonicTime()):delete e[BR]}a(UP,"setTimestamps");function HR(e,t,r){r.indexOf(oo.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(oo.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(oo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(oo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),W4.initializeDBIs(e,t,r)}a(HR,"initializeTransaction");async function iJ(e,t,r,n,s=Ti.getNextMonotonicTime()){kR(e,t,r,n),HR(e,t,r);let i=new Q4,o=[],c=[],l=[];for(let d=0;d<n.length;d++){let u=n[d],_=u[t],E;try{E=FR(e,t,u,_,i,!0,s)}catch{i.skipped_hashes.push(_),o.push(d);continue}c.push(E),l.push(_)}return xR(c,l,n,i,s,o)}a(iJ,"updateRecords");async function oJ(e,t,r,n,s=Ti.getNextMonotonicTime()){try{kR(e,t,r,n)}catch(l){throw eJ(l,l.message,tJ.HTTP_STATUS_CODES.BAD_REQUEST)}HR(e,t,r);let i=new z4,o=[],c=[];for(let l=0;l<n.length;l++){let d=n[l],u;X4.isEmpty(d[t])?(u=Z4.v4(),d[t]=u):u=d[t];let _=FR(e,t,d,u,i,!1,s);o.push(_),c.push(u)}return xR(o,c,n,i,s)}a(oJ,"upsertRecords");async function xR(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,l=o.length;c<l;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Ti.getNextMonotonicTime(),sJ(r,i),n}a(xR,"finalizeWrite");function FR(e,t,r,n,s,i=!1,o){let c=e.dbis[t],l=c.getEntry(n),d=l?.value,u=d;if(!d){if(i)return!1;d={}}if(UP(r,!u,o),Number.isInteger(r[uc])&&d[uc]>r[uc])return!1;u&&s.original_records.push(d);let _,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let S=r[h],T=e.dbis[h];if(T===void 0)continue;let g=d[h];if(typeof S=="function"){let C=S([[d]]);Array.isArray(C)&&(S=C[0][oo.FUNC_VAL],r[h]=S)}if(S===g)continue;let m=Ti.getIndexedValues(g);if(m){Kh&&T.prefetch(m.map(C=>({key:C,value:n})),Wh);for(let C=0,O=m.length;C<O;C++)T.remove(m[C],n)}if(m=Ti.getIndexedValues(S),m){Kh&&T.prefetch(m.map(C=>({key:C,value:n})),Wh);for(let C=0,O=m.length;C<O;C++)T.put(m[C],n)}}let f={...d,...r};c.put(n,f,f[uc])},"do_put");return l?_=c.ifVersion(n,l.version,E):_=c.ifNoExists(n,E),_.then(f=>f?!0:FR(e,t,r,n,s,i,o))}a(FR,"updateUpsertRecord");function aJ(e,t,r){if(Ti.validateEnv(e),t===void 0)throw new Error(T_.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(T_.WRITE_ATTRIBUTES_REQUIRED):new Error(T_.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(aJ,"validateBasic");function kR(e,t,r,n){if(aJ(e,t,r),!Array.isArray(n))throw n===void 0?new Error(T_.RECORDS_REQUIRED):new Error(T_.RECORDS_MUST_BE_ARRAY)}a(kR,"validateWrite");function Wh(){}a(Wh,"noop");vP.exports={insertRecords:rJ,updateRecords:iJ,upsertRecords:oJ}});var ao=y((kAe,cJ)=>{cJ.exports={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:"url"},{attribute:"routes"}]},hdb_certificate:{hash_attribute:"name",name:"hdb_certificate",schema:"system",attributes:[{attribute:"name"},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{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 Ri=y((GAe,xP)=>{"use strict";var HP=ee(),BP=M(),Vl=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,gi=require("joi"),ra={schema_format:{pattern:Vl,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},lJ=gi.alternatives(gi.string().min(1).max(ra.schema_length.maximum).pattern(Vl).messages({"string.pattern.base":"{:#label} "+ra.schema_format.message}),gi.number(),gi.array()).required(),uJ=gi.alternatives(gi.string().min(1).max(ra.schema_length.maximum).pattern(Vl).messages({"string.pattern.base":"{:#label} "+ra.schema_format.message}),gi.number()),dJ=gi.alternatives(gi.string().min(1).max(ra.schema_length.maximum).pattern(Vl).messages({"string.pattern.base":"{:#label} "+ra.schema_format.message}),gi.number()).required();function _J(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ra.schema_length.maximum?`'${e}' maximum of 250 characters`:Vl.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(_J,"checkValidTable");function fJ(e,t){return HP.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(fJ,"validateSchemaExists");function EJ(e,t){let r=t.state.ancestors[0].schema;return HP.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(EJ,"validateTableExists");function hJ(e,t){return e.toLowerCase()===BP.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${BP.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(hJ,"validateSchemaName");xP.exports={common_validators:ra,schema_regex:Vl,hdb_schema_table:lJ,validateSchemaExists:fJ,validateTableExists:EJ,validateSchemaName:hJ,checkValidTable:_J,hdb_database:uJ,hdb_table:dJ}});var St=y(($Ae,FP)=>{"use strict";var ln=require("validate.js");ln.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||ln.validators.type.checks[t](e)?null:` must be a '${t}' value`};ln.validators.type.checks={Object:function(e){return ln.isObject(e)&&!ln.isArray(e)},Array:ln.isArray,Integer:ln.isInteger,Number:ln.isNumber,String:ln.isString,Date:ln.isDate,Boolean:function(e){return typeof e=="boolean"}};ln.validators.hasValidFileExt=function(e,t){return ln.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};FP.exports={validateObject:pJ,validateObjectAsync:mJ,validateBySchema:SJ};function pJ(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=ln(e,t,{format:"flat"});return r?new Error(r):null}a(pJ,"validateObject");async function mJ(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ln.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(mJ,"validateObjectAsync");function SJ(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(SJ,"validateBySchema")});var jh=y((YAe,kP)=>{var{common_validators:Ai}=Ri(),R_=St(),g_="is required",tr={database:{presence:!1,format:Ai.schema_format,length:Ai.schema_length},schema:{presence:!1,format:Ai.schema_format,length:Ai.schema_length},table:{presence:!0,format:Ai.schema_format,length:Ai.schema_length},attribute:{presence:!0,format:Ai.schema_format,length:Ai.schema_length},hash_attribute:{presence:!0,format:Ai.schema_format,length:Ai.schema_length}};function A_(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(A_,"makeAttributesStrings");function TJ(e){return e=A_(e),tr.table.presence=!1,tr.attribute.presence=!1,tr.hash_attribute.presence=!1,R_.validateObject(e,tr)}a(TJ,"schema_object");function gJ(e){return e=A_(e),tr.table.presence={message:g_},tr.attribute.presence=!1,tr.hash_attribute.presence=!1,R_.validateObject(e,tr)}a(gJ,"table_object");function RJ(e){return e=A_(e),tr.table.presence={message:g_},tr.attribute.presence=!1,R_.validateObject(e,tr)}a(RJ,"create_table_object");function AJ(e){return e=A_(e),tr.table.presence={message:g_},tr.attribute.presence={message:g_},tr.hash_attribute.presence=!1,R_.validateObject(e,tr)}a(AJ,"attribute_object");function bJ(e){return e=A_(e),tr.table.presence={message:g_},tr.attribute.presence=!1,tr.hash_attribute.presence=!1,R_.validateObject(e,tr)}a(bJ,"describe_table");function yJ(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(yJ,"validateTableResidence");kP.exports={schema_object:TJ,create_table_object:RJ,table_object:gJ,attribute_object:AJ,describe_table:bJ,validateTableResidence:yJ}});var qP=y((WAe,GP)=>{"use strict";var OJ=require("uuid"),GR=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||OJ.v4(),this.schema_table=`${this.schema}.${this.table}`}};GP.exports=GR});var Qh=y((QAe,$P)=>{"use strict";var NJ=qP(),qR=class extends NJ{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}};$P.exports=qR});var YP=y((JAe,VP)=>{"use strict";VP.exports=wJ;var IJ="inserted";function wJ(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===IJ?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(wJ,"returnObject")});var zh=y((ebe,QP)=>{"use strict";var CJ=M(),$R=_t(),DJ=dc(),{getSystemSchemaPath:PJ,getSchemaPath:LJ}=mt(),ZAe=ao(),MJ=jh(),UJ=Qh(),vJ=YP(),{handleHDBError:KP,hdb_errors:jP}=ce(),WP=ee(),{HTTP_STATUS_CODES:BJ}=jP,HJ="inserted";QP.exports=xJ;async function xJ(e){let t=MJ.attribute_object(e);if(t)throw KP(new Error,t.message,jP.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&WP.checkGlobalSchemaTable(e.schema,e.table);if(r)throw KP(new Error,r,BJ.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=WP.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 UJ(e.schema,e.table,e.attribute,e.id);try{let i=await $R.openEnvironment(LJ(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}`);$R.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await $R.openEnvironment(PJ(),CJ.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:l}=await DJ.insertRecords(o,HDB_TABLE_INFO.hash_attribute,hdb_attribute_attributes,[s]);return vJ(HJ,c,{records:[s]},l)}catch(i){throw i}}a(xJ,"lmdbCreateAttribute")});var YR=y((rbe,JP)=>{var{hdb_table:FJ,hdb_database:zP}=Ri(),kJ=St(),VR=require("joi"),GJ={undefined:"undefined",null:"null"},qJ=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||GJ[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"),$J=VR.object({database:zP,schema:zP,table:FJ,records:VR.array().items(VR.object().custom(qJ)).required()});JP.exports=function(e){return kJ.validateBySchema(e,$J)}});var b_=y((ibe,ZP)=>{"use strict";var co=ee(),XP=V(),sbe=YR(),{getDatabases:VJ}=(De(),ne(at)),{ClientError:_c}=ce();ZP.exports=YJ;function YJ(e){if(co.isEmpty(e))throw new _c("invalid update parameters defined.");if(co.isEmptyOrZeroLength(e.schema))throw new _c("invalid schema specified.");if(co.isEmptyOrZeroLength(e.table))throw new _c("invalid table specified.");if(!Array.isArray(e.records))throw new _c("records must be an array");let t=VJ()[e.schema]?.[e.table];if(co.isEmpty(t))throw new _c(`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&&co.isEmptyOrZeroLength(o[r]))throw XP.error("a valid hash attribute must be provided with update record:",o),new _c("a valid hash attribute must be provided with update record, check log for more info");if(!co.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw XP.error(`a valid hash value must be provided with ${e.operation} record:`,o),new _c(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!co.isEmpty(o[r])&&o[r]!==""&&n.has(co.autoCast(o[r]))&&(o.skip=!0),n.add(co.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(YJ,"insertUpdateValidate")});var y_=y((abe,eL)=>{"use strict";var KJ=M().OPERATIONS_ENUM,KR=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=KJ.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};eL.exports=KR});var O_=y((ube,rL)=>{"use strict";var lbe=y_(),Jh=M(),WR=ee(),tL=V(),WJ=require("uuid"),{handleHDBError:Xh,hdb_errors:jJ}=ce(),{HDB_ERROR_MSGS:Zh,HTTP_STATUS_CODES:ep}=jJ;rL.exports=QJ;function QJ(e,t,r){for(let s=0;s<t.length;s++)zJ(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];JJ(i,r,e.operation)}}a(QJ,"processRows");function zJ(e){if(Buffer.byteLength(String(e))>Jh.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Xh(new Error,Zh.ATTR_NAME_LENGTH_ERR(e),ep.BAD_REQUEST,void 0,void 0,!0);if(WR.isEmptyOrZeroLength(e)||WR.isEmpty(e.trim()))throw Xh(new Error,Zh.ATTR_NAME_NULLISH_ERR,ep.BAD_REQUEST,void 0,void 0,!0)}a(zJ,"validateAttribute");function JJ(e,t,r){if(!e.hasOwnProperty(t)||WR.isEmptyOrZeroLength(e[t])){if(r===Jh.OPERATIONS_ENUM.INSERT||r===Jh.OPERATIONS_ENUM.UPSERT){e[t]=WJ.v4();return}throw tL.error("Update transaction aborted due to record with no hash value:",e),Xh(new Error,Zh.RECORD_MISSING_HASH_ERR,ep.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>Jh.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw tL.error(e),Xh(new Error,Zh.HASH_VAL_LENGTH_ERR,ep.BAD_REQUEST,void 0,void 0,!0)}a(JJ,"validateHash")});var sL=y((_be,nL)=>{"use strict";var jR=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};nL.exports=jR});var aL=y((Ebe,oL)=>{"use strict";var QR=_t(),XJ=V(),iL=Ln().LMDB_ERRORS_ENUM;oL.exports=ZJ;async function ZJ(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 QR.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==iL.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await QR.closeEnvironment(global.lmdb_map[n]),await QR.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==iL.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){XJ.error(t)}}a(ZJ,"cleanLMDBMap")});var lo=y((pbe,dL)=>{"use strict";var N_=require("crypto"),e3=te(),{CONFIG_PARAMS:t3}=M(),lL="aes-256-cbc",r3=32,n3=16,zR=64,uL=32,s3=zR+uL,cL=new Map;dL.exports={encrypt:i3,decrypt:o3,createNatsTableStreamName:a3};function i3(e){let t=N_.randomBytes(r3),r=N_.randomBytes(n3),n=N_.createCipheriv(lL,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(i3,"encrypt");function o3(e){let t=e.substr(0,zR),r=e.substr(zR,uL),n=e.substr(s3,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=N_.createDecipheriv(lL,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(o3,"decrypt");function a3(e,t){let r=e3.get(t3.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=cL.get(r);return n||(n=N_.createHash("md5").update(r).digest("hex"),cL.set(r,n)),n}a(a3,"createNatsTableStreamName")});var uo=y((Tbe,fL)=>{"use strict";var Sbe=jr(),I_=V(),_L=jh(),c3=lo(),tp=ee(),{handleHDBError:rp,hdb_errors:l3}=ce(),{HDB_ERROR_MSGS:np,HTTP_STATUS_CODES:JR}=l3,u3=te();u3.initSync();var{getDatabases:XR}=(De(),ne(at)),d3=require("fs-extra");fL.exports={describeAll:_3,describeTable:sp,describeSchema:f3};async function _3(e){try{let t=tp.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=XR(),i={},o={},c=[],l=e?.exact_count;for(let u in s){i[u]=!0,!t&&!n&&(o[u]=e.hdb_user.role.permission[u].describe);let _=s[u];for(let E in _)try{let f;if(t||n)f=await sp({schema:u,table:E,exact_count:l});else if(r&&r[u].describe&&r[u].tables[E].describe){let h=r[u].tables[E].attribute_permissions;f=await sp({schema:u,table:E,exact_count:l},h)}f&&c.push(f)}catch(f){I_.error(f)}}let d={};for(let u in c)t||n?(d[c[u].schema]==null&&(d[c[u].schema]={}),d[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]):o[c[u].schema]&&(d[c[u].schema]==null&&(d[c[u].schema]={}),d[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]);for(let u in i)t||n?d[u]={}:o[u]&&(d[u]={});return d}catch(t){return I_.error("Got an error in describeAll"),I_.error(t),rp(new Error,np.DESCRIBE_ALL_ERR)}}a(_3,"describeAll");async function sp(e,t){tp.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=_L.describe_table(e);if(i)throw i;let c=XR()[r];if(!c)throw rp(new Error,np.SCHEMA_NOT_FOUND(e.schema),JR.NOT_FOUND);let l=c[n];if(!l)throw rp(new Error,np.TABLE_NOT_FOUND(e.schema,e.table),JR.NOT_FOUND);function d(f){u.push({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(h=>({type:h.type,name:h.name})):void 0})}a(d,"pushAtt");let u=[];if(s){let f={};s.forEach(h=>{h.describe&&(f[h.attribute_name]=!0)}),l.attributes.forEach(h=>{f[h.name]&&d(h)})}else l.attributes?.forEach(f=>d(f));let _;try{_=(await d3.stat(l.primaryStore.env.path)).size}catch(f){I_.warn("unable to get database size",f)}let E={schema:r,name:l.tableName,hash_attribute:l.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:u,db_size:_};E.clustering_stream_name=c3.createNatsTableStreamName(E.schema,E.name);try{let f=l.getRecordCount({exactCount:e.exact_count==="true"});E.record_count=f.recordCount,E.estimated_record_range=f.estimatedRange;let h=l.auditStore;if(h)for(let S of h.getKeys({reverse:!0,limit:1}))E.last_updated_record=S[0];if(!E.last_updated_record&&l.indices.__updatedtime__)for(let S of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))E.last_updated_record=S}catch(f){I_.warn(`unable to stat table dbi due to ${f}`)}return E}a(sp,"descTable");async function f3(e){tp.transformReq(e);let t=_L.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=XR()[n];if(!i)throw rp(new Error,np.SCHEMA_NOT_FOUND(e.schema),JR.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),tp.isEmpty(l)||l.describe){let d=await sp({schema:e.schema,table:c,exact_count:e.exact_count},l?l.attribute_permissions:null);d&&(o[d.name]=d)}}return o}a(f3,"describeSchema")});var _s=y((bbe,SL)=>{var E3=ao(),{callbackify:hL,promisify:h3}=require("util"),{getDatabases:pL}=(De(),ne(at));SL.exports={setSchemaDataToGlobal:EL,getTableSchema:p3,getSystemSchema:m3,setSchemaDataToGlobalAsync:h3(EL)};var mL=uo(),Rbe=hL(mL.describeAll),Abe=hL(mL.describeTable);function EL(e){global.hdb_schema=pL(),e&&e()}a(EL,"setSchemaDataToGlobal");function p3(e,t,r){let n=pL()[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(p3,"getTableSchema");function m3(){return E3}a(m3,"getSystemSchema")});var un=y((Obe,AL)=>{"use strict";var op=YR(),Cr=ee(),S3=require("util"),ap=Hn(),T3=_s(),TL=V(),{handleHDBError:fc,hdb_errors:g3}=ce(),{HTTP_STATUS_CODES:Ec}=g3,R3=S3.promisify(T3.getTableSchema),A3="updated",gL="inserted",RL="upserted";AL.exports={insert:y3,update:O3,upsert:N3,validation:b3,flush:I3};async function b3(e){if(Cr.isEmpty(e))throw new Error("invalid update parameters defined.");if(Cr.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Cr.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await R3(e.schema,e.table),r=op(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&&Cr.isEmptyOrZeroLength(c[n]))throw TL.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(!Cr.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw TL.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Cr.isEmpty(c[n])&&c[n]!==""&&s.has(Cr.autoCast(c[n]))&&(c.skip=!0),s.add(Cr.autoCast(c[n]));for(let l in c)i[l]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(b3,"validation");async function y3(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=op(e);if(t)throw fc(new Error,t.message,Ec.BAD_REQUEST);Cr.transformReq(e);let r=Cr.checkSchemaTableExist(e.schema,e.table);if(r)throw fc(new Error,r,Ec.BAD_REQUEST);let n=await ap.createRecords(e);return ip(gL,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(y3,"insertData");async function O3(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=op(e);if(t)throw fc(new Error,t.message,Ec.BAD_REQUEST);Cr.transformReq(e);let r=Cr.checkSchemaTableExist(e.schema,e.table);if(r)throw fc(new Error,r,Ec.BAD_REQUEST);let n=await ap.updateRecords(e);return Cr.isEmpty(n.existing_rows)?ip(A3,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):ip(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(O3,"updateData");async function N3(e){if(e.operation!=="upsert")throw fc(new Error,"invalid operation, must be upsert",Ec.INTERNAL_SERVER_ERROR);let t=op(e);if(t)throw fc(new Error,t.message,Ec.BAD_REQUEST);Cr.transformReq(e);let r=Cr.checkSchemaTableExist(e.schema,e.table);if(r)throw fc(new Error,r,Ec.BAD_REQUEST);let n=await ap.upsertRecords(e);return ip(RL,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(N3,"upsertData");function ip(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===gL?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===RL?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(ip,"returnObject");function I3(e){return Cr.transformReq(e),ap.flush(e.schema,e.table)}a(I3,"flush")});var eA=y((Ibe,OL)=>{var w3=St(),ZR=require("joi"),{hdb_table:C3,hdb_database:bL}=Ri(),yL={schema:bL,database:bL,table:C3},D3={date:ZR.date().iso().required()},P3={timestamp:ZR.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};OL.exports=function(e,t){let r=t==="timestamp"?{...yL,...P3}:{...yL,...D3},n=ZR.object(r);return w3.validateBySchema(e,n)}});var wL=y((wbe,IL)=>{var L3=St(),tA=require("joi"),{hdb_table:M3,hdb_database:NL}=Ri(),U3=tA.object({schema:NL,database:NL,table:M3,hash_values:tA.array().required(),ids:tA.array()});IL.exports=function(e){return L3.validateBySchema(e,U3)}});var iA=y((Cbe,CL)=>{"use strict";var rA=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}},nA=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}},sA=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};CL.exports={InsertObject:rA,NoSQLSeachObject:nA,DeleteResponseObject:sA}});var mc=y((Pbe,UL)=>{"use strict";var PL=eA(),v3=wL(),hc=ee(),DL=require("moment"),LL=V(),{promisify:B3,callbackify:H3}=require("util"),pc=M(),x3=_s(),oA=B3(x3.getTableSchema),aA=Hn(),{DeleteResponseObject:F3}=iA(),{handleHDBError:na,hdb_errors:k3}=ce(),{HDB_ERROR_MSGS:cp,HTTP_STATUS_CODES:sa}=k3,G3="records successfully deleted",q3=H3(ML);UL.exports={delete:q3,deleteRecord:ML,deleteFilesBefore:$3,deleteAuditLogsBefore:V3};async function $3(e){let t=PL(e,"date");if(t)throw na(t,t.message,sa.BAD_REQUEST,void 0,void 0,!0);if(hc.transformReq(e),!DL(e.date,DL.ISO_8601).isValid())throw na(new Error,cp.INVALID_DATE,sa.BAD_REQUEST,pc.LOG_LEVELS.ERROR,cp.INVALID_DATE,!0);let n=hc.checkSchemaTableExist(e.schema,e.table);if(n)throw na(new Error,n,sa.NOT_FOUND,pc.LOG_LEVELS.ERROR,n,!0);let s=await aA.deleteRecordsBefore(e);if(await oA(e.schema,e.table),LL.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a($3,"deleteFilesBefore");async function V3(e){let t=PL(e,"timestamp");if(t)throw na(t,t.message,sa.BAD_REQUEST,void 0,void 0,!0);if(hc.transformReq(e),isNaN(e.timestamp))throw na(new Error,cp.INVALID_VALUE("Timestamp"),sa.BAD_REQUEST,pc.LOG_LEVELS.ERROR,cp.INVALID_VALUE("Timestamp"),!0);let r=hc.checkSchemaTableExist(e.schema,e.table);if(r)throw na(new Error,r,sa.NOT_FOUND,pc.LOG_LEVELS.ERROR,r,!0);let n=await aA.deleteAuditLogsBefore(e);return await oA(e.schema,e.table),LL.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(V3,"deleteAuditLogsBefore");async function ML(e){e.ids&&(e.hash_values=e.ids);let t=v3(e);if(t)throw na(t,t.message,sa.BAD_REQUEST,void 0,void 0,!0);hc.transformReq(e);let r=hc.checkSchemaTableExist(e.schema,e.table);if(r)throw na(new Error,r,sa.NOT_FOUND,pc.LOG_LEVELS.ERROR,r,!0);try{await oA(e.schema,e.table);let n=await aA.deleteRecords(e);return hc.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${G3}`),n}catch(n){if(n.message===pc.SEARCH_NOT_FOUND_MESSAGE){let s=new F3;return s.message=pc.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(ML,"deleteRecord")});var lp=y((Mbe,HL)=>{var Y3=require("crypto"),vL=9;function K3(e){let t=j3(vL),r=BL(e+t);return t+r}a(K3,"createHash");function W3(e,t){let r=e?.substr(0,vL),n=r+BL(t+r);return e===n}a(W3,"validateHash");function j3(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(j3,"generateSalt");function BL(e){return Y3.createHash("md5").update(e).digest("hex")}a(BL,"md5");HL.exports={hash:K3,validate:W3}});var FL=y((vbe,xL)=>{var cA=St(),Qr={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 Q3(e){return Qr.password.presence=!0,Qr.username.presence=!0,Qr.role.presence=!0,Qr.active.presence=!0,cA.validateObject(e,Qr)}a(Q3,"addUserValidation");function z3(e){return Qr.password.presence=!1,Qr.username.presence=!0,Qr.role.presence=!1,Qr.active.presence=!1,cA.validateObject(e,Qr)}a(z3,"alterUserValidation");function J3(e){return Qr.password.presence=!1,Qr.username.presence=!0,Qr.role.presence=!1,Qr.active.presence=!1,cA.validateObject(e,Qr)}a(J3,"dropUserValidation");xL.exports={addUserValidation:Q3,alterUserValidation:z3,dropUserValidation:J3}});var At=y((xbe,GL)=>{"use strict";var{platform:Hbe}=require("os"),X3="nats-server.zip",lA="nats-server",Z3=process.platform==="win32"?`${lA}.exe`:lA,eX=/^[^\s.,*>]+$/,kL="__request__",tX=a(e=>`${e}.${kL}`,"REQUEST_SUBJECT"),rX={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},nX={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},sX={HUB:"hub.pid",LEAF:"leaf.pid"},iX={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},oX={SUCCESS:"success",ERROR:"error"},aX={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},cX={TXN:"txn",MSGID:"msgid"},Yl={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},lX={[Yl.ERR]:1,[Yl.WRN]:2,[Yl.INF]:3,[Yl.DBG]:4,[Yl.TRC]:5},uX={debug:"-D",trace:"-DVV"};GL.exports={NATS_SERVER_ZIP:X3,NATS_SERVER_NAME:lA,NATS_BINARY_NAME:Z3,PID_FILES:sX,NATS_CONFIG_FILES:nX,SERVER_SUFFIX:iX,NATS_TERM_CONSTRAINTS_RX:eX,REQUEST_SUFFIX:kL,UPDATE_REMOTE_RESPONSE_STATUSES:oX,CLUSTER_STATUS_STATUSES:aX,REQUEST_SUBJECT:tX,SUBJECT_PREFIXES:cX,MSG_HEADERS:rX,LOG_LEVELS:Yl,LOG_LEVEL_FLAGS:uX,LOG_LEVEL_HIERARCHY:lX}});var uA=y(qL=>{"use strict";var dX={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
8
+ `),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
9
+ `)},_X="certificate.pem",fX="privateKey.pem",EX="caCertificate.pem",hX="natsCertificate.pem",pX="natsCaCertificate.pem",bt={DEFAULT:"default","DEFAULT-CA":"default-ca",SERVER:"server",CA:"ca","OPERATIONS-API":"operations-api","OPERATIONS-CA":"operations-ca"},mX={tls_certificate:bt.SERVER,tls_certificateAuthority:bt.CA,customFunctions_tls_certificate:bt.SERVER,customFunctions_tls_certificateAuthority:bt.CA,operationsApi_tls_certificate:bt["OPERATIONS-API"],operationsApi_tls_certificateAuthority:bt["OPERATIONS-CA"]},SX={[bt.SERVER]:2,[bt.DEFAULT]:1},TX={[bt["OPERATIONS-API"]]:3,[bt.SERVER]:2,[bt.DEFAULT]:1},gX={[bt["OPERATIONS-API"]]:3,[bt.SERVER]:2,[bt.DEFAULT]:1},RX={[bt["OPERATIONS-CA"]]:3,[bt.CA]:2,[bt["DEFAULT-CA"]]:1},AX={[bt["OPERATIONS-CA"]]:3,[bt.CA]:2,[bt["DEFAULT-CA"]]:1},bX={[bt.CA]:2,[bt["DEFAULT-CA"]]:1};Object.assign(qL,{CERTIFICATE_PEM_NAME:_X,PRIVATEKEY_PEM_NAME:fX,CA_PEM_NAME:EX,CERT_NAME:bt,CERT_CONFIG_NAME_MAP:mX,CERT_PREFERENCE_APP:SX,CERT_PREFERENCE_OPS:TX,CERT_PREFERENCE_REP:gX,CA_CERT_PREFERENCE_REP:RX,CA_CERT_PREFERENCE_OPS:AX,CA_CERT_PREFERENCE_APP:bX,CERTIFICATE_VALUES:dX,NATS_CERTIFICATE_PEM_NAME:hX,NATS_CA_PEM_NAME:pX})});var _A=y((qbe,jL)=>{"use strict";var KL=require("fs-extra"),me=require("joi"),yX=require("os"),{boolean:qe,string:It,number:xt,array:Tc}=me.types(),{totalmem:$L}=require("os"),Sc=require("path"),OX=V(),dA=ee(),Gbe=uA(),VL=M(),NX=St(),YL="log",IX="components",wX="Invalid logging.rotation.maxSize unit. Available units are G, M or K",CX="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",DX="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",PX="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",LX="rootPath config parameter is undefined",Es=me.alternatives([xt.min(0),It]).optional().empty(null),up=me.alternatives([Tc.items(It,{host:It.required(),port:Es},{hostname:It.required(),port:Es}).empty(null),Tc.items(It)]),bi,WL=!1;jL.exports={configValidator:MX,routesValidator:FX,route_constraints:up};function MX(e,t=!1){if(WL=t,bi=e.rootPath,dA.isEmpty(bi))throw LX;let r=qe.optional(),n=xt.min(0).max(1e3).empty(null).default(xX),s=It.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(w_),i=It.optional().empty(null),o=It.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=me.string().empty(null).default(w_),l=me.custom(vX).empty(null).default(w_),d=e.clustering?.enabled,u=me.object({certificate:i,certificateAuthority:i,privateKey:i}),_;return d===!0?_=me.object({enabled:r,hubServer:me.object({cluster:me.object({name:me.required().empty(null),network:me.object({port:Es,routes:up}).required()}).required(),leafNodes:me.object({network:me.object({port:Es}).required()}).required(),network:me.object({port:Es}).required()}).required(),leafServer:me.object({network:me.object({port:Es,routes:up}).required(),streams:me.object({maxAge:xt.min(120).allow(null).optional(),maxBytes:xt.min(1).allow(null).optional(),maxMsgs:xt.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:me.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:qe.optional(),databaseLevel:qe.optional(),tls:me.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:qe.required(),verify:qe.optional()}),user:It.optional().empty(null)}).optional():_=me.object({enabled:r,tls:me.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:qe.optional()})}).optional(),me.object({authentication:me.object({authorizeLocal:qe,cacheTTL:xt.required(),enableSessions:qe}),analytics:me.object({aggregatePeriod:xt}),replication:me.object({hostname:me.alternatives(It,xt).optional().empty(null),url:It.optional().empty(null),port:xt.optional().empty(null),securePort:xt.optional().empty(null),routes:Tc.optional().empty(null),databases:me.alternatives(It,Tc),enableRootCAs:qe.optional()}),componentsRoot:s.optional(),clustering:_,localStudio:me.object({enabled:r}).required(),logging:me.object({auditAuthEvents:me.object({logFailed:qe,logSuccessful:qe}),file:qe.required(),level:me.valid("notify","fatal","error","warn","info","debug","trace"),rotation:me.object({enabled:qe.optional(),compress:qe.optional(),interval:It.custom(HX).optional().empty(null),maxSize:It.custom(BX).optional().empty(null),path:It.optional().empty(null).default(w_)}).required(),root:s,stdStreams:qe.required(),auditLog:qe.required()}).required(),operationsApi:me.object({network:me.object({cors:qe.optional(),corsAccessList:Tc.optional(),headersTimeout:xt.min(1).optional(),keepAliveTimeout:xt.min(1).optional(),port:Es,domainSocket:me.optional().empty("hdb/operations-server").default(w_),securePort:Es,timeout:xt.min(1).optional()}).optional(),tls:me.alternatives([me.array().items(u),u])}).required(),rootPath:It.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:me.object({network:me.object({port:Es,securePort:Es,mtls:me.alternatives([qe.optional(),me.object({user:It.optional(),certificateAuthority:i,required:qe.optional()})])}).required(),webSocket:qe.optional(),requireAuthentication:qe.optional()}),http:me.object({compressionThreshold:xt.optional(),cors:qe.optional(),corsAccessList:Tc.optional(),headersTimeout:xt.min(1).optional(),port:Es,securePort:Es,maxHeaderSize:xt.optional(),mtls:me.alternatives([qe.optional(),me.object({user:It.optional(),certificateAuthority:i,required:qe.optional()})]),threadRange:me.alternatives([Tc.optional(),It.optional()])}).required(),threads:me.alternatives(n.optional(),me.object({count:n.optional(),debug:me.alternatives(qe.optional(),me.object({startingPort:xt.min(1).optional(),host:It.optional(),waitForDebugger:qe.optional()})),maxHeapMemory:xt.min(0).optional()})),storage:me.object({writeAsync:qe.required(),overlappingSync:qe.optional(),caching:qe.optional(),compression:me.alternatives([qe.optional(),me.object({dictionary:It.optional(),threshold:xt.optional()})]),compactOnStart:qe.optional(),compactOnStartKeepBackup:qe.optional(),noReadAhead:qe.optional(),path:l,prefetchWrites:qe.optional(),maxFreeSpaceToLoad:xt.optional(),maxFreeSpaceToRetain:xt.optional()}).required(),ignoreScripts:qe.optional(),tls:me.alternatives([me.array().items(u),u])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(MX,"configValidator");function UX(e){return WL||KL.existsSync(e)?null:`Specified path ${e} does not exist.`}a(UX,"doesPathExist");function vX(e,t){me.assert(e,It.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=UX(e);if(r)return t.message(r)}a(vX,"validatePath");function BX(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(wX);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(DX):e}a(BX,"validateRotationMaxSize");function HX(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(CX);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(PX):e}a(HX,"validateRotationInterval");function xX(e,t){let r=t.state.path.join("."),n=yX.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||$L();return i=Math.round(Math.min(i,$L())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),OX.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(xX,"setDefaultThreads");function w_(e,t){let r=t.state.path.join(".");if(!dA.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(dA.isEmpty(bi))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Sc.join(bi,IX);case"logging.root":return Sc.join(bi,YL);case"clustering.leafServer.streams.path":return Sc.join(bi,"clustering","leaf");case"storage.path":let n=Sc.join(bi,VL.LEGACY_DATABASES_DIR_NAME);return KL.existsSync(n)?n:Sc.join(bi,VL.DATABASES_DIR_NAME);case"logging.rotation.path":return Sc.join(bi,YL);case"operationsApi.network.domainSocket":return r==null?null:Sc.join(bi,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(w_,"setDefaultRoot");function FX(e){let t=me.object({routes:up});return NX.validateBySchema({routes:e},t)}a(FX,"routesValidator")});var yt=y(sM=>{"use strict";var dn=M(),Er=ee(),hr=V(),{configValidator:kX,routesValidator:QL}=_A(),zr=require("fs-extra"),JL=require("yaml"),Fn=require("path"),GX=require("is-number"),XL=require("properties-reader"),qX=require("lodash"),{handleHDBError:$X}=ce(),{HTTP_STATUS_CODES:VX,HDB_ERROR_MSGS:Kl}=Ln(),{server:YX}=(Wr(),ne(ic)),{DATABASES_PARAM_CONFIG:C_,CONFIG_PARAMS:xn,CONFIG_PARAM_MAP:js}=dn,KX="Unable to get config value because config is uninitialized",WX="Config successfully initialized",jX="Error backing up config file",QX="Empty parameter sent to getConfigValue",ZL=Fn.join(dn.PACKAGE_ROOT,"config","yaml",dn.HDB_DEFAULT_CONFIG_FILE),zX=Fn.join(dn.PACKAGE_ROOT,"config","yaml","defaultNatsConfig.yaml"),JX="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",zL={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"},dp,Wt,_p;Object.assign(sM,{createConfigFile:XX,getDefaultConfig:ZX,getConfigValue:tM,initConfig:fp,flattenConfig:Wl,updateConfigValue:rM,updateConfigObject:tZ,getConfiguration:sZ,setConfiguration:iZ,readConfigFile:pA,getClusteringRoutes:oZ,initOldConfig:nM,getConfigFromFile:aZ,getConfigFilePath:gc,addConfig:cZ,deleteConfigFromFile:lZ,getConfigObj:uZ,resolvePath:fA,getFlatConfigObj:dZ});function fA(e){if(e?.startsWith("~/"))return Fn.join(Er.getHomeDir(),e.slice(1));let t=te();return Fn.resolve(t.getHdbBasePath(),e)}a(fA,"resolvePath");function XX(e,t=!1){let r=ia(ZL);if(e.clustering_enabled||e.CLUSTERING_ENABLED||e.clustering){let c=JL.parseDocument(zr.readFileSync(zX,"utf8"),{simpleKeys:!0});r.addIn(["clustering"],c.toJSON().clustering)}dp=Wl(r.toJSON());let n;for(let c in e){let l=js[c.toLowerCase()];if(l===xn.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(d=>({[d]:e[c][d]}));continue}if(!l&&(c.endsWith("_package")||c.endsWith("_port"))&&(l=c),l!==void 0){let d=l.split("_"),u=EA(l,e[c]);l==="rootPath"&&u?.endsWith("/")&&(u=u.slice(0,-1));try{r.setIn([...d],u)}catch(_){hr.error(_)}}}n&&eM(r,n),hA(r,t);let s=r.toJSON();Wt=Wl(s);let i=r.getIn(["rootPath"]),o=Fn.join(i,dn.HDB_CONFIG_FILE);zr.createFileSync(o),zr.writeFileSync(o,String(r)),hr.trace(`Config file written to ${o}`)}a(XX,"createConfigFile");function eM(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Er.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(C_.TABLES))for(let i in n[s][C_.TABLES])for(let o in n[s][C_.TABLES][i]){let c=n[s][C_.TABLES][i][o],l=[xn.DATABASES,s,C_.TABLES,i,o];e.hasIn(l)?e.setIn(l,c):e.addIn(l,c)}else for(let i in n[s]){let o=n[s][i],c=[xn.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){hr.error("Error parsing schemas CLI/env config arguments",n)}}a(eM,"setSchemasConfig");function ZX(e){if(dp===void 0){let r=ia(ZL);dp=Wl(r.toJSON())}let t=js[e.toLowerCase()];if(t!==void 0)return dp[t.toLowerCase()]}a(ZX,"getDefaultConfig");function tM(e){if(e==null){hr.info(QX);return}if(Wt===void 0){hr.trace(KX);return}let t=js[e.toLowerCase()];if(t!==void 0)return Wt[t.toLowerCase()]}a(tM,"getConfigValue");function gc(e=Er.getPropsFilePath()){let t=Er.getEnvCliRootPath();if(t)return fA(Fn.join(t,dn.HDB_CONFIG_FILE));let r=XL(e);return fA(r.get(dn.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}a(gc,"getConfigFilePath");function fp(e=!1){if(Wt===void 0||e){let t;if(!Er.noBootFile()){t=Er.getPropsFilePath();try{zr.accessSync(t,zr.constants.F_OK|zr.constants.R_OK)}catch(i){throw hr.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=gc(t),n;if(r.includes("config/settings.js"))try{nM(r);return}catch(i){if(i.code!==dn.NODE_ERROR_CODES.ENOENT)throw i}try{n=ia(r)}catch(i){if(i.code===dn.NODE_ERROR_CODES.ENOENT){hr.trace(`HarperDB config file not found at ${r}.
10
+ This can occur during early stages of install where the config file has not yet been created`);return}else throw hr.error(i),new Error(`Error reading HarperDB config file at ${r}`)}eZ(n,r),hA(n);let s=n.toJSON();if(YX.config=s,Wt=Wl(s),Wt.logging_rotation_rotate)for(let i in zL)Wt[i]&&hr.error(`Config ${zL[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);hr.trace(WX)}}a(fp,"initConfig");function eZ(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Fn.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Fn.join(r,"log")),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&&(hr.trace("Updating config file with missing config params"),zr.writeFileSync(t,String(e)))}a(eZ,"checkForUpdatedConfig");function hA(e,t=!1){let r=e.toJSON();if(r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads),r.http?.port&&r.http?.port===r.http?.securePort)throw Kl.CONFIG_VALIDATION("http.port and http.securePort cannot be the same value");if(r.operationsApi?.network?.port&&r.operationsApi?.network?.port===r.operationsApi?.network?.securePort)throw Kl.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=kX(r,t);if(n.error)throw Kl.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(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket),r?.clustering?.enabled&&e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path)}a(hA,"validateConfig");function tZ(e,t){Wt===void 0&&(Wt={});let r=js[e.toLowerCase()];if(r===void 0){hr.trace(`Unable to update config object because config param '${e}' does not exist`);return}Wt[r.toLowerCase()]=t}a(tZ,"updateConfigObject");function rM(e,t,r=void 0,n=!1,s=!1,i=!1){Wt===void 0&&fp();let o=tM(js.hdb_root),c=Fn.join(o,dn.HDB_CONFIG_FILE),l=ia(c),d;if(r===void 0&&e.toLowerCase()===xn.DATABASES)d=t;else if(r===void 0){let E;if(i)E=e;else if(E=js[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=EA(E,t);l.setIn([...f],h)}else for(let E in r){let f=js[E.toLowerCase()];if(f===xn.HTTP_SECUREPORT&&r[E]===Wt[xn.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),f===xn.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===Wt[xn.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),f===xn.DATABASES){d=r[E];continue}if(f?.startsWith("threads_")){let h=l.getIn(["threads"]);h>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),S=dn.LEGACY_CONFIG_PARAMS[E.toUpperCase()];S&&S.startsWith("customFunctions")&&l.hasIn(S.split("_"))&&(f=S,h=S.split("_"));let T=EA(f,r[E]);f==="rootPath"&&T?.endsWith("/")&&(T=T.slice(0,-1));try{h.length>1&&typeof l.getIn(h.slice(0,-1))=="boolean"&&l.deleteIn(h.slice(0,-1)),l.setIn([...h],T)}catch(g){hr.error(g)}}}d&&eM(l,d),hA(l);let u=l.getIn(["rootPath"]),_=Fn.join(u,dn.HDB_CONFIG_FILE);n===!0&&rZ(c,u),zr.writeFileSync(_,String(l)),s&&(Wt=Wl(l.toJSON())),hr.trace(`Config parameter: ${e} updated with value: ${t}`)}a(rM,"updateConfigValue");function rZ(e,t){try{let r=Fn.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${dn.HDB_CONFIG_FILE}.bak`);zr.copySync(e,r),hr.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){hr.error(jX),hr.error(r)}}a(rZ,"backupConfigFile");var nZ=["databases"];function Wl(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network={...e.http,...e.operationsApi.network}),e?.operationsApi&&(e.operationsApi.tls={...e.tls,...e.operationsApi.tls}),_p=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])&&!nZ.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!xn[l.toUpperCase()]&&js[l]&&(s[js[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Wl,"flattenConfig");function EA(e,t){if(e===xn.CLUSTERING_NODENAME||e===xn.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(GX(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Er.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 Er.autoCast(t)}a(EA,"castConfigValue");function sZ(){let e=Er.getPropsFilePath(),t=gc(e);return ia(t).toJSON()}a(sZ,"getConfiguration");async function iZ(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return rM(void 0,void 0,s,!0),JX}catch(i){throw typeof i=="string"||i instanceof String?$X(i,i,VX.BAD_REQUEST,void 0,void 0,!0):i}}a(iZ,"setConfiguration");function pA(){let e=Er.getPropsFilePath();try{zr.accessSync(e,zr.constants.F_OK|zr.constants.R_OK)}catch(n){if(!Er.noBootFile())throw hr.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=gc(e);return ia(t).toJSON()}a(pA,"readConfigFile");function ia(e){return JL.parseDocument(zr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ia,"parseYamlDoc");function oZ(){let e=pA(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Er.isEmptyOrZeroLength(t)?[]:t;let r=QL(t);if(r)throw Kl.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Er.isEmptyOrZeroLength(n)?[]:n;let s=QL(n);if(s)throw Kl.CONFIG_VALIDATION(s.message);if(!Er.isEmptyOrZeroLength(n)&&!Er.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Er.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Kl.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(oZ,"getClusteringRoutes");function nM(e){let t=XL(e);Wt={};for(let r in js){let n=t.get(r.toUpperCase());if(Er.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=js[r].toLowerCase();s===xn.LOGGING_ROOT?Wt[s]=Fn.dirname(n):Wt[s]=n}return Wt}a(nM,"initOldConfig");function aZ(e){let t=pA();return qX.get(t,e.replaceAll("_","."))}a(aZ,"getConfigFromFile");async function cZ(e,t){let r=ia(gc());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await zr.writeFile(gc(),String(r))}a(cZ,"addConfig");function lZ(e){let t=gc(Er.getPropsFilePath()),r=ia(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Fn.join(n,dn.HDB_CONFIG_FILE);zr.writeFileSync(s,String(r))}a(lZ,"deleteConfigFromFile");function uZ(){return _p||(fp(),_p)}a(uZ,"getConfigObj");function dZ(){return Wt||fp(),Wt}a(dZ,"getFlatConfigObj")});var oM=y((Kbe,iM)=>{"use strict";var Ep=M(),hp=class{static{a(this,"BaseLicense")}constructor(t=0,r=Ep.RAM_ALLOCATION_ENUM.DEFAULT,n=Ep.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},mA=class extends hp{static{a(this,"ExtendedLicense")}constructor(t=0,r=Ep.RAM_ALLOCATION_ENUM.DEFAULT,n=Ep.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};iM.exports={BaseLicense:hp,ExtendedLicense:mA}});var Rc=y((jbe,fM)=>{"use strict";var Ql=require("fs-extra"),cM=lp(),lM=require("crypto"),_Z=require("moment"),fZ=require("uuid").v4,Jr=V(),TA=require("path"),EZ=ee(),oa=M(),{totalmem:aM}=require("os"),hZ=oM().ExtendedLicense,jl="invalid license key format",pZ="061183",mZ="mofi25",SZ="aes-256-cbc",TZ=16,gZ=32,uM=te(),{resolvePath:dM}=yt();uM.initSync();var SA;fM.exports={validateLicense:_M,generateFingerPrint:AZ,licenseSearch:AA,getLicense:OZ,checkMemoryLimit:NZ};function gA(){return TA.join(uM.getHdbBasePath(),oa.LICENSE_KEY_DIR_NAME,oa.LICENSE_FILE_NAME)}a(gA,"getLicenseDirPath");function RZ(){let e=gA();return dM(TA.join(e,oa.LICENSE_FILE_NAME))}a(RZ,"getLicenseFilePath");function RA(){let e=gA();return dM(TA.join(e,oa.REG_KEY_FILE_NAME))}a(RA,"getFingerPrintFilePath");async function AZ(){let e=RA();try{return await Ql.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await bZ();throw Jr.error(`Error writing fingerprint file to ${e}`),Jr.error(t),new Error("There was an error generating the fingerprint")}}a(AZ,"generateFingerPrint");async function bZ(){let e=fZ(),t=cM.hash(e),r=RA();try{await Ql.mkdirp(gA()),await Ql.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Jr.error(`Error writing fingerprint file to ${r}`),Jr.error(n),new Error("There was an error generating the fingerprint")}return t}a(bZ,"writeFingerprint");function _M(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:oa.RAM_ALLOCATION_ENUM.DEFAULT,version:oa.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Jr.error("empty license key passed to validate."),r;let n=RA(),s=!1;try{s=Ql.statSync(n)}catch(i){Jr.error(i)}if(s){let i;try{i=Ql.readFileSync(n,"utf8")}catch{Jr.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(mZ),c=o[1];c=Buffer.concat([Buffer.from(c)],TZ);let l=Buffer.concat([Buffer.from(i)],gZ),d=lM.createDecipheriv(SZ,l,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let u=null;try{u=d.update(o[0],"hex","utf8"),u.trim(),u+=d.final("utf8")}catch{let f=yZ(o[0],i);if(f)u=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(jl),Jr.error(jl),new Error(jl)}let _;if(isNaN(u))try{_=JSON.parse(u),r.version=_.version,r.exp_date=_.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),_.ram_allocation&&(r.ram_allocation=_.ram_allocation)}catch{throw console.error(jl),Jr.error(jl),new Error(jl)}else r.exp_date=u;r.exp_date<_Z().valueOf()&&(r.valid_date=!1),cM.validate(o[1],`${pZ}${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||Jr.error("Invalid licence"),r}a(_M,"validateLicense");function yZ(e,t){try{let r=lM.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Jr.warn("Check old license failed")}}a(yZ,"checkOldLicense");function AA(){let e=new hZ,t=[];try{t=Ql.readFileSync(RZ(),"utf-8").split(oa.NEW_LINE)}catch(r){r.code==="ENOENT"?Jr.debug("no license file found"):Jr.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(EZ.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=_M(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){Jr.error("There was an error parsing the license string."),Jr.error(s),e.ram_allocation=oa.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return SA=e,e}a(AA,"licenseSearch");async function OZ(){return SA||await AA(),SA}a(OZ,"getLicense");function NZ(){let e=AA().ram_allocation,t=process.constrainedMemory?.()||aM();if(t=Math.round(Math.min(t,aM())/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(NZ,"checkMemoryLimit")});var _n=y((Zbe,CM)=>{"use strict";var mM="username is required",SM="nothing to update, must supply active, role or password to update",TM="password cannot be an empty string",gM="If role is specified, it cannot be empty.",RM="active must be true or false";CM.exports={addUser:vZ,alterUser:BZ,dropUser:xZ,getSuperUser:qZ,userInfo:FZ,listUsers:mp,listUsersExternal:kZ,setUsersToGlobal:Jl,findAndValidateUser:IM,getClusterUser:$Z,USERNAME_REQUIRED:mM,ALTERUSER_NOTHING_TO_UPDATE:SM,EMPTY_PASSWORD:TM,EMPTY_ROLE:gM,ACTIVE_BOOLEAN:RM};var AM=un(),IZ=mc(),OA=lp(),bM=FL(),yM=jr(),NA=_o(),kn=ee(),OM=require("validate.js"),$e=V(),{promisify:wZ}=require("util"),IA=lo(),EM=M(),hM=At(),CZ=yt(),zbe=te(),Jbe=Rc(),DZ=ao(),{table:Xbe}=(De(),ne(at)),{handleHDBError:yi,hdb_errors:PZ}=ce(),{HTTP_STATUS_CODES:Oi,AUTHENTICATION_ERROR_MSGS:bA,HDB_ERROR_MSGS:zl}=PZ,{UserEventMsg:wA}=Qs(),yA=require("lodash"),{server:CA}=(Wr(),ne(ic)),LZ=V();CA.getUser=(e,t)=>IM(e,t,t!=null);var NM={username:!0,active:!0,role:!0,password:!0},pM=new Map,pp=yM.searchByValue,MZ=yM.searchByHash,UZ=wZ(IZ.delete);async function vZ(e){let t=OM.cleanAttributes(e,NM),r=bM.addUserValidation(t);if(r)throw yi(new Error,r.message,Oi.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 pp(n),s=s&&Array.from(s)}catch(l){throw $e.error("There was an error searching for a role in add user"),$e.error(l),l}if(!s||s.length<1)throw yi(new Error,zl.ROLE_NAME_NOT_FOUND(t.role),Oi.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw yi(new Error,zl.DUP_ROLES_FOUND(t.role),Oi.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=IA.encrypt(t.password)),t.password=OA.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await AM.insert(i)}catch(l){throw $e.error("There was an error searching for a user."),$e.error(l),l}$e.debug(o);try{await Jl()}catch(l){throw $e.error("Got an error setting users to global"),$e.error(l),l}if(o.skipped_hashes.length===1)throw yi(new Error,zl.USER_ALREADY_EXISTS(t.username),Oi.CONFLICT,void 0,void 0,!0);let c={...t};return c.role=s[0],NA.signalUserChange(new wA(process.pid)),`${c.username} successfully added`}a(vZ,"addUser");async function BZ(e){let t=OM.cleanAttributes(e,NM);if(kn.isEmptyOrZeroLength(t.username))throw new Error(mM);if(kn.isEmptyOrZeroLength(t.password)&&kn.isEmptyOrZeroLength(t.role)&&kn.isEmptyOrZeroLength(t.active))throw new Error(SM);if(!kn.isEmpty(t.password)&&kn.isEmptyOrZeroLength(t.password.trim()))throw new Error(TM);if(!kn.isEmpty(t.active)&&!kn.isBoolean(t.active))throw new Error(RM);let r=HZ(t.username);if(!kn.isEmpty(t.password)&&!kn.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=IA.encrypt(t.password)),t.password=OA.hash(t.password)),t.role==="")throw new Error(gM);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 pp(i)||[])}catch(c){throw $e.error("Got an error searching for a role."),$e.error(c),c}if(!o||o.length===0){let c=zl.ALTER_USER_ROLE_NOT_FOUND(t.role);throw $e.error(c),yi(new Error,c,Oi.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=zl.ALTER_USER_DUP_ROLES(t.role);throw $e.error(c),yi(new Error,c,Oi.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 AM.update(n)}catch(i){throw $e.error("Error during update."),$e.error(i),i}try{await Jl()}catch(i){throw $e.error("Got an error setting users to global"),$e.error(i),i}return NA.signalUserChange(new wA(process.pid)),s}a(BZ,"alterUser");function HZ(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(HZ,"isClusterUser");async function xZ(e){try{let t=bM.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(kn.isEmpty(global.hdb_users.get(e.username)))throw yi(new Error,zl.USER_NOT_EXIST(e.username),Oi.NOT_FOUND,void 0,void 0,!0);let n;try{n=await UZ(r)}catch(s){throw $e.error("Got an error deleting a user."),$e.error(s),s}$e.debug(n);try{await Jl()}catch(s){throw $e.error("Got an error setting users to global."),$e.error(s),s}return NA.signalUserChange(new wA(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(xZ,"dropUser");async function FZ(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=yA.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await MZ(r)}catch(s){throw $e.error("Got an error searching for a role."),$e.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw $e.error(r),r}return t}a(FZ,"userInfo");async function kZ(){let e;try{e=await mp()}catch(t){throw $e.error("Got an error listing users."),$e.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(kZ,"listUsersExternal");async function mp(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await pp(e)}catch(o){throw $e.error("Got an error searching for roles."),$e.error(o),o}let r={};for(let o of t)r[o.id]=yA.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 pp(n)}catch(o){throw $e.error("Got an error searching for users."),$e.error(o),o}let i=new Map;for(let o of s)o=yA.cloneDeep(o),o.role=r[o.role],GZ(o.role),i.set(o.username,o);return i}catch(e){throw $e.error("got an error listing users"),$e.error(e),kn.errorizeMessage(e)}return null}a(mp,"listUsers");function GZ(e){try{if(!e){$e.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(DZ)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){$e.error("Got an error trying to set system permissions."),$e.error(t)}}a(GZ,"appendSystemTablesToRole");async function Jl(){try{let e=await mp();global.hdb_users=e}catch(e){throw $e.error(e),e}}a(Jl,"setUsersToGlobal");async function IM(e,t,r=!0){global.hdb_users||await Jl();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw yi(new Error,bA.GENERIC_AUTH_FAIL,Oi.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw yi(new Error,bA.USER_INACTIVE,Oi.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(pM.get(t)===n.password)return s;if(OA.validate(n.password,t))pM.set(t,n.password);else throw yi(new Error,bA.GENERIC_AUTH_FAIL,Oi.UNAUTHORIZED,void 0,void 0,!0)}return s}a(IM,"findAndValidateUser");async function qZ(){global.hdb_users||await Jl();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(qZ,"getSuperUser");async function $Z(){let e=await mp(),t=CZ.getConfigFromFile(EM.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!kn.isEmpty(r)&&r?.role?.role===EM.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=IA.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+hM.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+hM.SERVER_SUFFIX.ADMIN,r}a($Z,"getClusterUser");var wM=[];CA.invalidateUser=function(e){for(let t of wM)try{t(e)}catch(r){LZ.error("Error invalidating user",r)}};CA.onInvalidatedUser=function(e){wM.push(e)}});var P_=y((nye,MM)=>{"use strict";var Ac=V(),Gn=M(),VZ=aL(),tye=_s(),rye=uo(),YZ=_n(),{validateEvent:DM}=Qs(),D_=Hn(),KZ=require("process"),{resetDatabases:WZ}=(De(),ne(at)),jZ={[Gn.ITC_EVENT_TYPES.SCHEMA]:QZ,[Gn.ITC_EVENT_TYPES.USER]:LM};async function QZ(e){let t=DM(e);if(t){Ac.error(t);return}Ac.trace("ITC schemaHandler received schema event:",e),await VZ(e.message),await zZ(e.message)}a(QZ,"schemaHandler");async function zZ(e){try{D_.resetReadTxn(Gn.SYSTEM_SCHEMA_NAME,Gn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),D_.resetReadTxn(Gn.SYSTEM_SCHEMA_NAME,Gn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),D_.resetReadTxn(Gn.SYSTEM_SCHEMA_NAME,Gn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=WZ();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Ac.error(t)}}a(zZ,"syncSchemaMetadata");var PM=[];async function LM(e){try{try{D_.resetReadTxn(Gn.SYSTEM_SCHEMA_NAME,Gn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),D_.resetReadTxn(Gn.SYSTEM_SCHEMA_NAME,Gn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Ac.warn(r)}let t=DM(e);if(t){Ac.error(t);return}Ac.trace(`ITC userHandler ${Gn.HDB_ITC_CLIENT_PREFIX}${KZ.pid} received user event:`,e),await YZ.setUsersToGlobal();for(let r of PM)r()}catch(t){Ac.error(t)}}a(LM,"userHandler");LM.addListener=function(e){PM.push(e)};MM.exports=jZ});var Qs=y((lye,vM)=>{"use strict";var iye=V(),DA=ee(),JZ=M(),{ITC_ERRORS:L_}=Ln(),{parentPort:oye,threadId:XZ,isMainThread:ZZ,workerData:aye}=require("worker_threads"),{onMessageFromWorkers:e5,broadcast:cye,broadcastWithAcknowledgement:t5}=ut();vM.exports={sendItcEvent:r5,validateEvent:UM,SchemaEventMsg:n5,UserEventMsg:s5};var Sp;e5(async(e,t)=>{Sp=Sp||P_(),UM(e),Sp[e.type]&&await Sp[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function r5(e){return!ZZ&&e.message&&(e.message.originator=XZ),t5(e)}a(r5,"sendItcEvent");function UM(e){if(typeof e!="object")return L_.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||DA.isEmpty(e.type))return L_.MISSING_TYPE;if(!e.hasOwnProperty("message")||DA.isEmpty(e.message))return L_.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||DA.isEmpty(e.message.originator))return L_.MISSING_ORIGIN;if(JZ.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return L_.INVALID_EVENT(e.type)}a(UM,"validateEvent");function n5(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(n5,"SchemaEventMsg");function s5(e){this.originator=e}a(s5,"UserEventMsg")});var _o=y((_ye,FM)=>{"use strict";var BM=M(),dye=ee(),Tp=V(),HM=sL(),Xl,{sendItcEvent:xM}=Qs();function i5(e){try{Tp.info("signalSchemaChange called with message:",e),Xl=Xl||P_();let t=new HM(BM.ITC_EVENT_TYPES.SCHEMA,e);return Xl.schema(t),xM(t)}catch(t){Tp.error(t)}}a(i5,"signalSchemaChange");function o5(e){try{Tp.trace("signalUserChange called with message:",e),Xl=Xl||P_();let t=new HM(BM.ITC_EVENT_TYPES.USER,e);return Xl.user(t),xM(t)}catch(t){Tp.error(t)}}a(o5,"signalUserChange");FM.exports={signalSchemaChange:i5,signalUserChange:o5}});var gp=y((Eye,GM)=>{"use strict";var kM=ee(),a5=M(),c5=V(),l5=zh(),u5=Qh(),d5=_o(),{SchemaEventMsg:_5}=Qs(),f5="already exists in";GM.exports=E5;async function E5(e,t,r){if(kM.isEmptyOrZeroLength(r))return r;let n=[];kM.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 h5(e,t.schema,t.name,i)})),s}a(E5,"lmdbCheckForNewAttributes");async function h5(e,t,r,n){let s=new u5(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await p5(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(f5))c5.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(h5,"createNewAttribute");async function p5(e){let t;return t=await l5(e),d5.signalSchemaChange(new _5(process.pid,a5.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(p5,"createAttribute")});var Zl=y((pye,qM)=>{"use strict";var PA=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}};qM.exports=PA});var VM=y((Sye,$M)=>{"use strict";var m5=Zl(),S5=M().OPERATIONS_ENUM,LA=class extends m5{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(S5.INSERT,r,n,s,i),this.records=t}};$M.exports=LA});var KM=y((gye,YM)=>{"use strict";var T5=Zl(),g5=M().OPERATIONS_ENUM,MA=class extends T5{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(g5.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};YM.exports=MA});var jM=y((Aye,WM)=>{"use strict";var R5=Zl(),A5=M().OPERATIONS_ENUM,UA=class extends R5{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(A5.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};WM.exports=UA});var zM=y((yye,QM)=>{"use strict";var b5=Zl(),y5=M().OPERATIONS_ENUM,vA=class extends b5{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(y5.DELETE,n,s,t,i),this.original_records=r}};QM.exports=vA});var M_=y((Iye,eU)=>{"use strict";var Nye=require("path"),JM=_t(),O5=VM(),N5=KM(),I5=jM(),w5=zM(),eu=Bt(),XM=ee(),{CONFIG_PARAMS:C5}=M(),ZM=te();ZM.initSync();var Rp=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:D5}=mt();eU.exports=P5;async function P5(e,t){if(ZM.get(C5.LOGGING_AUDITLOG)===!1)return;let r=D5(e.schema,e.table),n=await JM.openEnvironment(r,e.table,!0),s=L5(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){JM.initializeDBIs(n,eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,eu.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),XM.isEmpty(s.user_name)||n.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(P5,"writeTransaction");function L5(e,t){let r=XM.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===Rp.INSERT)return new O5(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Rp.UPDATE)return new N5(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Rp.UPSERT)return new I5(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Rp.DELETE)return new w5(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(L5,"createTransactionObject")});var BA=y((Dye,tU)=>{"use strict";var M5=b_(),Cye=y_(),U_=M(),U5=O_(),v5=dc().insertRecords,B5=_t(),H5=V(),x5=gp(),{getSchemaPath:F5}=mt(),k5=M_();tU.exports=G5;async function G5(e){try{let{schema_table:t,attributes:r}=M5(e);U5(e,r,t.hash_attribute),e.schema!==U_.SYSTEM_SCHEMA_NAME&&(r.includes(U_.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(U_.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(U_.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(U_.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await x5(e.hdb_auth_header,t,r),s=F5(e.schema,e.table),i=await B5.openEnvironment(s,e.table),o=await v5(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await k5(e,o)}catch(c){H5.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(G5,"lmdbCreateRecords")});var sU=y((Lye,nU)=>{"use strict";var rU=M(),q5=BA(),$5=y_(),V5=require("fs-extra"),{getSchemaPath:Y5}=mt();nU.exports=K5;async function K5(e){let t=[{name:e.schema,createddate:Date.now()}],r=new $5(rU.SYSTEM_SCHEMA_NAME,rU.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await q5(r),await V5.mkdirp(Y5(e.schema))}a(K5,"lmdbCreateSchema")});var oU=y((Uye,iU)=>{"use strict";var HA=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}};iU.exports=HA});var uU=y((Fye,lU)=>{"use strict";var aU=_t(),xA=an(),FA=Ln().LMDB_ERRORS_ENUM,W5=Bt(),cU=V(),Bye=ee(),j5=require("lmdb"),Q5=oU(),z5=M(),{OVERFLOW_MARKER:Hye,MAX_SEARCH_KEY_LENGTH:xye}=W5,J5=z5.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function X5(e,t,r,n){if(xA.validateEnv(e),t===void 0)throw new Error(FA.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(FA.IDS_REQUIRED):new Error(FA.IDS_MUST_BE_ITERABLE);try{let s=aU.listDBIs(e);aU.initializeDBIs(e,t,s);let i=new Q5,o,c=[],l=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[J5]>n){i.skipped.push(o);continue}let S=e.dbis[t].ifVersion(o,j5.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let T=0;T<s.length;T++){let g=s[T];if(!h.hasOwnProperty(g)||g===t)continue;let m=e.dbis[g],C=h[g];if(C!=null)try{let O=xA.getIndexedValues(C);if(O)for(let x=0,F=O.length;x<F;x++)m.remove(O[x],o)}catch{cU.warn(`cannot delete from attribute: ${g}, ${C}:${o}`)}}});c.push(S),l.push(o),i.original_records.push(h)}catch(h){cU.warn(h),i.skipped.push(o)}let d=[],u=await Promise.all(c);for(let E=0,f=u.length;E<f;E++)u[E]===!0?i.deleted.push(l[E]):(i.skipped.push(l[E]),d.push(E));let _=0;for(let E=0;E<d.length;E++){let f=d[E];i.original_records.splice(f-_,1),_++}return i.txn_time=xA.getNextMonotonicTime(),i}catch(s){throw s}}a(X5,"deleteRecords");lU.exports={deleteRecords:X5}});var v_=y((Gye,_U)=>{"use strict";var tu=ee(),Z5=uU(),e6=_t(),{getSchemaPath:t6}=mt(),r6=M_(),n6=V();_U.exports=s6;async function s6(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(tu.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(tu.isEmptyOrZeroLength(e.hash_values)&&!tu.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let l=e.records[c][n];tu.isEmpty(l)||e.hash_values.push(l)}}if(tu.isEmptyOrZeroLength(e.hash_values))return dU([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(tu.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=t6(e.schema,e.table),i=await e6.openEnvironment(s,e.table),o=await Z5.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await r6(e,o)}catch(c){n6.error(`unable to write transaction due to ${c.message}`)}return dU(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(s6,"lmdbDeleteRecords");function dU(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(dU,"createDeleteResponse")});var GA=y((Vye,fU)=>{"use strict";var i6=M(),$ye=an();function kA(e,t){let r=Object.create(null);if(t.length===1&&i6.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(kA,"parseRow");function o6(e,t,r,n){let s=kA(r,e);n.push(s)}a(o6,"searchAll");function a6(e,t,r,n){let s=kA(r,e);n[t]=s}a(a6,"searchAllToMap");function c6(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(c6,"iterateDBI");function bc(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(bc,"pushResults");function l6(e,t,r,n,s,i){t.toString().endsWith(e)&&bc(t,r,n,s,i)}a(l6,"endsWith");function u6(e,t,r,n,s,i){t.toString().includes(e)&&bc(t,r,n,s,i)}a(u6,"contains");function d6(e,t,r,n,s,i){t>e&&bc(t,r,n,s,i)}a(d6,"greaterThanCompare");function _6(e,t,r,n,s,i){t>=e&&bc(t,r,n,s,i)}a(_6,"greaterThanEqualCompare");function f6(e,t,r,n,s,i){t<e&&bc(t,r,n,s,i)}a(f6,"lessThanCompare");function E6(e,t,r,n,s,i){t<=e&&bc(t,r,n,s,i)}a(E6,"lessThanEqualCompare");fU.exports={parseRow:kA,searchAll:o6,searchAllToMap:a6,iterateDBI:c6,endsWith:l6,contains:u6,greaterThanCompare:d6,greaterThanEqualCompare:_6,lessThanCompare:f6,lessThanEqualCompare:E6,pushResults:bc}});var ru=y((Qye,gU)=>{"use strict";var aa=_t(),Kye=V(),qn=an(),Ap=Bt(),jt=Ln().LMDB_ERRORS_ENUM,Wye=ee(),h6=M(),bp=GA(),{parseRow:p6}=bp,jye=require("lmdb"),{OVERFLOW_MARKER:EU,MAX_SEARCH_KEY_LENGTH:m6}=Ap;function hU(e,t,r,n=!1,s=void 0,i=void 0){return yc(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(hU,"iterateFullIndex");function B_(e,t,r,n,s,i=!1,o=void 0,c=void 0,l=!1,d=!1){return yc(e,t,r,(u,_,E,f)=>{let m={transaction:u,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!l:!d,exclusiveStart:i===!0?d:l};return f===r?(m.values=!1,_.getRange(m).map(C=>({value:C}))):_.getRange(m)})}a(B_,"iterateRangeBetween");function yc(e,t,r,n){let s=e.database||e,i=aa.openDBI(s,r);i[Ap.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&aa.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(yc,"setupTransaction");function pU(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(EU)){if(!s)if(r)s=aa.openDBI(e,r);else{let l=aa.listDBIs(e);for(let d=0,u=l.length;d<u&&(s=aa.openDBI(e,l[d]),!s[Ap.DBI_DEFINITION_NAME].is_hash_attribute);d++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(pU,"getOverflowCheck");function S6(e,t,r,n=!1,s=void 0,i=void 0){if(qn.validateEnv(e),t===void 0)throw new Error(jt.HASH_ATTRIBUTE_REQUIRED);return yc(e,t,t,(o,c,l)=>(yp(r),r=H_(l,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(d=>p6(d.value,r))))}a(S6,"searchAll");function T6(e,t,r,n=!1,s=void 0,i=void 0){if(qn.validateEnv(e),t===void 0)throw new Error(jt.HASH_ATTRIBUTE_REQUIRED);yp(r),r=H_(e.database||e,r);let o=new Map;for(let{key:c,value:l}of hU(e,t,t,n,s,i))o.set(c,bp.parseRow(l,r));return o}a(T6,"searchAllToMap");function g6(e,t,r=!1,n=void 0,s=void 0){if(qn.validateEnv(e),t===void 0)throw new Error(jt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=hU(e,void 0,t,r,n,s),c=o.transaction,l=pU(c.database,c,void 0,t);for(let{key:d,value:u}of o){let _=l(d,u);i[_]===void 0&&(i[_]=[]),i[_].push(u)}return i}a(g6,"iterateDBI");function R6(e,t){if(qn.validateEnv(e),t===void 0)throw new Error(jt.HASH_ATTRIBUTE_REQUIRED);return aa.statDBI(e,t).entryCount}a(R6,"countAll");function A6(e,t,r,n,s=!1,i=void 0,o=void 0){return ca(e,r,n),yc(e,t,r,(c,l,d,u)=>(n=qn.convertKeyValueToWrite(n),u===r?l.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:l.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(_=>({key:n,value:_}))))}a(A6,"equals");function b6(e,t,r){return ca(e,t,r),aa.openDBI(e,t).getValuesCount(r)}a(b6,"count");function y6(e,t,r,n,s=!1,i=void 0,o=void 0){return ca(e,r,n),yc(e,null,r,(c,l)=>{n=qn.convertKeyValueToWrite(n);let d=!0;typeof n=="number"&&(d=!1);let u;if(s===!0){let _;for(let E of l.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){_=E;break}return _!==void 0&&(Number.isInteger(o)?o++:i++),u=l.getRange({transaction:c,start:_,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==_){if(f.toString().startsWith(n))return E;if(d===!0)return u.DONE}}),u.filter(E=>E)}else return u=l.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(_=>{if(_.key.toString().startsWith(n))return _;if(d===!0)return u.DONE}),d?u:u.filter(_=>_)})}a(y6,"startsWith");function O6(e,t,r,n,s=!1,i=void 0,o=void 0){return mU(e,t,r,n,s,i,o,!0)}a(O6,"endsWith");function mU(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ca(e,r,n),yc(e,null,r,(l,d,u,_)=>{let E=pU(u,l,_,r);return o=Number.isInteger(o)?o:0,d.getKeys({transaction:l,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(EU)?d.getValues(f,{transaction:l}).map(S=>{let T=E(f,S);if(c?T.endsWith(n):T.includes(n))return{key:T,value:S}}).filter(S=>S):(c?h.endsWith(n):h.includes(n))?d[Ap.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:d.getValues(f,{transaction:l}).map(S=>({key:f,value:S})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(mU,"contains");function N6(e,t,r,n,s=!1,i=void 0,o=void 0){ca(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),B_(e,t,r,n,l,s,i,o,!0,!1)}a(N6,"greaterThan");function I6(e,t,r,n,s=!1,i=void 0,o=void 0){ca(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),B_(e,t,r,n,l,s,i,o,!1,!1)}a(I6,"greaterThanEqual");function w6(e,t,r,n,s=!1,i=void 0,o=void 0){ca(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),B_(e,t,r,l,n,s,i,o,!1,!0)}a(w6,"lessThan");function C6(e,t,r,n,s=!1,i=void 0,o=void 0){ca(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),B_(e,t,r,l,n,s,i,o,!1,!1)}a(C6,"lessThanEqual");function D6(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(qn.validateEnv(e),r===void 0)throw new Error(jt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(jt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(jt.END_VALUE_REQUIRED);if(n=qn.convertKeyValueToWrite(n),s=qn.convertKeyValueToWrite(s),n>s)throw new Error(jt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return B_(e,t,r,n,s,i,o,c)}a(D6,"between");function P6(e,t,r,n){qn.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(jt.HASH_ATTRIBUTE_REQUIRED);if(yp(r),r=H_(s,r),n===void 0)throw new Error(jt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=bp.parseRow(c,r)),o}a(P6,"searchByHash");function L6(e,t,r){qn.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(jt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(jt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(L6,"checkHashExists");function M6(e,t,r,n,s=[]){return TU(e,t,r,n,s),SU(e,t,r,n,s).map(i=>i[1])}a(M6,"batchSearchByHash");function U6(e,t,r,n,s=[]){TU(e,t,r,n,s);let i=new Map;for(let[o,c]of SU(e,t,r,n,s))i.set(o,c);return i}a(U6,"batchSearchByHashToMap");function SU(e,t,r,n,s=[]){return yc(e,t,t,(i,o,c)=>{r=H_(c,r);let l=r.length<3;return n.map(d=>{let u=c.dbis[t].get(d,{transaction:i,lazy:l});if(u)return[d,bp.parseRow(u,r)];s.push(d)}).filter(d=>d)})}a(SU,"batchHashSearch");function TU(e,t,r,n,s){if(qn.validateEnv(e),t===void 0)throw new Error(jt.HASH_ATTRIBUTE_REQUIRED);if(yp(r),n==null)throw new Error(jt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(jt.IDS_MUST_BE_ITERABLE)}a(TU,"initializeBatchSearchByHash");function yp(e){if(!Array.isArray(e))throw e===void 0?new Error(jt.FETCH_ATTRIBUTES_REQUIRED):new Error(jt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(yp,"validateFetchAttributes");function ca(e,t,r){if(qn.validateEnv(e),t===void 0)throw new Error(jt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(jt.SEARCH_VALUE_REQUIRED);if(r?.length>m6)throw new Error(jt.SEARCH_VALUE_TOO_LARGE)}a(ca,"validateComparisonFunctions");function H_(e,t){return t.length===1&&h6.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=aa.listDBIs(e)),t}a(H_,"setGetWholeRowAttributes");gU.exports={searchAll:S6,searchAllToMap:T6,count:b6,countAll:R6,equals:A6,startsWith:y6,endsWith:O6,contains:mU,searchByHash:P6,setGetWholeRowAttributes:H_,batchSearchByHash:M6,batchSearchByHashToMap:U6,checkHashExists:L6,iterateDBI:g6,greaterThan:N6,greaterThanEqual:I6,lessThan:w6,lessThanEqual:C6,between:D6}});var nu=y((Jye,OU)=>{var RU=require("lodash"),AU=St(),Be=require("joi"),v6=ee(),{hdb_schema_table:x_,checkValidTable:bU,hdb_table:yU,hdb_database:Op}=Ri(),{handleHDBError:B6,hdb_errors:H6}=ce(),{getDatabases:x6}=(De(),ne(at)),{HTTP_STATUS_CODES:F6}=H6,k6=Be.object({database:Op,schema:Op,table:yU,search_attribute:x_,search_value:Be.any().required(),get_attributes:Be.array().min(1).items(Be.alternatives(x_,Be.object())).optional(),desc:Be.bool(),limit:Be.number().integer().min(1),offset:Be.number().integer().min(0)}),G6=Be.object({database:Op,schema:Op,table:yU,operator:Be.string().valid("and","or").default("and").lowercase(),offset:Be.number().integer().min(0),limit:Be.number().integer().min(1),get_attributes:Be.array().min(1).items(Be.alternatives(x_,Be.object())).optional(),sort:Be.object({attribute:Be.alternatives(x_,Be.array().min(1)),descending:Be.bool().optional()}).optional(),conditions:Be.array().min(1).items(Be.alternatives(Be.object({operator:Be.string().valid("and","or").default("and").lowercase(),conditions:Be.array()}),Be.object({search_attribute:Be.alternatives(x_,Be.array().min(1)),search_type:Be.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:Be.when("search_type",{switch:[{is:"equals",then:Be.any()},{is:"between",then:Be.array().items(Be.alternatives([Be.string(),Be.number()])).length(2)}],otherwise:Be.alternatives(Be.string(),Be.number())}).required()}))).required()});OU.exports=function(e,t){let r=null;switch(t){case"value":r=AU.validateBySchema(e,k6);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(bU("database",e.schema)),i(bU("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=AU.validateBySchema(e,G6);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=v6.checkGlobalSchemaTable(e.schema,e.table);if(s)return B6(new Error,s,F6.NOT_FOUND);let o=x6()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let l=a(u=>{for(let _=0,E=u.conditions.length;_<E;_++){let f=u.conditions[_];f.conditions?l(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&l(e);let d=RU.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!Array.isArray(u)&&!u.name&&!RU.some(o,_=>_===u||_.attribute===u||_.attribute===u.attribute));if(d&&d.length>0){let u=d.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var qA=y((Zye,NU)=>{"use strict";var q6=_t(),$6=nu(),{getSchemaPath:V6}=mt();NU.exports=Y6;function Y6(e){let t=$6(e,"hashes");if(t)throw t;let r=V6(e.schema,e.table);return q6.openEnvironment(r,e.table)}a(Y6,"initialize")});var $A=y((tOe,IU)=>{"use strict";var K6=ru(),W6=qA();IU.exports=j6;async function j6(e){let t=await W6(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return K6.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(j6,"lmdbGetDataByHash")});var su=y((nOe,wU)=>{"use strict";var VA=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};wU.exports=VA});var DU=y((oOe,CU)=>{"use strict";var iOe=su(),Q6=ru(),z6=qA();CU.exports=J6;async function J6(e){let t=await z6(e),r=global.hdb_schema[e.schema][e.table];return Q6.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(J6,"lmdbSearchByHash")});var zs=y((cOe,PU)=>{"use strict";var YA=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,l=!1,d=void 0,u=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=l,this.limit=d,this.offset=u}};PU.exports=YA});var Np=y((uOe,HU)=>{"use strict";var Xr=ru(),X6=_t(),Z6=ee(),He=Bt(),Oc=M(),e8=ao(),LU=Ln().LMDB_ERRORS_ENUM,{getSchemaPath:t8}=mt(),fo=Oc.SEARCH_WILDCARDS;async function r8(e,t,r){let n;e.schema===Oc.SYSTEM_SCHEMA_NAME?n=e8[e.table]:n=global.hdb_schema[e.schema][e.table];let s=BU(e,n.hash_attribute,r,t);return UU(e,s,n.hash_attribute,r)}a(r8,"prepSearch");async function UU(e,t,r,n){let s=t8(e.schema,e.table),i=await X6.openEnvironment(s,e.table),o=vU(i,e,t,r),c=o.transaction||i;if([He.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,He.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,He.SEARCH_TYPES.SEARCH_ALL,He.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(n8(e,r)===!1){let u=e.search_attribute;if(u===r)return n?MU(o,()=>!0):o.map(E=>({[r]:E.key}));let _=a(E=>({[r]:E.value,[u]:E.key}),"toObject");return n?MU(o,_):o.map(_)}let d=e.search_attribute===r?o.map(u=>u.key):o.map(u=>u.value);return n===!0?Xr.batchSearchByHashToMap(c,r,e.get_attributes,d):Xr.batchSearchByHash(c,r,e.get_attributes,d)}a(UU,"executeSearch");function vU(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:l}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,l=Number.isInteger(l)?l:void 0,r){case He.SEARCH_TYPES.EQUALS:s=Xr.equals(e,i,t.search_attribute,t.search_value,o,c,l);break;case He.SEARCH_TYPES.CONTAINS:s=Xr.contains(e,i,t.search_attribute,t.search_value,o,c,l);break;case He.SEARCH_TYPES.ENDS_WITH:case He.SEARCH_TYPES._ENDS_WITH:s=Xr.endsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case He.SEARCH_TYPES.STARTS_WITH:case He.SEARCH_TYPES._STARTS_WITH:s=Xr.startsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case He.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Xr.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case He.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Xr.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case He.SEARCH_TYPES.SEARCH_ALL:return Xr.searchAll(e,n,t.get_attributes,o,c,l);case He.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Xr.searchAllToMap(e,n,t.get_attributes,o,c,l);case He.SEARCH_TYPES.BETWEEN:s=Xr.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,l);break;case He.SEARCH_TYPES.GREATER_THAN:case He.SEARCH_TYPES._GREATER_THAN:s=Xr.greaterThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case He.SEARCH_TYPES.GREATER_THAN_EQUAL:case He.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Xr.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;case He.SEARCH_TYPES.LESS_THAN:case He.SEARCH_TYPES._LESS_THAN:s=Xr.lessThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case He.SEARCH_TYPES.LESS_THAN_EQUAL:case He.SEARCH_TYPES._LESS_THAN_EQUAL:s=Xr.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;default:return Object.create(null)}return s}a(vU,"searchByType");function MU(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(MU,"createMapFromIterable");function n8(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(n8,"checkToFetchMore");function BU(e,t,r,n){if(Z6.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),fo.indexOf(s)>-1)return r===!0?He.SEARCH_TYPES.SEARCH_ALL_TO_MAP:He.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(fo[0])<0&&s.indexOf(fo[1])<0)return c===!0?r===!0?He.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:He.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:He.SEARCH_TYPES.EQUALS;if(fo.indexOf(i)>=0&&fo.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),He.SEARCH_TYPES.CONTAINS;if(fo.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),He.SEARCH_TYPES.ENDS_WITH;if(fo.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),He.SEARCH_TYPES.STARTS_WITH;if(s.includes(fo[0])||s.includes(fo[1]))return He.SEARCH_TYPES.EQUALS;throw new Error(LU.UNKNOWN_SEARCH_TYPE)}else switch(n){case Oc.VALUE_SEARCH_COMPARATORS.BETWEEN:return He.SEARCH_TYPES.BETWEEN;case Oc.VALUE_SEARCH_COMPARATORS.GREATER:return He.SEARCH_TYPES.GREATER_THAN;case Oc.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return He.SEARCH_TYPES.GREATER_THAN_EQUAL;case Oc.VALUE_SEARCH_COMPARATORS.LESS:return He.SEARCH_TYPES.LESS_THAN;case Oc.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return He.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(LU.UNKNOWN_SEARCH_TYPE)}}a(BU,"createSearchTypeFromSearchObject");HU.exports={executeSearch:UU,createSearchTypeFromSearchObject:BU,prepSearch:r8,searchByType:vU}});var FU=y((fOe,xU)=>{"use strict";var _Oe=zs(),s8=nu(),i8=ee(),o8=M(),a8=Np();xU.exports=c8;function c8(e,t){if(!i8.isEmpty(t)&&o8.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=s8(e,"value");if(n)throw n;return a8.prepSearch(e,t,!0)}a(c8,"lmdbGetDataByValue")});var F_=y((pOe,kU)=>{"use strict";var hOe=zs(),l8=nu(),u8=ee(),d8=M(),_8=Np();kU.exports=f8;async function f8(e,t){if(!u8.isEmpty(t)&&d8.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=l8(e,"value");if(n)throw n;return _8.prepSearch(e,t,!1)}a(f8,"lmdbSearchByValue")});var qU=y((TOe,GU)=>{"use strict";var SOe=Bt(),KA=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}},WA=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},jA=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};GU.exports={SearchByConditionsObject:KA,SearchCondition:WA,SortAttribute:jA}});var WU=y((bOe,KU)=>{"use strict";var ROe=qU().SearchByConditionsObject,E8=zs(),h8=nu(),QA=ru(),Ip=Bt(),{Resource:AOe}=(ls(),ne(zA)),YU=Np(),p8=GA(),m8=require("lodash"),{getSchemaPath:S8}=mt(),$U=_t(),{handleHDBError:T8,hdb_errors:g8}=ce(),{HTTP_STATUS_CODES:R8}=g8,A8=1e8;KU.exports=b8;async function b8(e){let t=h8(e,"conditions");if(t)throw T8(t,t.message,R8.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=S8(e.schema,e.table),n=await $U.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let d of e.conditions)$U.openDBI(n,d.search_attribute);let i=m8.sortBy(e.conditions,d=>{if(d.estimated_count===void 0){let u=d.search_type;u===Ip.SEARCH_TYPES.EQUALS?d.estimated_count=QA.count(n,d.search_attribute,d.search_value):u===Ip.SEARCH_TYPES.CONTAINS||u===Ip.SEARCH_TYPES.ENDS_WITH?d.estimated_count=1/0:d.estimated_count=A8}return d.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await VU(o,e,i[0],s.hash_attribute),l;if(!e.operator||e.operator.toLowerCase()==="and"){let d=n.dbis[s.hash_attribute],u=i.slice(1).map(YU.filterByType),_=u.length,E=QA.setGetWholeRowAttributes(n,e.get_attributes);l=c.map(f=>d.get(f,{transaction:o,lazy:!0})),_>0&&(l=l.filter(f=>{for(let h=0;h<_;h++)if(!u[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(l=l.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),l=l.map(f=>p8.parseRow(f,E))}else{for(let _=1;_<i.length;_++){let E=i[_],f=await VU(o,e,E,s.hash_attribute);c=c.concat(f)}let d=new Set,u=e.offset||0;c=c.filter(_=>d.has(_)?!1:(d.add(_),!0)).slice(u,e.limit&&e.limit+u),l=QA.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return l.onDone=()=>{o.done()},l}a(b8,"lmdbSearchByConditions");async function VU(e,t,r,n){let s=new E8(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===Ip.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,YU.searchByType(e,s,i,n).map(o=>o.value)}a(VU,"executeConditionSearch")});var k_=y((OOe,jU)=>{"use strict";var y8=M().OPERATIONS_ENUM,JA=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=y8.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};jU.exports=JA});var XA=y((IOe,rv)=>{"use strict";var XU=zs(),ZU=k_(),ev=F_(),tv=v_(),fn=M(),QU=ee(),zU=_t(),{getTransactionAuditStorePath:O8,getSchemaPath:N8}=mt(),JU=V();rv.exports=I8;async function I8(e){try{if(QU.isEmpty(global.hdb_schema[e.schema])||QU.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await w8(e),await C8(e);let t=N8(e.schema,e.table);try{await zU.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")JU.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=O8(e.schema,e.table);await zU.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")JU.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(I8,"lmdbDropTable");async function w8(e){let t=new XU(fn.SYSTEM_SCHEMA_NAME,fn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,fn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[fn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await ev(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 ZU(fn.SYSTEM_SCHEMA_NAME,fn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await tv(s)}a(w8,"deleteAttributesFromSystem");async function C8(e){let t=new XU(fn.SYSTEM_SCHEMA_NAME,fn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,fn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[fn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,fn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,fn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await ev(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 ZU(fn.SYSTEM_SCHEMA_NAME,fn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await tv(s)}catch(i){throw i}}a(C8,"dropTableFromSystem")});var sv=y((COe,nv)=>{"use strict";var D8=require("fs-extra"),P8=zs(),L8=su(),M8=k_(),U8=XA(),v8=v_(),B8=$A(),H8=F_(),Eo=M(),{getSchemaPath:x8}=mt(),{handleHDBError:F8,hdb_errors:k8}=ce(),{HDB_ERROR_MSGS:G8,HTTP_STATUS_CODES:q8}=k8;nv.exports=$8;async function $8(e){let t;try{t=await V8(e.schema);let r=new P8(Eo.SYSTEM_SCHEMA_NAME,Eo.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Eo.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Eo.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await H8(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await U8(c)}catch(l){if(l.message!=="invalid environment")throw l}}let s=new M8(Eo.SYSTEM_SCHEMA_NAME,Eo.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await v8(s);let i=x8(t);await D8.remove(i)}catch(r){throw r}}a($8,"lmdbDropSchema");async function V8(e){let t=new L8(Eo.SYSTEM_SCHEMA_NAME,Eo.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Eo.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await B8(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw F8(new Error,G8.SCHEMA_NOT_FOUND(e),q8.NOT_FOUND,void 0,void 0,!0);return n}a(V8,"validateDropSchema")});var G_=y((POe,iv)=>{"use strict";var ZA=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};iv.exports=ZA});var tb=y((UOe,ov)=>{"use strict";var Y8=require("fs-extra"),wp=_t(),{getTransactionAuditStorePath:K8}=mt(),eb=Bt(),MOe=G_();ov.exports=W8;async function W8(e){let t;try{let r=K8(e.schema,e.table);await Y8.mkdirp(r),t=await wp.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{wp.createDBI(t,eb.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),wp.createDBI(t,eb.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),wp.createDBI(t,eb.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(W8,"createTransactionsAuditEnvironment")});var lv=y((HOe,cv)=>{"use strict";var rb=M(),av=_t(),j8=dc(),{getSystemSchemaPath:Q8,getSchemaPath:z8}=mt(),BOe=ao(),J8=zh(),nb=Qh(),X8=V(),Z8=tb();cv.exports=e9;async function e9(e,t){let r=z8(t.schema,t.table),n=new nb(t.schema,t.table,rb.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new nb(t.schema,t.table,rb.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new nb(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await av.createEnvironment(r,t.table),e!==void 0){let o=await av.openEnvironment(Q8(),rb.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await j8.insertRecords(o,HDB_TABLE_INFO.hash_attribute,hdb_table_attributes,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await sb(n),await sb(s),await sb(i)}await Z8(t)}catch(o){throw o}}a(e9,"lmdbCreateTable");async function sb(e){try{await J8(e)}catch(t){X8.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(sb,"createAttribute")});var dv=y((FOe,uv)=>{"use strict";var t9=b_(),r9=O_(),n9=gp(),q_=M(),s9=dc().updateRecords,i9=_t(),{getSchemaPath:o9}=mt(),a9=M_(),c9=V();uv.exports=l9;async function l9(e){try{let{schema_table:t,attributes:r}=t9(e);r9(e,r,t.hash_attribute),e.schema!==q_.SYSTEM_SCHEMA_NAME&&(r.includes(q_.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(q_.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(q_.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(q_.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await n9(e.hdb_auth_header,t,r),s=o9(e.schema,e.table),i=await i9.openEnvironment(s,e.table),o=await s9(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await a9(e,o)}catch(c){c9.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(l9,"lmdbUpdateRecords")});var fv=y((GOe,_v)=>{"use strict";var u9=M().OPERATIONS_ENUM,ib=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=u9.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};_v.exports=ib});var hv=y((VOe,Ev)=>{"use strict";var $Oe=fv(),d9=b_(),_9=O_(),f9=gp(),$_=M(),E9=dc().upsertRecords,h9=_t(),{getSchemaPath:p9}=mt(),m9=M_(),S9=V(),{handleHDBError:T9,hdb_errors:g9}=ce();Ev.exports=R9;async function R9(e){let t;try{t=d9(e)}catch(l){throw T9(l,l.message,g9.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;_9(e,n,r.hash_attribute),e.schema!==$_.SYSTEM_SCHEMA_NAME&&(n.includes($_.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push($_.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes($_.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push($_.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await f9(e.hdb_auth_header,r,n),i=p9(e.schema,e.table),o=await h9.openEnvironment(i,e.table),c=await E9(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await m9(e,c)}catch(l){S9.error(`unable to write transaction due to ${l.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(R9,"lmdbUpsertRecords")});var mv=y((KOe,pv)=>{"use strict";var ob=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};pv.exports=ob});var Tv=y((jOe,Sv)=>{"use strict";var ab=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}};Sv.exports=ab});var Av=y((JOe,Rv)=>{"use strict";var cb=_t(),{getTransactionAuditStorePath:A9}=mt(),zOe=mv(),V_=Bt(),b9=ee(),gv=Tv(),y9=require("util").promisify,O9=y9(setTimeout),N9=1e4,I9=100;Rv.exports=w9;async function w9(e){let t=A9(e.schema,e.table),r=await cb.openEnvironment(t,e.table,!0),n=cb.listDBIs(r);cb.initializeDBIs(r,V_.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new gv;do s=await C9(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 O9(I9);while(s.transactions_deleted>0);return i}a(w9,"deleteAuditLogsBefore");async function C9(e,t){let r=new gv;try{let n=e.dbis[V_.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[V_.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];b9.isEmpty(c)||(s=e.dbis[V_.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let l=0;l<o.hash_values.length;l++)s=e.dbis[V_.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[l],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>N9)break}return await s,r}catch(n){throw n}}a(C9,"deleteTransactions")});var yv=y((ZOe,bv)=>{"use strict";var lb=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};bv.exports=lb});var Nv=y((rNe,Ov)=>{"use strict";var D9=zs(),P9=k_(),tNe=yv(),Ni=M(),L9=ee(),ub=_t(),M9=ao(),U9=F_(),v9=v_(),{getSchemaPath:B9}=mt();Ov.exports=H9;async function H9(e,t=!0){let r;e.schema===Ni.SYSTEM_SCHEMA_NAME?r=M9[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await F9(e),s=B9(e.schema,e.table),i=await ub.openEnvironment(s,e.table);return t===!0&&await x9(e,i,r.hash_attribute),ub.dropDBI(i,e.attribute),n}a(H9,"lmdbDropAttribute");async function x9(e,t,r){let n=ub.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:l}of n.getRange({start:!1,versions:!0})){let d={};for(let u in c)u!==i&&(d[u]=c[u]);s=t.dbis[r].put(o,d,l)}await s}a(x9,"removeAttributeFromAllObjects");async function F9(e){let t=new D9(Ni.SYSTEM_SCHEMA_NAME,Ni.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Ni.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Ni.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Ni.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await U9(t)).filter(o=>o[Ni.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(L9.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[Ni.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new P9(Ni.SYSTEM_SCHEMA_NAME,Ni.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return v9(i)}a(F9,"dropAttributeFromSystem")});var Lv=y((iNe,Pv)=>{"use strict";var db=_t(),iu=Bt(),sNe=an(),_b=M(),Iv=ee(),{getTransactionAuditStorePath:k9}=mt(),G9=ru(),Cp=Zl(),q9=V();Pv.exports=$9;async function $9(e){let t=k9(e.schema,e.table),r=await db.openEnvironment(t,e.table,!0),n=db.listDBIs(r);db.initializeDBIs(r,iu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case _b.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return wv(r,e.search_values);case _b.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,Y9(r,e.search_values,s);case _b.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return V9(r,e.search_values);default:return wv(r)}}a($9,"readAuditLog");function wv(e,t=[0,Date.now()]){Iv.isEmpty(t[0])&&(t[0]=0),Iv.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[iu.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 Cp,s))}a(wv,"searchTransactionsByTimestamp");function V9(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[iu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,Dv(e,i))}return Object.fromEntries(r)}a(V9,"searchTransactionsByUsername");function Y9(e,t,r){let n=new Map;for(let c=0,l=t.length;c<l;c++){let d=t[c],u=G9.equals(e,iu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,iu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,d);for(let{value:_}of u){let E=Number(_);n.has(E)?n.get(E).push(d.toString()):n.set(E,[d.toString()])}}let s=Array.from(n.keys()),i=Dv(e,s),o=new Map;for(let c=0;c<i.length;c++){let l=i[c],d=l.timestamp,u=n.get(d);Cv(l,"records",r,u,o),Cv(l,"original_records",r,u,o)}return Object.fromEntries(o)}a(Y9,"searchTransactionsByHashValues");function Cv(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],l=c[r].toString();if(n.indexOf(l)>=0)if(s.has(l)){let d=s.get(l),u=d[d.length-1];if(u.timestamp===i)u[t]=[c];else{let _=new Cp(e.operation,e.user_name,i,void 0);_[t]=[c],d.push(_)}}else{let d=new Cp(e.operation,e.user_name,i,void 0);d[t]=[c],s.set(l,[d])}}}a(Cv,"loopRecords");function Dv(e,t){let r=[];try{let n=e.dbis[iu.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 Cp,i);r.push(o)}}catch(i){q9.warn(i)}return r}catch(n){throw n}}a(Dv,"batchSearchTransactions")});var Uv=y((lNe,Mv)=>{"use strict";var{getSchemaPath:aNe}=mt(),cNe=_t(),{database:K9}=(De(),ne(at));Mv.exports={writeTransaction:W9};async function W9(e,t,r){return K9({database:e,table:t}).transaction(r)}a(W9,"writeTransaction")});var xv=y((dNe,Hv)=>{"use strict";var{getSchemaPath:vv}=mt(),Bv=_t();Hv.exports={flush:j9,resetReadTxn:Q9};async function j9(e,t){return(await Bv.openEnvironment(vv(e,t),t.toString())).flushed}a(j9,"flush");async function Q9(e,t){try{(await Bv.openEnvironment(vv(e,t),t.toString())).resetReadTxn()}catch{}}a(Q9,"resetReadTxn")});var qv=y((fNe,Gv)=>{"use strict";var{Readable:z9}=require("stream"),{getDatabases:J9}=(De(),ne(at)),{readSync:X9,openSync:Z9,createReadStream:Fv}=require("fs"),{open:e7}=require("lmdb"),kv=p_(),t7=m_(),{AUDIT_STORE_OPTIONS:r7}=(io(),ne($v)),{INTERNAL_DBIS_NAME:n7,AUDIT_STORE_NAME:s7}=Bt();Gv.exports=o7;var fb=32768,i7=100;async function o7(e){let t=e.database||e.schema||"data",r=J9()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let d=r[s[0]];if(!d)throw new Error(`Can not find table ${s[0]}`);let u=d.dbisDB,_=e7({noSync:!0,maxDbs:t7.MAX_DBS}),E,f=_.openDB(n7,new kv(!1)),h=u.useReadTransaction(),S=0,T=a(async function(m,C){C.encoding="binary",C.encoder=void 0;let O=_.openDB(m,C),x=u.openDB(m,C);for(let{key:F,version:Y,value:$}of x.getRange({start:null,transaction:h,versions:x.useVersions}))E=O.put(F,$,Y),S++%i7===0&&(await new Promise(Z=>setTimeout(Z,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:m,value:C}of u.getRange({transaction:h,start:!1}))if(s.some(O=>m.startsWith?.(O+"/"))){f.put(m,C);let[,O]=m.split("/"),x=!O,F=new kv(!x,x);await T(m,F)}e.include_audit&&await T(s7,{...r7}),await E;let g=Fv(_.path);return g.headers=l(),g.on("close",()=>{h.done(),_.close()}),g}let o=r[Object.keys(r)[0]].primaryStore,c=Z9(o.path);return o.transaction(()=>{let d=Buffer.alloc(fb);X9(c,d,0,fb),o.resetReadTxn();let u=o.useReadTransaction();u.renew();let _=Fv(null,{fd:c,start:fb}),E=new z9.from(async function*(){yield d;for await(let f of _)u.openTimer&&(u.openTimer=0),yield f;u.done()}());return E.headers=l(),E});function l(){let d=new Map;return d.set("content-type","application/octet-stream"),d.set("content-disposition",`attachment; filename="${t}"`),d.set("date",n),d}}a(o7,"getBackup")});var Kv=y((hNe,Yv)=>{"use strict";var a7=V(),{handleHDBError:c7}=ce(),l7=aP(),u7=zh(),d7=BA(),_7=sU(),f7=v_(),E7=$A(),h7=DU(),p7=FU(),m7=F_(),S7=WU(),T7=sv(),g7=lv(),R7=dv(),A7=hv(),b7=Av(),y7=XA(),O7=Nv(),N7=Lv(),I7=Uv(),Vv=xv(),w7=qv(),Eb=class extends l7{static{a(this,"LMDBBridge")}async searchByConditions(t){return S7(t)}async getDataByHash(t){return await E7(t)}async searchByHash(t){return await h7(t)}async getDataByValue(t,r){return await p7(t,r)}async searchByValue(t){return await m7(t)}async createSchema(t){return await _7(t)}async dropSchema(t){return await T7(t)}async createTable(t,r){return await g7(t,r)}async dropTable(t){return await y7(t)}async createAttribute(t){return await u7(t)}async createRecords(t){return await d7(t)}async updateRecords(t){return await R7(t)}async upsertRecords(t){try{return await A7(t)}catch(r){throw c7(r,null,null,a7.ERR,r)}}async deleteRecords(t){return await f7(t)}async dropAttribute(t){return await O7(t)}async deleteAuditLogsBefore(t){return await b7(t)}async readAuditLog(t){return await N7(t)}writeTransaction(t,r,n){return I7.writeTransaction(t,r,n)}flush(t,r){return Vv.flush(t,r)}resetReadTxn(t,r){return Vv.resetReadTxn(t,r)}getBackup(t){return w7(t)}};Yv.exports=Eb});function e0(e){pb=e}function L7(){P7=setInterval(function(){for(let e of hb)if(e.stale){let t=e[xe]?.url;zv.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},D7).unref()}var mb,Qv,zv,Jv,Xv,Zv,Wv,hb,C7,Y_,jv,pb,Nc,Dp,D7,P7,Pp=Ce(()=>{mb=B(an()),Qv=B(ce()),zv=B(V());ls();Jv=B(te()),Xv=B(M()),Zv=B(ee()),Wv=100,hb=new Set,C7=(0,Zv.convertToMS)(Jv.get(Xv.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(e0,"replicationConfirmation");Nc=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;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.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),hb.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(hb.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Y_&&!this.overloadChecked&&performance.now()-jv>C7)throw new Qv.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}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,mb.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let _=this.validated;this.validated=this.writes.length;for(let f=_;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=_;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let S=_;S<this.validated;S++){let T=this.writes[S];if(!T)continue;let g=T[f===0?"before":"beforeIntermediate"];if(g){let m=g();h?h.push?h.push(m):h=[h,m]:h=m}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(_){throw this.abort(),_}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(_=>_);let c=a(_=>{_.commit(r,_.entry,n)},"doWrite"),l=a(()=>{let _=this.writes[o++];if(_)if(_.key){n>0&&(_.entry=_.store.getEntry(_.key));let E=_.store.ifVersion(_.key,_.entry?.version??null,l);s=s||E}else l();else for(let E of this.writes)c(E)},"nextCondition"),d=this.lmdbDb;if(this.writes.length>0&&(d?.retryRisk&&(d.retryRisk*=.99),this.writes.length+(d?.retryRisk||0)<Wv>>n?l():s=this.writes[0].store.transaction(()=>{for(let _ of this.writes)_.entry=_.store.getEntry(_.key),c(_);return!0})),s)return Y_||(Y_=s,jv=performance.now(),Y_.then(()=>{Y_=null})),s.then(_=>{if(_){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let E=this.writes[0].store.rootStore.databaseName,f=this.writes[this.writes.length-1];pb&&f&&i.push(pb(E,f.store.getEntry(f.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return d&&(d.retryRisk=(d.retryRisk||0)+Wv/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let u={txnTime:r};if(this.next){let _=this.next?.commit(t);if(_?.then)return _?.then(E=>({txnTime:r,next:E}));u.next=_}return u}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},Dp=class extends Nc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,mb.getNextMonotonicTime)())}getReadTxn(){}},D7=3e4;a(L7,"startMonitoringTxns");L7()});function wt(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 Nc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n[xe]=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 l=n.commit({letItLinger:r?.letItLinger});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var t0,Ic=Ce(()=>{t0=B(no());ls();Pp();a(wt,"transaction");(0,t0._assignPackageExport)("transaction",wt);wt.commit=function(e){let t=(e[xe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};wt.abort=function(e){let t=(e[xe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var u0={};tt(u0,{ResourceBridge:()=>gb});function Rb({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 n0(e,t){let r=Ii(e),n=Rb(e,r);if(!r)throw new Js.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;wt(i,()=>new Promise(d=>o=d));let c=e.ids||e.hash_values,l=0;return{[Symbol.asyncIterator](){return{async next(){if(l<c.length){let d=c[l++],u=await r.get({id:d,lazy:s,select:n},i);return u=u&&Mp(u),t?{value:{key:d,value:u}}:{value:u}}else return o(),{done:!0}},return(d){return o(),{value:d,done:!0}},throw(d){return o(),{done:!0}}}}}}function Ii(e){let t=e.database||e.schema||U7,r=ft()[t];if(!r)throw(0,Js.handleHDBError)(new Error,M7.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function s0(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*i0(e,t,r,n){let s,i=0;for await(let o of e.getHistory(t,r)){let c=o.operation??o.type;c==="put"&&(c="upsert");let{id:l,version:d,value:u}=o;if(s?.timestamp===d)s.hash_values.push(l),s.records.push(u);else{if(s&&(yield s,i++,n&&n<=i)){s=void 0;break}s={operation:c,user_name:o.user,timestamp:d,hash_values:[l],records:[u]}}}s&&(yield s)}var o0,Lp,Js,a0,c0,Xs,Sb,Tb,l0,M7,U7,v7,B7,r0,gb,d0=Ce(()=>{"use strict";o0=B(Kv()),Lp=B(nu()),Js=B(ce());De();a0=B(b_()),c0=B(O_()),Xs=B(M()),Sb=B(_o()),Tb=B(Qs()),l0=B(ee());Ic();Up();({HDB_ERROR_MSGS:M7}=Js.hdb_errors),U7="data",v7=1e4,B7=10,gb=class extends o0.default{static{a(this,"ResourceBridge")}constructor(t){super(t),r0=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,Lp.default)(t,"conditions");if(r)throw(0,Js.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=Ii(t);if(!n)throw new Js.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:Rb(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 Js.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}]}dt({database:r.database??r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await Ii(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Ii(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,l)=>(c={...c},delete c[n],r.primaryStore.ifVersion(o,l,()=>r.primaryStore.put(o,c,l)).then(d=>{if(!d){let{value:u,version:_}=r.primaryStore.getEntry(o);return i(o,u,_)}})),"deleteRecord");for(let{key:o,value:c,version:l}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,l),await new Promise(d=>setImmediate(d));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Ii(t).dropTable()}createSchema(t){return ou({database:t.schema,table:null}),Sb.signalSchemaChange(new Tb.SchemaEventMsg(process.pid,Xs.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Ab(t.schema),Sb.signalSchemaChange(new Tb.SchemaEventMsg(process.pid,Xs.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,r0.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,a0.default)(t);(0,c0.default)(t,n,r.primaryKey);let s,i=ft()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt,originatingOperation:t.operation};return t.replicateTo&&(o.replicateTo=t.replicateTo),t.replicatedConfirmation&&(o.replicatedConfirmation=t.replicatedConfirmation),wt(o,async c=>{if(!i.schemaDefined){s=[];for(let u of n)i.attributes.find(E=>E.name==u)||s.push(u);s.length>0&&await i.addAttributes(s.map(u=>({name:u,indexed:!0})))}let l=[],d=[];for(let u of t.records){let _=await i.get(u[i.primaryKey],o);if(t.requires_existing&&!_||t.requires_no_existing&&_){d.push(u[i.primaryKey]);continue}_&&(_=Mp(_));for(let E in u)if(Object.prototype.hasOwnProperty.call(u,E)){let f=u[E];if(typeof f=="function")try{let h=f([[_]]);Array.isArray(h)&&(f=h[0].func_val,u[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(u),h}}if(_)for(let E in _)Object.prototype.hasOwnProperty.call(u,E)||(u[E]=_[E]);await i.put(u,o),l.push(u[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:l,new_attributes:s,skipped_hashes:d}})}async deleteRecords(t){let r=ft()[t.schema][t.table],n={user:t.hdb_user};return t.replicateTo&&(n.replicateTo=t.replicateTo),t.replicatedConfirmation&&(n.replicatedConfirmation=t.replicatedConfirmation),wt(n,async s=>{let i=t.hash_values||t.records.map(l=>l[r.primaryKey]),o=[],c=[];for(let l of i)await r.delete(l,n)?o.push(l):c.push(l);return s0(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=ft()[t.schema][t.table];if(!r.createdTimeProperty)throw new Js.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:Xs.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,l=[],d=a(async()=>{let u=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:l});i.push(...u.deleted_hashes),o.push(...u.skipped_hashes),await(0,l0.async_set_timeout)(B7),l=[],s=!0},"chunkDelete");for await(let u of n)l.push(u[r.primaryKey]),c++,c%v7===0&&await d();return l.length>0&&await d(),s?s0(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,Lp.default)(t,"hashes");if(r)throw r;return n0(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of n0(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Xs.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,Lp.default)(t,"value");if(n)throw n;let s=Ii(t);if(!s)throw new Js.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===Xs.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:Rb(t,s)})}async getDataByValue(t,r){let n=new Map,s=Ii(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){Ii({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Ii(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Ii(t),n={};switch(t.search_type){case Xs.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.operation??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 Xs.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of i0(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return i0(r,t.search_values?.[0],t.search_values?.[1],t.limit)}}};a(Rb,"getSelect");a(n0,"getRecords");a(Ii,"getTable");a(s0,"createDeleteResponse");a(i0,"groupRecordsInHistory")});var Hn=y((DNe,_0)=>{"use strict";var{ResourceBridge:H7}=(d0(),ne(u0)),x7=te();x7.initSync();var vp;function F7(){return vp||(vp=new H7,vp)}a(F7,"getBridge");_0.exports=F7()});var p0=y((LNe,h0)=>{"use strict";var f0=require("lodash"),K_=require("mathjs"),k7=require("jsonata"),E0=ee();h0.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?f0.uniqWith(e,f0.isEqual):e,searchJSON:G7,mad:W_.bind(null,K_.mad),mean:W_.bind(null,K_.mean),mode:W_.bind(null,K_.mode),prod:W_.bind(null,K_.prod),median:W_.bind(null,K_.median)};function W_(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(W_,"aggregateFunction");function G7(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(E0.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),E0.isEmpty(this.__ala__.res[r])){let n=k7(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(G7,"searchJSON")});var S0=y((UNe,m0)=>{"use strict";var rr=require("moment"),bb="YYYY-MM-DDTHH:mm:ss.SSSZZ";rr.suppressDeprecationWarnings=!0;m0.exports={current_date:()=>rr().utc().format("YYYY-MM-DD"),current_time:()=>rr().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return rr(e).utc().format("YYYY");case"month":return rr(e).utc().format("MM");case"day":return rr(e).utc().format("DD");case"hour":return rr(e).utc().format("HH");case"minute":return rr(e).utc().format("mm");case"second":return rr(e).utc().format("ss");case"millisecond":return rr(e).utc().format("SSS");default:break}},date:e=>rr(e).utc().format(bb),date_format:(e,t)=>rr(e).utc().format(t),date_add:(e,t,r)=>rr(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>rr(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=rr(e).utc(),s=rr(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>rr().utc().valueOf(),get_server_time:()=>rr().format(bb),offset_utc:(e,t)=>rr(e).utc().utcOffset(t).format(bb)}});var A0=y((vNe,R0)=>{"use strict";var q7=require("@turf/area"),$7=require("@turf/length"),V7=require("@turf/circle"),Y7=require("@turf/difference"),K7=require("@turf/distance"),W7=require("@turf/boolean-contains"),j7=require("@turf/boolean-equal"),Q7=require("@turf/boolean-disjoint"),z7=require("@turf/helpers"),T0=M(),Ge=ee(),ho=V();R0.exports={geoArea:J7,geoLength:X7,geoCircle:Z7,geoDifference:eee,geoDistance:g0,geoNear:tee,geoContains:ree,geoEqual:nee,geoCrosses:see,geoConvert:iee};function J7(e){if(Ge.isEmpty(e))return NaN;typeof e=="string"&&(e=Ge.autoCastJSON(e));try{return q7.default(e)}catch(t){return ho.trace(t,e),NaN}}a(J7,"geoArea");function X7(e,t){if(Ge.isEmpty(e))return NaN;typeof e=="string"&&(e=Ge.autoCastJSON(e));try{return $7.default(e,{units:t||"kilometers"})}catch(r){return ho.trace(r,e),NaN}}a(X7,"geoLength");function Z7(e,t,r){if(Ge.isEmpty(e))return NaN;if(Ge.isEmpty(t))return NaN;typeof e=="string"&&(e=Ge.autoCastJSON(e));try{return V7.default(e,t,{units:r||"kilometers"})}catch(n){return ho.trace(n,e,t),NaN}}a(Z7,"geoCircle");function eee(e,t){if(Ge.isEmpty(e))return NaN;if(Ge.isEmpty(t))return NaN;typeof e=="string"&&(e=Ge.autoCastJSON(e)),typeof t=="string"&&(t=Ge.autoCastJSON(t));try{return Y7(e,t)}catch(r){return ho.trace(r,e,t),NaN}}a(eee,"geoDifference");function g0(e,t,r){if(Ge.isEmpty(e))return NaN;if(Ge.isEmpty(t))return NaN;typeof e=="string"&&(e=Ge.autoCastJSON(e)),typeof t=="string"&&(t=Ge.autoCastJSON(t));try{return K7.default(e,t,{units:r||"kilometers"})}catch(n){return ho.trace(n,e,t),NaN}}a(g0,"geoDistance");function tee(e,t,r,n){if(Ge.isEmpty(e)||Ge.isEmpty(t))return!1;if(Ge.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Ge.autoCastJSON(e)),typeof t=="string"&&(t=Ge.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return g0(e,t,n)<=r}catch(s){return ho.trace(s,e,t),!1}}a(tee,"geoNear");function ree(e,t){if(Ge.isEmpty(e)||Ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Ge.autoCastJSON(e)),typeof t=="string"&&(t=Ge.autoCastJSON(t));try{return W7.default(e,t)}catch(r){return ho.trace(r,e,t),!1}}a(ree,"geoContains");function nee(e,t){if(Ge.isEmpty(e)||Ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Ge.autoCastJSON(e)),typeof t=="string"&&(t=Ge.autoCastJSON(t));try{return j7.default(e,t)}catch(r){return ho.trace(r,e,t),!1}}a(nee,"geoEqual");function see(e,t){if(Ge.isEmpty(e)||Ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Ge.autoCastJSON(e)),typeof t=="string"&&(t=Ge.autoCastJSON(t));try{return!Q7.default(e,t)}catch(r){return ho.trace(r,e,t),!1}}a(see,"geoCrosses");function iee(e,t,r){if(Ge.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Ge.isEmpty(t))throw new Error("geo_type is required");if(Ge.isEmpty(T0.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(T0.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Ge.autoCastJSON(e)),z7[t](e,r)}a(iee,"geoConvert")});var Bp=y((HNe,b0)=>{var wc=p0(),$n=S0(),wi=A0();b0.exports=e=>{e.aggr.mad=e.aggr.MAD=wc.mad,e.aggr.mean=e.aggr.MEAN=wc.mean,e.aggr.mode=e.aggr.MODE=wc.mode,e.aggr.prod=e.aggr.PROD=wc.prod,e.aggr.median=e.aggr.MEDIAN=wc.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=wc.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=wc.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=$n.current_date,e.fn.current_time=e.fn.CURRENT_TIME=$n.current_time,e.fn.extract=e.fn.EXTRACT=$n.extract,e.fn.date=e.fn.DATE=$n.date,e.fn.date_format=e.fn.DATE_FORMAT=$n.date_format,e.fn.date_add=e.fn.DATE_ADD=$n.date_add,e.fn.date_sub=e.fn.DATE_SUB=$n.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=$n.date_diff,e.fn.now=e.fn.NOW=$n.now,e.fn.offset_utc=e.fn.OFFSET_UTC=$n.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=$n.get_server_time,e.fn.getdate=e.fn.GETDATE=$n.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=$n.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=wi.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=wi.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=wi.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=wi.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=wi.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=wi.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=wi.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=wi.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=wi.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=wi.geoNear}});var I0=y((xNe,N0)=>{"use strict";var j_=require("lodash"),En=require("alasql");En.options.cache=!1;var oee=Bp(),y0=require("clone"),Hp=require("recursive-iterator"),Me=V(),Ze=ee(),au=Hn(),aee=M(),{hdb_errors:cee}=ce(),{getDatabases:O0}=(De(),ne(at)),lee="IS NULL",Zs="There was a problem performing this search. Please check the logs and try again.";oee(En);var yb=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ze.isEmpty(t))throw Me.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(),Ze.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Ze.isEmptyOrZeroLength(n))return Me.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw Me.error("Error thrown from checkEmptySQL in SQLSearch class method search."),Me.error(n),new Error(Zs)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw Me.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),Me.error(n),new Error(Zs)}if(Object.keys(this.data).length===0)return Me.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw Me.error("Error thrown from processJoins in SQLSearch class method search."),Me.error(n),new Error(Zs)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw Me.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),Me.error(n),new Error(Zs)}try{return t=await this._finalSQL(),t}catch(n){throw Me.error("Error thrown from finalSQL in SQLSearch class method search."),Me.error(n),new Error(Zs)}}_getColumns(){let t=new Hp(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(y0(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=j_.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=O0()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ze.isEmpty(this.statement.where)){Me.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Hp(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ze.isEmpty(r)&&r.right)if(Ze.isNotEmptyAndHasValue(r.right.value)){let n=Ze.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new En.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Ze.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new En.yy.LogicValue({value:i}):n instanceof En.yy.StringValue&&Ze.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new En.yy.NumValue({value:i}))});if(t){Me.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Hp(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(!Ze.isEmpty(aee.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ze.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ze.isEmptyOrZeroLength(r.left.columnid)||Ze.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(Ze.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"=":!Ze.isEmpty(r.right.value)||!Ze.isEmpty(r.left.value)?n.add(Ze.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let l=Array.isArray(r.right)?r.right:r.left;for(let d=0;d<l.length;d++)if(l[d].value)n.add(l[d].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(Ze.isEmptyOrZeroLength(this.all_table_attributes)&&Ze.isEmptyOrZeroLength(this.statement.from)&&Ze.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&&j_.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(Ze.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Ze.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(Ze.isEmptyOrZeroLength(this.all_table_attributes)&&!Ze.isEmptyOrZeroLength(this.columns.columns))return t;if(Ze.isEmptyOrZeroLength(this.all_table_attributes)&&Ze.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await En.promise(r)}catch(r){throw Me.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),Me.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(y0(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(Ze.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(lee)>-1&&this.tables.forEach(s=>{let i={columnid:O0()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=j_.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]},l=!1,d=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(l=!0),!Ze.isEmpty(this.exact_search_values[d])&&!this.exact_search_values[d].ignore&&!Ze.isEmptyOrZeroLength(this.exact_search_values[d].values))if(l)try{c.hash_values=Array.from(this.exact_search_values[d].values);let u=await au.getDataByHash(c);for(let _ of c.hash_values)u.get(_)&&!this.data[i].__merged_data[_]&&(this.data[i].__merged_data[_]=[...n[i]],this._setMergedHashAttribute(i,_))}catch(u){throw Me.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),Me.error(u),new Error(Zs)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[d].values).map(async u=>{let _={...c};_.search_value=u;let E=await au.getDataByValue(_);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(u){throw Me.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),Me.error(u),new Error(Zs)}else if(!Ze.isEmpty(this.comparator_search_values[d])&&!this.comparator_search_values[d].ignore&&!Ze.isEmptyOrZeroLength(this.comparator_search_values[d].comparators))try{let u=this.comparator_search_values[d].comparators;for(let _=0,E=u.length;_<E;_++){let f=u[_];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await au.getDataByValue(c,f.operation);if(l)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,T]of h)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,s.attribute,T[s.attribute]):(this.data[i].__merged_data[S]=[...n[i]],this._updateMergedAttribute(i,S,s.attribute,T[s.attribute]),this._setMergedHashAttribute(i,S))}}catch(u){throw Me.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),Me.error(u),new Error(Zs)}else try{c.search_attribute=s.attribute,c.search_value="*";let u=await au.getDataByValue(c);if(l)for(let[_]of u)this.data[i].__merged_data[_]||(this.data[i].__merged_data[_]=[...n[i]],this._setMergedHashAttribute(i,_));else for(let[_,E]of u)this.data[i].__merged_data[_]?this._updateMergedAttribute(i,_,s.attribute,E[s.attribute]):(this.data[i].__merged_data[_]=[...n[i]],this._updateMergedAttribute(i,_,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,_))}catch(u){throw Me.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),Me.error(u),new Error(Zs)}}}_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 En.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 En.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new En.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 En.yy.FuncValue:new En.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(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,S=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${S}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${S}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let l=this.statement.where?"WHERE "+this.statement.where:"";l=l.replace(/NOT\(NULL\)/g,"NOT NULL");let d="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(d="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let u="",_="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(u=this.statement.limit?"LIMIT "+this.statement.limit:"",_=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${l} ${d} ${u} ${_}`,h=this._convertColumnsToIndexes(f,s);E=await En.promise(h,t),t=null}catch(f){throw Me.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),Me.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let S=E[f];o.forEach(T=>{S[T.key]!==null&&S[T.key]!==void 0&&T.keys.add(S[T.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),S=j_.difference(h,[...f.keys].map(T=>T.toString()));for(let T=0,g=S.length;T<g;T++){let m=S[T];delete this.data[`${f.schema}_${f.table}`].__merged_data[m]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new Hp(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=j_.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 Me.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),Me.error(i),new Error(Zs)}}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 u in i)o.push(i[u][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},l=await au.getDataByHash(c),d=s.columns.length;for(let u=0,_=o.length;u<_;u++){let E=o[u],f=l.get(E);for(let h=0;h<d;h++){let S=s.columns[h],T=f[S]===void 0?null:f[S];this.data[n].__merged_data[E].push(T)}}}}catch(r){throw Me.error("Error thrown from getDataByHash function in SQLSearch class method getData."),Me.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,l=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===l}).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();Me.trace(`Final SQL: ${s}`),n=await En.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),Me.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw Me.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),Me.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 Me.error(cee.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),Me.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 l=s[i],d=new RegExp(`${l}.\`${o}\``,"g"),u=`${l}.[${c}]`;n=n.replace(d,u)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let l=new RegExp(`\`${o}\``,"g"),d=`[${c}]`;n=n.replace(l,d)});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 au.getDataByValue(i);for(let[c,l]of o)this.data[s].__merged_data[c]||(l[n.attribute]===void 0&&(l[n.attribute]=null),this.data[s].__merged_data[c]={...r[s]}),this.data[s].__merged_data[c][t[n.attribute]]=l[n.attribute]??null}catch(o){throw Me.error("There was an error when processing this SQL operation. Check your logs"),Me.error(o),new Error(Zs)}}return Object.values(Object.values(this.data)[0].__merged_data)}};N0.exports=yb});var jr=y((kNe,w0)=>{"use strict";var uee=iP();w0.exports={searchByConditions:_ee,searchByHash:fee,searchByValue:Eee,search:hee};var Ob=Hn(),{transformReq:Nb}=ee(),dee=I0();async function _ee(e){return Nb(e),Ob.searchByConditions(e)}a(_ee,"searchByConditions");async function fee(e){Nb(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Ob.searchByHash(e))r&&t.push(r);return t}a(fee,"searchByHash");async function Eee(e){Nb(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Ob.searchByValue(e))t.push(r);return t}a(Eee,"searchByValue");function hee(e,t){try{let r=new uee(e);r.validate(),new dee(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(hee,"search")});var xp=y((qNe,C0)=>{"use strict";var pee=Hn();C0.exports={writeTransaction:mee};function mee(e,t,r){return pee.writeTransaction(e,t,r)}a(mee,"writeTransaction")});var M0=y((YNe,L0)=>{"use strict";var See=jr(),Tee=_s(),D0=V(),gee=un(),VNe=xp(),Ree=require("clone"),wb=require("alasql"),Aee=Bp(),P0=require("util"),bee=P0.promisify(Tee.getTableSchema),yee=P0.promisify(See.search),Oee=M(),Ib=ee();Aee(wb);L0.exports={update:Iee};var Nee="There was a problem performing this update. Please check the logs and try again.";async function Iee({statement:e,hdb_user:t}){let r=await bee(e.table.databaseid,e.table.tableid),n=wee(e.columns);Ib.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=Ree(s),c=Ib.isEmpty(i)?"":` WHERE ${i.toString()}`,l=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,d=wb.parse(l).statements[0],u=await yee(d),_=Cee(n,u);return Dee(o,_,t)}a(Iee,"update");function wee(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=wb.compile(`SELECT ${r.expression.toString()} AS [${Oee.FUNC_VAL}] FROM ?`)}),t}catch(t){throw D0.error(t),new Error(Nee)}}a(wee,"createUpdateRecord");function Cee(e,t){return Ib.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(Cee,"buildUpdateRecords");async function Dee(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await gee.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){D0.error(`Error delete new_attributes from update response: ${i}`)}return s}a(Dee,"updateRecords")});var v0=y((QNe,U0)=>{var Pee=require("alasql"),Lee=jr(),Mee=V(),Uee=Hn(),Db=require("util"),Cb=ee(),vee=M(),Bee=_s(),WNe=xp(),jNe=un(),Hee="record",xee="successfully deleted",Fee=Db.callbackify($ee),kee=Db.promisify(Lee.search),Gee=Db.promisify(Bee.getTableSchema);U0.exports={convertDelete:Fee};function qee(e){return`${e.deleted_hashes.length} ${Hee}${e.deleted_hashes.length===1?"":"s"} ${xee}`}a(qee,"generateReturnMessage");async function $ee({statement:e,hdb_user:t}){let r=await Gee(e.table.databaseid,e.table.tableid);Cb.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=Cb.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=Pee.parse(o).statements[0],l={operation:vee.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{l.records=await kee(c);let d=await Uee.deleteRecords(l);return Cb.isEmptyOrZeroLength(d.message)&&(d.message=qee(d)),delete d.txn_time,d}catch(d){throw Mee.error(d),d.hdb_code?d.message:d}}a($ee,"convertDelete")});var k0=y((JNe,F0)=>{"use strict";var Vee=uo(),{hdb_errors:B0}=ce(),{getDatabases:H0}=(De(),ne(at));F0.exports={checkSchemaExists:x0,checkSchemaTableExists:Yee,schema_describe:Vee};async function x0(e){if(!H0()[e])return B0.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(x0,"checkSchemaExists");async function Yee(e,t){let r=await x0(e);if(r)return r;if(!H0()[e][t])return B0.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Yee,"checkSchemaTableExists")});var Cc=y((ZNe,Kee)=>{Kee.exports={name:"harperdb",version:"4.4.0-beta.1",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","enterprise","Fastify","NATS","HarperDB","Harper","clustering","replication","REST","WebSockets","decentralized","server-sent events","document store"],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","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:replication && 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 --no-clean --reporter=lcovonly npm run test:security && 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:replication && 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 && npm run test:security && 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","test:security":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/security/**/*.js' --config '../unitTests/.mocharc.json'","test:replication":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/replication/**/*.js' --config '../unitTests/.mocharc.json'","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",format:"prettier .","format:fix":"npm run format -- --write",lint:"eslint . --ignore-path .gitignore --ignore-pattern 'studio/' --ignore-pattern 'application-template/'","lint:fix":"npm run lint -- --fix"},dependencies:{"@aws-sdk/client-s3":"3.635.0","@aws-sdk/lib-storage":"3.635.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.10.0","@fastify/compress":"~6.5.0","@fastify/cors":"~9.0.1","@fastify/static":"~7.0.4","@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.6.0",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.28.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.9.0","gunzip-maybe":"1.4.2","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.1.2",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",moment:"2.30.1","mqtt-packet":"~9.0.0",msgpackr:"1.11.0",nats:"2.19.0",needle:"3.3.1","node-forge":"^1.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.4.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^1.1.0","serve-static":"2.1.0",ses:"1.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.23.5","tar-fs":"3.0.6",ulidx:"0.5.0",uuid:"10.0.0","validate.js":"0.13.1",ws:"8.18.0",yaml:"2.5.0"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"20.14.8","@typescript-eslint/eslint-plugin":"^7.18.0","@typescript-eslint/parser":"^7.18.0",axios:"1.7.5",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",eslint:"^8.57.0","eslint-config-prettier":"8.3.0","eslint-plugin-sonarjs":"^2.0.2",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mkcert:"1.5.1",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:"6.1.3","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"3.3.3",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:{alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","segfault-handler":"^1.3.0","utf-8-validate":"^5.0.10"}}});var Z_={};tt(Z_,{addAnalyticsListener:()=>X_,recordAction:()=>Rr,recordActionBinary:()=>Vn,setAnalyticsEnabled:()=>Wee});function Wee(e){Q0=e}function Rr(e,t,r,n,s){if(!Q0)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Gp.get(i);if(o)if(typeof e=="number"){let c=o.values,l=c.index++;if(l>=c.length){let d=c;o.values=c=new Float32Array(l*2),c.set(d),c.index=l+1}c[l]=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},Gp.set(i,o)}Fp||jee()}function Vn(e,t,r,n,s){Rr(!!e,t,r,n,s)}function X_(e){X0.push(e)}function jee(){Fp=performance.now(),setTimeout(async()=>{let e=performance.now()-Fp;Fp=0;let t=[],r={time:Date.now(),period:e,threadId:Dc.threadId,metrics:t};for(let[s,i]of Gp){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,l=0,d=[],u;for(let _ of Z0){let E=Math.floor(c*_),f=o[E-1];if(E>l){let h=E-l;if(f===u){let S=d[d.length-1];typeof S=="number"?d[d.length-1]={value:S,count:1+h}:S.count+=h}else d.push(h>1?{value:f,count:h}:f),u=f;l=E}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:d,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 eB()}let n=process.memoryUsage();t.push({metric:"memory",threadId:Dc.threadId,byThread:!0,...n});for(let s of X0)s(t);Gp=new Map,Dc.parentPort?Dc.parentPort.postMessage({type:J0,report:r}):nB({report:r})},z0).unref()}async function Qee(e,t=6e4){let r=Mb(),n=tB(),s=new Promise(S=>{let T=performance.now();setImmediate(()=>{let g=performance.now();g-T>5e3&&(0,Q_.warn)("Unusually high event queue latency on the main thread of "+Math.round(g-T)+"ms"),T=performance.now()}),n.primaryStore.prefetch([1],()=>{let g=performance.now();g-T>5e3&&(0,Q_.warn)("Unusually high task queue latency on the main thread of "+Math.round(g-T)+"ms"),S(g-T)})}),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,l=new Map,d=[],u;for(let{key:S,value:T}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!T)continue;if(o){if(S>o+t)break}else o=S;u=S;let{metrics:g,threadId:m}=T;for(let C of g||[]){let{path:O,method:x,type:F,metric:Y,count:$,total:Z,distribution:Q,threads:_e,...K}=C;$||($=1);let ie=Y+(O?"-"+O:"");x!==void 0&&(ie+="-"+x),F!==void 0&&(ie+="-"+F);let le=c.get(ie);if(le){if(le.threads){let ve=le.threads[m];if(ve)le=ve;else{le.threads[m]={...K};continue}}le.count||(le.count=1);let we=le.count;for(let ve in K){let et=K[ve];typeof et=="number"&&(le[ve]=(le[ve]*we+et*$)/(we+$))}le.count+=$,Z>=0&&(le.total+=Z,le.ratio=le.total/le.count)}else le={period:t,...C},delete le.distribution,c.set(ie,le),le.byThread&&(le.threads=[],le.threads[m]={...K},d.push(le));if(Q){Q=Q.map(ve=>typeof ve=="number"?{value:ve,count:1}:ve);let we=l.get(ie);we?we.push(...Q):l.set(ie,Q)}}await eB()}for(let S of d){let{path:T,method:g,type:m,metric:C,count:O,total:x,distribution:F,threads:Y,...$}=S;Y=Y.filter(Z=>Z);for(let Z in $){if(typeof S[Z]!="number")continue;let Q=0;for(let _e of Y){let K=_e[Z];typeof K=="number"&&(Q+=K)}S[Z]=Q}S.count=Y.length,delete S.threads,delete S.byThread}for(let[S,T]of l){let g=c.get(S);T.sort((ve,et)=>ve.value>et.value?1:-1);let m=g.count-1,C=[],O=0,x=0,F;for(let ve of Z0){let et=m*ve;for(;O<et;)F=T[x++],O+=F.count,x===1&&O--;let Ja=T[x>1?x-2:0];F||(F=T[0]),C.push(F.value-(F.value-Ja.value)*(O-et)/F.count)}let[Y,$,Z,Q,_e,K,ie,le,we]=C;Object.assign(g,{p1:Y,p10:$,p25:Z,median:Q,p75:_e,p90:K,p95:ie,p99:le,p999:we})}let _;for(let[S,T]of c)T.id=(0,kp.getNextMonotonicTime)(),T.time=u,n.primaryStore.put(T.id,T,{append:!0}).then(g=>{g||n.primaryStore.put(T.id,T)}),_=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(_||h*10>f){let S=(0,kp.getNextMonotonicTime)(),T={id:S,metric:"main-thread-utilization",idle:f-G0,active:h-q0,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(S,T,{append:!0}).then(g=>{g||n.primaryStore.put(S,T)})}G0=f,q0=h}async function $0(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function Mb(){return V0||(V0=dt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function tB(){return Y0||(Y0=dt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function Xee(){rB=!0;let e=(0,J_.get)(Lb.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await Qee(z0,e),await $0(Mb(),zee),await $0(tB(),Jee)},Math.min(e/2,2147483647)).unref()}function nB(e,t){let r=e.report;r.threadId=t?.threadId||Dc.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(K0+=n.mean*n.count);r.totalBytesProcessed=K0,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(W0.get(t))}),W0.set(t,t.performance.eventLoopUtilization())),r.id=(0,kp.getNextMonotonicTime)(),Mb().primaryStore.put(r.id,r),rB||Xee(),Zee&&(sB=tte(r))}async function tte(e){if(await sB,!la){let r=(0,z_.dirname)((0,Q_.getLogFilePath)());try{la=await(0,Pb.open)((0,z_.join)(r,"analytics.log"),"r+")}catch{la=await(0,Pb.open)((0,z_.join)(r,"analytics.log"),"w+")}}let t=(await la.stat()).size;if(t>ete){let r=Buffer.alloc(t);await la.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await la.write(r,{position:0}),await la.truncate(r.length),t=r.length}await la.write(JSON.stringify(e)+`
11
+ `,t)}var Dc,j0,Q_,z_,Pb,kp,J_,Lb,Gp,Q0,Fp,z0,J0,X0,Z0,G0,q0,eB,zee,Jee,V0,Y0,rB,K0,W0,Zee,sB,la,ete,Ci=Ce(()=>{Dc=require("worker_threads"),j0=B(ut());De();Q_=B(V()),z_=require("path"),Pb=require("fs/promises"),kp=B(an()),J_=B(te()),Lb=B(M());Wr();(0,J_.initSync)();Gp=new Map,Q0=(0,J_.get)(Lb.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(Wee,"setAnalyticsEnabled");a(Rr,"recordAction");nt.recordAnalytics=Rr;a(Vn,"recordActionBinary");Fp=0,z0=1e3,J0="analytics-report",X0=[];a(X_,"addAnalyticsListener");Z0=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(jee,"sendAnalytics");a(Qee,"aggregation");G0=0,q0=0,eB=a(()=>new Promise(setImmediate),"rest");a($0,"cleanup");zee=36e5,Jee=31536e6;a(Mb,"getRawAnalyticsTable");a(tB,"getAnalyticsTable");(0,j0.setChildListenerByType)(J0,nB);a(Xee,"startScheduledTasks");K0=0,W0=new Map,Zee=!1;a(nB,"recordAnalytics");ete=1e6;a(tte,"logAnalytics")});var xb=y((_Ie,pB)=>{"use strict";var{decode:rte}=require("msgpackr"),{isMainThread:lIe,parentPort:uIe,threadId:dIe}=require("worker_threads"),Vp=nr(),cu=At(),Bb=M(),Zr=V(),vb=te(),nte=M(),{onMessageByType:ste}=ut(),cB=lo(),{recordAction:iB,recordActionBinary:ite}=(Ci(),ne(Z_)),{publishToStream:ote}=Vp,{ConsumerEvents:oB}=require("nats"),ate=jr(),{promisify:cte}=require("util"),lB=cte(setTimeout),Yp=1e4,Kp,$p,lte,ute,uB,ef=new Map,lu=new Map;pB.exports={initialize:dB,ingestConsumer:Hb,setSubscription:dte,setIgnoreOrigin:Ete,getDatabaseSubscriptions:fte,updateConsumer:_B};async function dB(){ste(Bb.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await _B(n)}),uB=!0,Zr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await Vp.getNATSReferences();Kp=e,$p=e.info.server_name,lte=t,ute=r}a(dB,"initialize");async function _B(e){if(e.status==="start"){let{js:t,jsm:r}=await fB(e.node_domain_name);Hb(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=ef.get(e.stream_name+e.node_domain_name);t&&(Zr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),ef.set(e.stream_name+e.node_domain_name,"close")),lu.get(e.node_domain_name)==="failed"&&lu.set(e.node_domain_name,"close")}}a(_B,"updateConsumer");var Wp=new Map;function dte(e,t,r){let n=Wp.get(e);n||Wp.set(e,n=new Map),n.set(t,r),uB||dB().then(_te)}a(dte,"setSubscription");async function _te(){let e=await ate.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+cu.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await fB(r),!n))break;let{schema:o,table:c}=i,l=cB.createNatsTableStreamName(o,c);Hb(l,n,s,r)}}}a(_te,"accessConsumers");async function fB(e){let t,r,n=1;for(;!r;)try{t=await Kp.jetstream({domain:e}),r=await Kp.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(lu.get(e)==="close")break;lu.set(e,"failed"),n%10===1&&Zr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<Yp?n++*100:Yp;await lB(i)}return{js:t,jsm:r}}a(fB,"connectToRemoteJS");function fte(){return Wp}a(fte,"getDatabaseSubscriptions");var EB;function Ete(e){EB=e}a(Ete,"setIgnoreOrigin");var hB=100,aB=new Array(hB),qp=0;async function Hb(e,t,r,n){let{connection:s}=await Vp.getNATSReferences();Kp=s,$p=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,$p),Zr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(d){if(lu.get(n)==="close")break;o%10===1&&Zr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",d.message),d.code==="404"&&(Zr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await Vp.createConsumer(r,e,$p,new Date(Date.now()).toISOString()));let u=o++*100<Yp?o++*100:Yp;await lB(u)}let c=!1,l;for(;!c;){if(ef.get(e+n)==="close"||lu.get(n)==="close"){ef.delete(e+n),c=!0;continue}l=await i.consume({max_messages:vb.get(Bb.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),ef.set(e+n,l);let d=!1;(async()=>{for await(let u of await l.status())if(u.type===oB.ConsumerDeleted&&(await l.close(),c=!0),u.type===oB.HeartbeatsMissed){let _=u.data;Zr.trace(`${_} clustering ingest consumer heartbeats missed, node: ${n} stream: ${l.consumer.stream}`),_===100&&(Zr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${l.consumer.stream}`),l.stop(),d=!0)}})();try{for await(let u of l)await aB[qp],aB[qp]=hte(u).catch(_=>{Zr.error(_)}),++qp>=hB&&(qp=0)}catch(u){u.message==="consumer deleted"?(Zr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",l.consumer.stream),await l.close(),c=!0):Zr.error("Error consuming clustering ingest, restarting consumer",u)}}}a(Hb,"ingestConsumer");async function hte(e){let t=rte(e.data);iB(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),Zr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=vb.get(Bb.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(cu.MSG_HEADERS.TRANSACTED_NODES)&&r.values(cu.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(cu.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!EB),ite(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(cu.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:l,table:d,records:u,hash_values:_,__origin:E,expiresAt:f}=t;Zr.trace("processing message:",o,c,d,(u?"records: "+u.map(x=>x?.id):"")+(_?"ids: "+_:""),"with sequence:",e.seq),Zr.trace(`messageProcessor nats msg id: ${e.headers.get(cu.MSG_HEADERS.NATS_MSG_ID)}`);let h;u||(u=_);let S=new Promise(x=>h=x),{timestamp:T,user:g,node_name:m}=E||{},C=Wp.get(c)?.get(d);if(!C)throw new Error("Missing table for replication message",d);if(o==="define_schema")t.type=o,t.onCommit=h,C.send(t);else if(u.length===1&&!l)C.send({type:Ub(o),value:u[0],id:_?.[0],expiresAt:f,timestamp:T,table:d,onCommit:h,user:g,nodeName:m});else{let x=u.map((F,Y)=>({type:Ub(o),value:F,expiresAt:f,id:_?.[Y],table:d}));for(;l;)x.push({type:Ub(l.operation),value:l.record,expiresAt:l.expiresAt,id:l.id,table:l.table}),l=l.next;C.send({type:"transaction",writes:x,table:d,timestamp:T,onCommit:h,user:g,nodeName:m})}vb.get(nte.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&ote(e.subject.split(".").slice(0,-1).join("."),cB.createNatsTableStreamName(c,d),e.headers,e.data),await S;let O=Date.now()-T;T&&iB(O,"replication-latency",e.subject,o,"ingest")}catch(o){Zr.error(o)}e.ack()}a(hte,"messageProcessor");function Ub(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(Ub,"convertOperation")});var nr=y((TIe,MB)=>{"use strict";var Ar=te();Ar.initSync();var pte=require("fs-extra"),mte=require("semver"),nf=require("path"),{monotonicFactory:Ste}=require("ulidx"),SB=Ste(),Tte=require("util"),TB=require("child_process"),gte=Tte.promisify(TB.exec),Rte=TB.spawn,Dr=At(),je=M(),jp=ee(),ei=V(),Qp=lo(),Ate=xp(),tf=yt(),{broadcast:bte,onMessageByType:yte,getWorkerIndex:Ote}=ut(),{isMainThread:gB}=require("worker_threads"),{Encoder:Nte,decode:qb}=require("msgpackr"),RB=new Nte,{isEmpty:Uc}=jp,AB=_n(),EIe=48*36e11;gB&&yte(je.ITC_EVENT_TYPES.RESTART,()=>{hn=void 0,Mc=void 0});var{connect:Ite,StorageType:wte,RetentionPolicy:Cte,AckPolicy:$b,DeliverPolicy:Vb,DiscardPolicy:Dte,NatsConnection:hIe,JetStreamManager:pIe,JetStreamClient:mIe,StringCodec:SIe,JSONCodec:Pte,createInbox:Yb,headers:Lte,ErrorCode:mB}=require("nats"),{PACKAGE_ROOT:Mte}=M(),Ute=Cc(),{recordAction:vte}=(Ci(),ne(Z_)),bB=Pte(),Bte="clustering",Hte=Ute.engines[Dr.NATS_SERVER_NAME],xte=nf.join(Mte,"dependencies"),Gb=nf.join(xte,`${process.platform}-${process.arch}`,Dr.NATS_BINARY_NAME),Fb,kb,rf,Pc,Lc;MB.exports={runCommand:yB,checkNATSServerInstalled:Fte,createConnection:Kb,getConnection:sf,getJetStreamManager:of,getJetStream:NB,getNATSReferences:Di,getServerList:Gte,createLocalStream:Wb,listStreams:IB,deleteLocalStream:qte,getServerConfig:uu,listRemoteStreams:$te,viewStream:Vte,viewStreamIterator:Yte,publishToStream:Kte,request:Qte,reloadNATS:jb,reloadNATSHub:zte,reloadNATSLeaf:Jte,extractServerName:jte,requestErrorHandler:Xte,createLocalTableStream:PB,createTableStreams:tre,purgeTableStream:LB,purgeSchemaTableStreams:rre,getStreamInfo:nre,updateLocalStreams:ire,closeConnection:kte,getJsmServerName:zp,addNatsMsgHeader:wB,clearClientCache:OB,updateRemoteConsumer:Zte,createConsumer:CB,updateConsumerIterator:ere};async function yB(e,t=void 0){let{stdout:r,stderr:n}=await gte(e,{cwd:t});if(n)throw new Error(n.replace(`
10
12
  `,""));return r.replace(`
11
- `,"")}a(uU,"runCommand");async function e6(){try{await L8.access(iR)}catch{return!1}let e=await uU(`${iR} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return P8.eq(t,X8)}a(e6,"checkNATSServerInstalled");async function uR(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await cU.getClusterUser();if(Aa(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}_s.trace("create nats connection called");let i=await k8({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),_s.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&_s.error("Error with Nats client connection, connection closed",o),_U()}),i}a(uR,"createConnection");function _U(){Br=void 0,Ta=void 0,ga=void 0,Ra=void 0}a(_U,"clearClientCache");async function t6(){Br&&(await Br.drain(),Br=void 0,Ta=void 0,ga=void 0,Ra=void 0)}a(t6,"closeConnection");var Br,Ra;async function Ju(){return Ra||(Ra=uR(Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Br=await Ra),Br||Ra}a(Ju,"getConnection");async function Xu(){if(Ta)return Ta;Aa(Br)&&await Ju();let{domain:e}=Lc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Aa(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ta=await Br.jetstreamManager({domain:e,timeout:6e4}),Ta}a(Xu,"getJetStreamManager");async function dU(){if(ga)return ga;Aa(Br)&&await Ju();let{domain:e}=Lc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Aa(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ga=Br.jetstream({domain:e,timeout:6e4}),ga}a(dU,"getJetStream");async function xs(){let e=Br||await Ju(),t=Ta||await Xu(),r=ga||await dU();return{connection:e,jsm:t,js:r}}a(xs,"getNATSReferences");async function r6(e){let t=Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await cU.getClusterUser(),s=await uR(t,r,n),i=lR(),o=s.subscribe(i),c=[],l,_=(async()=>{for await(let u of o){let d=lU.decode(u.data);d.response_time=Date.now()-l,c.push(d)}})();return l=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 NE.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(r6,"getServerList");async function _R(e,t){let{jsm:r}=await xs(),n=Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:V8.File,retention:$8.Limits,subjects:t,discard:Y8.Old,max_msgs:s,max_bytes:i,max_age:n})}a(_R,"createLocalStream");async function fU(){let{jsm:e}=await xs(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(fU,"listStreams");async function n6(e){let{jsm:t}=await xs();await t.streams.delete(e)}a(n6,"deleteLocalStream");async function s6(e){let{connection:t}=await xs(),r=[],n=lR(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(lU.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(s6,"listRemoteStreams");async function i6(e,t=void 0,r=void 0){let{jsm:n,js:s}=await xs(),i=sU(),o={durable_name:i,ack_policy:aR.Explicit};t&&(o.deliver_policy=cR.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let u of l){let d=oR(u.data),E={nats_timestamp:u.info.timestampNanos,nats_sequence:u.info.streamSequence,entry:d};if(u.headers&&(E.origin=u.headers.get(rr.MSG_HEADERS.ORIGIN)),_.push(E),u.ack(),u.info.pending===0)break}return await c.delete(),_}a(i6,"viewStream");async function*o6(e,t=void 0,r=void 0){let{jsm:n,js:s}=await xs(),i=sU(),o={durable_name:i,ack_policy:aR.Explicit};t&&(o.deliver_policy=cR.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of l){let u=oR(_.data);u[0]||(u=[u]);for(let d of u){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(rr.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(o6,"viewStreamIterator");async function a6(e,t,r,n){_s.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=EU(n,r);let{js:s}=await xs(),i=await IE(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:aU.encode(n);try{_s.trace(`publishToStream publishing to subject: ${o}`),z8(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(l){if(l.code&&l.code.toString()==="503")return pU(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){_s.trace(`publishToStream creating stream: ${t}`);let u=o.split(".");u[2]="*",await _R(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(a6,"publishToStream");function EU(e,t){t===void 0&&(t=W8());let r=Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(rr.MSG_HEADERS.ORIGIN)&&r&&t.append(rr.MSG_HEADERS.ORIGIN,r),t}a(EU,"addNatsMsgHeader");function Lc(e){e=e.toLowerCase();let t=zu.join(Wt.get(Ce.CONFIG_PARAMS.ROOTPATH),J8);if(e===Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return Aa(sR)&&(sR={port:Qu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Qu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME)+rr.SERVER_SUFFIX.HUB,config_file:rr.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:zu.join(t,rr.PID_FILES.HUB),hdb_nats_path:t}),sR;if(e===Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return Aa(nR)&&(nR={port:Qu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Qu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME)+rr.SERVER_SUFFIX.LEAF,config_file:rr.NATS_CONFIG_FILES.LEAF_SERVER,domain:Qu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME)+rr.SERVER_SUFFIX.LEAF,pid_file_path:zu.join(t,rr.PID_FILES.LEAF),hdb_nats_path:t}),nR;_s.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Lc,"getServerConfig");async function hU(e,t,r,n){try{await e.consumers.add(t,{ack_policy:aR.Explicit,durable_name:r,deliver_policy:cR.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(hU,"createConsumer");async function c6(e,t,r){await e.consumers.delete(t,r)}a(c6,"removeConsumer");function l6(e){return e.split(".")[1]}a(l6,"extractServerName");async function u6(e,t,r=6e4,n=lR()){if(!NE.isObject(t))throw new Error("data param must be an object");let s=aU.encode(t),{connection:i}=await xs(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return oR(c.data)}a(u6,"request");function dR(e){return new Promise(async(t,r)=>{let n=B8(iR,["--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(dR,"reloadNATS");async function _6(){let{pid_file_path:e}=Lc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await dR(e)}a(_6,"reloadNATSHub");async function d6(){let{pid_file_path:e}=Lc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await dR(e)}a(d6,"reloadNATSLeaf");function f6(e,t,r){let n;switch(e.code){case nU.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case nU.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(f6,"requestErrorHandler");async function E6(e,t){let r=t+rr.SERVER_SUFFIX.LEAF,{connection:n}=await xs(),{jsm:s}=await A6(r),{schema:i,table:o}=e,c=yE.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await pU(async()=>{if(e.subscribe===!0)await hU(s,c,n.info.server_name,l);else try{await c6(s,c,n.info.server_name)}catch(_){_s.trace(_)}})}a(E6,"updateRemoteConsumer");async function h6(e,t,r,n){let s=yE.createNatsTableStreamName(e,t),i=r+rr.SERVER_SUFFIX.LEAF,o={type:Ce.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!oU&&q8()<Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=rR();await c(o)}await G8(o),n==="stop"&&await NE.async_set_timeout(1e3)}a(h6,"updateConsumerIterator");function pU(e){return H8.writeTransaction(Ce.SYSTEM_SCHEMA_NAME,Ce.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(pU,"exclusiveLock");async function mU(e,t){let r=yE.createNatsTableStreamName(e,t),n=await IE(),s=T6(e,t,n);await _R(r,[s])}a(mU,"createLocalTableStream");async function p6(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await mU(n,s)}}a(p6,"createTableStreams");async function SU(e,t,r=void 0){if(Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=yE.createNatsTableStreamName(e,t),{domain:s}=Lc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Ju()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")_s.warn(n);else throw n}}a(SU,"purgeTableStream");async function m6(e,t){if(Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await SU(e,t[r])}a(m6,"purgeSchemaTableStreams");async function S6(e){return(await Xu()).streams.info(e)}a(S6,"getStreamInfo");function T6(e,t,r){return`${rr.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(T6,"createSubjectName");async function IE(){if(ju)return ju;if(ju=(await Xu())?.nc?.info?.server_name,ju===void 0)throw new Error("Unable to get jetstream manager server name");return ju}a(IE,"getJsmServerName");async function g6(){let e=await Xu(),t=await IE(),r=await fU();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=R6(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let u=_.join(".");_s.trace(`Updating stream subject name from: ${i} to: ${u}`),s.subjects[0]=u,await e.streams.update(s.name,s)}}a(g6,"updateLocalStreams");function R6(e){let{config:t}=e,r=!1,n=Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Wt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Wt.get(Ce.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(R6,"updateStreamLimits");async function A6(e){let t,r;try{t=await Br.jetstream({domain:e}),r=await Br.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw _s.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(A6,"connectToRemoteJS")});var LE=R((DRe,OU)=>{"use strict";var Pc=bf(),Mc=IM(),O6=k(),b6=require("uuid").v4,CRe=require("clone"),CE=hi(),Uc=D(),N6=require("util"),Eo=Hn(),{handleHDBError:Hr,hdb_errors:y6}=ie(),{HDB_ERROR_MSGS:wE,HTTP_STATUS_CODES:Gr}=y6,{SchemaEventMsg:DE}=os(),gU=gt(),{getDatabases:I6}=(Re(),ae($e)),{transformReq:vc}=Y();OU.exports={createSchema:w6,createSchemaStructure:RU,createTable:C6,createTableStructure:AU,createAttribute:U6,dropSchema:D6,dropTable:L6,dropAttribute:P6,getBackup:v6};async function w6(e){let t=await RU(e);return CE.signalSchemaChange(new DE(process.pid,e.operation,e.schema)),t}a(w6,"createSchema");async function RU(e){let t=Pc.schema_object(e);if(t)throw Hr(t,t.message,Gr.BAD_REQUEST,void 0,void 0,!0);if(vc(e),!await Mc.checkSchemaExists(e.schema))throw Hr(new Error,wE.SCHEMA_EXISTS_ERR(e.schema),Gr.BAD_REQUEST,Uc.LOG_LEVELS.ERROR,wE.SCHEMA_EXISTS_ERR(e.schema),!0);return await Eo.createSchema(e),`database '${e.schema}' successfully created`}a(RU,"createSchemaStructure");async function C6(e){return vc(e),e.hash_attribute=e.primary_key??e.hash_attribute,await AU(e)}a(C6,"createTable");async function AU(e){let t=Pc.create_table_object(e);if(t)throw Hr(t,t.message,Gr.BAD_REQUEST,void 0,void 0,!0);if(Pc.validateTableResidence(e.residence),!await Mc.checkSchemaTableExists(e.schema,e.table))throw Hr(new Error,wE.TABLE_EXISTS_ERR(e.schema,e.table),Gr.BAD_REQUEST,Uc.LOG_LEVELS.ERROR,wE.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:b6(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Eo.createTable(n,e);else throw Hr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Gr.BAD_REQUEST);else await Eo.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(AU,"createTableStructure");async function D6(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=Pc.schema_object(e),n=t??r;if(n)throw Hr(n,n.message,Gr.BAD_REQUEST,void 0,void 0,!0);vc(e);let s=await Mc.checkSchemaExists(e.schema);if(s)throw Hr(new Error,s,Gr.NOT_FOUND,Uc.LOG_LEVELS.ERROR,s,!0);let i=await Mc.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await Eo.dropSchema(e),CE.signalSchemaChange(new DE(process.pid,e.operation,e.schema)),await gU.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(D6,"dropSchema");async function L6(e){let t=Pc.table_object(e);if(t)throw Hr(t,t.message,Gr.BAD_REQUEST,void 0,void 0,!0);vc(e);let r=await Mc.checkSchemaTableExists(e.schema,e.table);if(r)throw Hr(new Error,r,Gr.NOT_FOUND,Uc.LOG_LEVELS.ERROR,r,!0);return await Eo.dropTable(e),await gU.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(L6,"dropTable");async function P6(e){let t=Pc.attribute_object(e);if(t)throw Hr(t,t.message,Gr.BAD_REQUEST,void 0,void 0,!0);vc(e);let r=await Mc.checkSchemaTableExists(e.schema,e.table);if(r)throw Hr(new Error,r,Gr.NOT_FOUND,Uc.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",Gr.BAD_REQUEST,void 0,void 0,!0);if(Uc.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Hr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Gr.BAD_REQUEST,void 0,void 0,!0);try{return await Eo.dropAttribute(e),M6(e),CE.signalSchemaChange(new DE(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw O6.error(`Got an error deleting attribute ${N6.inspect(e)}.`),n}}a(P6,"dropAttribute");function M6(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(M6,"dropAttributeFromGlobal");async function U6(e){vc(e);let t=I6()[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}`,Gr.BAD_REQUEST,void 0,void 0,!0);return await Eo.createAttribute(e),CE.signalSchemaChange(new DE(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(U6,"createAttribute");function v6(e){return Eo.getBackup(e)}a(v6,"getBackup")});var NU=R((PRe,bU)=>{"use strict";var{OPERATIONS_ENUM:B6}=D(),fR=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=B6.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};bU.exports=fR});var ER=R((vRe,DU)=>{"use strict";var H6=Hn(),URe=NU(),PE=Y(),ME=D(),G6=X(),{handleHDBError:yU,hdb_errors:x6}=ie(),{HDB_ERROR_MSGS:IU,HTTP_STATUS_CODES:wU}=x6,q6=Object.values(ME.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),CU="To use this operation audit log must be enabled in harperdb-config.yaml";DU.exports=F6;async function F6(e){if(PE.isEmpty(e.schema))throw new Error(IU.SCHEMA_REQUIRED_ERR);if(PE.isEmpty(e.table))throw new Error(IU.TABLE_REQUIRED_ERR);if(!G6.get(ME.CONFIG_PARAMS.LOGGING_AUDITLOG))throw yU(new Error,CU,wU.BAD_REQUEST,ME.LOG_LEVELS.ERROR,CU,!0);let t=PE.checkSchemaTableExist(e.schema,e.table);if(t)throw yU(new Error,t,wU.NOT_FOUND,ME.LOG_LEVELS.ERROR,t,!0);if(!PE.isEmpty(e.search_type)&&q6.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await H6.readAuditLog(e)}a(F6,"readAuditLog")});var PU=R((HRe,LU)=>{"use strict";var{OPERATIONS_ENUM:k6}=D(),hR=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=k6.GET_BACKUP,this.schema=t,this.table=r}};LU.exports=hR});var vU=R((FRe,UU)=>{"use strict";var V6=Hn(),xRe=PU(),pR=Y(),$6=D(),qRe=X(),{handleHDBError:Y6,hdb_errors:K6}=ie(),{HDB_ERROR_MSGS:MU,HTTP_STATUS_CODES:W6}=K6;UU.exports=Q6;async function Q6(e){if(pR.isEmpty(e.schema))throw new Error(MU.SCHEMA_REQUIRED_ERR);if(pR.isEmpty(e.table))throw new Error(MU.TABLE_REQUIRED_ERR);let t=pR.checkSchemaTableExist(e.schema,e.table);if(t)throw Y6(new Error,t,W6.NOT_FOUND,$6.LOG_LEVELS.ERROR,t,!0);return await V6.getBackup(read_audit_log_object)}a(Q6,"getBackup")});var FU=R((VRe,qU)=>{var ho=require("validate.js"),HU=nt(),Bc=D(),{handleHDBError:j6,hdb_errors:z6}=ie(),{HDB_ERROR_MSGS:Rt,HTTP_STATUS_CODES:J6}=z6,mR=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),X6={STRUCTURE_USER:"structure_user"},BU=Object.values(Bc.ROLE_TYPES_ENUM),Z6="attribute_permissions",e9="attribute_name",{PERMS_CRUD_ENUM:Hc}=Bc,t9=[Z6,...Object.values(Hc)],GU=[Hc.READ,Hc.INSERT,Hc.UPDATE],r9=[e9,...GU];function n9(e){let t=mR();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,xU(e,t)}a(n9,"addRoleValidation");function s9(e){let t=mR();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,xU(e,t)}a(s9,"alterRoleValidation");function i9(e){let t=mR();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,HU.validateObject(e,t)}a(i9,"dropRoleValidation");var o9=["operation","role","id","permission","hdb_user","hdb_auth_header"];function xU(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)o9.includes(n[o])||s.push(n[o]);s.length>0&&wt(Rt.INVALID_ROLE_JSON_KEYS(s),r);let i=HU.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{wt(o,r)}),e.permission){let o=a9(e);o&&wt(o,r),BU.forEach(c=>{e.permission[c]&&!ho.isBoolean(e.permission[c])&&wt(Rt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(BU.indexOf(o)<0){if(o===X6.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let _=0,u=l.length;_<u;_++){let d=l[_];global.hdb_schema[d]||wt(Rt.SCHEMA_NOT_FOUND(d),r)}continue}wt(Rt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){wt(Rt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let _=c.tables[l];if(!l||!global.hdb_schema[o][l]){wt(Rt.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(_).forEach(u=>{t9.includes(u)||wt(Rt.INVALID_PERM_KEY(u),r,o,l)}),Object.values(Hc).forEach(u=>{ho.isDefined(_[u])?ho.isBoolean(_[u])||wt(Rt.TABLE_PERM_NOT_BOOLEAN(u),r,o,l):wt(Rt.TABLE_PERM_MISSING(u),r,o,l)}),ho.isDefined(_.attribute_permissions)){if(!ho.isArray(_.attribute_permissions)){wt(Rt.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}}else{wt(Rt.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}if(_.attribute_permissions){let u=global.hdb_schema[o][l].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in _.attribute_permissions){let f=_.attribute_permissions[E];if(Object.keys(f).forEach(m=>{!r9.includes(m)&&m!==Hc.DELETE&&wt(Rt.INVALID_ATTR_PERM_KEY(m),r,o,l)}),!ho.isDefined(f.attribute_name)){wt(Rt.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=f.attribute_name;if(!u.includes(h)){wt(Rt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}GU.forEach(m=>{ho.isDefined(f[m])?ho.isBoolean(f[m])||wt(Rt.ATTR_PERM_NOT_BOOLEAN(m,h),r,o,l):wt(Rt.ATTR_PERM_MISSING(m,h),r,o,l)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let E=`${o}.${l}`;wt(Rt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,l)}}}}return c9(r)}a(xU,"customValidate");qU.exports={addRoleValidation:n9,alterRoleValidation:s9,dropRoleValidation:i9};function a9(e){let{operation:t,permission:r}=e;if(t===Bc.OPERATIONS_ENUM.ADD_ROLE||t===Bc.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 Rt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Bc.ROLE_TYPES_ENUM.SUPER_USER:Bc.ROLE_TYPES_ENUM.CLUSTER_USER;return Rt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(a9,"validateNoSUPerms");function c9(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:Rt.ROLE_PERMS_ERROR,...e};return j6(new Error,n,J6.BAD_REQUEST)}else return null}a(c9,"generateRolePermResponse");function wt(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(wt,"addPermError")});var vE=R((YRe,YU)=>{"use strict";var kU=Cr(),VU=ur(),l9=ia(),TR=FU(),gR=hi(),u9=require("uuid").v4,_9=require("util"),UE=D(),d9=Y(),RR=VU.searchByValue,f9=VU.searchByHash,E9=_9.promisify(l9.delete),h9=as(),p9=Nc(),{hdb_errors:m9,handleHDBError:Oa}=ie(),{HDB_ERROR_MSGS:$U,HTTP_STATUS_CODES:Zu}=m9,{UserEventMsg:AR}=os();YU.exports={addRole:S9,alterRole:T9,dropRole:g9,listRoles:R9};function SR(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(SR,"scrubRoleDetails");async function S9(e){let t=TR.addRoleValidation(e);if(t)throw t;e=SR(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 RR(r)||[])}catch(i){throw Oa(i)}if(n&&n.length>0)throw Oa(new Error,$U.ROLE_ALREADY_EXISTS(e.role),Zu.CONFLICT,void 0,void 0,!0);e.id||(e.id=u9());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await kU.insert(s),gR.signalUserChange(new AR(process.pid)),e=SR(e),e}a(S9,"addRole");async function T9(e){let t=TR.alterRoleValidation(e);if(t)throw t;e=SR(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await kU.update(r)}catch(s){throw Oa(s)}if(n&&n?.message==="updated 0 of 1 records")throw Oa(new Error,"Invalid role id",Zu.BAD_REQUEST,void 0,void 0,!0);return await gR.signalUserChange(new AR(process.pid)),e}a(T9,"alterRole");async function g9(e){let t=TR.dropRoleValidation(e);if(t)throw Oa(new Error,t,Zu.BAD_REQUEST,void 0,void 0,!0);let r=new p9(UE.SYSTEM_SCHEMA_NAME,UE.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await f9(r));if(n.length===0)throw Oa(new Error,$U.ROLE_NOT_FOUND,Zu.NOT_FOUND,void 0,void 0,!0);let s=new h9(UE.SYSTEM_SCHEMA_NAME,UE.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await RR(s)),o=!1;if(d9.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw Oa(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Zu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await E9(c),gR.signalUserChange(new AR(process.pid)),`${n[0].role} successfully deleted`}a(g9,"dropRole");async function R9(){return RR({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(R9,"listRoles")});var jU=R((WRe,QU)=>{"use strict";var A9=X(),po=require("joi"),O9=nt(),KU=require("moment"),b9=require("fs-extra"),OR=require("path"),N9=require("lodash"),e_=D(),{LOG_LEVELS:ba}=D(),y9="YYYY-MM-DD hh:mm:ss",I9=OR.resolve(__dirname,"../logs");QU.exports=function(e){return O9.validateBySchema(e,w9)};var w9=po.object({from:po.custom(WU),until:po.custom(WU),level:po.valid(ba.NOTIFY,ba.FATAL,ba.ERROR,ba.WARN,ba.INFO,ba.DEBUG,ba.TRACE),order:po.valid("asc","desc"),limit:po.number().min(1),start:po.number().min(0),log_name:po.custom(C9)});function WU(e,t){if(KU(e,KU.ISO_8601).format(y9)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(WU,"validateDatetime");function C9(e,t){if(N9.invert(e_.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=A9.get(e_.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?e_.LOG_NAMES.HDB:e,i=s===e_.LOG_NAMES.INSTALL?OR.join(I9,e_.LOG_NAMES.INSTALL):OR.join(n,s);return b9.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(C9,"validateReadLogPath")});var NR=R((jRe,JU)=>{"use strict";var BE=D(),D9=k(),L9=X(),P9=jU(),bR=require("path"),zU=require("fs-extra"),{once:M9}=require("events"),{handleHDBError:U9,hdb_errors:v9}=ie(),{PACKAGE_ROOT:B9}=D(),H9=bR.join(B9,"logs"),G9=1e3,x9=200;JU.exports=q9;async function q9(e){let t=P9(e);if(t)throw U9(t,t.message,v9.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=L9.get(BE.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?BE.LOG_NAMES.HDB:e.log_name,s=n===BE.LOG_NAMES.INSTALL?bR.join(H9,BE.LOG_NAMES.INSTALL):bR.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,l=c?new Date(e.from):void 0,_=e.until!==void 0,u=_?new Date(e.until):void 0,d=e.limit===void 0?G9:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,m=0;E==="desc"&&!l&&!u&&(m=Math.max(zU.statSync(s).size-(h+5)*x9,0));let S=zU.createReadStream(s,{start:m});S.on("error",U=>{D9.error(U)});let g=0,T=[],b="",N;S.on("data",U=>{let F=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;U=b+U;let M=0,W;for(;(W=F.exec(U))&&!S.destroyed;){N&&(N.message=U.slice(M,W.index),v(N));let[z,J,le]=W,ue=le.split("] ["),Ee=ue[0],Ge=ue[1];ue.splice(0,2),N={timestamp:J,thread:Ee,level:Ge,tags:ue,message:""},M=W.index+z.length}b=U.slice(M)}),S.on("end",U=>{S.destroyed||N&&(N.message=b.trim(),v(N))}),S.resume();function v(U){let F,M,W;switch(!0){case(i&&c&&_):F=new Date(U.timestamp),M=new Date(l),W=new Date(u),U.level===o&&F>=M&&F<=W&&g<f?g++:U.level===o&&F>=M&&F<=W&&(mo(U,E,T),g++,g===h&&S.destroy());break;case(i&&c):F=new Date(U.timestamp),M=new Date(l),U.level===o&&F>=M&&g<f?g++:U.level===o&&F>=M&&(mo(U,E,T),g++,g===h&&S.destroy());break;case(i&&_):F=new Date(U.timestamp),W=new Date(u),U.level===o&&F<=W&&g<f?g++:U.level===o&&F<=W&&(mo(U,E,T),g++,g===h&&S.destroy());break;case(c&&_):F=new Date(U.timestamp),M=new Date(l),W=new Date(u),F>=M&&F<=W&&g<f?g++:F>=M&&F<=W&&(mo(U,E,T),g++,g===h&&S.destroy());break;case i:U.level===o&&g<f?g++:U.level===o&&(mo(U,E,T),g++,g===h&&S.destroy());break;case c:F=new Date(U.timestamp),M=new Date(l),F>=M&&g<f?g++:F>=M&&g>=f&&(mo(U,E,T),g++,g===h&&S.destroy());break;case _:F=new Date(U.timestamp),W=new Date(u),F<=W&&g<f?g++:F<=W&&g>=f&&(mo(U,E,T),g++,g===h&&S.destroy());break;default:g<f?g++:(mo(U,E,T),g++,g===h&&S.destroy())}}return a(v,"onLogMessage"),await M9(S,"close"),T}a(q9,"readLog");function mo(e,t,r){t==="desc"?F9(e,r):t==="asc"?k9(e,r):r.push(e)}a(mo,"pushLineToResult");function F9(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(F9,"insertDescending");function k9(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(k9,"insertAscending")});var HE=R((eAe,tv)=>{"use strict";var yR=require("joi"),{string:t_,boolean:XU,date:V9}=yR.types(),$9=nt(),{validateSchemaExists:JRe,validateTableExists:XRe,validateSchemaName:ZRe}=Ls(),Y9=D(),K9=Ze(),ZU=X();ZU.initSync();var W9=t_.invalid(ZU.get(Y9.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(K9.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(),ev={operation:t_.valid("add_node","update_node","set_node_replication"),node_name:W9,subscriptions:yR.array().items({table:t_.optional(),schema:t_.optional(),database:t_.optional(),subscribe:XU.required(),publish:XU.required().custom(j9),start_time:V9.iso()}).min(1).required()};function Q9(e){return $9.validateBySchema(e,yR.object(ev))}a(Q9,"addUpdateNodeValidator");function j9(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(j9,"checkForFalsy");tv.exports={addUpdateNodeValidator:Q9,validation_schema:ev}});var nv=R((rAe,rv)=>{var z9=nt(),J9={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};rv.exports=function(e){return z9.validateObject(e,J9)}});var GE=R((nAe,sv)=>{"use strict";var X9=D().OPERATIONS_ENUM,IR=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=X9.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};sv.exports=IR});var ov=R((iAe,iv)=>{"use strict";var Z9={OPERATION:"operation",REFRESH:"refresh"},wR=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},CR=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};iv.exports={JWTTokens:wR,TOKEN_TYPE_ENUM:Z9,JWTRSAKeys:CR}});var s_=R((aAe,uv)=>{"use strict";var n_=require("jsonwebtoken"),DR=require("fs-extra"),LR=Y(),Gn=D(),{handleHDBError:xr,hdb_errors:e7}=ie(),{HTTP_STATUS_CODES:qr,AUTHENTICATION_ERROR_MSGS:Fr}=e7,r_=k(),av=xf(),UR=Lr(),t7=Cr().update,r7=GE(),n7=hi(),{UserEventMsg:s7}=os(),So=X();So.initSync();var PR=require("path"),{JWTTokens:i7,JWTRSAKeys:o7,TOKEN_TYPE_ENUM:xE}=ov(),a7=So.get(Gn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?So.get(Gn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",c7=So.get(Gn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?So.get(Gn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",qE="RS256",MR;uv.exports={createTokens:l7,validateOperationToken:_7,refreshOperationToken:u7,validateRefreshToken:lv};async function l7(e){if(LR.isEmpty(e)||typeof e!="object")throw xr(new Error,Fr.INVALID_AUTH_OBJECT,qr.BAD_REQUEST,void 0,void 0,!0);if(LR.isEmpty(e.username))throw xr(new Error,Fr.USERNAME_REQUIRED,qr.BAD_REQUEST,void 0,void 0,!0);if(LR.isEmpty(e.password))throw xr(new Error,Fr.PASSWORD_REQUIRED,qr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await UR.findAndValidateUser(e.username,e.password),!t)throw xr(new Error,Fr.INVALID_CREDENTIALS,qr.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw r_.error(E),xr(new Error,Fr.INVALID_CREDENTIALS,qr.UNAUTHORIZED,void 0,void 0,!0)}let r=await FE(),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 cv(i,r.private_key,r.passphrase),c=await n_.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:c7,algorithm:qE,subject:xE.REFRESH}),l=av.hash(c),_=new r7(Gn.SYSTEM_SCHEMA_NAME,Gn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:l}]),u,d;try{u=await t7(_)}catch(E){r_.error(E),d=E}if(d!==void 0||u.skipped_hashes.length>0)throw xr(new Error,Fr.REFRESH_TOKEN_SAVE_FAILED,qr.INTERNAL_SERVER_ERROR);return n7.signalUserChange(new s7(process.pid)),new i7(o,c)}a(l7,"createTokens");async function cv(e,t,r){return await n_.sign(e,{key:t,passphrase:r},{expiresIn:a7,algorithm:qE,subject:xE.OPERATION})}a(cv,"signOperationToken");async function FE(){if(MR===void 0)try{let e=PR.join(So.getHdbBasePath(),Gn.LICENSE_KEY_DIR_NAME,Gn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=PR.join(So.getHdbBasePath(),Gn.LICENSE_KEY_DIR_NAME,Gn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=PR.join(So.getHdbBasePath(),Gn.LICENSE_KEY_DIR_NAME,Gn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await DR.readFile(e)).toString(),s=(await DR.readFile(t)).toString(),i=(await DR.readFile(r)).toString();MR=new o7(i,s,n)}catch(e){throw r_.error(e),xr(new Error,Fr.NO_ENCRYPTION_KEYS,qr.INTERNAL_SERVER_ERROR)}return MR}a(FE,"getJWTRSAKeys");async function u7(e){if(!e)throw xr(new Error,Fr.INVALID_BODY,qr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw xr(new Error,Fr.REFRESH_TOKEN_REQUIRED,qr.BAD_REQUEST,void 0,void 0,!0);await lv(e.refresh_token);let t=await FE(),r=await n_.decode(e.refresh_token);return{operation_token:await cv({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(u7,"refreshOperationToken");async function _7(e){try{let t=await FE(),r=await n_.verify(e,t.public_key,{algorithms:qE,subject:xE.OPERATION});return await UR.findAndValidateUser(r.username,void 0,!1)}catch(t){throw r_.warn(t),t.name&&t.name==="TokenExpiredError"?xr(new Error,Fr.TOKEN_EXPIRED,qr.FORBIDDEN):xr(new Error,Fr.INVALID_TOKEN,qr.UNAUTHORIZED)}}a(_7,"validateOperationToken");async function lv(e){let t;try{let r=await FE(),n=await n_.verify(e,r.public_key,{algorithms:qE,subject:xE.REFRESH});t=await UR.findAndValidateUser(n.username,void 0,!1)}catch(r){throw r_.warn(r),r.name&&r.name==="TokenExpiredError"?xr(new Error,Fr.TOKEN_EXPIRED,qr.FORBIDDEN):xr(new Error,Fr.INVALID_TOKEN,qr.UNAUTHORIZED)}if(!av.validate(t.refresh_token,e))throw xr(new Error,Fr.INVALID_TOKEN,qr.UNAUTHORIZED);return t}a(lv,"validateRefreshToken")});var vR=R((uAe,fv)=>{"use strict";var d7=nv(),Gc=require("passport"),f7=require("passport-local").Strategy,E7=require("passport-http").BasicStrategy,h7=require("util"),p7=Lr(),dv=h7.callbackify(p7.findAndValidateUser),lAe=rn(),m7=D(),_v=s_();Gc.use(new f7(function(e,t,r){dv(e,t,r)}));Gc.use(new E7(function(e,t,r){dv(e,t,r)}));Gc.serializeUser(function(e,t){t(null,e)});Gc.deserializeUser(function(e,t){t(null,e)});function S7(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":Gc.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===m7.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?_v.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):_v.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Gc.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(S7,"authorize");function T7(e,t){let r=d7(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(T7,"checkPermissions");fv.exports={authorize:S7,checkPermissions:T7}});var xc=R((dAe,Ev)=>{"use strict";var BR=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},HR=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};Ev.exports={Node:BR,NodeSubscription:HR}});var pv=R((EAe,hv)=>{"use strict";var g7=D().OPERATIONS_ENUM,GR=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=g7.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};hv.exports=GR});var i_=R((pAe,mv)=>{"use strict";var xR=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},qR=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)}};mv.exports={RemotePayloadObject:xR,RemotePayloadSubscription:qR}});var Tv=R((SAe,Sv)=>{"use strict";var FR=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}};Sv.exports=FR});var Av=R((OAe,Rv)=>{"use strict";var R7=Tv(),gAe=_t(),gv=Ye(),A7=k(),{getSchemaPath:RAe,getTransactionAuditStorePath:AAe}=ze(),{getDatabases:O7}=(Re(),ae($e));Rv.exports=b7;async function b7(e){let t=new R7;try{let r=O7()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await gv.environmentDataSize(schema_path,e.name),o=await gv.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){A7.warn(`unable to stat table dbi due to ${r}`)}return t}a(b7,"lmdbGetTableSize")});var bv=R((NAe,Ov)=>{"use strict";var kR=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}};Ov.exports=kR});var gi=R((LAe,wv)=>{"use strict";var N7=require("fs-extra"),y7=require("path"),pr=require("systeminformation"),To=k(),Nv=gt(),IAe=Ze(),VE=D(),I7=Av(),w7=Ei(),{getThreadInfo:yv}=rt(),ZR=X();ZR.initSync();var C7=bv(),{openEnvironment:wAe}=Ye(),{getSchemaPath:CAe}=ze(),{database:DAe,databases:VR}=(Re(),ae($e)),kE;wv.exports={getHDBProcessInfo:WR,getNetworkInfo:jR,getDiskInfo:QR,getMemoryInfo:KR,getCPUInfo:YR,getTimeInfo:$R,getSystemInformation:zR,systemInformation:D7,getTableSize:JR,getMetrics:XR};function $R(){return pr.time()}a($R,"getTimeInfo");async function YR(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:_,...u}=await pr.cpu();u.cpu_speed=await pr.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:m,raw_currentload_user:S,cpus:g,...T}=await pr.currentLoad();return T.cpus=[],g.forEach(b=>{let{raw_load:N,raw_load_idle:v,raw_load_irq:U,raw_load_nice:F,raw_load_system:M,raw_load_user:W,...z}=b;T.cpus.push(z)}),u.current_load=T,u}catch(e){return To.error(`error in getCPUInfo: ${e}`),{}}}a(YR,"getCPUInfo");async function KR(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await pr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return To.error(`error in getMemoryInfo: ${e}`),{}}}a(KR,"getMemoryInfo");async function WR(){let e={core:[],clustering:[]};try{let t=await pr.processes(),r;try{r=Number.parseInt(await N7.readFile(y7.join(ZR.get(VE.CONFIG_PARAMS.ROOTPATH),VE.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===VE.NODE_ERROR_CODES.ENOENT)To.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 To.error(`error in getHDBProcessInfo: ${t}`),e}}a(WR,"getHDBProcessInfo");async function QR(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await pr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:l,..._}=await pr.fsStats();return e.read_write=_,e.size=await pr.fsSize(),e}catch(t){return To.error(`error in getDiskInfo: ${t}`),e}}a(QR,"getDiskInfo");async function jR(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await pr.networkInterfaceDefault(),e.latency=await pr.inetChecksite("google.com"),(await pr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:l,ieee8021xAuth:_,ieee8021xState:u,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await pr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return To.error(`error in getNetworkInfo: ${t}`),e}}a(jR,"getNetworkInfo");async function zR(){if(kE!==void 0)return kE;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await pr.osInfo();e=c;let l=await pr.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,kE=e,kE}catch(t){return To.error(`error in getSystemInformation: ${t}`),e}}a(zR,"getSystemInformation");async function JR(){let e=[],t=await w7.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await I7(n));return e}a(JR,"getTableSize");async function XR(){let e={};for(let t in VR){let r=e[t]={},n=r.tables={};for(let s in VR[t])try{let i=VR[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(l=>{let[_,u,d]=l.trim().split(" ");return{pid:_,thread:u,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=o[l];n[s]=c}catch(i){To.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(XR,"getMetrics");async function Iv(){if(ZR.get(VE.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await Nv.getNATSReferences(),t=await Nv.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(Iv,"getNatsStreamInfo");async function D7(e){let t=new C7;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await zR(),t.time=$R(),t.cpu=await YR(),t.memory=await KR(),t.disk=await QR(),t.network=await jR(),t.harperdb_processes=await WR(),t.table_size=await JR(),t.metrics=await XR(),t.threads=await yv(),t.replication=await Iv(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await zR();break;case"time":t.time=$R();break;case"cpu":t.cpu=await YR();break;case"memory":t.memory=await KR();break;case"disk":t.disk=await QR();break;case"network":t.network=await jR();break;case"harperdb_processes":t.harperdb_processes=await WR();break;case"table_size":t.table_size=await JR();break;case"database_metrics":case"metrics":t.metrics=await XR();break;case"threads":t.threads=await yv();break;case"replication":t.replication=await Iv();break;default:break}return t}a(D7,"systemInformation")});var Ri=R((MAe,Cv)=>{"use strict";Cv.exports={version:L7,printVersion:P7};var $E=ma();function L7(){if($E)return $E.version}a(L7,"version");function P7(){$E&&console.log(`HarperDB Version ${$E.version}`)}a(P7,"printVersion")});var Ai=R((HAe,Mv)=>{"use strict";var M7=Cr(),eA=Y(),U7=require("util"),Na=D(),Dv=X();Dv.initSync();var v7=vR(),Lv=ur(),{Node:vAe,NodeSubscription:BAe}=xc(),B7=Nc(),H7=pv(),{RemotePayloadObject:G7,RemotePayloadSubscription:x7}=i_(),{handleHDBError:q7,hdb_errors:F7}=ie(),{HTTP_STATUS_CODES:k7,HDB_ERROR_MSGS:V7}=F7,$7=as(),Y7=gi(),K7=Ri(),{getDatabases:W7}=(Re(),ae($e)),Q7=U7.promisify(v7.authorize),j7=Lv.searchByHash,z7=Lv.searchByValue;Mv.exports={authHeaderToUser:J7,isEmpty:X7,getNodeRecord:Z7,upsertNodeRecord:eee,buildNodePayloads:tee,checkClusteringEnabled:ree,getAllNodeRecords:nee,getSystemInfo:see,reverseSubscription:Pv};async function J7(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await Q7(t,null),e}a(J7,"authHeaderToUser");function X7(e){return e==null}a(X7,"isEmpty");async function Z7(e){let t=new B7(Na.SYSTEM_SCHEMA_NAME,Na.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return j7(t)}a(Z7,"getNodeRecord");async function eee(e){let t=new H7(Na.SYSTEM_SCHEMA_NAME,Na.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return M7.upsert(t)}a(eee,"upsertNodeRecord");function Pv(e){if(eA.isEmpty(e.subscribe)||eA.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(Pv,"reverseSubscription");function tee(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:l,table:_}=c,u=eA.getTableHashAttribute(l,_),{subscribe:d,publish:E}=Pv(c),f=W7()[l]?.[_],h=new x7(l,_,u,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new G7(r,t,s,n)}a(tee,"buildNodePayloads");function ree(){if(!Dv.get(Na.CONFIG_PARAMS.CLUSTERING_ENABLED))throw q7(new Error,V7.CLUSTERING_NOT_ENABLED,k7.BAD_REQUEST,void 0,void 0,!0)}a(ree,"checkClusteringEnabled");async function nee(){let e=new $7(Na.SYSTEM_SCHEMA_NAME,Na.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await z7(e))}a(nee,"getAllNodeRecords");async function see(){let e=await Y7.getSystemInformation();return{hdb_version:K7.version(),node_version:e.node_version,platform:e.platform}}a(see,"getSystemInfo")});var tA=R((xAe,Fv)=>{"use strict";var YE=gt(),Uv=Y(),vv=Ze(),Bv=D(),KE=k(),Hv=LE(),iee=Uu(),{RemotePayloadObject:oee}=i_(),{handleHDBError:Gv,hdb_errors:aee}=ie(),{HTTP_STATUS_CODES:xv}=aee,{NodeSubscription:qv}=xc();Fv.exports=cee;async function cee(e,t){let r;try{r=await YE.request(`${t}.${vv.REQUEST_SUFFIX}`,new oee(Bv.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),KE.trace("Response from remote describe all request:",r)}catch(o){KE.error(`addNode received error from describe all request to remote node: ${o}`);let c=YE.requestErrorHandler(o,"add_node",t);throw Gv(new Error,c,xv.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===vv.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw Gv(new Error,o,xv.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,l=o.database??o.schema??"data";if(l===Bv.SYSTEM_SCHEMA_NAME){await YE.createLocalTableStream(l,c);let h=new qv(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=Uv.doesSchemaExist(l),u=n[l]!==void 0,d=c?Uv.doesTableExist(l,c):!0,E=c?n?.[l]?.[c]!==void 0:!0;if(!_&&!u||!d&&!E){s.push(o);continue}if(!_&&u&&(KE.trace(`addNode creating schema: ${l}`),await Hv.createSchema({operation:"create_schema",schema:l})),!d&&E){KE.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new iee(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await Hv.createTable(h)}await YE.createLocalTableStream(l,c);let f=new qv(l,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(cee,"reviewSubscriptions")});var c_=R((FAe,$v)=>{"use strict";var{handleHDBError:WE,hdb_errors:lee}=ie(),{HTTP_STATUS_CODES:QE}=lee,{addUpdateNodeValidator:uee}=HE(),jE=k(),Vv=D(),kv=Ze(),_ee=Y(),o_=gt(),a_=Ai(),dee=X(),fee=tA(),{Node:Eee,NodeSubscription:hee}=xc(),{broadcast:pee}=rt(),mee="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",See="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Tee=dee.get(Vv.CONFIG_PARAMS.CLUSTERING_NODENAME);$v.exports=gee;async function gee(e,t=!1){jE.trace("addNode called with:",e),a_.checkClusteringEnabled();let r=uee(e);if(r)throw WE(r,r.message,QE.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await a_.getNodeRecord(n);if(!_ee.isEmptyOrZeroLength(d))throw WE(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,QE.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await fee(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=mee,o;let c=a_.buildNodePayloads(s,Tee,Vv.OPERATIONS_ENUM.ADD_NODE,await a_.getSystemInfo()),l=[];for(let d=0,E=s.length;d<E;d++){let f=s[d];s[d].start_time===void 0&&delete s[d].start_time,l.push(new hee(f.schema,f.table,f.publish,f.subscribe))}jE.trace("addNode sending remote payload:",c);let _;try{_=await o_.request(`${n}.${kv.REQUEST_SUFFIX}`,c)}catch(d){jE.error(`addNode received error from request: ${d}`);for(let f=0,h=s.length;f<h;f++){let m=s[f];m.publish=!1,m.subscribe=!1,await o_.updateRemoteConsumer(m,n)}let E=o_.requestErrorHandler(d,"add_node",n);throw WE(new Error,E,QE.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===kv.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw WE(new Error,d,QE.INTERNAL_SERVER_ERROR,"error",d)}jE.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await o_.updateRemoteConsumer(f,n),f.subscribe===!0&&await o_.updateConsumerIterator(f.schema,f.table,n,"start")}let u=new Eee(n,l,_.system_info);return await a_.upsertNodeRecord(u),pee({type:"nats_update"}),i.length>0?o.message=See:o.message=`Successfully added '${n}' to manifest`,o}a(gee,"addNode")});var sA=R(($Ae,Wv)=>{"use strict";var{handleHDBError:rA,hdb_errors:Ree}=ie(),{HTTP_STATUS_CODES:nA}=Ree,{addUpdateNodeValidator:Aee}=HE(),l_=k(),Kv=D(),Yv=Ze(),VAe=Y(),u_=gt(),__=Ai(),Oee=X(),{cloneDeep:bee}=require("lodash"),Nee=tA(),{Node:yee,NodeSubscription:Iee}=xc(),{broadcast:wee}=rt(),Cee="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Dee="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Lee=Oee.get(Kv.CONFIG_PARAMS.CLUSTERING_NODENAME);Wv.exports=Pee;async function Pee(e){l_.trace("updateNode called with:",e),__.checkClusteringEnabled();let t=Aee(e);if(t)throw rA(t,t.message,nA.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await __.getNodeRecord(r);s.length>0&&(n=bee(s));let{added:i,skipped:o}=await Nee(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=Cee,c;let l=__.buildNodePayloads(i,Lee,Kv.OPERATIONS_ENUM.UPDATE_NODE,await __.getSystemInfo());for(let u=0,d=i.length;u<d;u++){let E=i[u];l_.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[u].start_time===void 0&&delete i[u].start_time}l_.trace("updateNode sending remote payload:",l);let _;try{_=await u_.request(`${r}.${Yv.REQUEST_SUFFIX}`,l)}catch(u){l_.error(`updateNode received error from request: ${u}`);let d=u_.requestErrorHandler(u,"update_node",r);throw rA(new Error,d,nA.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===Yv.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw rA(new Error,u,nA.INTERNAL_SERVER_ERROR,"error",u)}l_.trace(_);for(let u=0,d=i.length;u<d;u++){let E=i[u];await u_.updateRemoteConsumer(E,r),E.subscribe===!0?await u_.updateConsumerIterator(E.schema,E.table,r,"start"):await u_.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new yee(r,[],_.system_info)]),await Mee(n[0],i,_.system_info),o.length>0?c.message=Dee:c.message=`Successfully updated '${r}'`,c}a(Pee,"updateNode");async function Mee(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let l=0,_=e.subscriptions.length;l<_;l++){let u=n.subscriptions[l];if(u.schema===o.schema&&u.table===o.table){u.publish=o.publish,u.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new Iee(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await __.upsertNodeRecord(n),wee({type:"nats_update"})}a(Mee,"updateNodeTable")});var Xv=R((KAe,Jv)=>{"use strict";var zv=require("joi"),{string:Qv}=zv.types(),Uee=nt(),jv=D(),vee=X(),Bee=Ze();Jv.exports=Hee;function Hee(e){let t=Qv.invalid(vee.get(jv.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Bee.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=zv.object({operation:Qv.valid(jv.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Uee.validateBySchema(e,r)}a(Hee,"removeNodeValidator")});var JE=R((QAe,n0)=>{"use strict";var{handleHDBError:Zv,hdb_errors:Gee}=ie(),{HTTP_STATUS_CODES:e0}=Gee,xee=Xv(),d_=k(),t0=Ai(),qee=Y(),zE=D(),r0=Ze(),iA=gt(),Fee=X(),{RemotePayloadObject:kee}=i_(),{NodeSubscription:Vee}=xc(),$ee=Mu(),Yee=ia(),{broadcast:Kee}=rt(),Wee=Fee.get(zE.CONFIG_PARAMS.CLUSTERING_NODENAME);n0.exports=Qee;async function Qee(e){d_.trace("removeNode called with:",e),t0.checkClusteringEnabled();let t=xee(e);if(t)throw Zv(t,t.message,e0.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await t0.getNodeRecord(r);if(qee.isEmptyOrZeroLength(n))throw Zv(new Error,`Node '${r}' was not found.`,e0.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new kee(zE.OPERATIONS_ENUM.REMOVE_NODE,Wee,[]),i,o=!1;for(let l=0,_=n.subscriptions.length;l<_;l++){let u=n.subscriptions[l];u.subscribe===!0&&await iA.updateConsumerIterator(u.schema,u.table,r,"stop");try{await iA.updateRemoteConsumer(new Vee(u.schema,u.table,!1,!1),r)}catch(d){d_.error(d)}}try{i=await iA.request(`${r}.${r0.REQUEST_SUFFIX}`,s),d_.trace("Remove node reply from remote node:",r,i)}catch(l){d_.error("removeNode received error from request:",l),o=!0}let c=new $ee(zE.SYSTEM_SCHEMA_NAME,zE.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Yee.deleteRecord(c),Kee({type:"nats_update"}),i?.status===r0.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(d_.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(Qee,"removeNode")});var o0=R((zAe,i0)=>{"use strict";var s0=require("joi"),{string:jee,array:zee}=s0.types(),Jee=nt(),Xee=HE();i0.exports=Zee;function Zee(e){let t=s0.object({operation:jee.valid("configure_cluster").required(),connections:zee.items(Xee.validation_schema).required()});return Jee.validateBySchema(e,t)}a(Zee,"configureClusterValidator")});var ZE=R((XAe,_0)=>{"use strict";var ete=D(),XE=k(),tte=Y(),rte=JE(),nte=c_(),a0=Ai(),ste=o0(),{handleHDBError:c0,hdb_errors:ite}=ie(),{HTTP_STATUS_CODES:l0}=ite,ote="Configure cluster complete.",ate="Failed to configure the cluster. Check the logs for more details.",cte="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";_0.exports=lte;async function lte(e){XE.trace("configure cluster called with:",e),a0.checkClusteringEnabled();let t=ste(e);if(t)throw c0(t,t.message,l0.BAD_REQUEST,void 0,void 0,!0);let r=await a0.getAllNodeRecords(),n=[];for(let u=0,d=r.length;u<d;u++){let E=await u0(rte,{operation:ete.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[u].name},r[u].name);n.push(E)}XE.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let u=0;u<i;u++){let d=e.connections[u],E=await u0(nte,d,d.node_name);s.push(E)}XE.trace("All results from configure_cluster add node:",s);let o=[],c=[],l=!1,_=n.concat(s);for(let u=0,d=_.length;u<d;u++){let E=_[u];E.status==="rejected"&&(XE.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(l=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(tte.isEmptyOrZeroLength(o))return{message:ote,connections:c};if(l)return{message:cte,failed_nodes:o,connections:c};throw c0(new Error,ate,l0.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(lte,"configureCluster");async function u0(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(u0,"functionWrapper")});var h0=R((eOe,E0)=>{"use strict";var f_=require("joi"),ute=nt(),{validateSchemaExists:d0,validateTableExists:_te,validateSchemaName:f0}=Ls(),dte=f_.object({operation:f_.string().valid("purge_stream"),schema:f_.string().custom(d0).custom(f0).optional(),database:f_.string().custom(d0).custom(f0).optional(),table:f_.string().custom(_te).required()});function fte(e){return ute.validateBySchema(e,dte)}a(fte,"purgeStreamValidator");E0.exports=fte});var oA=R((rOe,p0)=>{"use strict";var{handleHDBError:Ete,hdb_errors:hte}=ie(),{HTTP_STATUS_CODES:pte}=hte,mte=h0(),Ste=gt(),Tte=Ai();p0.exports=gte;async function gte(e){e.schema=e.schema??e.database;let t=mte(e);if(t)throw Ete(t,t.message,pte.BAD_REQUEST,void 0,void 0,!0);Tte.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await Ste.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(gte,"purgeStream")});var th=R((sOe,A0)=>{"use strict";var cA=Ai(),Rte=gt(),T0=X(),eh=D(),ya=Ze(),Ate=Y(),aA=k(),{RemotePayloadObject:Ote}=i_(),{ErrorCode:m0}=require("nats"),S0=T0.get(eh.CONFIG_PARAMS.CLUSTERING_ENABLED),g0=T0.get(eh.CONFIG_PARAMS.CLUSTERING_NODENAME);A0.exports={clusterStatus:bte,buildNodeStatus:R0};async function bte(){let e={node_name:g0,is_enabled:S0,connections:[]};if(!S0)return e;let t=await cA.getAllNodeRecords();if(Ate.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(R0(t[n],e.connections));return await Promise.allSettled(r),e}a(bte,"clusterStatus");async function R0(e,t){let r=e.name,n=new Ote(eh.OPERATIONS_ENUM.CLUSTER_STATUS,g0,void 0,await cA.getSystemInfo()),s,i,o=ya.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await Rte.request(ya.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===ya.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=ya.CLUSTER_STATUS_STATUSES.CLOSED,aA.error(`Error getting node status from ${r} `,s))}catch(l){aA.warn(`Error getting node status from ${r}`,l),l.code===m0.NoResponders?o=ya.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===m0.Timeout?o=ya.CLUSTER_STATUS_STATUSES.TIMEOUT:o=ya.CLUSTER_STATUS_STATUSES.CLOSED}let c=new Nte(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let l={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==eh.PRE_4_0_0_VERSION&&await cA.upsertNodeRecord(l)}catch(l){aA.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(R0,"buildNodeStatus");function Nte(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(Nte,"NodeStatusObject")});var nh=R((oOe,O0)=>{"use strict";var{handleHDBError:yte,hdb_errors:Ite}=ie(),{HTTP_STATUS_CODES:wte}=Ite,Cte=gt(),Dte=Ai(),lA=Y(),rh=require("joi"),Lte=nt(),Pte=2e3,Mte=rh.object({timeout:rh.number().min(1),connected_nodes:rh.boolean(),routes:rh.boolean()});O0.exports=Ute;async function Ute(e){Dte.checkClusteringEnabled();let t=Lte.validateBySchema(e,Mte);if(t)throw yte(t,t.message,wte.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||lA.autoCastBoolean(n),o=s===void 0||lA.autoCastBoolean(s),c={nodes:[]},l=await Cte.getServerList(r??Pte),_={};if(i)for(let u=0,d=l.length;u<d;u++){let E=l[u].statsz;E&&(_[l[u].server.name]=E.routes)}for(let u=0,d=l.length;u<d;u++){if(l[u].statsz)continue;let E=l[u].server,f=l[u].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:l[u].response_time};i&&(h.connected_nodes=[],_[E.name]&&_[E.name].forEach(m=>{h.connected_nodes.includes(m.name.slice(0,-4))||h.connected_nodes.push(m.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(m=>({host:m.split(":")[0],port:lA.autoCast(m.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Ute,"clusterNetwork")});var I0=R((cOe,y0)=>{"use strict";var uA=require("joi"),b0=nt(),{route_constraints:N0}=CT();y0.exports={setRoutesValidator:vte,deleteRoutesValidator:Bte};function vte(e){let t=uA.object({server:uA.valid("hub","leaf").required(),routes:N0.required()});return b0.validateBySchema(e,t)}a(vte,"setRoutesValidator");function Bte(e){let t=uA.object({routes:N0.required()});return b0.validateBySchema(e,t)}a(Bte,"deleteRoutesValidator")});var ih=R((uOe,L0)=>{"use strict";var Ia=Et(),_A=Y(),sh=D(),w0=I0(),{handleHDBError:C0,hdb_errors:Hte}=ie(),{HTTP_STATUS_CODES:D0}=Hte,Gte="cluster routes successfully set",xte="cluster routes successfully deleted";L0.exports={setRoutes:qte,getRoutes:Fte,deleteRoutes:kte};function qte(e){let t=w0.setRoutesValidator(e);if(t)throw C0(t,t.message,D0.BAD_REQUEST,void 0,void 0,!0);let r=Ia.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,l=e.routes.length;c<l;c++){let _=e.routes[c];_.port=_A.autoCast(_.port);let u=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);u||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Ia.updateConfigValue(sh.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Ia.updateConfigValue(sh.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:Gte,set:o,skipped:i}}a(qte,"setRoutes");function Fte(){let e=Ia.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(Fte,"getRoutes");function kte(e){let t=w0.deleteRoutesValidator(e);if(t)throw C0(t,t.message,D0.BAD_REQUEST,void 0,void 0,!0);let r=Ia.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,l=!1;for(let _=0,u=e.routes.length;_<u;_++){let d=e.routes[_],E=!1;for(let f=0,h=n.length;f<h;f++){let m=n[f];if(d.host===m.host&&d.port===m.port){n.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,m=s.length;h<m;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),l=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=_A.isEmptyOrZeroLength(n)?null:n,Ia.updateConfigValue(sh.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),l&&(s=_A.isEmptyOrZeroLength(s)?null:s,Ia.updateConfigValue(sh.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:xte,deleted:i,skipped:o}}a(kte,"deleteRoutes")});var M0=R((dOe,P0)=>{"use strict";var E_=require("alasql"),wa=require("recursive-iterator"),ds=k(),Vte=Y(),h_=D(),dA=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,Yte(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=>h_.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=>!h_.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][h_.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=$te(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let l=this.affected_attributes.get(i).get(o).filter(_=>!h_.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let u=new E_.yy.Column({columnid:_});s.tableid&&(u.tableid=s.tableid),this.ast.columns.push(u),l.includes(_)||l.push(_)}),this.affected_attributes.get(i).set(o,l)}}),this.ast}};function $te(e){return e.filter(t=>t[h_.PERMS_CRUD_ENUM.READ])}a($te,"filterReadRestrictedAttrs");function Yte(e,t,r,n,s){Kte(e,t,r,n,s)}a(Yte,"interpretAST");function p_(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(p_,"addSchemaTableToMap");function Kte(e,t,r,n,s){if(!e){ds.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof E_.yy.Insert?zte(e,t,r):e instanceof E_.yy.Select?Wte(e,t,r,n,s):e instanceof E_.yy.Update?Qte(e,t,r):e instanceof E_.yy.Delete?jte(e,t,r):ds.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(Kte,"getRecordAttributesAST");function Wte(e,t,r,n,s){if(!e){ds.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(Vte.isEmptyOrZeroLength(i)){ds.error("No schema specified");return}e.from.forEach(c=>{p_(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),p_(c.table,t,r,n,s)});let o=new wa(e.columns);for(let{node:c}of o)if(c&&c.columnid){let l=c.tableid,_=n.has(l)?n.get(l):i;if(l||(l=e.from[0].tableid),!t.get(_).has(l))if(r.has(l))l=r.get(l);else{ds.info(`table specified as ${l} not found.`);return}t.get(_).get(l).indexOf(c.columnid)<0&&t.get(_).get(l).push(c.columnid)}if(e.where){let c=new wa(e.where),l=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let u=_.tableid?_.tableid:l;if(!t.get(i).has(u))if(r.has(u))u=r.get(u);else{ds.info(`table specified as ${u} not found.`);continue}t.get(i).get(u).indexOf(_.columnid)<0&&t.get(i).get(u).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let l=new wa(c.on);for(let{node:_}of l)if(_&&_.columnid){let u=_.tableid,d=s.get(u);if(!t.get(d).has(u))if(r.has(u))u=r.get(u);else{ds.info(`table specified as ${u} not found.`);continue}t.get(d).get(u).indexOf(_.columnid)<0&&t.get(d).get(u).push(_.columnid)}}),e.order){let c=new wa(e.order);for(let{node:l}of c)if(l&&l.columnid){let _=l.tableid,u=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(u).has(_))if(r.has(_))_=r.get(_);else{ds.info(`table specified as ${_} not found.`);return}t.get(u).get(_).indexOf(l.columnid)<0&&t.get(u).get(_).push(l.columnid)}}}a(Wte,"getSelectAttributes");function Qte(e,t,r){if(!e){ds.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new wa(e.columns),s=e.table.databaseid;p_(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&fA(e.table.tableid,s,i.columnid,t,r)}a(Qte,"getUpdateAttributes");function jte(e,t,r){if(!e){ds.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new wa(e.where),s=e.table.databaseid;p_(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&fA(e.table.tableid,s,i.columnid,t,r)}a(jte,"getDeleteAttributes");function zte(e,t,r){if(!e){ds.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new wa(e.columns),s=e.into.databaseid;p_(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&fA(e.into.tableid,s,i.columnid,t,r)}a(zte,"getInsertAttributes");function fA(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(fA,"pushAttribute");P0.exports=dA});var ah=R((EOe,H0)=>{var oh=la(),U0=require("chalk"),En=k(),v0=require("prompt"),{promisify:Jte}=require("util"),EA=D(),Xte=require("fs-extra"),Zte=require("path"),ere=Y(),tre=Ri(),B0=X();B0.initSync();var rre=require("moment"),nre=Jte(v0.get),sre=Zte.join(B0.getHdbBasePath(),EA.LICENSE_KEY_DIR_NAME,EA.LICENSE_FILE_NAME,EA.LICENSE_FILE_NAME);H0.exports={getFingerprint:ore,setLicense:ire,parseLicense:hA,register:are,getRegistrationInfo:lre};async function ire(e){if(e&&e.key&&e.company){try{En.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await hA(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw En.error(r),En.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(ire,"setLicense");async function ore(){let e={};try{e=await oh.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw En.error(r),En.error(t),new Error(r)}return e}a(ore,"getFingerprint");async function hA(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");En.info("Validating license input...");let r=oh.validateLicense(e,t);if(En.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(En.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(En.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{En.info("writing license to disk"),await Xte.writeFile(sre,JSON.stringify({license_key:e,company:t}))}catch(n){throw En.error("Failed to write License"),n}return"Registration successful."}a(hA,"parseLicense");async function are(){let e=await cre();return hA(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(are,"register");async function cre(){let e=await oh.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:U0.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:U0.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{v0.start()}catch(n){En.error(n)}let r;try{r=await nre(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(cre,"promptForRegistration");async function lre(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await oh.getLicense()}catch(r){throw En.error(`There was an error when searching licenses due to: ${r.message}`),r}if(ere.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=tre.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=rre.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(lre,"getRegistrationInfo")});var x0=R((pOe,G0)=>{"use strict";var ure=Ze(),pA=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,l,_,u,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+ure.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:l},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};G0.exports=pA});var k0=R((SOe,F0)=>{"use strict";var q0=Ze(),mA=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,l,_,u,d){this.port=t,d===null&&(d=void 0),this.server_name=r+q0.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+q0.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:u,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:l,jetstream:"enabled"}},this.system_account="SYS"}};F0.exports=mA});var $0=R((gOe,V0)=>{"use strict";var SA=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};V0.exports=SA});var K0=R((AOe,Y0)=>{"use strict";var _re=Ze(),TA=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+_re.SERVER_SUFFIX.ADMIN,this.password=r}};Y0.exports=TA});var dh=R((bOe,j0)=>{"use strict";var qc=require("path"),uh=require("fs-extra"),dre=x0(),fre=k0(),Ere=$0(),hre=K0(),gA=Lr(),kc=Y(),kr=Et(),lh=D(),m_=Ze(),{CONFIG_PARAMS:At}=lh,Vc=k(),S_=X(),W0=fi(),RA=gt(),Fc="clustering",pre=1e4,Q0=50;j0.exports={generateNatsConfig:Sre,removeNatsConfig:Tre,getHubConfigPath:mre};function mre(){let e=S_.get(At.ROOTPATH);return qc.join(e,Fc,m_.NATS_CONFIG_FILES.HUB_SERVER)}a(mre,"getHubConfigPath");async function Sre(e=!1,t=void 0){S_.initSync();let r=S_.get(At.ROOTPATH),n=qc.join(r,Fc,m_.PID_FILES.HUB),s=qc.join(r,Fc,m_.PID_FILES.LEAF),i=kr.getConfigFromFile(At.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=qc.join(r,Fc,m_.NATS_CONFIG_FILES.HUB_SERVER),c=qc.join(r,Fc,m_.NATS_CONFIG_FILES.LEAF_SERVER),l=kr.getConfigFromFile(At.CLUSTERING_TLS_CERTIFICATE),_=kr.getConfigFromFile(At.CLUSTERING_TLS_PRIVATEKEY),u=kr.getConfigFromFile(At.CLUSTERING_TLS_CERT_AUTH),d=kr.getConfigFromFile(At.CLUSTERING_TLS_INSECURE),E=kr.getConfigFromFile(At.CLUSTERING_TLS_VERIFY),f=kr.getConfigFromFile(At.CLUSTERING_NODENAME),h=kr.getConfigFromFile(At.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await RA.checkNATSServerInstalled()||_h("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let m=await gA.listUsers(),S=kr.getConfigFromFile(At.CLUSTERING_USER),g=await gA.getClusterUser();(kc.isEmpty(g)||g.active!==!0)&&_h(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await ch(At.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await ch(At.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await ch(At.CLUSTERING_HUBSERVER_NETWORK_PORT),await ch(At.CLUSTERING_LEAFSERVER_NETWORK_PORT));let T=[],b=[];for(let[z,J]of m.entries())J.role.role===lh.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(T.push(new hre(J.username,W0.decrypt(J.hash))),b.push(new Ere(J.username,W0.decrypt(J.hash))));let N=[],{hub_routes:v}=kr.getClusteringRoutes();if(!kc.isEmptyOrZeroLength(v))for(let z of v)N.push(`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@${z.host}:${z.port}`);let U=new dre(kr.getConfigFromFile(At.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,l,_,u,d,E,h,kr.getConfigFromFile(At.CLUSTERING_HUBSERVER_CLUSTER_NAME),kr.getConfigFromFile(At.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),N,T,b);u==null&&(delete U.tls.ca_file,delete U.leafnodes.tls.ca_file),t=kc.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===lh.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await uh.writeJson(o,U),Vc.trace(`Hub server config written to ${o}`));let F=`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,M=`tls://${g.uri_encoded_name}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,W=new fre(kr.getConfigFromFile(At.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[F],[M],T,b,l,_,u,d);u==null&&delete W.tls.ca_file,(t===void 0||t===lh.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await uh.writeJson(c,W),Vc.trace(`Leaf server config written to ${c}`))}a(Sre,"generateNatsConfig");async function ch(e){let t=S_.get(e);return kc.isEmpty(t)&&_h(`port undefined for '${e}'`),await kc.isPortTaken(t)&&_h(`'${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(ch,"isPortAvailable");function _h(e){let t=`Error generating clustering config: ${e}`;Vc.error(t),console.error(t),process.exit(1)}a(_h,"generateNatsConfigError");async function Tre(e){let{port:t,config_file:r}=RA.getServerConfig(e),{username:n,decrypt_hash:s}=await gA.getClusterUser(),i=0,o=2e3;for(;i<Q0;){try{let u=await RA.createConnection(t,n,s,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Vc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=Q0)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&&Vc.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await kc.async_set_timeout(_)}let c="0".repeat(pre),l=qc.join(S_.get(At.ROOTPATH),Fc,r);await uh.writeFile(l,c),await uh.remove(l),Vc.notify(e,"started.")}a(Tre,"removeNatsConfig")});var tB=R((yOe,eB)=>{"use strict";var hn=X(),gre=la(),Te=D(),T_=Ze(),Oi=require("path"),{PACKAGE_ROOT:Eh}=D(),z0=X(),fh=Y(),$c="/dev/null",Rre=Oi.join(Eh,"launchServiceScripts"),J0=Oi.join(Eh,"utility/scripts"),Are=Oi.join(J0,Te.HDB_RESTART_SCRIPT),X0=Oi.resolve(Eh,"dependencies",`${process.platform}-${process.arch}`,T_.NATS_BINARY_NAME);function Z0(){let t=gre.licenseSearch().ram_allocation||Te.RAM_ALLOCATION_ENUM.DEFAULT,r=Te.MEM_SETTING_KEY+t,n={[Te.PROCESS_NAME_ENV_PROP]:Te.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return fh.noBootFile()&&(n[Te.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=fh.getEnvCliRootPath()),{name:Te.PROCESS_DESCRIPTORS.HDB,script:Te.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:Eh}}a(Z0,"generateMainServerConfig");var Ore=9930;function bre(){hn.initSync(!0);let e=hn.get(Te.CONFIG_PARAMS.ROOTPATH),t=Oi.join(e,"clustering",T_.NATS_CONFIG_FILES.HUB_SERVER),r=Oi.join(hn.get(Te.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Te.LOG_NAMES.HDB),n=z0.get(Te.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=T_.LOG_LEVEL_FLAGS[hn.get(Te.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==Ore?"-"+n:""),script:X0,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Te.PROCESS_NAME_ENV_PROP]:Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return hn.get(Te.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=$c,i.error_file=$c),i}a(bre,"generateNatsHubServerConfig");var Nre=9940;function yre(){hn.initSync(!0);let e=hn.get(Te.CONFIG_PARAMS.ROOTPATH),t=Oi.join(e,"clustering",T_.NATS_CONFIG_FILES.LEAF_SERVER),r=Oi.join(hn.get(Te.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Te.LOG_NAMES.HDB),n=z0.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=T_.LOG_LEVEL_FLAGS[hn.get(Te.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==Nre?"-"+n:""),script:X0,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Te.PROCESS_NAME_ENV_PROP]:Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return hn.get(Te.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=$c,i.error_file=$c),i}a(yre,"generateNatsLeafServerConfig");function Ire(){hn.initSync();let e=Oi.join(hn.get(Te.CONFIG_PARAMS.LOGGING_ROOT),Te.LOG_NAMES.HDB),t={name:Te.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Te.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Te.PROCESS_NAME_ENV_PROP]:Te.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Rre,autorestart:!1};return hn.get(Te.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=$c,t.error_file=$c),t}a(Ire,"generateClusteringUpgradeV4ServiceConfig");function wre(){let e={[Te.PROCESS_NAME_ENV_PROP]:Te.PROCESS_DESCRIPTORS.RESTART_HDB};return fh.noBootFile()&&(e[Te.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=fh.getEnvCliRootPath()),{...{name:Te.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:J0},script:Are}}a(wre,"generateRestart");function Cre(){return{apps:[Z0()]}}a(Cre,"generateAllServiceConfigs");eB.exports={generateAllServiceConfigs:Cre,generateMainServerConfig:Z0,generateRestart:wre,generateNatsHubServerConfig:bre,generateNatsLeafServerConfig:yre,generateClusteringUpgradeV4ServiceConfig:Ire}});var Yc=R((COe,EB)=>{"use strict";var He=D(),Dre=Y(),Ni=dh(),hh=gt(),bi=Ze(),go=tB(),ph=X(),Ro=k(),Lre=Ai(),{startWorker:rB,onMessageFromWorkers:Pre}=rt(),Mre=gi(),wOe=require("util"),Ure=require("child_process"),vre=require("fs"),{execFile:Bre}=Ure,De;EB.exports={enterPM2Mode:Hre,start:Ao,stop:AA,reload:sB,restart:iB,list:OA,describe:aB,connect:yi,kill:kre,startAllServices:Vre,startService:bA,getUniqueServicesList:cB,restartAllServices:$re,isServiceRegistered:lB,reloadStopStart:uB,restartHdb:oB,deleteProcess:qre,startClusteringProcesses:dB,startClusteringThreads:fB,isHdbRestartRunning:Fre,isClusteringRunning:Kre,stopClustering:Yre,reloadClustering:Wre};var g_=!1;Pre(e=>{e.type==="restart"&&ph.initSync(!0)});function Hre(){g_=!0}a(Hre,"enterPM2Mode");function yi(){return De||(De=require("pm2")),new Promise((e,t)=>{De.connect((r,n)=>{Ro.setupConsoleLogging(),r&&t(r),e(n)})})}a(yi,"connect");var Vr,Gre=10,nB;function Ao(e,t=!1){if(g_)return xre(e);let r=Bre(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Vr.indexOf(r);o>-1&&Vr.splice(o,1),!nB&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<Gre&&(vre.existsSync(Ni.getHubConfigPath())?Ao(e):(await Ni.generateNatsConfig(!0),Ao(e),await new Promise(c=>setTimeout(c,3e3)),await Ni.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ni.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=ph.get(He.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,l,_=0,u;for(;l=c.exec(i);){if(l.index&&bi.LOG_LEVEL_HIERARCHY[o]>=bi.LOG_LEVEL_HIERARCHY[u||"info"]){let f=u===bi.LOG_LEVELS.ERR||u===bi.LOG_LEVELS.WRN?Ro.OUTPUTS.STDERR:Ro.OUTPUTS.STDOUT;Ro.logCustomLevel(u||"info",f,n,i.slice(_,l.index).trim())}let[d,E]=l;_=l.index+d.length,u=bi.LOG_LEVELS[E]}if(bi.LOG_LEVEL_HIERARCHY[o]>=bi.LOG_LEVEL_HIERARCHY[u||"info"]){let d=u===bi.LOG_LEVELS.ERR||u===bi.LOG_LEVELS.WRN?Ro.OUTPUTS.STDERR:Ro.OUTPUTS.STDOUT;Ro.logCustomLevel(u||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Vr=[],!Vr&&!t){let i=a(()=>{nB=!0,Vr&&(Vr.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)}Vr.push(r)}a(Ao,"start");function xre(e){return new Promise(async(t,r)=>{try{await yi()}catch(n){r(n)}De.start(e,(n,s)=>{n&&(De.disconnect(),r(n)),De.disconnect(),t(s)})})}a(xre,"startWithPM2");function AA(e){if(!g_){for(let t of Vr||[])t.name===e&&(Vr.splice(Vr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await yi()}catch(n){r(n)}De.stop(e,async(n,s)=>{n&&(De.disconnect(),r(n)),De.delete(e,(i,o)=>{i&&(De.disconnect(),r(n)),De.disconnect(),t(o)})})})}a(AA,"stop");function sB(e){return new Promise(async(t,r)=>{try{await yi()}catch(n){r(n)}De.reload(e,(n,s)=>{n&&(De.disconnect(),r(n)),De.disconnect(),t(s)})})}a(sB,"reload");function iB(e){if(!g_)for(let t of Vr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await yi()}catch(n){r(n)}De.restart(e,(n,s)=>{De.disconnect(),t(s)})})}a(iB,"restart");function qre(e){return new Promise(async(t,r)=>{try{await yi()}catch(n){r(n)}De.delete(e,(n,s)=>{n&&(De.disconnect(),r(n)),De.disconnect(),t(s)})})}a(qre,"deleteProcess");async function oB(){await Ao(go.generateRestart())}a(oB,"restartHdb");async function Fre(){let e=await OA();for(let t in e)if(e[t].name===He.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(Fre,"isHdbRestartRunning");function OA(){return new Promise(async(e,t)=>{try{await yi()}catch(r){t(r)}De.list((r,n)=>{r&&(De.disconnect(),t(r)),De.disconnect(),e(n)})})}a(OA,"list");function aB(e){return new Promise(async(t,r)=>{try{await yi()}catch(n){r(n)}De.describe(e,(n,s)=>{n&&(De.disconnect(),r(n)),De.disconnect(),t(s)})})}a(aB,"describe");function kre(){if(!g_){for(let e of Vr||[])e.kill();Vr=[];return}return new Promise(async(e,t)=>{try{await yi()}catch(r){t(r)}De.killDaemon((r,n)=>{r&&(De.disconnect(),t(r)),De.disconnect(),e(n)})})}a(kre,"kill");async function Vre(){try{await dB(),await fB(),await Ao(go.generateAllServiceConfigs())}catch(e){throw De?.disconnect(),e}}a(Vre,"startAllServices");async function bA(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case He.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=go.generateMainServerConfig();break;case He.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=go.generateNatsIngestServiceConfig();break;case He.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=go.generateNatsReplyServiceConfig();break;case He.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=go.generateNatsHubServerConfig(),await Ao(r,t),await Ni.removeNatsConfig(e);return;case He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=go.generateNatsLeafServerConfig(),await Ao(r,t),await Ni.removeNatsConfig(e);return;case He.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=go.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ao(r)}catch(r){throw De?.disconnect(),r}}a(bA,"startService");async function cB(){try{let e=await OA(),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 De?.disconnect(),e}}a(cB,"getUniqueServicesList");async function $re(e=[]){try{let t=!1,r=await cB();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===He.PROCESS_DESCRIPTORS.HDB?t=!0:await iB(o))}t&&await uB(He.PROCESS_DESCRIPTORS.HDB)}catch(t){throw De?.disconnect(),t}}a($re,"restartAllServices");async function lB(e){if(Vr?.find(r=>r.name===e))return!0;let t=await Mre.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(lB,"isServiceRegistered");async function uB(e){let t=ph.get(He.CONFIG_PARAMS.THREADS_COUNT)??ph.get(He.CONFIG_PARAMS.THREADS),r=await aB(e),n=Dre.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await AA(e),await bA(e)):e===He.PROCESS_DESCRIPTORS.HDB?await oB():await sB(e)}a(uB,"reloadStopStart");var _B;async function dB(e=!1){for(let t in He.CLUSTERING_PROCESSES){let r=He.CLUSTERING_PROCESSES[t];await bA(r,e)}}a(dB,"startClusteringProcesses");async function fB(){_B=rB(He.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:He.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await hh.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await hh.updateLocalStreams();let e=await Lre.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===He.PRE_4_0_0_VERSION){Ro.info("Starting clustering upgrade 4.0.0 process"),rB(He.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(fB,"startClusteringThreads");async function Yre(){for(let e in He.CLUSTERING_PROCESSES)if(e!==He.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===He.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await _B.terminate();else{let t=He.CLUSTERING_PROCESSES[e];await AA(t)}}a(Yre,"stopClustering");async function Kre(){for(let e in He.CLUSTERING_PROCESSES){let t=He.CLUSTERING_PROCESSES[e];if(await lB(t)===!1)return!1}return!0}a(Kre,"isClusteringRunning");async function Wre(){await Ni.generateNatsConfig(!0),await hh.reloadNATSHub(),await hh.reloadNATSLeaf(),await Ni.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ni.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(Wre,"reloadClustering")});var Th={};Ve(Th,{compactOnStart:()=>Qre,copyDb:()=>gB});async function Qre(){A_.notify("Running compact on start"),console.log("Running compact on start");let e=(0,NA.get)(Oo.CONFIG_PARAMS.ROOTPATH),t=new Map,r=Mr();try{for(let n in r){if(n==="system")continue;let s;for(let l in r[n]){s=r[n][l].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,mh.join)(e,"backup",n+".mdb"),o=(0,mh.join)(e,Oo.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await hB(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 gB(n,o),console.log("Backing up",n,"to",i),await(0,Ca.move)(s,i,{overwrite:!0})}R_();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,Ca.move)(i,s,{overwrite:!0}),await(0,Ca.remove)((0,mh.join)(e,Oo.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));R_()}catch(n){A_.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,yA.updateConfigValue)(Oo.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,Ca.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw R_(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await hB(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let l=`There is a discrepancy between pre and post compact record count for database ${n}.
13
+ `,"")}a(yB,"runCommand");async function Fte(){try{await pte.access(Gb)}catch{return!1}let e=await yB(`${Gb} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return mte.eq(t,Hte)}a(Fte,"checkNATSServerInstalled");async function Kb(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await AB.getClusterUser();if(Uc(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}ei.trace("create nats connection called");let i=await Ite({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Ar.get(je.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ar.get(je.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ar.get(je.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),ei.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&ei.error("Error with Nats client connection, connection closed",o),OB()}),i}a(Kb,"createConnection");function OB(){hn=void 0,Pc=void 0,Lc=void 0,Mc=void 0}a(OB,"clearClientCache");async function kte(){hn&&(await hn.drain(),hn=void 0,Pc=void 0,Lc=void 0,Mc=void 0)}a(kte,"closeConnection");var hn,Mc;async function sf(){return Mc||(Mc=Kb(Ar.get(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),hn=await Mc),hn||Mc}a(sf,"getConnection");async function of(){if(Pc)return Pc;Uc(hn)&&await sf();let{domain:e}=uu(je.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Uc(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Pc=await hn.jetstreamManager({domain:e,timeout:6e4}),Pc}a(of,"getJetStreamManager");async function NB(){if(Lc)return Lc;Uc(hn)&&await sf();let{domain:e}=uu(je.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Uc(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Lc=hn.jetstream({domain:e,timeout:6e4}),Lc}a(NB,"getJetStream");async function Di(){let e=hn||await sf(),t=Pc||await of(),r=Lc||await NB();return{connection:e,jsm:t,js:r}}a(Di,"getNATSReferences");async function Gte(e){let t=Ar.get(je.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await AB.getClusterUser(),s=await Kb(t,r,n),i=Yb(),o=s.subscribe(i),c=[],l,d=(async()=>{for await(let u of o){let _=bB.decode(u.data);_.response_time=Date.now()-l,c.push(_)}})();return l=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 jp.async_set_timeout(e),await o.drain(),await s.close(),await d,c}a(Gte,"getServerList");async function Wb(e,t){let{jsm:r}=await Di(),n=Ar.get(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ar.get(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Ar.get(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:wte.File,retention:Cte.Limits,subjects:t,discard:Dte.Old,max_msgs:s,max_bytes:i,max_age:n})}a(Wb,"createLocalStream");async function IB(){let{jsm:e}=await Di(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(IB,"listStreams");async function qte(e){let{jsm:t}=await Di();await t.streams.delete(e)}a(qte,"deleteLocalStream");async function $te(e){let{connection:t}=await Di(),r=[],n=Yb(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(bB.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($te,"listRemoteStreams");async function Vte(e,t=void 0,r=void 0){let{jsm:n,js:s}=await Di(),i=SB(),o={durable_name:i,ack_policy:$b.Explicit};t&&(o.deliver_policy=Vb.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let d=[];for await(let u of l){let _=qb(u.data),E={nats_timestamp:u.info.timestampNanos,nats_sequence:u.info.streamSequence,entry:_};if(u.headers&&(E.origin=u.headers.get(Dr.MSG_HEADERS.ORIGIN)),d.push(E),u.ack(),u.info.pending===0)break}return await c.delete(),d}a(Vte,"viewStream");async function*Yte(e,t=void 0,r=void 0){let{jsm:n,js:s}=await Di(),i=SB(),o={durable_name:i,ack_policy:$b.Explicit};t&&(o.deliver_policy=Vb.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let d of l){let u=qb(d.data);u[0]||(u=[u]);for(let _ of u){let E={nats_timestamp:d.info.timestampNanos,nats_sequence:d.info.streamSequence,entry:_};d.headers&&(E.origin=d.headers.get(Dr.MSG_HEADERS.ORIGIN)),yield E}if(d.ack(),d.info.pending===0)break}await c.delete()}a(Yte,"viewStreamIterator");async function Kte(e,t,r,n){ei.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=wB(n,r);let{js:s}=await Di(),i=await zp(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:RB.encode(n);try{ei.trace(`publishToStream publishing to subject: ${o}`),vte(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(l){if(l.code&&l.code.toString()==="503")return DB(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){ei.trace(`publishToStream creating stream: ${t}`);let u=o.split(".");u[2]="*",await Wb(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(Kte,"publishToStream");function wB(e,t){t===void 0&&(t=Lte());let r=Ar.get(je.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Dr.MSG_HEADERS.ORIGIN)&&r&&t.append(Dr.MSG_HEADERS.ORIGIN,r),t}a(wB,"addNatsMsgHeader");function uu(e){e=e.toLowerCase();let t=nf.join(Ar.get(je.CONFIG_PARAMS.ROOTPATH),Bte);if(e===je.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return Uc(kb)&&(kb={port:tf.getConfigFromFile(je.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:tf.getConfigFromFile(je.CONFIG_PARAMS.CLUSTERING_NODENAME)+Dr.SERVER_SUFFIX.HUB,config_file:Dr.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:nf.join(t,Dr.PID_FILES.HUB),hdb_nats_path:t}),kb;if(e===je.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return Uc(Fb)&&(Fb={port:tf.getConfigFromFile(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:tf.getConfigFromFile(je.CONFIG_PARAMS.CLUSTERING_NODENAME)+Dr.SERVER_SUFFIX.LEAF,config_file:Dr.NATS_CONFIG_FILES.LEAF_SERVER,domain:tf.getConfigFromFile(je.CONFIG_PARAMS.CLUSTERING_NODENAME)+Dr.SERVER_SUFFIX.LEAF,pid_file_path:nf.join(t,Dr.PID_FILES.LEAF),hdb_nats_path:t}),Fb;ei.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(uu,"getServerConfig");async function CB(e,t,r,n){try{await e.consumers.add(t,{ack_policy:$b.Explicit,durable_name:r,deliver_policy:Vb.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(CB,"createConsumer");async function Wte(e,t,r){await e.consumers.delete(t,r)}a(Wte,"removeConsumer");function jte(e){return e.split(".")[1]}a(jte,"extractServerName");async function Qte(e,t,r=6e4,n=Yb()){if(!jp.isObject(t))throw new Error("data param must be an object");let s=RB.encode(t),{connection:i}=await Di(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return qb(c.data)}a(Qte,"request");function jb(e){return new Promise(async(t,r)=>{let n=Rte(Gb,["--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(jb,"reloadNATS");async function zte(){let{pid_file_path:e}=uu(je.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await jb(e)}a(zte,"reloadNATSHub");async function Jte(){let{pid_file_path:e}=uu(je.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await jb(e)}a(Jte,"reloadNATSLeaf");function Xte(e,t,r){let n;switch(e.code){case mB.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case mB.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Xte,"requestErrorHandler");async function Zte(e,t){let r=t+Dr.SERVER_SUFFIX.LEAF,{connection:n}=await Di(),{jsm:s}=await are(r),{schema:i,table:o}=e,c=Qp.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await DB(async()=>{if(e.subscribe===!0)await CB(s,c,n.info.server_name,l);else try{await Wte(s,c,n.info.server_name)}catch(d){ei.trace(d)}})}a(Zte,"updateRemoteConsumer");async function ere(e,t,r,n){let s=Qp.createNatsTableStreamName(e,t),i=r+Dr.SERVER_SUFFIX.LEAF,o={type:je.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!gB&&Ote()<Ar.get(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=xb();await c(o)}await bte(o),n==="stop"&&await jp.async_set_timeout(1e3)}a(ere,"updateConsumerIterator");function DB(e){return Ate.writeTransaction(je.SYSTEM_SCHEMA_NAME,je.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(DB,"exclusiveLock");async function PB(e,t){let r=Qp.createNatsTableStreamName(e,t),n=await zp(),s=sre(e,t,n);await Wb(r,[s])}a(PB,"createLocalTableStream");async function tre(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await PB(n,s)}}a(tre,"createTableStreams");async function LB(e,t,r=void 0){if(Ar.get(je.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Qp.createNatsTableStreamName(e,t),{domain:s}=uu(je.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await sf()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")ei.warn(n);else throw n}}a(LB,"purgeTableStream");async function rre(e,t){if(Ar.get(je.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await LB(e,t[r])}a(rre,"purgeSchemaTableStreams");async function nre(e){return(await of()).streams.info(e)}a(nre,"getStreamInfo");function sre(e,t,r){return`${Dr.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(sre,"createSubjectName");async function zp(){if(rf)return rf;if(rf=(await of())?.nc?.info?.server_name,rf===void 0)throw new Error("Unable to get jetstream manager server name");return rf}a(zp,"getJsmServerName");async function ire(){let e=await of(),t=await zp(),r=await IB();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=ore(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let d=i.split(".");d[d.length-1]=t;let u=d.join(".");ei.trace(`Updating stream subject name from: ${i} to: ${u}`),s.subjects[0]=u,await e.streams.update(s.name,s)}}a(ire,"updateLocalStreams");function ore(e){let{config:t}=e,r=!1,n=Ar.get(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ar.get(je.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Ar.get(je.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(ore,"updateStreamLimits");async function are(e){let t,r;try{t=await hn.jetstream({domain:e}),r=await hn.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw ei.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(are,"connectToRemoteJS")});var du=y(Xp=>{var Jp=V();for(let e of["trace","debug","info","warn","error","fatal","notify"])Jp.logsAtLevel(e)&&(Xp[e]=Jp[e]);Xp.loggerWithTag=e=>Jp.loggerWithTag(e,!0);Xp.setLogLevel=Jp.setLogLevel});function Qb(e){let t=e.get(Zp),r=t?(0,_u.unpack)(t):null;r||(r={remoteNameToId:{}});let n=lt(),s=!1;r.nodeName=lt();let i=r.remoteNameToId;if(i[n]!==0){let o=0,c;for(let l in i){let d=i[l];d===0?c=l:d>o&&(o=d)}if(c){o++,i[c]=o;let l=[Symbol.for("seq"),o];e.rootStore.dbisDb.transactionSync(()=>{e.rootStore.dbisDb.get(l)||e.rootStore.dbisDb.putSync(l,{seqId:cf(e)??1,nodes:[]})})}i[n]=0,e.putSync(Zp,(0,_u.pack)(r))}return r}function af(e){return Qb(e).remoteNameToId}function vB(e,t,r){let n=Qb(r),s=n.remoteNameToId,i=new Map,o=!1;for(let c in t){let l=t[c],d=s[c];if(d==null){let u=0;for(let _ in s){let E=s[_];E>u&&(u=E)}d=u+1,s[c]=d,o=!0}i.set(l,d)}return o&&r.putSync(Zp,(0,_u.pack)(n)),i}function em(e,t){let r=Qb(t),n=r.remoteNameToId,s=n[e];if(s==null){let i=0;for(let o in n){let c=n[o];c>i&&(i=c)}s=i+1,n[e]=s,t.putSync(Zp,(0,_u.pack)(r))}return UB.info?.("The remote node name map",e,n,s),s}var UB,_u,Zp,zb=Ce(()=>{UB=B(du());hs();_u=require("msgpackr"),Zp=Symbol.for("remote-ids");a(Qb,"getIdMappingRecord");a(af,"exportIdMapping");a(vB,"remoteToLocalNodeId");a(em,"getIdOfRemoteNode")});var ua,Jb=Ce(()=>{ua=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}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 xB={};tt(xB,{Resources:()=>tm,keyArrayToString:()=>fu,resetResources:()=>cre,resources:()=>da});function cre(){return da=new tm}function fu(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var BB,HB,tm,da,lf=Ce(()=>{Ic();Jb();BB=B(V()),HB=B(ce()),tm=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,exportTypes:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s){let c=new HB.ServerError(`Conflicting paths for ${t}`);BB.default.error(c),i.Resource=new ua(c)}super.set(t,i);for(let[c,l]of this){let d=2;for(;(d=c.indexOf("/",d))>-1;){let u=this.get(c.slice(0,d));u&&(u.hasSubPaths=!0),d+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),l=this.get(c);if(!l&&c.indexOf(".")>-1){let d=c.split(".");l=this.get(d[0])}if(l&&(!r||l.exportTypes?.[r]!==!1)){if(l.relativeURL=t.slice(n),!l.hasSubPaths)return l;s=l}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),!s&&o.indexOf(".")>-1&&(s=this.get(o.split(".")[0])),s&&(!r||s.exportTypes?.[r]!==!1)?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(!r||s.exportTypes?.[r]!==!1)&&(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 wt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(cre,"resetResources");a(fu,"keyArrayToString")});function ey(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=kB,lre(e.primaryStore,e.auditStore)):(c=FB,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{GB(FB[i])})));let l=c[i]||(c[i]=[]);if(l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now()),s?.scope==="full-database")return;let d=l[o];d||(d=l[o]=new Map,d.envs=l,d.tableId=o,d.store=e.primaryStore),t=fu(t);let u=new Zb(r);u.startTime=n;let _=d.get(t);return _?_.push(u):(d.set(t,_=[u]),_.tables=d,_.key=t),u.subscriptions=_,u}function GB(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),qB(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Ht(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=fu(c),d=0;do{let u=o.get(l);if(u){for(let E of u)if(!(d>0&&!(E.includeDescendants&&!(E.onlyChildren&&d>1)))){if(E.startTime>=n){(0,Xb.info)("omitting",c,E.startTime,n);continue}try{let f;E.supportsTransactions&&E.txnInProgress!==i.version&&(f=!0,E.txnInProgress||(r?r.push(E):r=[E]),E.txnInProgress=i.version),E.listener(c,i,n,f)}catch(f){console.error(f),(0,Xb.info)(f)}}}if(l==null)break;let _=l.lastIndexOf?.("/",l.length-2);_>-1?l=l.slice(0,_):l=null,d++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function lre(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let l=kB[s];if(!l)return;let d=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{GB(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",d)&&d()})}}function qB(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function $B(e){return e.nextTransaction||(ey({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),qB(e)),e.nextTransaction}var Xb,FB,kB,Zb,ty=Ce(()=>{Xb=B(V());kl();lf();io();FB=Object.create(null),kB=Object.create(null);a(ey,"addSubscription");Zb=class extends Mn{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;if(t){let 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(GB,"notifyFromTransactionData");a(lre,"listenToCommits");a(qB,"nextTransaction");a($B,"whenNextTransaction")});var WB={};tt(WB,{commits_awaiting_replication:()=>pu,getHDBNodeTable:()=>Pr,iterateRoutes:()=>df,shouldReplicateToNode:()=>uf,subscribeToNodeUpdates:()=>mu});function Pr(){return VB||(VB=dt({table:"hdb_nodes",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"},{attribute:"ca"},{attribute:"replicates"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]}))}function mu(e){Pr().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;server.nodes=server.nodes.filter(s=>s.name!==n),r.type==="put"&&n!==lt()&&(r.value?server.nodes.push(r.value):console.error("Invalid node update event",r)),(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function uf(e,t){return(e.replicates===!0||e.replicates?.sends)&&databases[t]&&Pr().primaryStore.get(lt())?.replicates||e.subscriptions?.some(r=>(r.database||r.schema)===t&&r.subscribe)}function ure(){mu(e=>{_a({},(t,r)=>{let n=e.name,s=YB.get(n);if(s||YB.set(n,s=new Map),s.has(r))return;let i;for(let o in t)if(i=t[o].auditStore,i)break;if(i){let o=new Float64Array(i.getUserSharedBuffer(["replicated",r,n],new ArrayBuffer(8),{callback:()=>{let c=o[0],l=o.lastTime;for(let{txnTime:d,onConfirm:u}of pu.get(r)||[])d>l&&d<=c&&u();o.lastTime=c}}));o.lastTime=0,s.set(r,o)}})})}function*df(e){for(let t of e.routes||[]){let r=t.url,n;if(typeof t=="string"?t.includes("://")?r=t:n=t:n=t.hostname??t.host,n&&!r){let s=Eu.default.get(hu.CONFIG_PARAMS.REPLICATION_SECUREPORT)??(!Eu.default.get(hu.CONFIG_PARAMS.REPLICATION_PORT)&&Eu.default.get(hu.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT)),i;(i=n.match(/:(\d+)$/)?.[1])?n=n.slice(0,-i[0].length-1):t.port?i=t.port:i=s||Eu.default.get(hu.CONFIG_PARAMS.REPLICATION_PORT)||Eu.default.get(hu.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT);let o=i?.lastIndexOf?.(":");o>0&&(i=+i.slice(o+1).replace(/[\[\]]/g,"")),r=(s?"wss://":"ws://")+n+":"+i}if(!r){KB.isMainThread&&console.error("Invalid route, must specify a url or host (with port)");continue}yield{url:r,subscription:t.subscriptions,routes:t.routes}}}var KB,Eu,hu,VB,YB,pu,Su=Ce(()=>{De();hs();Pp();KB=require("worker_threads"),Eu=B(te()),hu=B(M());server.nodes=[];a(Pr,"getHDBNodeTable");a(mu,"subscribeToNodeUpdates");a(uf,"shouldReplicateToNode");YB=new Map;e0((e,t,r)=>{pu||(pu=new Map,ure());let n=pu.get(e);return n||pu.set(e,n=[]),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:()=>{++i===r&&s()}})})});a(ure,"startSubscriptionToReplications");a(df,"iterateRoutes")});var JB={};tt(JB,{connectedToNode:()=>vc,disconnectedFromNode:()=>Ru,ensureNode:()=>mo,requestClusterStatus:()=>zB,startOnMainThread:()=>ny});async function ny(e){let t=0,r=ft();for(let i of Object.getOwnPropertyNames(r)){let o=r[i];for(let c in o){let l=o[c];if(l.auditStore){rm.set(i,cf(l.auditStore));break}}}Pi.whenThreadsStarted.then(async()=>{let i=[];for await(let o of r.system.hdb_nodes.search([]))i.push(o);for(let o of df(e))try{let c=!o.subscriptions;if(c){let d=lt();Pr().primaryStore.get(d)===void 0&&await mo(d,{name:d,url:e.url??fa(),replicates:!0})}let l=o.trusted!==!1;if(c&&o.replicates==null&&(o.replicates=!0),i.find(d=>d.url===o.url))continue;s(o)}catch(c){console.error(c)}mu(s)});let n;function s(i,o=i?.name){let c=lt()&&o===lt()||fa()&&i?.url===fa();if(c){let _=!!i?.replicates;if(n!==void 0&&n!==_)for(let E of Pr().search([]))E.replicates&&E.name!==o&&s(E,E.name);n=_}if(Ct.trace("Setting up node replication for",i),!i){for(let[_,E]of po){let f;for(let[h,{worker:S,nodes:T}]of E){let g=T[0];if(g&&g.name==o){f=!0;for(let[m,{worker:C}]of E)E.delete(m),C?.postMessage({type:"unsubscribe-from-node",node:o,database:m,url:_});break}}if(f){po.get(_).iterator.remove(),po.delete(_);return}}return}if(c)return;if(!i.url){Ct.info(`Node ${i.name} is missing url`);return}let l=po.get(i.url);if(l&&l.iterator.remove(),!(i.replicates===!0||i.replicates?.sends)&&!i.subscriptions?.length&&!l)return;if(Ct.info(`Added node ${i.name} at ${i.url} for process ${lt()}`),i.replicates&&i.subscriptions&&(i={...i,subscriptions:null}),i.name){for(let[_,E]of Tu)if(i.url===E.url){Tu.delete(_);break}Tu.set(i.name,i)}let d=ft();if(l||(l=new Map,po.set(i.url,l)),l.iterator=_a(e,(_,E,f)=>{f?u(E,!0):u(E,!1)}),i.subscriptions)for(let _ of i.subscriptions){let E=_.database||_.schema;d[E]||(Ct.warn(`Database ${E} not found for node ${i.name}, making a subscription anyway`),u(E,!1))}function u(_,E){Ct.trace("Setting up replication for database",_,"on node",i.name);let f=l.get(_),h,S=[{replicateByDefault:E,...i}];rm.has(_)&&(S.push({replicateByDefault:E,name:lt(),start_time:rm.get(_),end_time:Date.now(),replicates:!0}),rm.delete(_));let T=uf(i,_),g=Pi.workers.filter(m=>m.name==="http");if(f?(h=f.worker,f.nodes=S):T&&(t=t%g.length,h=g[t++],l.set(_,{worker:h,nodes:S,url:i.url}),h?.on("exit",()=>{l.get(_)?.worker===h&&(l.delete(_),u(_,E))})),T)setTimeout(()=>{let m={type:"subscribe-to-node",database:_,nodes:S};h?h.postMessage(m):gu(m)},dre);else{Pr().primaryStore.get(lt())?.replicates||(n=!1);let m={type:"unsubscribe-from-node",database:_,url:i.url};h?h.postMessage(m):sm(m)}}a(u,"onDatabase")}a(s,"onNodeUpdate"),Ru=a(function(i){try{Ct.info("Disconnected from node",i.name,i.url,"finished",!!i.finished);let o=Array.from(Tu.keys()),c=o.sort(),l=c.indexOf(i.name||Li(i.url));if(l===-1){Ct.warn("Disconnected node not found in node map",i.name,o);return}let d=po.get(i.url),u=d?.get(i.database);if(!u){Ct.warn("Disconnected node not found in replication map",i.database,d);return}if(u.connected=!1,i.finished)return;let _=u.nodes[0];if(!(_.replicates===!0||_.replicates?.sends||_.subscriptions?.length))return;let E=(l+1)%c.length;for(;l!==E;){let f=c[E],h=Tu.get(f);d=po.get(h.url);let S=d?.get(i.database);if(!S){E=(E+1)%c.length;continue}let{worker:T,nodes:g}=S,m=!1;for(let C of u.nodes){if(g.some(O=>O.name===C.name)){Ct.info(`Disconnected node is already failing over to ${f} for ${i.database}`);continue}g.push(C),m=!0}if(!m){Ct.info(`Disconnected node ${i.name} has no nodes to fail over to ${f}`);return}u.redirectingTo=S,Ct.info(`Failing over ${i.database} from ${i.name} to ${f}`),T?T.postMessage({type:"subscribe-to-node",database:i.database,nodes:g}):gu({database:i.database,nodes:g});return}Ct.warn("Unable to find any other node to fail over to",i.name,i.url)}catch(o){Ct.error("Error failing over node",o)}},"disconnectedFromNode"),vc=a(function(i){let o=po.get(i.url),c=o?.get(i.database);if(!c){Ct.warn("Connected node not found in replication map, this may be because the node is being removed",i.database,o);return}if(c.connected=!0,c.latency=i.latency,c.catchingUpFrom=i.lastSendTime,c.redirectingTo){let{worker:l,nodes:d}=c.redirectingTo,u=d.find(_=>_.name===i.name);c.redirectingTo=null,u&&(d.splice(d.indexOf(u),1),l?l.postMessage({type:"subscribe-to-node",database:i.database,nodes:d}):gu({database:i.database,nodes:d}))}},"connectedToNode"),(0,Pi.onMessageByType)("disconnected-from-node",Ru),(0,Pi.onMessageByType)("connected-to-node",vc),(0,Pi.onMessageByType)("request-cluster-status",zB)}function zB(e,t){let r=[];for(let[n,s]of Tu)try{let i=po.get(s.url);Ct.info("Getting cluster status for",n,s.url,"has dbs",i?.size);let o=[];if(i){for(let[l,{worker:d,connected:u,nodes:_,latency:E,catchingUpFrom:f}]of i)o.push({database:l,connected:u,latency:E,catchingUpFrom:f?new Date(f).toISOString():"up-to-date",threadId:d?.threadId,nodes:_.map(h=>h.name)});let c=(0,ry.cloneDeep)(s);c.database_sockets=o,delete c.ca,delete c.node_name,delete c.__updatedtime__,delete c.__createdtime__,r.push(c)}}catch(i){Ct.warn("Error getting cluster status for",s?.url,i)}return t?.postMessage({type:"cluster-status",connections:r}),{connections:r}}async function mo(e,t){let r=Pr();e=e??Li(t.url),t.name=e;let n=r.primaryStore.get(e);if(Ct.info(`Ensuring node ${e} at ${t.url}, existing record:`,n),!n)await r.put(t);else{t.replicates&&!jB.default.get(QB.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(t.subscriptions=null);for(let s in t)if(n[s]!==t[s]&&s==="subscriptions"&&t[s]&&n[s]){let i=[],o=(0,ry.cloneDeep)(n[s]);for(let c of t[s]){let l=!1;for(let d of o)if((c.database??c.schema)===(d.database??d.schema)&&c.table===d.table){d.publish=c.publish,d.subscribe=c.subscribe,l=!0;break}l||i.push(c)}t.subscriptions=[...o,...i];break}Ct.info(`Updating node ${e} at ${t.url}`),await r.patch(t)}}var Pi,nm,Ct,ry,jB,QB,dre,po,Ru,vc,Tu,rm,_f=Ce(()=>{De();Pi=B(ut());hs();nm=require("worker_threads");Su();Ct=B(V()),ry=require("lodash"),jB=B(te()),QB=B(M()),dre=200,po=new Map,Tu=new Map,rm=new Map;a(ny,"startOnMainThread");a(zB,"requestClusterStatus");nm.parentPort&&(Ru=a(e=>{nm.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),vc=a(e=>{nm.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,Pi.onMessageByType)("subscribe-to-node",e=>{gu(e)}),(0,Pi.onMessageByType)("unsubscribe-from-node",e=>{sm(e)}));a(mo,"ensureNode")});var Ss=y(AH=>{"use strict";var Mr=require("path"),ps=require("fs-extra"),Au=require("node-forge"),nH=require("net"),{generateKeyPair:iy,X509Certificate:ha,createPrivateKey:sH}=require("crypto"),_re=require("util");iy=_re.promisify(iy);var Dt=Au.pki,So=require("joi"),{v4:fre}=require("uuid"),{validateBySchema:iH}=St(),Tt=V(),ms=te(),ti=M(),{CONFIG_PARAMS:Hc}=ti,Mi=uA(),{ClientError:ff}=ce(),xc=require("node:tls"),{relative:oH,join:aH}=require("node:path"),{CERT_PREFERENCE_APP:WIe,CERTIFICATE_VALUES:Ere}=Mi,hre=Jo(),oy=yt(),XB=parseInt(process.version.slice(1))<20,{table:pre,getDatabases:mre,databases:sy}=(De(),ne(at));Object.assign(AH,{generateKeys:EH,updateConfigCert:pH,createCsr:Ore,signCertificate:Nre,setCertTable:bu,loadCertificates:_H,reviewSelfSignedCert:dy,createTLSSelector:TH,listCertificates:gH,addCertificate:Lre,removeCertificate:Ure,createNatsCerts:Cre,generateCertsKeys:wre,getReplicationCert:hf,getReplicationCertAuth:yre,renewSelfSigned:Dre,hostnamesFromCert:RH});var{urlToNodeName:cH,getThisNodeUrl:Sre,getThisNodeName:om,clearThisNodeName:Tre}=(hs(),ne(ma)),{readFileSync:gre,watchFile:Rre,statSync:lH}=require("node:fs"),jIe=te(),{getTicketKeys:Are,onMessageFromWorkers:bre}=ut(),Ea=V(),{isMainThread:uH}=require("worker_threads"),{TLSSocket:dH,createSecureContext:QIe}=require("node:tls"),cy=3650,Ef=["127.0.0.1","localhost","::1"],ly=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];bre(async e=>{e.type===ti.ITC_EVENT_TYPES.RESTART&&(ms.initSync(!0),await dy())});var Lr;function pa(){return Lr||(Lr=mre().system.hdb_certificate,Lr||(Lr=pre({table:"hdb_certificate",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{attribute:"__updatedtime__"}]}))),Lr}a(pa,"getCertTable");async function hf(){let e=TH("operations-api"),t={secureContexts:null,setSecureContext:s=>{}};await e.initialize(t);let r=t.secureContexts.get(om());if(!r)return;let n=new ha(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(hf,"getReplicationCert");async function yre(){pa();let e=(await hf()).options.cert,r=new ha(e).issuer.match(/CN=(.*)/)?.[1];return Lr.get(r)}a(yre,"getReplicationCertAuth");var ZB,Fc=new Map;function _H(){if(ZB)return;ZB=!0;let e=[{configKey:Hc.TLS},{configKey:Hc.OPERATIONSAPI_TLS}];pa();let t=Mr.dirname(oy.getConfigFilePath()),r;for(let{configKey:n}of e){let s=oy.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&oH(aH(t,"keys"),o);c&&eH(o,l=>{Fc.set(c,l)},"private key");for(let l of[!1,!0]){let d=i[l?"certificateAuthority":"certificate"];if(d&&uH){let u;eH(d,_=>{if(Ere.cert===_)return;let E=i.hostname??i.hostnames??i.host??i.hosts;E&&!Array.isArray(E)&&(E=[E]);let f=mH(d),h=new ha(f),S;try{S=_y(h)}catch(C){Tt.error("error extracting common name from certificate",C);return}if(S==null){Tt.error("error extracting common name from certificate");return}let T=Lr.primaryStore.get(S),g=lH(d).mtimeMs,m=!T||T.is_self_signed?1:T.file_timestamp??T.__updatedtime__;if(T&&g<=m){g<m&&Tt.info(`Certificate ${S} at ${d} is older (${new Date(g)}) than the certificate in the database (${m>1?new Date(m):"only self signed certificate available"})`);return}r=Lr.put({name:S,uses:["https",...n.includes("operations")?["operations"]:[]],ciphers:i.ciphers,certificate:f,private_key_name:c,is_authority:l,hostnames:E,file_timestamp:g,details:{issuer:h.issuer.replace(/\n/g," "),subject:h.subject.replace(/\n/g," "),subject_alt_name:h.subjectAltName,serial_number:h.serialNumber,valid_from:h.validFrom,valid_to:h.validTo}})},l?"certificate authority":"certificate")}}}}}return r}a(_H,"loadCertificates");function eH(e,t,r){let n,s=a((i,o)=>{try{let c=i.mtimeMs;c&&c!==n&&(o&&uH&&Tt.warn(`Reloading ${r}:`,e),n=c,t(mH(e)))}catch(c){Tt.error(`Error loading ${r}:`,e,c)}},"loadFile");ps.existsSync(e)?s(lH(e)):Tt.error(`${r} file not found:`,e),Rre(e,{persistent:!1},s)}a(eH,"loadAndWatch");function tH(){let e=Sre();if(e==null){let t=Ef[0];return Tt.info("replication url is missing from harperdb-config.yaml, using default host"+t),t}return cH(e)}a(tH,"getHost");function im(){let e=om();if(e==null){let t=Ef[0];return Tt.info("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(im,"getCommonName");async function Ore(){let e=await hf(),t=Dt.certificateFromPem(e.options.cert),r=Dt.privateKeyFromPem(e.options.key);Tt.info("Creating CSR with cert named:",e.name);let n=Dt.createCertificationRequest();n.publicKey=t.publicKey;let s=[{name:"commonName",value:im()},...ly];Tt.info("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:fH()}];return Tt.info("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),Au.pki.certificationRequestToPem(n)}a(Ore,"createCsr");function fH(){let e=Ef.includes(im())?Ef:[...Ef,im()];return e.includes(tH())||e.push(tH()),[{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"nsCertType",client:!0,server:!0},{name:"subjectAltName",altNames:e.map(t=>nH.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(fH,"certExtensions");async function Nre(e){let t={},r=Mr.join(ms.getHdbBasePath(),ti.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;pa();for await(let u of Lr.search([]))if(u.is_authority&&!u.details.issuer.includes("HarperDB-Certificate-Authority")){if(Fc.has(u.private_key_name)){n=Fc.get(u.private_key_name),s=u;break}else if(u.private_key_name&&await ps.exists(Mr.join(r,u.private_key_name))){n=ps.readFile(Mr.join(r,u.private_key_name)),s=u;break}}if(!n){let u=await ay();s=u.ca,n=u.private_key}n=Dt.privateKeyFromPem(n),t.signingCA=s.certificate;let i=Dt.certificateFromPem(s.certificate);Tt.info("Signing CSR with cert named",s.name);let o=Dt.certificationRequestFromPem(e.csr);try{o.verify()}catch(u){return Tt.error(u),new Error("Error verifying CSR: "+u.message)}let c=Au.pki.createCertificate();c.serialNumber=Math.random().toString().slice(2,10),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+cy),Tt.info("sign cert setting validity:",c.validity),Tt.info("sign cert setting subject from CSR:",o.subject.attributes),c.setSubject(o.subject.attributes),Tt.info("sign cert setting issuer:",i.subject.attributes),c.setIssuer(i.subject.attributes);let d=o.getAttribute({name:"extensionRequest"}).extensions;Tt.info("sign cert adding extensions from CSR:",d),c.setExtensions(d),c.publicKey=o.publicKey,c.sign(n,Au.md.sha256.create()),t.certificate=Dt.certificateToPem(c)}else Tt.info("Sign cert did not receive a CSR from:",e.url,"only the CA will be returned");return t}a(Nre,"signCertificate");async function Ire(e,t){await bu({name:om(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await bu({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:Dt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}a(Ire,"createCertificateTable");async function bu(e){let t=new ha(e.certificate);e.details={issuer:t.issuer.replace(/\n/g," "),subject:t.subject.replace(/\n/g," "),subject_alt_name:t.subjectAltName,serial_number:t.serialNumber,valid_from:t.validFrom,valid_to:t.validTo},pa(),await Lr.patch(e)}a(bu,"setCertTable");async function EH(){let e=await iy("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{public_key:Dt.publicKeyFromPem(e.publicKey),private_key:Dt.privateKeyFromPem(e.privateKey)}}a(EH,"generateKeys");async function uy(e,t,r){let n=Dt.createCertificate();if(!t){let o=await hf();t=Dt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=Math.random().toString().slice(2,10),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+cy);let i=[{name:"commonName",value:im()},...ly];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(fH()),n.sign(e,Au.md.sha256.create()),Dt.certificateToPem(n)}a(uy,"generateCertificates");async function ay(){let e=await gH(),t;for(let r of e){if(!r.is_authority)continue;let n=Fc.get(r.private_key_name);if(r.private_key_name&&n&&new ha(r.certificate).checkPrivateKey(sH(n))){Tt.trace(`CA named: ${r.name} found with matching private key`),t={ca:r,private_key:n};break}}if(t)return t;Tt.trace("No CA found with matching private key")}a(ay,"getCertAuthority");async function hH(e,t){let r=Dt.createCertificate();r.publicKey=t,r.serialNumber=Math.random().toString().slice(2,10),r.validity.notBefore=new Date;let n=new Date;r.validity.notAfter=n,r.validity.notAfter.setDate(n.getDate()+cy);let s=[{name:"commonName",value:`HarperDB-Certificate-Authority-${ms.get(Hc.REPLICATION_HOSTNAME)??cH(ms.get(Hc.REPLICATION_URL))??fre().split("-")[0]}`},...ly];r.setSubject(s),r.setIssuer(s),r.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,critical:!0}]),r.sign(e,Au.md.sha256.create());let i=Mr.join(ms.getHdbBasePath(),ti.LICENSE_KEY_DIR_NAME),o=Mr.join(i,Mi.PRIVATEKEY_PEM_NAME);return await ps.writeFile(o,Dt.privateKeyToPem(e)),r}a(hH,"generateCertAuthority");async function wre(){let{private_key:e,public_key:t}=await EH(),r=await hH(e,t),n=await uy(e,t,r);await Ire(n,r),pH()}a(wre,"generateCertsKeys");async function Cre(){let e=await uy(Dt.privateKeyFromPem(Mi.CERTIFICATE_VALUES.key),void 0,Dt.certificateFromPem(Mi.CERTIFICATE_VALUES.cert)),t=Mr.join(ms.getHdbBasePath(),ti.LICENSE_KEY_DIR_NAME),r=Mr.join(t,Mi.NATS_CERTIFICATE_PEM_NAME);await ps.exists(r)||await ps.writeFile(r,e);let n=Mr.join(t,Mi.NATS_CA_PEM_NAME);await ps.exists(n)||await ps.writeFile(n,Mi.CERTIFICATE_VALUES.cert)}a(Cre,"createNatsCerts");async function Dre(){pa();for await(let e of Lr.search([{attribute:"is_self_signed",value:!0}]))await Lr.delete(e.name);await dy()}a(Dre,"renewSelfSigned");async function dy(){Tre(),await _H(),pa();let e,t=ms.get(Hc.TLS_PRIVATEKEY),r=a(async()=>e||(e=Dt.privateKeyFromPem(await ps.readFile(t)),e),"getPrivateKey"),n,s=await ay();if(!s){n=!0,Tt.info("No self signed Cert Authority found, generating new self signed CA"),await r();let o=await hH(e,Dt.setRsaPublicKey(e.n,e.e));await bu({name:o.subject.getField("CN").value,uses:["https","wss"],certificate:Dt.certificateToPem(o),private_key_name:oH(aH(ms.get(Hc.ROOTPATH),"keys"),t),is_authority:!0,is_self_signed:!0})}if(!await hf()){let o=om();Tt.info(`A suitable replication certificate was not found, creating new self singed cert named: ${o}`),s=s??await ay();let c=Dt.certificateFromPem(s.ca.certificate),l=c.publicKey,d=await uy(Dt.privateKeyFromPem(s.private_key),l,c);await bu({name:o,uses:["https","operations","wss"],certificate:d,is_authority:!1,private_key_name:s.ca.private_key_name,is_self_signed:!0})}}a(dy,"reviewSelfSignedCert");function pH(){let e=hre(Object.keys(ti.CONFIG_PARAM_MAP),!0),t=Mr.join(ms.getHdbBasePath(),ti.LICENSE_KEY_DIR_NAME),r=Mr.join(t,Mi.PRIVATEKEY_PEM_NAME),n=Mr.join(t,Mi.NATS_CERTIFICATE_PEM_NAME),s=Mr.join(t,Mi.NATS_CA_PEM_NAME),i=ti.CONFIG_PARAMS,o={[i.TLS_PRIVATEKEY]:e[i.TLS_PRIVATEKEY.toLowerCase()]?e[i.TLS_PRIVATEKEY.toLowerCase()]:r};e[i.TLS_CERTIFICATE.toLowerCase()]&&(o[i.TLS_CERTIFICATE]=e[i.TLS_CERTIFICATE.toLowerCase()]),e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.TLS_CERTIFICATEAUTHORITY]=e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATE]=e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_PRIVATEKEY]=e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),(e[i.CLUSTERING_ENABLED.toLowerCase()]||e.clustering)&&(o[i.CLUSTERING_TLS_CERTIFICATE]=e[i.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]??n,o[i.CLUSTERING_TLS_CERT_AUTH]=e[i.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]??s,o[i.CLUSTERING_TLS_PRIVATEKEY]=e[i.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]??r),oy.updateConfigValue(void 0,void 0,o,!1,!0)}a(pH,"updateConfigCert");function mH(e){return e.startsWith("-----BEGIN")?e:gre(e,"utf8")}a(mH,"readPEM");var rH=xc.createSecureContext;xc.createSecureContext=function(e){if(!e.cert||!e.key)return rH(e);let t={...e};delete t.key,delete t.cert;let r=rH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var SH=xc.Server;xc.Server=function(e,t){return e.ALPNCallback&&(e.ALPNProtocols=null),SH.call(this,e,t)};xc.Server.prototype=SH.prototype;var Pre=dH.prototype._init;dH.prototype._init=function(e,t){Pre.call(this,e,t);let r=this;this._handle.oncertcb=function(n){let s=n.servername;r._SNICallback(s,(i,o)=>{this.sni_context=o.context||o,this.certCbDone()})}};var Bc=new Map;function TH(e,t){let r=new Map,n,s=!1;return i.initialize=o=>i.ready?i.ready:(o&&(o.secureContexts=r,o.secureContextsListeners=[]),i.ready=new Promise((c,l)=>{async function d(){try{r.clear(),Bc.clear();let u=0;for await(let _ of sy.system.hdb_certificate.search([])){if(e!=="operations-api"&&_.uses?.includes?.("operations"))continue;let E=_.certificate,f=new ha(E);_.is_authority&&(f.asString=E,Bc.set(f.subject,E))}for await(let _ of sy.system.hdb_certificate.search([]))try{if(_.is_authority||!(e==="operations-api")&&_.uses?.includes?.("operations"))continue;let f=_.is_self_signed?1:2,h=Fc.get(_.private_key_name);!h&&_.private_key_name&&(h=await ps.readFile(Mr.join(ms.get(Hc.ROOTPATH),ti.LICENSE_KEY_DIR_NAME,_.private_key_name)));let S=_.certificate,T=new ha(S);if(Bc.has(T.issuer)&&(S+=`
14
+ `+Bc.get(T.issuer)),!h||!S)throw new Error("Missing private key or certificate for secure server");let g={ciphers:_.ciphers,ticketKeys:Are(),availableCAs:Bc,ca:t&&Array.from(Bc.values()),cert:S,key:h,key_file:_.private_key_name,is_self_signed:_.is_self_signed};o&&(g.sessionIdContext=o.sessionIdContext);let m=xc.createSecureContext(g);m.name=_.name,m.options=g,m.quality=f,m.certificateAuthorities=Array.from(Bc),m.certStart=S.toString().slice(0,100);let C=_.hostnames??RH(T);Array.isArray(C)||(C=[C]);let O;for(let x of C)if(x){x[0]==="*"&&(s=!0,x=x.slice(1)),nH.isIP(x)&&(O=!0);let F=r.get(x)?.quality??0;f>F&&r.set(x,m)}else Ea.error("No hostname found for certificate at",xc.certificate);f>u&&(i.defaultContext=n=m,u=f,o&&(o.defaultContext=m,Ea.trace("Applying default TLS",m.name,"for",o.ports,"cert named",_.name)))}catch(E){Ea.error("Error applying TLS for",_.name,E)}o?.secureContextsListeners.forEach(_=>_()),c(n)}catch(u){l(u)}}a(d,"updateTLS"),sy.system.hdb_certificate.subscribe({listener:d,omitCurrent:!0}),d()})),i;function i(o,c){Ea.info("TLS requested for",o,this.isReplicationConnection);let l=o;for(;;){let u=r.get(l);if(u)return Ea.debug("Found certificate for",o,u.certStart),u.replicationContext&&(this.isReplicationConnection||XB)&&(u=u.replicationContext),c(null,u);if(s&&l){let _=l.indexOf(".",1);_<0?l="":l=l.slice(_)}else break}o?Ea.debug("No certificate found to match",o,"using the default certificate"):Ea.debug("No SNI, using the default certificate");let d=n;d?d.replicationContext&&(this.isReplicationConnection||XB)&&(d=d.replicationContext):Ea.info("No default certificate found"),c(null,d)}a(i,"SNICallback")}a(TH,"createTLSSelector");async function gH(){pa();let e=[];for await(let t of Lr.search([]))e.push(t);return e}a(gH,"listCertificates");async function Lre(e){let t=iH(e,So.object({name:So.string().required(),certificate:So.string().required(),is_authority:So.boolean().required(),private_key:So.string(),hosts:So.array(),uses:So.array()}));if(t)throw new ff(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new ha(n),c=!1,l=!1,d;for(let[f,h]of Fc)!s&&!c&&o.checkPrivateKey(sH(h))&&(c=!0,d=f),s&&s===h&&(l=!0,d=f);if(!i&&!s&&!c)throw new ff("A suitable private key was not found for this certificate");let u;if(!r){try{u=_y(o)}catch(f){Tt.error(f)}if(u==null)throw new ff("Error extracting certificate common name, please provide a name parameter")}let _=Mre(r??u);s&&!c&&!l&&(await ps.writeFile(Mr.join(ms.getHdbBasePath(),ti.LICENSE_KEY_DIR_NAME,_+".pem"),s),Fc.set(_,s));let E={name:r??u,certificate:n,is_authority:i,hosts:e.hosts,uses:e.uses};return(!i||i&&d||i&&s)&&(E.private_key_name=d??_+".pem"),await bu(E),"Successfully added certificate: "+_}a(Lre,"addCertificate");function Mre(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(Mre,"sanitizeName");async function Ure(e){let t=iH(e,So.object({name:So.string().required()}));if(t)throw new ff(t.message);let{name:r}=e;pa();let n=await Lr.get(r);if(!n)throw new ff(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await Lr.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Tt.info("Removing private key named",s),await ps.remove(Mr.join(ms.getHdbBasePath(),ti.LICENSE_KEY_DIR_NAME,s)))}return await Lr.delete(r),"Successfully removed "+r}a(Ure,"removeCertificate");function _y(e){return e.subject.match(/CN=(.*)/)?.[1]}a(_y,"extractCommonName");function RH(e){return e.subjectAltName?e.subjectAltName.split(",").map(t=>{let r=t.indexOf(":");if(t=t.slice(r+1),t=t.trim(),t[0]==='"')try{t=JSON.parse(t)}catch{}return t.indexOf("=")>-1?t.match(/CN=([^,]*)/)?.[1]:t}).filter(t=>t):[_y(e)]}a(RH,"hostnamesFromCert")});async function Sy(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=lt(),i;if(e.includes("wss://")){if(!Ey){let l=(0,HH.createTLSSelector)("operations-api"),d={secureContexts:null};await l.initialize(d),Ey=d.secureContexts}if(i=Ey.get(s),i&&de.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,FH.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,ALPNProtocols:["http/1.1","harperdb-replication"],rejectUnauthorized:n!==!1,secureContext:void 0};return n!==!1&&i&&(c.secureContext=xH.createSecureContext({...i.options,ca:Array.from(Ta)})),new vH.WebSocket(e,"harperdb-replication-v1",c)}function _m(e,t,r){let n=t.port||t.securePort,s=my.pid%1e3+"-"+BH.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3),i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),d=t.database,u=t.databaseSubscriptions||kc,_,E,f=!1,h=t.subscription;h?.then&&h.then(re=>h=re);let S=t.tables||d&&ft()[d];if(!r){de.error?.("No authorization provided"),Oe(1008,"Unauthorized");return}let T=new Map,g=[],m=r.name;m&&t.connection&&(t.connection.nodeName=m);let C,O,x,F,Y,$,Z=1e3,Q,_e=0,K=0;if(t.url){let re=a(()=>{Y?e.terminate():(Y=performance.now(),e.ping())},"send_ping");x=setInterval(re,MH).unref(),re()}else ie();function ie(){clearTimeout(F),F=setTimeout(()=>{de.warn?.(`Timeout waiting for ping from ${m}, terminating connection and reconnecting`),e.terminate()},MH*2).unref()}a(ie,"resetPingTimer"),d&&Bl(d);let le,we,ve=[],et=[],Ja,Xa=[],Dn=[],Yd=[],Kd=150,mh=0,Lg=0,Rt,Za,os,$s,Sh;e.on("message",re=>{_e=performance.now();try{let ge=re.dataView=new Ou(re.buffer,re.byteOffset,re.byteLength);if(re[0]>127){let p=(0,ct.decode)(re),[R,b,A]=p;switch(R){case yH:{if(b){if(m){if(m!==b){de.error?.(s,`Node name mismatch, expecting to connect to ${m}, but peer reported name as ${b}, disconnecting`),e.send((0,ct.encode)([yu])),Oe(1008,"Node name mismatch");return}}else if(m=b,t.connection?.tentativeNode){let P=t.connection.tentativeNode;P.name=m,t.connection.tentativeNode=null,mo(m,P)}if(t.connection&&(t.connection.nodeName=m),de.debug?.(s,"received node name:",m,"db:",d),!d)try{Bl(d=p[2]),d==="system"&&(le=_a(t,(P,H)=>{hi(H)&&tc(H)}),e.on("close",()=>{le?.remove()}))}catch(P){de.warn?.(s,"Error setting database",P),e.send((0,ct.encode)([yu])),Oe(1008,P.message);return}Th()}break}case PH:{de.debug?.(s,"Received table definitions for",b.map(P=>P.table));for(let P of b){let H=p[2];P.database=H;let k;hi(H)&&(H==="system"?Ve[H]?.[P.table]||(k=hy(P,Ve[H]?.[P.table])):k=hy(P,Ve[H]?.[P.table]),_||(_=k?.auditStore),S||(S=ft()?.[H]))}break}case yu:Oe();break;case wH:try{let P=r?.replicates||r?.subscribers||r?.name;server.operation(b,{user:r},!P).then(H=>{Array.isArray(H)&&(H={results:H}),H.requestId=b.requestId,e.send((0,ct.encode)([cm,H]))},H=>{e.send((0,ct.encode)([cm,{requestId:b.requestId,error:H instanceof Error?H.toString():H}]))})}catch(P){e.send((0,ct.encode)([cm,{requestId:b.requestId,error:P instanceof Error?P.toString():P}]))}break;case cm:let{resolve:I,reject:w}=T.get(b.requestId);b.error?w(new Error(b.error)):I(b),T.delete(b.requestId);break;case fy:let N=p[3];S||(d?de.error?.(s,"No tables found for",d):de.error?.(s,"Database name never received"));let v=S[N];v=hy({table:N,database:d,attributes:b.attributes,schemaDefined:b.schemaDefined},v),ve[A]={name:N,decoder:new ct.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:b.typedStructs,structures:b.structures}),getEntry(P){return v.primaryStore.getEntry(P)},rootStore:v.primaryStore.rootStore};break;case OH:Sh=_?vB(m,b,_):new Map,Ja=p[2],de.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${Ja}`);break;case NH:let U=A;Yd[U]=b;break;case DH:let L=["replicated",d,m];E||(E=new Float64Array(_.getUserSharedBuffer(L,new ArrayBuffer(8)))),E[0]=b,de.trace?.(s,"received and broadcasting committed update",b),E.buffer.notify();break;case CH:C=b,h.send({type:"end_txn",localTime:C,remoteNodeIds:g});break;case IH:{let P=b,H;try{let k=p[3],ue=et[A]||(et[A]=S[p[4]]);if(!ue)return de.warn?.("Unknown table id trying to handle record request",A);let X=ue.primaryStore.getBinaryFast(Symbol.for("structures")),Ne=X.length;if(Ne!==Lg){Lg=Ne;let he=(0,ct.decode)(X);e.send((0,ct.encode)([fy,{typedStructs:he.typed,structures:he.named},A,ue.tableName]))}let fe=ue.primaryStore.getBinaryFast(k);if(fe){let he=ue.primaryStore.decoder.decode(fe,{valueAsBuffer:!0});H=(0,ct.encode)([am,P,{value:he.value,expiresAt:he.expiresAt,version:he.version,residencyId:he.residencyId,nodeId:he.nodeId,user:he.user}])}else H=(0,ct.encode)([am,P])}catch(k){H=(0,ct.encode)([am,P,{error:k.message}])}e.send(H);break}case am:{let{resolve:P,reject:H,tableId:k,key:ue}=T.get(p[1]),X=p[2];if(X?.error)H(new Error(X.error));else if(X){let Ne=ve[k].decoder.decode(X.value);X.value=Ne,X.key=ue,P(X)}else P();T.delete(p[1]);break}case bH:{$s=b;let P,H,k=!1;if(h){if(d!==h.databaseName&&!h.then){de.error?.("Subscription request for wrong database",d,h.databaseName);return}}else h=u.get(d);if(de.debug?.(s,"received subscription request for",d,"at",$s),!h){let pe;h=new Promise(be=>{de.debug?.("Waiting for subscription to database "+d),pe=be}),h.ready=pe,kc.set(d,h)}if(r.name)H=Pr().subscribe(r.name),H.then(async pe=>{P=pe;for await(let be of P){let Ke=be.value;if(!(Ke?.replicates===!0||Ke?.replicates?.receives||Ke?.subscriptions?.some(Xe=>(Xe.database||Xe.schema)===d&&Xe.publish!==!1))){k=!0,e.send((0,ct.encode)([yu])),Oe(1008,`Unauthorized database subscription to ${d}`);return}}},pe=>{de.error?.(s,"Error subscribing to HDB nodes",pe)});else if(!(r?.permissions?.super_user||r.replicates)){e.send((0,ct.encode)([yu])),Oe(1008,`Unauthorized database subscription to ${d}`);return}if(os&&(de.debug?.(s,"stopping previous subscription",d),os.emit("close")),$s.length===0)return;let ue,X=$s[0],Ne=a(pe=>{if(pe&&(X.replicateByDefault?!X.tables.includes(pe.tableName):X.tables.includes(pe.tableName)))return ue=pe,{table:pe}},"tableToTableEntry"),fe={txnTime:0},he,se,z=1/0,Re,ke=a((pe,be)=>{if(z=be,pe.type==="end_txn"){fe.txnTime&&(o[i]!==66&&de.error?.("Invalid encoding of message"),rc(9),rc(dm),Wd(Re=be),Yt()),i=c,fe.txnTime=0;return}let Ke=pe.nodeId,Xe=pe.tableId,We=se[Xe];if(!We&&(We=se[Xe]=Ne(h.tableById[Xe]),!We))return de.debug?.("Not subscribed to table",Xe);let ot=We.table,gr=ot.primaryStore,Yr=gr.encoder;if(pe.extendedType&Fh||!Yr.typedStructs){let jo=pe.getValue(gr,!0);JSON.stringify(jo)}let Kr=he[Ke];if(!(Kr&&Kr.startTime<be&&(!Kr.endTime||Kr.endTime>be)))return pf&&de.trace?.(s,"skipping replication update",pe.recordId,"to:",m,"from:",Ke,"subscribed:",he),SC();pf&&de.trace?.(s,"sending replication update",pe.recordId,"to:",m,"from:",Ke,"subscribed:",he);let Mg=pe.version;fe.txnTime!==Mg&&(fe.txnTime&&(pf&&de.trace?.(s,"new txn time, sending queued txn",fe.txnTime),o[i]!==66&&de.error?.("Invalid encoding of message"),Yt()),fe.txnTime=Mg,i=c,Wd(Mg));let sc=pe.residencyId,Ug=ec(sc,ot),gh;if(Ug&&!Ug.includes(m)){let jo=ec(pe.previousResidencyId,ot);if(jo&&!jo.includes(m)&&(pe.type==="put"||pe.type==="patch")||ot.getResidencyById)return SC();let jd=pe.recordId;de.trace?.(s,"sending invalidation",jd,m,"from",Ke);let Hg=0;sc&&(Hg|=cc),pe.previousResidencyId&&(Hg|=lc);let xg,Rh=null;for(let TC in ot.indices){if(!Rh){if(xg=pe.getValue(gr,!0),!xg)break;Rh={}}Rh[TC]=xg[TC]}gh=ql(pe.version,Xe,jd,null,Ke,pe.user,pe.type==="put"||pe.type==="patch"?"invalidate":pe.type,Yr.encode(Rh),Hg,sc,pe.previousResidencyId,pe.expiresAt)}function SC(){de.trace?.(s,"skipping audit record",pe.recordId),$||($=setTimeout(()=>{$=null,(Re||0)+LH/2<z&&(pf&&de.trace?.(s,"sending skipped sequence update",z),e.send((0,ct.encode)([CH,z])))},LH).unref())}a(SC,"skipAuditRecord");let vg=Yr.typedStructs,Bg=Yr.structures;if((vg?.length!=We.typed_length||Bg?.length!=We.structure_length)&&(We.typed_length=vg?.length,We.structure_length=Bg.length,de.debug?.(s,"send table struct",We.typed_length,We.structure_length),We.sentName||(We.sentName=!0),e.send((0,ct.encode)([fy,{typedStructs:vg,structures:Bg,attributes:ot.attributes,schemaDefined:ot.schemaDefined},Xe,We.table.tableName]))),sc&&!Dn[sc]&&(e.send((0,ct.encode)([NH,Ug,sc])),Dn[sc]=!0),gh)rc(gh.length),nc(gh);else{let jo=pe.encoded,jd=jo[0]===66?8:0;rc(jo.length-jd),nc(jo,jd)}},"sendAuditRecord"),Yt=a(()=>{c-i>8?(e.send(o.subarray(i,c)),de.debug?.(s,"Sent message, size:",c-i)):de.debug?.(s,"skipping empty transaction")},"sendQueuedData");os=new py.EventEmitter,os.once("close",()=>{k=!0,P?.end()});for(let{startTime:pe}of $s)pe<z&&(z=pe);(H||Promise.resolve()).then(async()=>{h=await h,_=h.auditStore,se=h.tableById.map(Ne),he=[];for(let{name:be,startTime:Ke,endTime:Xe}of $s){let We=em(be,_);de.debug?.("subscription to",be,"using local id",We,"starting",Ke),he[We]={startTime:Ke,endTime:Xe}}tc(d),le||(le=Gc(be=>{be.databaseName===d&&tc(d)}),we=mf(be=>{be===d&&(e.send((0,ct.encode)([yu])),Oe())}),e.on("close",()=>{le?.remove(),we?.remove()})),e.send((0,ct.encode)([OH,af(h.auditStore),$s.map(({name:be})=>be)]));let pe=!0;do{isFinite(z)||(de.warn?.("Invalid sequence id "+z),Oe(1008,"Invalid sequence id"+z));let be;if(pe&&!k&&(pe=!1,!(Ty(_)<=z)&&server.nodes[0]?.name===m)){de.info?.("Replicating all tables to",m);let We=z,ot=fm(_);for(let gr in S){let Yr=S[gr];for(let Kr of Yr.primaryStore.getRange({snapshot:!1})){if(k)return;Kr.localTime>=z&&(de.trace?.(s,"Copying record from",d,gr,Kr.key,Kr.localTime),We=Math.max(Kr.localTime,We),be=!0,ke({recordId:Kr.key,tableId:Yr.tableId,type:"put",getValue(){return Kr.value},encoded:Yr.primaryStore.getBinary(Kr.key),version:Kr.version,residencyId:Kr.residencyId,nodeId:ot},Kr.localTime))}}z=We}for(let{key:Xe,value:We}of _.getRange({start:z||1,exclusiveStart:!0,snapshot:!1})){if(k)return;K=Xe;let ot=Ht(We);ke(ot,Xe),e._socket.writableNeedDrain&&await new Promise(gr=>e._socket.once("drain",gr)),os.startTime=Xe,be=!0}be&&ke({type:"end_txn"},z);let Ke=lm.get(ue);Ke||lm.set(ue,Ke=[]),Ke.push(Xe=>{}),K=0,await $B(_)}while(!k)}).catch(pe=>{de.error?.(s,"Error handling subscription to node",pe),Oe(1008,"Error handling subscription to node")});break}}return}ge.position=8;let it=!0,Te,G;do{let p=ge.readInt();if(p===9&&ge.getUint8(ge.position)==dm){ge.position++,C=G=ge.readFloat64(),de.trace?.("received remote sequence update",C,d);break}let R=ge.position,b=Ht(re.subarray(R,R+p)),A=ve[b.tableId];A||de.error?.(`No table found with an id of ${b.tableId}`);let I;b.residencyId&&(I=Yd[b.residencyId],de.trace?.(s,"received residency list",I,b.type,b.recordId)),Te={table:A.name,id:b.recordId,type:b.type,nodeId:Sh.get(b.nodeId),residencyList:I,timestamp:b.version,value:b.getValue(A),user:b.user,beginTxn:it,expiresAt:b.expiresAt},it=!1,pf&&de.trace?.(s,"received replication message",b.type,"id",Te.id,"version",b.version,"nodeId",Te.nodeId,"name",Te.value?.name),h.send(Te),ge.position=R+p}while(ge.position<re.byteLength);mh++,Rr(re.byteLength,"bytes-received",m+"."+d+"."+Te.table,"replication","ingest"),mh>Kd&&!Rt&&(Rt=!0,e.pause()),h.send({type:"end_txn",localTime:C,remoteNodeIds:g,onCommit(){if(Te){let p=Date.now()-Te.timestamp;Rr(p,"replication-latency",m+"."+d+"."+Te.table,Te.type,"ingest")}mh--,Rt&&(Rt=!1,e.resume()),!O&&G&&(de.trace?.(s,"queuing confirmation of a commit at",G),setTimeout(()=>{e.send((0,ct.encode)([DH,O])),de.trace?.(s,"sent confirmation of a commit at",O),O=null},vre)),O=G}})}catch(ge){de.error?.(s,"Error handling incoming replication message",ge)}}),e.on("ping",ie),e.on("pong",()=>{t.connection&&(t.connection.latency=performance.now()-Y,vc({name:m,database:d,url:t.url,lastSendTime:K,latency:t.connection.latency})),Y=null}),e.on("close",(re,ge)=>{clearInterval(x),clearTimeout(F),os&&os.emit("close"),Za&&Za.end();for(let[it,{reject:Te}]of T)Te(new Error("Connection closed"));de.debug?.(s,"closed",re,ge?.toString())});function mC(){}a(mC,"recordRemoteNodeSequence");function Oe(re,ge){e.isFinished=!0,e.close(re,ge)}a(Oe,"close");function Th(){if(f||(f=!0,t.connection?.on("subscriptions-updated",Th)),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let re=new Map;try{for(let Te of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let G of Te.value.nodes||[])G.seqId>(re.get(G.id)??0)&&re.set(G.id,G.seqId)}catch(Te){if(!Te.message.includes("Can not re"))throw Te}let ge=t.connection?.nodeSubscriptions?.[0];g=[];let it=t.connection?.nodeSubscriptions.map((Te,G)=>{let p=[],{replicateByDefault:R}=Te;if(Te.subscriptions){for(let w of Te.subscriptions)if(w.subscribe&&(w.schema||w.database)===d){let N=w.table;S?.[N]?.replicate!==!1&&p.push(N)}R=!1}else for(let w in S)(R?S[w].replicate===!1:S[w].replicate)&&p.push(w);let b=_&&em(Te.name,_),A=h?.dbisDB?.get([Symbol.for("seq"),b])??1,I=Math.max(A?.seqId??1,(typeof Te.start_time=="string"?new Date(Te.start_time).getTime():Te.start_time)??1);if(de.debug?.("Starting time recorded in db",Te.name,b,d,A?.seqId,"start time:",I),ge!==Te){I>5e3&&(I-=5e3);let w=_&&em(ge.name,_),N=h?.dbisDB?.get([Symbol.for("seq"),w])??1;for(let v of N?.nodes||[])v.name===Te.name&&(I=v.seqId,de.debug?.("Using sequence id from proxy node",ge.name,I))}return g.push(b),re.get(b)>I&&(I=re.get(b),de.debug?.("Updating start time from more recent txn recorded",ge.name,I)),{name:Te.name,replicateByDefault:R,tables:p,startTime:I,endTime:Te.end_time}});if(it)if(de.debug?.(s,"sending subscription request",it,h?.dbisDB?.path),clearTimeout(Q),it.length>0)e.send((0,ct.encode)([bH,it]));else{let Te=a(()=>{let G=performance.now();Q=setTimeout(()=>{_e<=G?Oe(1008,"No nodes to subscribe to"):Te()},Z)},"schedule_close");Te()}}a(Th,"sendSubscriptionRequestUpdate");function ec(re,ge){if(!re)return;let it=Xa[re];return it||(it=ge.getResidencyRecord(re),Xa[re]=it),it}a(ec,"getResidence");function hi(re){return!(Sa&&Sa!="*"&&!Sa[re]&&!Sa.includes?.(re)&&!Sa.some?.(ge=>ge.name===re))}a(hi,"checkDatabaseAccess");function Bl(re){if(h=h||u.get(re),!hi(re))throw new Error(`Access to database "${re}" is not permitted`);h||de.warn?.(`No database named "${re}" was declared and registered`),_=h?.auditStore,S||(S=ft()?.[re]);let ge=lt();if(ge===m)throw ge?new Error("Should not connect to self",ge):new Error("Node name not defined");return Hl(ge,re),!0}a(Bl,"setDatabase");function Hl(re,ge){let it=ft()?.[ge],Te=[];for(let G in it){let p=it[G];Te.push({table:G,schemaDefined:p.schemaDefined,attributes:p.attributes.map(R=>({name:R.name,type:R.type,isPrimaryKey:R.isPrimaryKey}))})}de.trace?.("Sending database info for node",re,"database name",ge),e.send((0,ct.encode)([yH,re,ge,Te]))}a(Hl,"sendNodeDBName");function tc(re){let ge=ft()?.[re],it=[];for(let Te in ge){if($s&&!$s.some(p=>p.replicateByDefault?!p.tables.includes(Te):p.tables.includes(Te)))continue;let G=ge[Te];it.push({table:Te,schemaDefined:G.schemaDefined,attributes:G.attributes.map(p=>({name:p.name,type:p.type,isPrimaryKey:p.isPrimaryKey}))})}e.send((0,ct.encode)([PH,it,re]))}a(tc,"sendDBSchema");let Vr=1,xl=[];return{end(){Za&&Za.end(),os&&os.emit("close")},getRecord(re){let ge=Vr++;return new Promise((it,Te)=>{let G=[IH,ge,re.table.tableId,re.id];xl[re.table.tableId]||(G.push(re.table.tableName),xl[re.table.tableId]=!0),e.send((0,ct.encode)(G)),T.set(ge,{tableId:re.table.tableId,key:re.id,resolve(p){let{table:R,entry:b}=re;it(p),p&&R._recordRelocate(b,p)},reject:Te})})},sendOperation(re){let ge=Vr++;return re.requestId=ge,e.send((0,ct.encode)([wH,re])),new Promise((it,Te)=>{T.set(ge,{resolve:it,reject:Te})})}};function rc(re){Wo(5),re<128?o[c++]=re:re<16384?(l.setUint16(c,re|32768),c+=2):re<1056964608?(l.setUint32(c,re|3221225472),c+=4):(o[c]=255,l.setUint32(c+1,re),c+=5)}function nc(re,ge=0,it=re.length){let Te=it-ge;Wo(Te),re.copy(o,c,ge,it),c+=Te}function Wd(re){Wo(8),l.setFloat64(c,re),c+=8}function Wo(re){if(re+16>o.length-c){let ge=Buffer.allocUnsafeSlow(c+re-i+65536>>10<<11);o.copy(ge,0,i,c),c=c-i,i=0,o=ge,l=new DataView(o.buffer,0,o.length)}}}function hy(e,t){let r=e.database??"data";if(r!=="data"&&!Ve[r]){de.warn?.("Database not found",e.database);return}t||(t={});let n=!1,s=e.schemaDefined,i=t.attributes||[];for(let o=0;o<e.attributes?.length;o++){let c=e.attributes[o],l=i[o];(!l||l.name!==c.name||l.type!==c.type)&&(n=!0,s||(c.indexed=!0),i[o]=c)}return n?(de.debug?.("(Re)creating",e),dt({table:e.table,database:e.database,schemaDefined:e.schemaDefined,attributes:i,...t})):t}var ct,vH,BH,de,py,HH,xH,my,FH,bH,yH,OH,yu,NH,fy,IH,am,wH,cm,CH,DH,PH,lm,kc,pf,LH,vre,MH,Ey,UH,um,kH=Ce(()=>{De();io();zb();ty();hs();$l();ct=require("msgpackr"),vH=require("ws"),BH=require("worker_threads"),de=B(du());_f();py=require("events"),HH=B(Ss()),xH=B(require("node:tls"));Su();my=B(require("node:process")),FH=require("node:net");Ci();bH=129,yH=140,OH=141,yu=142,NH=130,fy=132,IH=133,am=134,wH=136,cm=137,CH=143,DH=144,PH=145,lm=new Map,kc=new Map,pf=!0,LH=300,vre=2,MH=3e4;a(Sy,"createWebSocket");UH=1e3,um=class extends py.EventEmitter{constructor(r,n,s){super();this.url=r;this.subscription=n;this.databaseName=s;this.nodeName=Li(r)}static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=UH;retries=0;isConnected=!0;isFinished=!1;nodeSubscriptions=[];latency=0;replicateTablesByDefault;session;sessionResolve;sessionReject;nodeName;async connect(){this.session||this.resetSession();let r=[];this.socket=await Sy(this.url,{serverName:this.nodeName});let n;de.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${my.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),de.info?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=UH,vc({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,n=_m(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this},{replicates:!0}),this.sessionResolve(n)}),this.socket.on("error",s=>{s.code==="SELF_SIGNED_CERT_IN_CHAIN"?(de.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),s.isHandled=!0):s.code!=="ECONNREFUSED"&&(s.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?de.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):de.error?.(`Error in connection to ${this.url} due to ${s.message}`)),this.sessionReject(s)}),this.socket.on("close",(s,i)=>{if(this.isConnected&&(Ru({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.socket.isFinished){this.isFinished=!0,n?.end(),this.emit("finished");return}if(++this.retries%20===1){let o=i?.toString();de.warn?.(`${n?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${o?'"'+o+'" ':""}(code: ${s})`)}n=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>3})}resetSession(){this.session=new Promise((r,n)=>{this.sessionResolve=r,this.sessionReject=n})}subscribe(r,n){this.nodeSubscriptions=r,this.replicateTablesByDefault=n,this.emit("subscriptions-updated",r)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(r){return this.session.then(n=>n.getRecord(r))}};a(_m,"replicateOverWS");a(hy,"ensureTableIfChanged")});var ma={};tt(ma,{clearThisNodeName:()=>qre,disableReplication:()=>xre,enabled_databases:()=>Sa,forEachReplicatedDatabase:()=>_a,getThisNodeId:()=>fm,getThisNodeName:()=>lt,getThisNodeUrl:()=>fa,hostnameToUrl:()=>pm,lastTimeInAuditStore:()=>cf,monitorNodeCAs:()=>QH,replicateOperation:()=>Vre,replication_certificate_authorities:()=>Ta,sendOperationToNode:()=>gf,servers:()=>jH,setReplicator:()=>JH,start:()=>Hre,startOnMainThread:()=>ny,subscribeToNode:()=>gu,unsubscribeFromNode:()=>sm,urlToNodeName:()=>Li});function Hre(e){if(e.port||(e.port=Ts.default.get(qc.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)),e.securePort||(e.securePort=Ts.default.get(qc.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT)),!lt())throw new Error("Can not load replication without a url (see replication.url in the config)");let t=new Map;for(let n of df(e))t.set(Li(n.url),n);Fre(e),e={subProtocol:"harperdb-replication-v1",mtls:!0,isOperationsServer:!0,...e};let r=nt.ws(async(n,s,i)=>{await i,n._socket.unref(),_m(n,e,s?.user),n.on("error",o=>{o.code!=="ECONNREFUSED"&&br.error("Error in connection to "+this.url,o.message)})},e);e.runFirst=!0,nt.http((n,s)=>{if(n.isWebSocket&&n.headers.get("Sec-WebSocket-Protocol")==="harperdb-replication-v1"){!n.authorized&&n._nodeRequest.socket.authorizationError&&br.error(`Incoming client connection from ${n.ip} did not have valid certificate `,n._nodeRequest.socket.authorizationError);let i=Pr().primaryStore;if(n.authorized&&n.peerCertificate.subject){let o=n.peerCertificate.subject,c=o&&(i.get(o.CN)||t.get(o.CN));c?n.user=c:br.warn(`No node found for certificate common name ${o.CN}, available nodes are ${Array.from(i.getRange({}).filter(({value:l})=>l).map(({key:l})=>l)).join(", ")} and routes ${Array.from(t.keys()).join(", ")}, connection will require credentials.`)}else{let o=i.get(n.ip)||t.get(n.ip);o?n.user=o:br.warn(`No node found for IP address ${n.ip}, available nodes are ${Array.from(new Set([...i.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}}return s(n)},e);for(let n of r)if(jH.push(n),n.secureContexts){let s=a(()=>{let i=new Set(n.secureContexts.values());n.defaultContext&&i.add(n.defaultContext);for(let o of i)try{let c=Array.from(Ta);o.options.availableCAs&&c.push(...o.options.availableCAs.values());let l={...o.options,ca:c};o.replicationContext=Tf.createSecureContext(l)}catch(c){br.error("Error creating replication TLS config",c)}},"updateContexts");n.secureContextsListeners.push(s),QH(s)}}function QH(e){let t=0;mu(r=>{if(r?.ca){if(Ta.add(r.ca),Ta.size!==t)t=Ta.size,e?.();else if(Ts.default.get(qc.CONFIG_PARAMS.REPLICATION_ENABLEROOTCAS)!==!1)for(let n of Tf.rootCertificates)Ta.add(n)}})}function xre(e=!0){WH=e}function Fre(e){WH||(ft(),Sa=e.databases,_a(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||kc;for(let[s,i]of Sf){let o=i.get(r);o&&(o.subscribe([],!1),i.delete(r))}n.delete(r);return}for(let n in t){let s=t[n];JH(r,s,e),lm.get(s)?.forEach(i=>i(s))}}))}function JH(e,t,r){if(!t)return console.error(`Attempt to replicate non-existent table ${t.name} from database ${e}`);if(t.replicate===!1||t.sources?.some(s=>s.isReplicator))return;let n;t.sourcedFrom(class zH extends wr{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||kc,o=i.get(e),c=o?.tableById||[];c[t.tableId]=t;let l=o?.ready;if(br.trace("Setting up replicator subscription to database",e,o&&Object.keys(o)),!o?.auditStore)return this.subscription=o=new Mn,i.set(e,o),o.tableById=c,o.auditStore=t.auditStore,o.dbisDB=t.dbisDB,o.databaseName=e,l&&l(o),o;this.subscription=o}static subscribeOnThisThread(i,o){return!0}static async load(i){if(i){let o=i.residencyId,c=i.residency||t.dbisDB.get([Symbol.for("residency_by_id"),o]);if(c){let l,d=new Set;do{let u;for(let E of c){let f=kre(E,zH.subscription,e);f?.isConnected&&!d.has(f)&&(!u||f.latency<u.latency)&&(u=f)}if(!u)throw l||new YH.ServerError("No connection to any other nodes are available",502);let _={requestId:Bre++,table:t,entry:i,id:i.key};d.add(u);try{return await u.getRecord(_)}catch(E){if(u.isConnected)throw E;br.warn("Error in load from node",hm,E),l||(l=E)}}while(!0)}}}static isReplicator=!0},{intermediateSource:!0})}function XH(e,t,r){let n=Sf.get(e);n||Sf.set(e,n=new Map);let s=n.get(r);if(s)return s;if(t)return n.set(r,s=new um(e,t,r)),s.connect(),s.once("finished",()=>n.delete(r)),s}function kre(e,t,r){let n=GH.get(e)?.get(r);if(n)return n;let s=Pr().primaryStore.get(e);return s?.url&&(n=XH(s.url,t,r),GH.set(e,Sf.get(s.url))),n}async function gf(e,t,r){r||(r={}),r.serverName=e.name;let n=await Sy(e.url,r),s=_m(n,{},{});return new Promise((i,o)=>{n.on("open",()=>{i(s.sendOperation(t))}),n.on("error",c=>{o(c)}),n.on("close",c=>{br.error("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function gu(e){try{KH.isMainThread&&br.trace("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=kc.get(e.database);if(!t){let n;t=new Promise(s=>{br.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,kc.set(e.database,t)}let r=XH(e.nodes[0].url,t,e.database);e.nodes[0].name===void 0&&(r.tentativeNode=e.nodes[0]),r.subscribe(e.nodes.filter(n=>uf(n,e.database)),e.replicateByDefault)}catch(t){br.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function sm({url:e,database:t}){let r=Sf.get(e);if(r){let n=r.get(t);n&&(n.unsubscribe(),r.delete(t))}}function Gre(){if(gy!==void 0)return gy;let e=Ts.default.get(qc.CONFIG_PARAMS.OPERATIONSAPI_TLS_CERTIFICATE)||Ts.default.get(qc.CONFIG_PARAMS.TLS_CERTIFICATE);if(e)return gy=new $H.X509Certificate((0,VH.readFileSync)(e)).subject.match(/CN=(.*)/)?.[1]??null}function lt(){return hm||(hm=Ts.default.get("replication_hostname")??Li(Ts.default.get("replication_url"))??Gre()??qH("operationsapi_network_secureport")??qH("operationsapi_network_port")??"127.0.0.1")}function qre(){hm=void 0}function qH(e){let t=Ts.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function Em(e){let t=Ts.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function fm(e){return af(e)?.[lt()]}function fa(){let e=Ts.default.get("replication_url");return e||pm(lt())}function pm(e){let t=Em("replication_port");if(t)return`ws://${e}:${t}`;if(t=Em("replication_secureport"),t)return`wss://${e}:${t}`;if(t=Em("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=Em("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function Li(e){if(e)return new URL(e).hostname}function _a(e,t){for(let n of Object.getOwnPropertyNames(Ve))r(n);return mf(n=>{r(n)}),Gc((n,s)=>{r(n.databaseName)});function r(n){let s=Ve[n];br.trace("Checking replication status of ",n,e?.databases),e?.databases===void 0||e.databases==="*"||e.databases.includes(n)||e.databases.some?.(i=>i.name===n)||!s?t(s,n,!0):$re(n)&&t(s,n,!1)}a(r,"forDatabase")}function $re(e){let t=Ve[e];for(let r in t)if(t[r].replicate)return!0}function cf(e){for(let t of e.getKeys({limit:1,reverse:!0}))return t}async function Vre(e){let t={message:""};if(e.replicated){e.replicated=!1,br.trace?.("Replicating operation",e,"to nodes",nt.nodes.map(n=>n.name));let r=await Promise.allSettled(nt.nodes.map(n=>gf(n,e)));t.replicated=r.map((n,s)=>{let i=n.status==="rejected"?{status:"failed",reason:n.reason.toString()}:n.value;return i.node=nt.nodes[s]?.name,i})}return t}var Ts,br,$H,VH,qc,Tf,YH,KH,WH,Bre,jH,Ta,Sa,Sf,GH,gy,hm,hs=Ce(()=>{De();ls();kl();kH();Wr();Ts=B(te()),br=B(V()),$H=require("crypto"),VH=require("fs");_f();Su();qc=B(M());zb();Tf=B(require("node:tls")),YH=B(ce()),KH=require("worker_threads"),Bre=1,jH=[],Ta=Ts.default.get(qc.CONFIG_PARAMS.REPLICATION_ENABLEROOTCAS)===!0?new Set(Tf.rootCertificates):new Set;a(Hre,"start");a(QH,"monitorNodeCAs");a(xre,"disableReplication");a(Fre,"assignReplicationSource");a(JH,"setReplicator");Sf=new Map;a(XH,"getConnection");GH=new Map;a(kre,"getConnectionByName");a(gf,"sendOperationToNode");a(gu,"subscribeToNode");a(sm,"unsubscribeFromNode");a(Gre,"getCommonNameFromCert");a(lt,"getThisNodeName");a(qre,"clearThisNodeName");Object.defineProperty(nt,"hostname",{get(){return lt()}});a(qH,"getHostFromListeningPort");a(Em,"getPortFromListeningPort");a(fm,"getThisNodeId");nt.replication={getThisNodeId:fm,exportIdMapping:af};a(fa,"getThisNodeUrl");a(pm,"hostnameToUrl");a(Li,"urlToNodeName");a(_a,"forEachReplicatedDatabase");a($re,"hasExplicitlyReplicatedTable");a(cf,"lastTimeInAuditStore");a(Vre,"replicateOperation")});var gm=y((ywe,nx)=>{"use strict";var Nu=jh(),Iu=k0(),Yre=V(),Kre=require("uuid").v4,bwe=require("clone"),Sm=_o(),wu=M(),Wre=require("util"),ga=Hn(),{handleHDBError:pn,hdb_errors:jre}=ce(),{HDB_ERROR_MSGS:mm,HTTP_STATUS_CODES:mn}=jre,{SchemaEventMsg:Tm}=Qs(),ZH=nr(),{getDatabases:Qre}=(De(),ne(at)),{transformReq:Cu}=ee(),{replicateOperation:ex}=(hs(),ne(ma));nx.exports={createSchema:zre,createSchemaStructure:tx,createTable:Jre,createTableStructure:rx,createAttribute:rne,dropSchema:Xre,dropTable:Zre,dropAttribute:ene,getBackup:nne};async function zre(e){let t=await tx(e);return Sm.signalSchemaChange(new Tm(process.pid,e.operation,e.schema)),t}a(zre,"createSchema");async function tx(e){let t=Nu.schema_object(e);if(t)throw pn(t,t.message,mn.BAD_REQUEST,void 0,void 0,!0);if(Cu(e),!await Iu.checkSchemaExists(e.schema))throw pn(new Error,mm.SCHEMA_EXISTS_ERR(e.schema),mn.BAD_REQUEST,wu.LOG_LEVELS.ERROR,mm.SCHEMA_EXISTS_ERR(e.schema),!0);return await ga.createSchema(e),`database '${e.schema}' successfully created`}a(tx,"createSchemaStructure");async function Jre(e){return Cu(e),e.hash_attribute=e.primary_key??e.hash_attribute,await rx(e)}a(Jre,"createTable");async function rx(e){let t=Nu.create_table_object(e);if(t)throw pn(t,t.message,mn.BAD_REQUEST,void 0,void 0,!0);if(Nu.validateTableResidence(e.residence),!await Iu.checkSchemaTableExists(e.schema,e.table))throw pn(new Error,mm.TABLE_EXISTS_ERR(e.schema,e.table),mn.BAD_REQUEST,wu.LOG_LEVELS.ERROR,mm.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:Kre(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ga.createTable(n,e);else throw pn(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",mn.BAD_REQUEST);else await ga.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(rx,"createTableStructure");async function Xre(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=Nu.schema_object(e),n=t??r;if(n)throw pn(n,n.message,mn.BAD_REQUEST,void 0,void 0,!0);Cu(e);let s=await Iu.checkSchemaExists(e.schema);if(s)throw pn(new Error,s,mn.NOT_FOUND,wu.LOG_LEVELS.ERROR,s,!0);let i=await Iu.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);await ga.dropSchema(e),Sm.signalSchemaChange(new Tm(process.pid,e.operation,e.schema)),await ZH.purgeSchemaTableStreams(e.schema,o);let c=await ex(e);return c.message=`successfully deleted '${e.schema}'`,c}a(Xre,"dropSchema");async function Zre(e){let t=Nu.table_object(e);if(t)throw pn(t,t.message,mn.BAD_REQUEST,void 0,void 0,!0);Cu(e);let r=await Iu.checkSchemaTableExists(e.schema,e.table);if(r)throw pn(new Error,r,mn.NOT_FOUND,wu.LOG_LEVELS.ERROR,r,!0);await ga.dropTable(e),await ZH.purgeTableStream(e.schema,e.table);let n=await ex(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}a(Zre,"dropTable");async function ene(e){let t=Nu.attribute_object(e);if(t)throw pn(t,t.message,mn.BAD_REQUEST,void 0,void 0,!0);Cu(e);let r=await Iu.checkSchemaTableExists(e.schema,e.table);if(r)throw pn(new Error,r,mn.NOT_FOUND,wu.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw pn(new Error,"You cannot drop a hash attribute",mn.BAD_REQUEST,void 0,void 0,!0);if(wu.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw pn(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,mn.BAD_REQUEST,void 0,void 0,!0);try{return await ga.dropAttribute(e),tne(e),Sm.signalSchemaChange(new Tm(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Yre.error(`Got an error deleting attribute ${Wre.inspect(e)}.`),n}}a(ene,"dropAttribute");function tne(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(tne,"dropAttributeFromGlobal");async function rne(e){Cu(e);let t=Qre()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw pn(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,mn.BAD_REQUEST,void 0,void 0,!0);return await ga.createAttribute(e),Sm.signalSchemaChange(new Tm(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(rne,"createAttribute");function nne(e){return ga.getBackup(e)}a(nne,"getBackup")});var ix=y((Nwe,sx)=>{"use strict";var{OPERATIONS_ENUM:sne}=M(),Ry=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=sne.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};sx.exports=Ry});var Ay=y((Cwe,ux)=>{"use strict";var ine=Hn(),wwe=ix(),Rm=ee(),Am=M(),one=te(),{handleHDBError:ox,hdb_errors:ane}=ce(),{HDB_ERROR_MSGS:ax,HTTP_STATUS_CODES:cx}=ane,cne=Object.values(Am.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),lx="To use this operation audit log must be enabled in harperdb-config.yaml";ux.exports=lne;async function lne(e){if(Rm.isEmpty(e.schema))throw new Error(ax.SCHEMA_REQUIRED_ERR);if(Rm.isEmpty(e.table))throw new Error(ax.TABLE_REQUIRED_ERR);if(!one.get(Am.CONFIG_PARAMS.LOGGING_AUDITLOG))throw ox(new Error,lx,cx.BAD_REQUEST,Am.LOG_LEVELS.ERROR,lx,!0);let t=Rm.checkSchemaTableExist(e.schema,e.table);if(t)throw ox(new Error,t,cx.NOT_FOUND,Am.LOG_LEVELS.ERROR,t,!0);if(!Rm.isEmpty(e.search_type)&&cne.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await ine.readAuditLog(e)}a(lne,"readAuditLog")});var _x=y((Pwe,dx)=>{"use strict";var{OPERATIONS_ENUM:une}=M(),by=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=une.GET_BACKUP,this.schema=t,this.table=r}};dx.exports=by});var hx=y((vwe,Ex)=>{"use strict";var dne=Hn(),Mwe=_x(),yy=ee(),_ne=M(),Uwe=te(),{handleHDBError:fne,hdb_errors:Ene}=ce(),{HDB_ERROR_MSGS:fx,HTTP_STATUS_CODES:hne}=Ene;Ex.exports=pne;async function pne(e){if(yy.isEmpty(e.schema))throw new Error(fx.SCHEMA_REQUIRED_ERR);if(yy.isEmpty(e.table))throw new Error(fx.TABLE_REQUIRED_ERR);let t=yy.checkSchemaTableExist(e.schema,e.table);if(t)throw fne(new Error,t,hne.NOT_FOUND,_ne.LOG_LEVELS.ERROR,t,!0);return await dne.getBackup(read_audit_log_object)}a(pne,"getBackup")});var Rx=y((Hwe,gx)=>{var Ra=require("validate.js"),mx=St(),Du=M(),{handleHDBError:mne,hdb_errors:Sne}=ce(),{HDB_ERROR_MSGS:Qt,HTTP_STATUS_CODES:Tne}=Sne,Oy=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),gne={STRUCTURE_USER:"structure_user"},px=Object.values(Du.ROLE_TYPES_ENUM),Rne="attribute_permissions",Ane="attribute_name",{PERMS_CRUD_ENUM:Pu}=Du,bne=[Rne,...Object.values(Pu)],Sx=[Pu.READ,Pu.INSERT,Pu.UPDATE],yne=[Ane,...Sx];function One(e){let t=Oy();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,Tx(e,t)}a(One,"addRoleValidation");function Nne(e){let t=Oy();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,Tx(e,t)}a(Nne,"alterRoleValidation");function Ine(e){let t=Oy();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,mx.validateObject(e,t)}a(Ine,"dropRoleValidation");var wne=["operation","role","id","permission","hdb_user","hdb_auth_header"];function Tx(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)wne.includes(n[o])||s.push(n[o]);s.length>0&&sr(Qt.INVALID_ROLE_JSON_KEYS(s),r);let i=mx.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{sr(o,r)}),e.permission){let o=Cne(e);o&&sr(o,r),px.forEach(c=>{e.permission[c]&&!Ra.isBoolean(e.permission[c])&&sr(Qt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(px.indexOf(o)<0){if(o===gne.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let d=0,u=l.length;d<u;d++){let _=l[d];global.hdb_schema[_]||sr(Qt.SCHEMA_NOT_FOUND(_),r)}continue}sr(Qt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){sr(Qt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let d=c.tables[l];if(!l||!global.hdb_schema[o][l]){sr(Qt.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(d).forEach(u=>{bne.includes(u)||sr(Qt.INVALID_PERM_KEY(u),r,o,l)}),Object.values(Pu).forEach(u=>{Ra.isDefined(d[u])?Ra.isBoolean(d[u])||sr(Qt.TABLE_PERM_NOT_BOOLEAN(u),r,o,l):sr(Qt.TABLE_PERM_MISSING(u),r,o,l)}),Ra.isDefined(d.attribute_permissions)){if(!Ra.isArray(d.attribute_permissions)){sr(Qt.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}}else{sr(Qt.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}if(d.attribute_permissions){let u=global.hdb_schema[o][l].attributes.map(({attribute:E})=>E),_={read:!1,insert:!1,update:!1};for(let E in d.attribute_permissions){let f=d.attribute_permissions[E];if(Object.keys(f).forEach(S=>{!yne.includes(S)&&S!==Pu.DELETE&&sr(Qt.INVALID_ATTR_PERM_KEY(S),r,o,l)}),!Ra.isDefined(f.attribute_name)){sr(Qt.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=f.attribute_name;if(!u.includes(h)){sr(Qt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}Sx.forEach(S=>{Ra.isDefined(f[S])?Ra.isBoolean(f[S])||sr(Qt.ATTR_PERM_NOT_BOOLEAN(S,h),r,o,l):sr(Qt.ATTR_PERM_MISSING(S,h),r,o,l)}),!_.read&&f.read===!0&&(_.read=!0),!_.insert&&f.insert===!0&&(_.insert=!0),!_.update&&f.update===!0&&(_.update=!0)}if(d.read===!1&&_.read===!0||d.insert===!1&&_.insert===!0||d.update===!1&&_.update===!0){let E=`${o}.${l}`;sr(Qt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,l)}}}}return Dne(r)}a(Tx,"customValidate");gx.exports={addRoleValidation:One,alterRoleValidation:Nne,dropRoleValidation:Ine};function Cne(e){let{operation:t,permission:r}=e;if(t===Du.OPERATIONS_ENUM.ADD_ROLE||t===Du.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 Qt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Du.ROLE_TYPES_ENUM.SUPER_USER:Du.ROLE_TYPES_ENUM.CLUSTER_USER;return Qt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Cne,"validateNoSUPerms");function Dne(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:Qt.ROLE_PERMS_ERROR,...e};return mne(new Error,n,Tne.BAD_REQUEST)}else return null}a(Dne,"generateRolePermResponse");function sr(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(sr,"addPermError")});var ym=y((kwe,Ox)=>{"use strict";var Ax=un(),bx=jr(),Pne=mc(),Iy=Rx(),wy=_o(),Fwe=require("uuid").v4,Lne=require("util"),bm=M(),Mne=ee(),Cy=bx.searchByValue,Une=bx.searchByHash,vne=Lne.promisify(Pne.delete),Bne=zs(),Hne=su(),{hdb_errors:xne,handleHDBError:$c}=ce(),{HDB_ERROR_MSGS:yx,HTTP_STATUS_CODES:Rf}=xne,{UserEventMsg:Dy}=Qs();Ox.exports={addRole:Fne,alterRole:kne,dropRole:Gne,listRoles:qne};function Ny(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(Ny,"scrubRoleDetails");async function Fne(e){let t=Iy.addRoleValidation(e);if(t)throw t;e=Ny(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 Cy(r)||[])}catch(i){throw $c(i)}if(n&&n.length>0)throw $c(new Error,yx.ROLE_ALREADY_EXISTS(e.role),Rf.CONFLICT,void 0,void 0,!0);e.id||(e.id=e.role);let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await Ax.insert(s),wy.signalUserChange(new Dy(process.pid)),e=Ny(e),e}a(Fne,"addRole");async function kne(e){let t=Iy.alterRoleValidation(e);if(t)throw t;e=Ny(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await Ax.update(r)}catch(s){throw $c(s)}if(n&&n?.message==="updated 0 of 1 records")throw $c(new Error,"Invalid role id",Rf.BAD_REQUEST,void 0,void 0,!0);return await wy.signalUserChange(new Dy(process.pid)),e}a(kne,"alterRole");async function Gne(e){let t=Iy.dropRoleValidation(e);if(t)throw $c(new Error,t,Rf.BAD_REQUEST,void 0,void 0,!0);let r=new Hne(bm.SYSTEM_SCHEMA_NAME,bm.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Une(r));if(n.length===0)throw $c(new Error,yx.ROLE_NOT_FOUND,Rf.NOT_FOUND,void 0,void 0,!0);let s=new Bne(bm.SYSTEM_SCHEMA_NAME,bm.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await Cy(s)),o=!1;if(Mne.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw $c(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Rf.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await vne(c),wy.signalUserChange(new Dy(process.pid)),`${n[0].role} successfully deleted`}a(Gne,"dropRole");async function qne(){return Cy({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(qne,"listRoles")});var Cx=y((qwe,wx)=>{"use strict";var $ne=te(),Aa=require("joi"),Vne=St(),Nx=require("moment"),Yne=require("fs-extra"),Py=require("path"),Kne=require("lodash"),Af=M(),{LOG_LEVELS:Vc}=M(),Wne="YYYY-MM-DD hh:mm:ss",jne=Py.resolve(__dirname,"../logs");wx.exports=function(e){return Vne.validateBySchema(e,Qne)};var Qne=Aa.object({from:Aa.custom(Ix),until:Aa.custom(Ix),level:Aa.valid(Vc.NOTIFY,Vc.FATAL,Vc.ERROR,Vc.WARN,Vc.INFO,Vc.DEBUG,Vc.TRACE),order:Aa.valid("asc","desc"),limit:Aa.number().min(1),start:Aa.number().min(0),log_name:Aa.custom(zne)});function Ix(e,t){if(Nx(e,Nx.ISO_8601).format(Wne)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(Ix,"validateDatetime");function zne(e,t){if(Kne.invert(Af.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=$ne.get(Af.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Af.LOG_NAMES.HDB:e,i=s===Af.LOG_NAMES.INSTALL?Py.join(jne,Af.LOG_NAMES.INSTALL):Py.join(n,s);return Yne.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(zne,"validateReadLogPath")});var My=y((Vwe,Px)=>{"use strict";var Om=M(),Jne=V(),Xne=te(),Zne=Cx(),Ly=require("path"),Dx=require("fs-extra"),{once:ese}=require("events"),{handleHDBError:tse,hdb_errors:rse}=ce(),{PACKAGE_ROOT:nse}=M(),sse=Ly.join(nse,"logs"),ise=1e3,ose=200;Px.exports=ase;async function ase(e){let t=Zne(e);if(t)throw tse(t,t.message,rse.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Xne.get(Om.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Om.LOG_NAMES.HDB:e.log_name,s=n===Om.LOG_NAMES.INSTALL?Ly.join(sse,Om.LOG_NAMES.INSTALL):Ly.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,l=c?new Date(e.from):void 0,d=e.until!==void 0,u=d?new Date(e.until):void 0,_=e.limit===void 0?ise:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+_,S=0;E==="desc"&&!l&&!u&&(S=Math.max(Dx.statSync(s).size-(h+5)*ose,0));let T=Dx.createReadStream(s,{start:S});T.on("error",F=>{Jne.error(F)});let g=0,m=[],C="",O;T.on("data",F=>{let Y=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;F=C+F;let $=0,Z;for(;(Z=Y.exec(F))&&!T.destroyed;){O&&(O.message=F.slice($,Z.index),x(O));let[Q,_e,K]=Z,ie=K.split("] ["),le=ie[0],we=ie[1];ie.splice(0,2),O={timestamp:_e,thread:le,level:we,tags:ie,message:""},$=Z.index+Q.length}C=F.slice($)}),T.on("end",F=>{T.destroyed||O&&(O.message=C.trim(),x(O))}),T.resume();function x(F){let Y,$,Z;switch(!0){case(i&&c&&d):Y=new Date(F.timestamp),$=new Date(l),Z=new Date(u),F.level===o&&Y>=$&&Y<=Z&&g<f?g++:F.level===o&&Y>=$&&Y<=Z&&(ba(F,E,m),g++,g===h&&T.destroy());break;case(i&&c):Y=new Date(F.timestamp),$=new Date(l),F.level===o&&Y>=$&&g<f?g++:F.level===o&&Y>=$&&(ba(F,E,m),g++,g===h&&T.destroy());break;case(i&&d):Y=new Date(F.timestamp),Z=new Date(u),F.level===o&&Y<=Z&&g<f?g++:F.level===o&&Y<=Z&&(ba(F,E,m),g++,g===h&&T.destroy());break;case(c&&d):Y=new Date(F.timestamp),$=new Date(l),Z=new Date(u),Y>=$&&Y<=Z&&g<f?g++:Y>=$&&Y<=Z&&(ba(F,E,m),g++,g===h&&T.destroy());break;case i:F.level===o&&g<f?g++:F.level===o&&(ba(F,E,m),g++,g===h&&T.destroy());break;case c:Y=new Date(F.timestamp),$=new Date(l),Y>=$&&g<f?g++:Y>=$&&g>=f&&(ba(F,E,m),g++,g===h&&T.destroy());break;case d:Y=new Date(F.timestamp),Z=new Date(u),Y<=Z&&g<f?g++:Y<=Z&&g>=f&&(ba(F,E,m),g++,g===h&&T.destroy());break;default:g<f?g++:(ba(F,E,m),g++,g===h&&T.destroy())}}return a(x,"onLogMessage"),await ese(T,"close"),m}a(ase,"readLog");function ba(e,t,r){t==="desc"?cse(e,r):t==="asc"?lse(e,r):r.push(e)}a(ba,"pushLineToResult");function cse(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(cse,"insertDescending");function lse(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(lse,"insertAscending")});var Nm=y((zwe,vx)=>{"use strict";var Uy=require("joi"),{string:Lu,boolean:Lx,date:use}=Uy.types(),dse=St(),{validateSchemaExists:Kwe,validateTableExists:Wwe,validateSchemaName:jwe}=Ri(),_se=M(),fse=At(),Mx=te();Mx.initSync();var Qwe=Lu.invalid(Mx.get(_se.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(fse.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),Ux={operation:Lu.valid("add_node","update_node","set_node_replication"),node_name:Lu.optional(),subscriptions:Uy.array().items({table:Lu.optional(),schema:Lu.optional(),database:Lu.optional(),subscribe:Lx.required(),publish:Lx.required().custom(hse),start_time:use.iso()})};function Ese(e){return dse.validateBySchema(e,Uy.object(Ux))}a(Ese,"addUpdateNodeValidator");function hse(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(hse,"checkForFalsy");vx.exports={addUpdateNodeValidator:Ese,validation_schema:Ux}});var Hx=y((Xwe,Bx)=>{var pse=St(),mse={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};Bx.exports=function(e){return pse.validateObject(e,mse)}});var Im=y((Zwe,xx)=>{"use strict";var Sse=M().OPERATIONS_ENUM,vy=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=Sse.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};xx.exports=vy});var kx=y((tCe,Fx)=>{"use strict";var Tse={OPERATION:"operation",REFRESH:"refresh"},By=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},Hy=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};Fx.exports={JWTTokens:By,TOKEN_TYPE_ENUM:Tse,JWTRSAKeys:Hy}});var Of=y((nCe,Vx)=>{"use strict";var yf=require("jsonwebtoken"),xy=require("fs-extra"),Fy=ee(),gs=M(),{handleHDBError:Sn,hdb_errors:gse}=ce(),{HTTP_STATUS_CODES:Tn,AUTHENTICATION_ERROR_MSGS:gn}=gse,bf=V(),Gx=lp(),qy=_n(),Rse=un().update,Ase=Im(),bse=_o(),{UserEventMsg:yse}=Qs(),ya=te();ya.initSync();var ky=require("path"),{JWTTokens:Ose,JWTRSAKeys:Nse,TOKEN_TYPE_ENUM:wm}=kx(),Ise=ya.get(gs.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?ya.get(gs.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",wse=ya.get(gs.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?ya.get(gs.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Cm="RS256",Gy;Vx.exports={createTokens:Cse,validateOperationToken:Pse,refreshOperationToken:Dse,validateRefreshToken:$x};async function Cse(e){if(Fy.isEmpty(e)||typeof e!="object")throw Sn(new Error,gn.INVALID_AUTH_OBJECT,Tn.BAD_REQUEST,void 0,void 0,!0);if(Fy.isEmpty(e.username))throw Sn(new Error,gn.USERNAME_REQUIRED,Tn.BAD_REQUEST,void 0,void 0,!0);if(Fy.isEmpty(e.password))throw Sn(new Error,gn.PASSWORD_REQUIRED,Tn.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await qy.findAndValidateUser(e.username,e.password),!t)throw Sn(new Error,gn.INVALID_CREDENTIALS,Tn.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw bf.error(E),Sn(new Error,gn.INVALID_CREDENTIALS,Tn.UNAUTHORIZED,void 0,void 0,!0)}let r=await Dm(),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 qx(i,r.private_key,r.passphrase),c=await yf.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:wse,algorithm:Cm,subject:wm.REFRESH}),l=Gx.hash(c),d=new Ase(gs.SYSTEM_SCHEMA_NAME,gs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:l}]),u,_;try{u=await Rse(d)}catch(E){bf.error(E),_=E}if(_!==void 0||u.skipped_hashes.length>0)throw Sn(new Error,gn.REFRESH_TOKEN_SAVE_FAILED,Tn.INTERNAL_SERVER_ERROR);return bse.signalUserChange(new yse(process.pid)),new Ose(o,c)}a(Cse,"createTokens");async function qx(e,t,r){return await yf.sign(e,{key:t,passphrase:r},{expiresIn:Ise,algorithm:Cm,subject:wm.OPERATION})}a(qx,"signOperationToken");async function Dm(){if(Gy===void 0)try{let e=ky.join(ya.getHdbBasePath(),gs.LICENSE_KEY_DIR_NAME,gs.JWT_ENUM.JWT_PASSPHRASE_NAME),t=ky.join(ya.getHdbBasePath(),gs.LICENSE_KEY_DIR_NAME,gs.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=ky.join(ya.getHdbBasePath(),gs.LICENSE_KEY_DIR_NAME,gs.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await xy.readFile(e)).toString(),s=(await xy.readFile(t)).toString(),i=(await xy.readFile(r)).toString();Gy=new Nse(i,s,n)}catch(e){throw bf.error(e),Sn(new Error,gn.NO_ENCRYPTION_KEYS,Tn.INTERNAL_SERVER_ERROR)}return Gy}a(Dm,"getJWTRSAKeys");async function Dse(e){if(!e)throw Sn(new Error,gn.INVALID_BODY,Tn.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Sn(new Error,gn.REFRESH_TOKEN_REQUIRED,Tn.BAD_REQUEST,void 0,void 0,!0);await $x(e.refresh_token);let t=await Dm(),r=await yf.decode(e.refresh_token);return{operation_token:await qx({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(Dse,"refreshOperationToken");async function Pse(e){try{let t=await Dm(),r=await yf.verify(e,t.public_key,{algorithms:Cm,subject:wm.OPERATION});return await qy.findAndValidateUser(r.username,void 0,!1)}catch(t){throw bf.warn(t),t.name&&t.name==="TokenExpiredError"?Sn(new Error,gn.TOKEN_EXPIRED,Tn.FORBIDDEN):Sn(new Error,gn.INVALID_TOKEN,Tn.UNAUTHORIZED)}}a(Pse,"validateOperationToken");async function $x(e){let t;try{let r=await Dm(),n=await yf.verify(e,r.public_key,{algorithms:Cm,subject:wm.REFRESH});t=await qy.findAndValidateUser(n.username,void 0,!1)}catch(r){throw bf.warn(r),r.name&&r.name==="TokenExpiredError"?Sn(new Error,gn.TOKEN_EXPIRED,Tn.FORBIDDEN):Sn(new Error,gn.INVALID_TOKEN,Tn.UNAUTHORIZED)}if(!Gx.validate(t.refresh_token,e))throw Sn(new Error,gn.INVALID_TOKEN,Tn.UNAUTHORIZED);return t}a($x,"validateRefreshToken")});var $y=y((oCe,Wx)=>{"use strict";var Lse=Hx(),Mu=require("passport"),Mse=require("passport-local").Strategy,Use=require("passport-http").BasicStrategy,vse=require("util"),Bse=_n(),Kx=vse.callbackify(Bse.findAndValidateUser),iCe=Ln(),Hse=M(),Yx=Of();Mu.use(new Mse(function(e,t,r){Kx(e,t,r)}));Mu.use(new Use(function(e,t,r){Kx(e,t,r)}));Mu.serializeUser(function(e,t){t(null,e)});Mu.deserializeUser(function(e,t){t(null,e)});function xse(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":Mu.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===Hse.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?Yx.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):Yx.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Mu.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(xse,"authorize");function Fse(e,t){let r=Lse(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(Fse,"checkPermissions");Wx.exports={authorize:xse,checkPermissions:Fse}});var Uu=y((cCe,jx)=>{"use strict";var Vy=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},Yy=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};jx.exports={Node:Vy,NodeSubscription:Yy}});var zx=y((uCe,Qx)=>{"use strict";var kse=M().OPERATIONS_ENUM,Ky=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=kse.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Qx.exports=Ky});var Nf=y((_Ce,Jx)=>{"use strict";var Wy=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},jy=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)}};Jx.exports={RemotePayloadObject:Wy,RemotePayloadSubscription:jy}});var Zx=y((ECe,Xx)=>{"use strict";var Qy=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}};Xx.exports=Qy});var tF=y((gCe,eF)=>{"use strict";var Gse=Zx(),pCe=Bt(),mCe=_t(),qse=V(),{getSchemaPath:SCe,getTransactionAuditStorePath:TCe}=mt(),{getDatabases:$se}=(De(),ne(at));eF.exports=Vse;async function Vse(e){let t=new Gse;try{let r=$se()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats();t.schema=e.schema,t.table=e.name,t.record_count=n.entryCount,t.transaction_log_record_count=s.entryCount}catch(r){qse.warn(`unable to stat table dbi due to ${r}`)}return t}a(Vse,"lmdbGetTableSize")});var nF=y((ACe,rF)=>{"use strict";var zy=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}};rF.exports=zy});var To=y((wCe,aF)=>{"use strict";var Yse=require("fs-extra"),Kse=require("path"),en=require("systeminformation"),Oa=V(),sF=nr(),yCe=At(),vu=M(),Wse=tF(),jse=uo(),{getThreadInfo:iF}=ut(),If=te();If.initSync();var Qse=nF(),{openEnvironment:OCe}=_t(),{getSchemaPath:NCe}=mt(),{database:ICe,databases:Jy}=(De(),ne(at)),Pm;aF.exports={getHDBProcessInfo:tO,getNetworkInfo:nO,getDiskInfo:rO,getMemoryInfo:eO,getCPUInfo:Zy,getTimeInfo:Xy,getSystemInformation:sO,systemInformation:zse,getTableSize:iO,getMetrics:oO};function Xy(){return en.time()}a(Xy,"getTimeInfo");async function Zy(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:d,...u}=await en.cpu();u.cpu_speed=await en.cpuCurrentSpeed();let{raw_currentload:_,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:S,raw_currentload_user:T,cpus:g,...m}=await en.currentLoad();return m.cpus=[],g.forEach(C=>{let{raw_load:O,raw_load_idle:x,raw_load_irq:F,raw_load_nice:Y,raw_load_system:$,raw_load_user:Z,...Q}=C;m.cpus.push(Q)}),u.current_load=m,u}catch(e){return Oa.error(`error in getCPUInfo: ${e}`),{}}}a(Zy,"getCPUInfo");async function eO(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await en.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Oa.error(`error in getMemoryInfo: ${e}`),{}}}a(eO,"getMemoryInfo");async function tO(){let e={core:[],clustering:[]};try{let t=await en.processes(),r;try{r=Number.parseInt(await Yse.readFile(Kse.join(If.get(vu.CONFIG_PARAMS.ROOTPATH),vu.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===vu.NODE_ERROR_CODES.ENOENT)Oa.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 Oa.error(`error in getHDBProcessInfo: ${t}`),e}}a(tO,"getHDBProcessInfo");async function rO(){let e={};try{if(!If.get(vu.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK))return e;let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await en.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:l,...d}=await en.fsStats();return e.read_write=d,e.size=await en.fsSize(),e}catch(t){return Oa.error(`error in getDiskInfo: ${t}`),e}}a(rO,"getDiskInfo");async function nO(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return If.get(vu.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)&&(e.default_interface=await en.networkInterfaceDefault(),e.latency=await en.inetChecksite("google.com"),(await en.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:l,ieee8021xAuth:d,ieee8021xState:u,carrier_changes:_,...E}=n;e.interfaces.push(E)}),(await en.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)})),e}catch(t){return Oa.error(`error in getNetworkInfo: ${t}`),e}}a(nO,"getNetworkInfo");async function sO(){if(Pm!==void 0)return Pm;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await en.osInfo();e=c;let l=await en.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,Pm=e,Pm}catch(t){return Oa.error(`error in getSystemInformation: ${t}`),e}}a(sO,"getSystemInformation");async function iO(){let e=[],t=await jse.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await Wse(n));return e}a(iO,"getTableSize");async function oO(){let e={};for(let t in Jy){let r=e[t]={},n=r.tables={};for(let s in Jy[t])try{let i=Jy[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(l=>{let[d,u,_]=l.trim().split(" ");return{pid:d,thread:u,txnid:_}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=o[l];n[s]=c}catch(i){Oa.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(oO,"getMetrics");async function oF(){if(If.get(vu.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await sF.getNATSReferences(),t=await sF.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(oF,"getNatsStreamInfo");async function zse(e){let t=new Qse;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await sO(),t.time=Xy(),t.cpu=await Zy(),t.memory=await eO(),t.disk=await rO(),t.network=await nO(),t.harperdb_processes=await tO(),t.table_size=await iO(),t.metrics=await oO(),t.threads=await iF(),t.replication=await oF(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await sO();break;case"time":t.time=Xy();break;case"cpu":t.cpu=await Zy();break;case"memory":t.memory=await eO();break;case"disk":t.disk=await rO();break;case"network":t.network=await nO();break;case"harperdb_processes":t.harperdb_processes=await tO();break;case"table_size":t.table_size=await iO();break;case"database_metrics":case"metrics":t.metrics=await oO();break;case"threads":t.threads=await iF();break;case"replication":t.replication=await oF();break;default:break}return t}a(zse,"systemInformation")});var go=y((DCe,cF)=>{"use strict";cF.exports={version:Jse,printVersion:Xse};var Lm=Cc();function Jse(){if(Lm)return Lm.version}a(Jse,"version");function Xse(){Lm&&console.log(`HarperDB Version ${Lm.version}`)}a(Xse,"printVersion")});var Ro=y((UCe,_F)=>{"use strict";var Zse=un(),aO=ee(),eie=require("util"),Yc=M(),lF=te();lF.initSync();var tie=$y(),uF=jr(),{Node:LCe,NodeSubscription:MCe}=Uu(),rie=su(),nie=zx(),{RemotePayloadObject:sie,RemotePayloadSubscription:iie}=Nf(),{handleHDBError:oie,hdb_errors:aie}=ce(),{HTTP_STATUS_CODES:cie,HDB_ERROR_MSGS:lie}=aie,uie=zs(),die=To(),_ie=go(),{getDatabases:fie}=(De(),ne(at)),Eie=eie.promisify(tie.authorize),hie=uF.searchByHash,pie=uF.searchByValue;_F.exports={authHeaderToUser:mie,isEmpty:Sie,getNodeRecord:Tie,upsertNodeRecord:gie,buildNodePayloads:Rie,checkClusteringEnabled:Aie,getAllNodeRecords:bie,getSystemInfo:yie,reverseSubscription:dF};async function mie(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await Eie(t,null),e}a(mie,"authHeaderToUser");function Sie(e){return e==null}a(Sie,"isEmpty");async function Tie(e){let t=new rie(Yc.SYSTEM_SCHEMA_NAME,Yc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return hie(t)}a(Tie,"getNodeRecord");async function gie(e){let t=new nie(Yc.SYSTEM_SCHEMA_NAME,Yc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return Zse.upsert(t)}a(gie,"upsertNodeRecord");function dF(e){if(aO.isEmpty(e.subscribe)||aO.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(dF,"reverseSubscription");function Rie(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:l,table:d}=c,u=aO.getTableHashAttribute(l,d),{subscribe:_,publish:E}=dF(c),f=fie()[l]?.[d],h=new iie(l,d,u,E,_,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new sie(r,t,s,n)}a(Rie,"buildNodePayloads");function Aie(){if(!lF.get(Yc.CONFIG_PARAMS.CLUSTERING_ENABLED))throw oie(new Error,lie.CLUSTERING_NOT_ENABLED,cie.BAD_REQUEST,void 0,void 0,!0)}a(Aie,"checkClusteringEnabled");async function bie(){let e=new uie(Yc.SYSTEM_SCHEMA_NAME,Yc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await pie(e))}a(bie,"getAllNodeRecords");async function yie(){let e=await die.getSystemInformation();return{hdb_version:_ie.version(),node_version:e.node_version,platform:e.platform}}a(yie,"getSystemInfo")});var cO=y((BCe,gF)=>{"use strict";var Mm=nr(),fF=ee(),EF=At(),hF=M(),Um=V(),pF=gm(),Oie=G_(),{RemotePayloadObject:Nie}=Nf(),{handleHDBError:mF,hdb_errors:Iie}=ce(),{HTTP_STATUS_CODES:SF}=Iie,{NodeSubscription:TF}=Uu();gF.exports=wie;async function wie(e,t){let r;try{r=await Mm.request(`${t}.${EF.REQUEST_SUFFIX}`,new Nie(hF.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Um.trace("Response from remote describe all request:",r)}catch(o){Um.error(`addNode received error from describe all request to remote node: ${o}`);let c=Mm.requestErrorHandler(o,"add_node",t);throw mF(new Error,c,SF.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===EF.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw mF(new Error,o,SF.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,l=o.database??o.schema??"data";if(l===hF.SYSTEM_SCHEMA_NAME){await Mm.createLocalTableStream(l,c);let h=new TF(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let d=fF.doesSchemaExist(l),u=n[l]!==void 0,_=c?fF.doesTableExist(l,c):!0,E=c?n?.[l]?.[c]!==void 0:!0;if(!d&&!u||!_&&!E){s.push(o);continue}if(!d&&u&&(Um.trace(`addNode creating schema: ${l}`),await pF.createSchema({operation:"create_schema",schema:l})),!_&&E){Um.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new Oie(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await pF.createTable(h)}await Mm.createLocalTableStream(l,c);let f=new TF(l,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(wie,"reviewSubscriptions")});var Kc={};tt(Kc,{addNodeBack:()=>Mie,removeNodeBack:()=>Uie,setNode:()=>Lie});async function Lie(e){e.node_name&&!e.hostname&&(e.hostname=e.node_name),e.verify_tls!==void 0&&(e.rejectUnauthorized=e.verify_tls);let{url:t,hostname:r}=e;t?r||(r=e.hostname=Li(t)):t=pm(r);let n=(0,AF.validateBySchema)(e,Pie);if(n)throw(0,Ui.handleHDBError)(n,n.message,Die.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new Ui.ClientError("url or hostname is required for remove_node operation");let _=r,E=Pr(),f=await E.get(_);if(!f)throw new Ui.ClientError(_+" does not exist");try{await gf({url:f.url},{operation:wf.OPERATIONS_ENUM.REMOVE_NODE_BACK,name:f?.subscriptions?.length>0?lt():_},void 0)}catch(h){Rs.warn(`Error removing node from target node ${_}, if it is offline and we be online in the future, you may need to clean up this node manually, or retry:`,h)}return await E.delete(_),`Successfully removed '${_}' from cluster`}if(!t)throw new Ui.ClientError("url required for this operation");let s=fa();if(s==null)throw new Ui.ClientError("replication url is missing from harperdb-config.yaml");let i,o,c;if(t?.startsWith("wss:")){if(e.operation==="add_node"&&!e.authorization)throw new Ui.ClientError("authorization parameter is required");i=await(0,As.getReplicationCert)();let _=await(0,As.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(o=await(0,As.createCsr)(),Rs.info("Sending CSR to target node:",t)):(c=_?.certificate,Rs.info("Sending CA named",_?.name,"to target node",t))}let l={operation:wf.OPERATIONS_ENUM.ADD_NODE_BACK,hostname:(0,bF.get)(wf.CONFIG_PARAMS.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c};if(e.subscriptions&&(l.subscriptions=e.subscriptions.map(RF)),e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let _=RF(e);l.subscribe=_.subscribe,l.publish=_.publish}e?.authorization?.username&&e?.authorization?.password&&(e.authorization="Basic "+Buffer.from(e.authorization.username+":"+e.authorization.password).toString("base64"));let d;try{d=await gf({url:t},l,e)}catch(_){throw _.message=`Error returned from ${t}: `+_.message,_}if(o&&(!d?.certificate||!d?.certificate?.includes?.("BEGIN CERTIFICATE")))throw new Error(`Unexpected certificate signature response from node ${t} response: ${JSON.stringify(d)}`);o&&(Rs.info("CSR response received from node:",t,"saving certificate and CA in hdb_certificate"),await(0,As.setCertTable)({name:Cie.certificateFromPem(d.signingCA).issuer.getField("CN").value,certificate:d.signingCA,is_authority:!0}),d.certificate&&await(0,As.setCertTable)({name:lt(),uses:["https","operations","wss"],certificate:d.certificate,private_key_name:i?.options?.key_file,is_authority:!1,is_self_signed:!1}),c=d.signingCA);let u={url:t,ca:d.usingCA};if(e.hostname&&(u.name=e.hostname),e.subscriptions?u.subscriptions=e.subscriptions:u.replicates=!0,e.start_time&&(u.start_time=typeof e.start_time=="string"?new Date(e.start_time).getTime():e.start_time),u.replicates){let _={url:s,ca:c,replicates:!0};e.start_time&&(_.start_time=e.start_time),await mo(lt(),_)}return await mo(d.nodeName,u),e.operation==="update_node"?`Successfully updated '${t}'`:`Successfully added '${t}' to cluster`}async function Mie(e){Rs.trace("addNodeBack received request:",e);let t=await(0,As.signCertificate)(e),r;e.csr?(r=t.signingCA,Rs.info("addNodeBack received CSR from node:",e.url,"this node will use and respond with CA that was used to issue CSR")):(r=e?.cert_auth,Rs.info("addNodeBack received CA from node:",e.url));let n={url:e.url,ca:r};e.subscriptions?n.subscriptions=e.subscriptions:n.replicates=!0,e.start_time&&(n.start_time=e.start_time);let s=await(0,As.getReplicationCertAuth)();if(n.replicates){let i={url:fa(),ca:s?.certificate,replicates:!0};e.start_time&&(i.start_time=e.start_time),await mo(lt(),i)}return await mo(e.hostname,n),t.nodeName=lt(),t.usingCA=s?.certificate,Rs.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function Uie(e){Rs.trace("removeNodeBack received request:",e),await Pr().delete(e.name)}function RF(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var As,AF,Bu,bF,wf,Rs,Ui,Cie,Die,Pie,Wc=Ce(()=>{As=B(Ss()),AF=B(St()),Bu=B(require("joi")),bF=B(te()),wf=B(M());_f();Su();hs();Rs=B(V()),Ui=B(ce()),{pki:Cie}=require("node-forge"),{HTTP_STATUS_CODES:Die}=Ui.hdb_errors,Pie=Bu.default.object({hostname:Bu.default.string(),verify_tls:Bu.default.boolean(),replicates:Bu.default.boolean(),subscriptions:Bu.default.array()});a(Lie,"setNode");a(Mie,"addNodeBack");a(Uie,"removeNodeBack");a(RF,"reverseSubscription")});var Pf=y((VCe,OF)=>{"use strict";var{handleHDBError:vm,hdb_errors:vie}=ce(),{HTTP_STATUS_CODES:Bm}=vie,{addUpdateNodeValidator:Bie}=Nm(),Hm=V(),xm=M(),yF=At(),Hie=ee(),Cf=nr(),Df=Ro(),lO=te(),xie=cO(),{Node:Fie,NodeSubscription:kie}=Uu(),{broadcast:Gie}=ut(),{setNode:qie}=(Wc(),ne(Kc)),qCe=te(),$Ce=M(),$ie="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Vie="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Yie=lO.get(xm.CONFIG_PARAMS.CLUSTERING_NODENAME);OF.exports=Kie;async function Kie(e,t=!1){if(Hm.trace("addNode called with:",e),lO.get(xm.CONFIG_PARAMS.REPLICATION_URL)||lO.get(xm.CONFIG_PARAMS.REPLICATION_HOSTNAME))return qie(e);Df.checkClusteringEnabled();let r=Bie(e);if(r)throw vm(r,r.message,Bm.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let _=await Df.getNodeRecord(n);if(!Hie.isEmptyOrZeroLength(_))throw vm(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Bm.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await xie(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=$ie,o;let c=Df.buildNodePayloads(s,Yie,xm.OPERATIONS_ENUM.ADD_NODE,await Df.getSystemInfo()),l=[];for(let _=0,E=s.length;_<E;_++){let f=s[_];s[_].start_time===void 0&&delete s[_].start_time,l.push(new kie(f.schema,f.table,f.publish,f.subscribe))}Hm.trace("addNode sending remote payload:",c);let d;try{d=await Cf.request(`${n}.${yF.REQUEST_SUFFIX}`,c)}catch(_){Hm.error(`addNode received error from request: ${_}`);for(let f=0,h=s.length;f<h;f++){let S=s[f];S.publish=!1,S.subscribe=!1,await Cf.updateRemoteConsumer(S,n)}let E=Cf.requestErrorHandler(_,"add_node",n);throw vm(new Error,E,Bm.INTERNAL_SERVER_ERROR,"error",E)}if(d.status===yF.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let _=`Error returned from remote node ${n}: ${d.message}`;throw vm(new Error,_,Bm.INTERNAL_SERVER_ERROR,"error",_)}Hm.trace(d);for(let _=0,E=s.length;_<E;_++){let f=s[_];await Cf.updateRemoteConsumer(f,n),f.subscribe===!0&&await Cf.updateConsumerIterator(f.schema,f.table,n,"start")}let u=new Fie(n,l,d.system_info);return await Df.upsertNodeRecord(u),Gie({type:"nats_update"}),i.length>0?o.message=Vie:o.message=`Successfully added '${n}' to manifest`,o}a(Kie,"addNode")});var fO=y((WCe,IF)=>{"use strict";var{handleHDBError:uO,hdb_errors:Wie}=ce(),{HTTP_STATUS_CODES:dO}=Wie,{addUpdateNodeValidator:jie}=Nm(),Lf=V(),Fm=M(),NF=At(),KCe=ee(),Mf=nr(),Uf=Ro(),_O=te(),{cloneDeep:Qie}=require("lodash"),zie=cO(),{Node:Jie,NodeSubscription:Xie}=Uu(),{broadcast:Zie}=ut(),{setNode:eoe}=(Wc(),ne(Kc)),toe="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",roe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",noe=_O.get(Fm.CONFIG_PARAMS.CLUSTERING_NODENAME);IF.exports=soe;async function soe(e){if(Lf.trace("updateNode called with:",e),_O.get(Fm.CONFIG_PARAMS.REPLICATION_URL)??_O.get(Fm.CONFIG_PARAMS.REPLICATION_HOSTNAME))return eoe(e);Uf.checkClusteringEnabled();let t=jie(e);if(t)throw uO(t,t.message,dO.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Uf.getNodeRecord(r);s.length>0&&(n=Qie(s));let{added:i,skipped:o}=await zie(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=toe,c;let l=Uf.buildNodePayloads(i,noe,Fm.OPERATIONS_ENUM.UPDATE_NODE,await Uf.getSystemInfo());for(let u=0,_=i.length;u<_;u++){let E=i[u];Lf.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[u].start_time===void 0&&delete i[u].start_time}Lf.trace("updateNode sending remote payload:",l);let d;try{d=await Mf.request(`${r}.${NF.REQUEST_SUFFIX}`,l)}catch(u){Lf.error(`updateNode received error from request: ${u}`);let _=Mf.requestErrorHandler(u,"update_node",r);throw uO(new Error,_,dO.INTERNAL_SERVER_ERROR,"error",_)}if(d.status===NF.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${d.message}`;throw uO(new Error,u,dO.INTERNAL_SERVER_ERROR,"error",u)}Lf.trace(d);for(let u=0,_=i.length;u<_;u++){let E=i[u];await Mf.updateRemoteConsumer(E,r),E.subscribe===!0?await Mf.updateConsumerIterator(E.schema,E.table,r,"start"):await Mf.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new Jie(r,[],d.system_info)]),await ioe(n[0],i,d.system_info),o.length>0?c.message=roe:c.message=`Successfully updated '${r}'`,c}a(soe,"updateNode");async function ioe(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let l=0,d=e.subscriptions.length;l<d;l++){let u=n.subscriptions[l];if(u.schema===o.schema&&u.table===o.table){u.publish=o.publish,u.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new Xie(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Uf.upsertNodeRecord(n),Zie({type:"nats_update"})}a(ioe,"updateNodeTable")});var LF=y((QCe,PF)=>{"use strict";var DF=require("joi"),{string:wF}=DF.types(),ooe=St(),CF=M(),aoe=te(),coe=At();PF.exports=loe;function loe(e){let t=wF.invalid(aoe.get(CF.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(coe.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=DF.object({operation:wF.valid(CF.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return ooe.validateBySchema(e,r)}a(loe,"removeNodeValidator")});var km=y((JCe,HF)=>{"use strict";var{handleHDBError:MF,hdb_errors:uoe}=ce(),{HTTP_STATUS_CODES:UF}=uoe,doe=LF(),vf=V(),vF=Ro(),_oe=ee(),Hu=M(),BF=At(),EO=nr(),hO=te(),{RemotePayloadObject:foe}=Nf(),{NodeSubscription:Eoe}=Uu(),hoe=k_(),poe=mc(),{broadcast:moe}=ut(),{setNode:Soe}=(Wc(),ne(Kc)),Toe=hO.get(Hu.CONFIG_PARAMS.CLUSTERING_NODENAME);HF.exports=goe;async function goe(e){if(vf.trace("removeNode called with:",e),hO.get(Hu.CONFIG_PARAMS.REPLICATION_URL)??hO.get(Hu.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Soe(e);vF.checkClusteringEnabled();let t=doe(e);if(t)throw MF(t,t.message,UF.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await vF.getNodeRecord(r);if(_oe.isEmptyOrZeroLength(n))throw MF(new Error,`Node '${r}' was not found.`,UF.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new foe(Hu.OPERATIONS_ENUM.REMOVE_NODE,Toe,[]),i,o=!1;for(let l=0,d=n.subscriptions.length;l<d;l++){let u=n.subscriptions[l];u.subscribe===!0&&await EO.updateConsumerIterator(u.schema,u.table,r,"stop");try{await EO.updateRemoteConsumer(new Eoe(u.schema,u.table,!1,!1),r)}catch(_){vf.error(_)}}try{i=await EO.request(`${r}.${BF.REQUEST_SUFFIX}`,s),vf.trace("Remove node reply from remote node:",r,i)}catch(l){vf.error("removeNode received error from request:",l),o=!0}let c=new hoe(Hu.SYSTEM_SCHEMA_NAME,Hu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await poe.deleteRecord(c),moe({type:"nats_update"}),i?.status===BF.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(vf.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(goe,"removeNode")});var kF=y((ZCe,FF)=>{"use strict";var xF=require("joi"),{string:Roe,array:Aoe}=xF.types(),boe=St(),yoe=Nm();FF.exports=Ooe;function Ooe(e){let t=xF.object({operation:Roe.valid("configure_cluster").required(),connections:Aoe.items(yoe.validation_schema).required()});return boe.validateBySchema(e,t)}a(Ooe,"configureClusterValidator")});var pO=y((tDe,YF)=>{"use strict";var GF=M(),Gm=V(),Noe=ee(),Ioe=te(),woe=km(),Coe=Pf(),Doe=Ro(),Poe=kF(),{handleHDBError:qF,hdb_errors:Loe}=ce(),{HTTP_STATUS_CODES:$F}=Loe,Moe="Configure cluster complete.",Uoe="Failed to configure the cluster. Check the logs for more details.",voe="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";YF.exports=Boe;async function Boe(e){Gm.trace("configure cluster called with:",e);let t=Poe(e);if(t)throw qF(t,t.message,$F.BAD_REQUEST,void 0,void 0,!0);let r=await Doe.getAllNodeRecords(),n=[];if(Ioe.get(GF.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let u=0,_=r.length;u<_;u++){let E=await VF(woe,{operation:GF.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[u].name},r[u].name);n.push(E)}Gm.trace("All results from configure_cluster remove node:",n)}let s=[],i=e.connections.length;for(let u=0;u<i;u++){let _=e.connections[u],E=await VF(Coe,_,_.node_name);s.push(E)}Gm.trace("All results from configure_cluster add node:",s);let o=[],c=[],l=!1,d=n.concat(s);for(let u=0,_=d.length;u<_;u++){let E=d[u];E.status==="rejected"&&(Gm.error(E.node_name,E?.error?.message,E?.error?.stack),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(l=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,response:E?.result})}if(Noe.isEmptyOrZeroLength(o))return{message:Moe,connections:c};if(l)return{message:voe,failed_nodes:o,connections:c};throw qF(new Error,Uoe,$F.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(Boe,"configureCluster");async function VF(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(VF,"functionWrapper")});var QF=y((nDe,jF)=>{"use strict";var Bf=require("joi"),Hoe=St(),{validateSchemaExists:KF,validateTableExists:xoe,validateSchemaName:WF}=Ri(),Foe=Bf.object({operation:Bf.string().valid("purge_stream"),schema:Bf.string().custom(KF).custom(WF).optional(),database:Bf.string().custom(KF).custom(WF).optional(),table:Bf.string().custom(xoe).required()});function koe(e){return Hoe.validateBySchema(e,Foe)}a(koe,"purgeStreamValidator");jF.exports=koe});var mO=y((iDe,zF)=>{"use strict";var{handleHDBError:Goe,hdb_errors:qoe}=ce(),{HTTP_STATUS_CODES:$oe}=qoe,Voe=QF(),Yoe=nr(),Koe=Ro();zF.exports=Woe;async function Woe(e){e.schema=e.schema??e.database;let t=Voe(e);if(t)throw Goe(t,t.message,$oe.BAD_REQUEST,void 0,void 0,!0);Koe.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await Yoe.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(Woe,"purgeStream")});var $m=y((aDe,nk)=>{"use strict";var TO=Ro(),joe=nr(),qm=te(),xu=M(),jc=At(),Qoe=ee(),SO=V(),{RemotePayloadObject:zoe}=Nf(),{ErrorCode:JF}=require("nats"),{parentPort:XF}=require("worker_threads"),{onMessageByType:Joe}=ut(),{getThisNodeName:Xoe}=(hs(),ne(ma)),{requestClusterStatus:Zoe}=(_f(),ne(JB)),ZF=qm.get(xu.CONFIG_PARAMS.CLUSTERING_ENABLED),ek=qm.get(xu.CONFIG_PARAMS.CLUSTERING_NODENAME);nk.exports={clusterStatus:eae,buildNodeStatus:rk};var tk;Joe("cluster-status",async e=>{tk(e)});async function eae(){if(qm.get(xu.CONFIG_PARAMS.REPLICATION_URL)||qm.get(xu.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;return XF?(XF.postMessage({type:"request-cluster-status"}),n=await new Promise(s=>{tk=s})):n=Zoe(),n.node_name=Xoe(),n.is_enabled=!0,n}let e={node_name:ek,is_enabled:ZF,connections:[]};if(!ZF)return e;let t=await TO.getAllNodeRecords();if(Qoe.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(rk(t[n],e.connections));return await Promise.allSettled(r),e}a(eae,"clusterStatus");async function rk(e,t){let r=e.name,n=new zoe(xu.OPERATIONS_ENUM.CLUSTER_STATUS,ek,void 0,await TO.getSystemInfo()),s,i,o=jc.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await joe.request(jc.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===jc.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=jc.CLUSTER_STATUS_STATUSES.CLOSED,SO.error(`Error getting node status from ${r} `,s))}catch(l){SO.warn(`Error getting node status from ${r}`,l),l.code===JF.NoResponders?o=jc.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===JF.Timeout?o=jc.CLUSTER_STATUS_STATUSES.TIMEOUT:o=jc.CLUSTER_STATUS_STATUSES.CLOSED}let c=new tae(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let l={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==xu.PRE_4_0_0_VERSION&&await TO.upsertNodeRecord(l)}catch(l){SO.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(rk,"buildNodeStatus");function tae(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(tae,"NodeStatusObject")});var Ym=y((lDe,sk)=>{"use strict";var{handleHDBError:rae,hdb_errors:nae}=ce(),{HTTP_STATUS_CODES:sae}=nae,iae=nr(),oae=Ro(),gO=ee(),Vm=require("joi"),aae=St(),cae=2e3,lae=Vm.object({timeout:Vm.number().min(1),connected_nodes:Vm.boolean(),routes:Vm.boolean()});sk.exports=uae;async function uae(e){oae.checkClusteringEnabled();let t=aae.validateBySchema(e,lae);if(t)throw rae(t,t.message,sae.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||gO.autoCastBoolean(n),o=s===void 0||gO.autoCastBoolean(s),c={nodes:[]},l=await iae.getServerList(r??cae),d={};if(i)for(let u=0,_=l.length;u<_;u++){let E=l[u].statsz;E&&(d[l[u].server.name]=E.routes)}for(let u=0,_=l.length;u<_;u++){if(l[u].statsz)continue;let E=l[u].server,f=l[u].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:l[u].response_time};i&&(h.connected_nodes=[],d[E.name]&&d[E.name].forEach(S=>{h.connected_nodes.includes(S.name.slice(0,-4))||h.connected_nodes.push(S.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(S=>({host:S.split(":")[0],port:gO.autoCast(S.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(uae,"clusterNetwork")});var ck=y((dDe,ak)=>{"use strict";var RO=require("joi"),ik=St(),{route_constraints:ok}=_A();ak.exports={setRoutesValidator:dae,deleteRoutesValidator:_ae};function dae(e){let t=RO.object({server:RO.valid("hub","leaf"),routes:ok.required()});return ik.validateBySchema(e,t)}a(dae,"setRoutesValidator");function _ae(e){let t=RO.object({routes:ok.required()});return ik.validateBySchema(e,t)}a(_ae,"deleteRoutesValidator")});var Km=y((fDe,hk)=>{"use strict";var Ao=yt(),AO=ee(),bs=M(),Fu=te(),lk=ck(),{handleHDBError:uk,hdb_errors:fae}=ce(),{HTTP_STATUS_CODES:dk}=fae,_k="cluster routes successfully set",fk="cluster routes successfully deleted";hk.exports={setRoutes:hae,getRoutes:pae,deleteRoutes:mae};function Eae(e){let t=Ao.getClusteringRoutes(),r=e.server==="hub"?t.hub_routes:t.leaf_routes,n=e.server==="hub"?t.leaf_routes:t.hub_routes,s=[],i=[];for(let o=0,c=e.routes.length;o<c;o++){let l=e.routes[o];l.port=AO.autoCast(l.port);let d=r.some(_=>_.host===l.host&&_.port===l.port),u=n.some(_=>_.host===l.host&&_.port===l.port);d||u?s.push(l):(r.push(l),i.push(l))}return e.server==="hub"?Ao.updateConfigValue(bs.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):Ao.updateConfigValue(bs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:_k,set:i,skipped:s}}a(Eae,"setRoutesNats");function hae(e){let t=lk.setRoutesValidator(e);if(t)throw uk(t,t.message,dk.BAD_REQUEST,void 0,void 0,!0);if(Fu.get(bs.CONFIG_PARAMS.CLUSTERING_ENABLED))return Eae(e);let r=[],n=[],s=Fu.get(bs.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{Ek(s,i)?n.push(i):(s.push(i),r.push(i))}),Ao.updateConfigValue(bs.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:_k,set:r,skipped:n}}a(hae,"setRoutes");function Ek(e,t){return typeof t=="string"?e.includes(t):typeof t=="object"&&t!==null?e.some(r=>(r.host===t.host||r.hostname===t.hostname)&&r.port===t.port):!1}a(Ek,"existsInArray");function pae(){if(Fu.get(bs.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=Ao.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return Fu.get(bs.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(pae,"getRoutes");function mae(e){let t=lk.deleteRoutesValidator(e);if(t)throw uk(t,t.message,dk.BAD_REQUEST,void 0,void 0,!0);if(Fu.get(bs.CONFIG_PARAMS.CLUSTERING_ENABLED))return Sae(e);let r=[],n=[],s=Fu.get(bs.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{Ek(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),Ao.updateConfigValue(bs.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:fk,deleted:r,skipped:n}}a(mae,"deleteRoutes");function Sae(e){let t=Ao.getClusteringRoutes(),r=t.hub_routes,n=t.leaf_routes,s=[],i=[],o=!1,c=!1;for(let l=0,d=e.routes.length;l<d;l++){let u=e.routes[l],_=!1;for(let E=0,f=r.length;E<f;E++){let h=r[E];if(u.host===h.host&&u.port===h.port){r.splice(E,1),_=!0,o=!0,s.push(u);break}}if(!_){let E=!0;for(let f=0,h=n.length;f<h;f++){let S=n[f];if(u.host===S.host&&u.port===S.port){n.splice(f,1),c=!0,E=!1,s.push(u);break}}E&&i.push(u)}}return o&&(r=AO.isEmptyOrZeroLength(r)?null:r,Ao.updateConfigValue(bs.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=AO.isEmptyOrZeroLength(n)?null:n,Ao.updateConfigValue(bs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:fk,deleted:s,skipped:i}}a(Sae,"deleteRoutesNats")});var mk=y((hDe,pk)=>{"use strict";var Hf=require("alasql"),Qc=require("recursive-iterator"),ri=V(),Tae=ee(),xf=M(),bO=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,Rae(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=>xf.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=>!xf.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][xf.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=gae(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(d=>({attribute_name:d.attribute}));let l=this.affected_attributes.get(i).get(o).filter(d=>!xf.SEARCH_WILDCARDS.includes(d));c.forEach(({attribute_name:d})=>{let u=new Hf.yy.Column({columnid:d});s.tableid&&(u.tableid=s.tableid),this.ast.columns.push(u),l.includes(d)||l.push(d)}),this.affected_attributes.get(i).set(o,l)}}),this.ast}};function gae(e){return e.filter(t=>t[xf.PERMS_CRUD_ENUM.READ])}a(gae,"filterReadRestrictedAttrs");function Rae(e,t,r,n,s){Aae(e,t,r,n,s)}a(Rae,"interpretAST");function Ff(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(Ff,"addSchemaTableToMap");function Aae(e,t,r,n,s){if(!e){ri.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Hf.yy.Insert?Nae(e,t,r):e instanceof Hf.yy.Select?bae(e,t,r,n,s):e instanceof Hf.yy.Update?yae(e,t,r):e instanceof Hf.yy.Delete?Oae(e,t,r):ri.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(Aae,"getRecordAttributesAST");function bae(e,t,r,n,s){if(!e){ri.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(Tae.isEmptyOrZeroLength(i)){ri.error("No schema specified");return}e.from.forEach(c=>{Ff(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Ff(c.table,t,r,n,s)});let o=new Qc(e.columns);for(let{node:c}of o)if(c&&c.columnid){let l=c.tableid,d=n.has(l)?n.get(l):i;if(l||(l=e.from[0].tableid),!t.get(d).has(l))if(r.has(l))l=r.get(l);else{ri.info(`table specified as ${l} not found.`);return}t.get(d).get(l).indexOf(c.columnid)<0&&t.get(d).get(l).push(c.columnid)}if(e.where){let c=new Qc(e.where),l=e.from[0].tableid;for(let{node:d}of c)if(d&&d.columnid){let u=d.tableid?d.tableid:l;if(!t.get(i).has(u))if(r.has(u))u=r.get(u);else{ri.info(`table specified as ${u} not found.`);continue}t.get(i).get(u).indexOf(d.columnid)<0&&t.get(i).get(u).push(d.columnid)}}if(e.joins&&e.joins.forEach(c=>{let l=new Qc(c.on);for(let{node:d}of l)if(d&&d.columnid){let u=d.tableid,_=s.get(u);if(!t.get(_).has(u))if(r.has(u))u=r.get(u);else{ri.info(`table specified as ${u} not found.`);continue}t.get(_).get(u).indexOf(d.columnid)<0&&t.get(_).get(u).push(d.columnid)}}),e.order){let c=new Qc(e.order);for(let{node:l}of c)if(l&&l.columnid){let d=l.tableid,u=n.has(d)?n.get(d):i;if(d||(d=e.from[0].tableid),!t.get(u).has(d))if(r.has(d))d=r.get(d);else{ri.info(`table specified as ${d} not found.`);return}t.get(u).get(d).indexOf(l.columnid)<0&&t.get(u).get(d).push(l.columnid)}}}a(bae,"getSelectAttributes");function yae(e,t,r){if(!e){ri.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new Qc(e.columns),s=e.table.databaseid;Ff(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&yO(e.table.tableid,s,i.columnid,t,r)}a(yae,"getUpdateAttributes");function Oae(e,t,r){if(!e){ri.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new Qc(e.where),s=e.table.databaseid;Ff(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&yO(e.table.tableid,s,i.columnid,t,r)}a(Oae,"getDeleteAttributes");function Nae(e,t,r){if(!e){ri.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new Qc(e.columns),s=e.into.databaseid;Ff(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&yO(e.into.tableid,s,i.columnid,t,r)}a(Nae,"getInsertAttributes");function yO(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(yO,"pushAttribute");pk.exports=bO});var jm=y((mDe,Rk)=>{var Wm=Rc(),Sk=require("chalk"),Yn=V(),Tk=require("prompt"),{promisify:Iae}=require("util"),OO=M(),wae=require("fs-extra"),Cae=require("path"),Dae=ee(),Pae=go(),gk=te();gk.initSync();var Lae=require("moment"),Mae=Iae(Tk.get),Uae=Cae.join(gk.getHdbBasePath(),OO.LICENSE_KEY_DIR_NAME,OO.LICENSE_FILE_NAME,OO.LICENSE_FILE_NAME);Rk.exports={getFingerprint:Bae,setLicense:vae,parseLicense:NO,register:Hae,getRegistrationInfo:Fae};async function vae(e){if(e&&e.key&&e.company){try{Yn.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await NO(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Yn.error(r),Yn.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(vae,"setLicense");async function Bae(){let e={};try{e=await Wm.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Yn.error(r),Yn.error(t),new Error(r)}return e}a(Bae,"getFingerprint");async function NO(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Yn.info("Validating license input...");let r=Wm.validateLicense(e,t);if(Yn.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Yn.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Yn.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Yn.info("writing license to disk"),await wae.writeFile(Uae,JSON.stringify({license_key:e,company:t}))}catch(n){throw Yn.error("Failed to write License"),n}return"Registration successful."}a(NO,"parseLicense");async function Hae(){let e=await xae();return NO(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(Hae,"register");async function xae(){let e=await Wm.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:Sk.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:Sk.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{Tk.start()}catch(n){Yn.error(n)}let r;try{r=await Mae(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(xae,"promptForRegistration");async function Fae(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Wm.getLicense()}catch(r){throw Yn.error(`There was an error when searching licenses due to: ${r.message}`),r}if(Dae.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=Pae.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=Lae.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(Fae,"getRegistrationInfo")});var bk=y((TDe,Ak)=>{"use strict";var kae=At(),IO=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,l,d,u,_,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+kae.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:l},this.leafnodes={port:d,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:_,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};Ak.exports=IO});var Nk=y((RDe,Ok)=>{"use strict";var yk=At(),wO=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,l,d,u,_){this.port=t,_===null&&(_=void 0),this.server_name=r+yk.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+yk.SERVER_SUFFIX.LEAF},this.tls={cert_file:d,key_file:u,ca_file:_,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:_,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:_,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};Ok.exports=wO});var wk=y((bDe,Ik)=>{"use strict";var CO=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};Ik.exports=CO});var Dk=y((ODe,Ck)=>{"use strict";var Gae=At(),DO=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+Gae.SERVER_SUFFIX.ADMIN,this.password=r}};Ck.exports=DO});var Xm=y((IDe,Mk)=>{"use strict";var ku=require("path"),Gu=require("fs-extra"),qae=bk(),$ae=Nk(),Vae=wk(),Yae=Dk(),PO=_n(),$u=ee(),Rn=yt(),zm=M(),kf=At(),{CONFIG_PARAMS:zt}=zm,Vu=V(),Gf=te(),Pk=lo(),LO=nr(),Kae=Ss(),qu="clustering",Wae=1e4,Lk=50;Mk.exports={generateNatsConfig:Qae,removeNatsConfig:zae,getHubConfigPath:jae};function jae(){let e=Gf.get(zt.ROOTPATH);return ku.join(e,qu,kf.NATS_CONFIG_FILES.HUB_SERVER)}a(jae,"getHubConfigPath");async function Qae(e=!1,t=void 0){Gf.initSync();let r=Rn.getConfigFromFile(zt.CLUSTERING_TLS_CERT_AUTH),n=Rn.getConfigFromFile(zt.CLUSTERING_TLS_PRIVATEKEY),s=Rn.getConfigFromFile(zt.CLUSTERING_TLS_CERTIFICATE);!await Gu.exists(s)&&!await Gu.exists(!r)&&await Kae.createNatsCerts();let i=Gf.get(zt.ROOTPATH),o=ku.join(i,qu,kf.PID_FILES.HUB),c=ku.join(i,qu,kf.PID_FILES.LEAF),l=Rn.getConfigFromFile(zt.CLUSTERING_LEAFSERVER_STREAMS_PATH),d=ku.join(i,qu,kf.NATS_CONFIG_FILES.HUB_SERVER),u=ku.join(i,qu,kf.NATS_CONFIG_FILES.LEAF_SERVER),_=Rn.getConfigFromFile(zt.CLUSTERING_TLS_INSECURE),E=Rn.getConfigFromFile(zt.CLUSTERING_TLS_VERIFY),f=Rn.getConfigFromFile(zt.CLUSTERING_NODENAME),h=Rn.getConfigFromFile(zt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await LO.checkNATSServerInstalled()||Jm("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let S=await PO.listUsers(),T=Rn.getConfigFromFile(zt.CLUSTERING_USER),g=await PO.getClusterUser();($u.isEmpty(g)||g.active!==!0)&&Jm(`Invalid cluster user '${T}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Qm(zt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Qm(zt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Qm(zt.CLUSTERING_HUBSERVER_NETWORK_PORT),await Qm(zt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let m=[],C=[];for(let[Q,_e]of S.entries())_e.role.role===zm.ROLE_TYPES_ENUM.CLUSTER_USER&&_e.active&&(m.push(new Yae(_e.username,Pk.decrypt(_e.hash))),C.push(new Vae(_e.username,Pk.decrypt(_e.hash))));let O=[],{hub_routes:x}=Rn.getClusteringRoutes();if(!$u.isEmptyOrZeroLength(x))for(let Q of x)O.push(`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@${Q.host}:${Q.port}`);let F=new qae(Rn.getConfigFromFile(zt.CLUSTERING_HUBSERVER_NETWORK_PORT),f,o,s,n,r,_,E,h,Rn.getConfigFromFile(zt.CLUSTERING_HUBSERVER_CLUSTER_NAME),Rn.getConfigFromFile(zt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),O,m,C);r==null&&(delete F.tls.ca_file,delete F.leafnodes.tls.ca_file),t=$u.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===zm.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Gu.writeJson(d,F),Vu.trace(`Hub server config written to ${d}`));let Y=`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,$=`tls://${g.uri_encoded_name}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,Z=new $ae(Rn.getConfigFromFile(zt.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,c,l,[Y],[$],m,C,s,n,r,_);r==null&&delete Z.tls.ca_file,(t===void 0||t===zm.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Gu.writeJson(u,Z),Vu.trace(`Leaf server config written to ${u}`))}a(Qae,"generateNatsConfig");async function Qm(e){let t=Gf.get(e);return $u.isEmpty(t)&&Jm(`port undefined for '${e}'`),await $u.isPortTaken(t)&&Jm(`'${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(Qm,"isPortAvailable");function Jm(e){let t=`Error generating clustering config: ${e}`;Vu.error(t),console.error(t),process.exit(1)}a(Jm,"generateNatsConfigError");async function zae(e){let{port:t,config_file:r}=LO.getServerConfig(e),{username:n,decrypt_hash:s}=await PO.getClusterUser(),i=0,o=2e3;for(;i<Lk;){try{let u=await LO.createConnection(t,n,s,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Vu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=Lk)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 d=o*(i*2);d>3e4&&Vu.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await $u.async_set_timeout(d)}let c="0".repeat(Wae),l=ku.join(Gf.get(zt.ROOTPATH),qu,r);await Gu.writeFile(l,c),await Gu.remove(l),Vu.notify(e,"started.")}a(zae,"removeNatsConfig")});var Fk=y((CDe,xk)=>{"use strict";var Kn=te(),Jae=Rc(),Fe=M(),qf=At(),bo=require("path"),{PACKAGE_ROOT:eS}=M(),Uk=te(),Zm=ee(),Yu="/dev/null",Xae=bo.join(eS,"launchServiceScripts"),vk=bo.join(eS,"utility/scripts"),Zae=bo.join(vk,Fe.HDB_RESTART_SCRIPT),Bk=bo.resolve(eS,"dependencies",`${process.platform}-${process.arch}`,qf.NATS_BINARY_NAME);function Hk(){let t=Jae.licenseSearch().ram_allocation||Fe.RAM_ALLOCATION_ENUM.DEFAULT,r=Fe.MEM_SETTING_KEY+t,n={[Fe.PROCESS_NAME_ENV_PROP]:Fe.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Zm.noBootFile()&&(n[Fe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Zm.getEnvCliRootPath()),{name:Fe.PROCESS_DESCRIPTORS.HDB,script:Fe.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:eS}}a(Hk,"generateMainServerConfig");var ece=9930;function tce(){Kn.initSync(!0);let e=Kn.get(Fe.CONFIG_PARAMS.ROOTPATH),t=bo.join(e,"clustering",qf.NATS_CONFIG_FILES.HUB_SERVER),r=bo.join(Kn.get(Fe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Fe.LOG_NAMES.HDB),n=Uk.get(Fe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=qf.LOG_LEVEL_FLAGS[Kn.get(Fe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Fe.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==ece?"-"+n:""),script:Bk,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Fe.PROCESS_NAME_ENV_PROP]:Fe.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Kn.get(Fe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Yu,i.error_file=Yu),i}a(tce,"generateNatsHubServerConfig");var rce=9940;function nce(){Kn.initSync(!0);let e=Kn.get(Fe.CONFIG_PARAMS.ROOTPATH),t=bo.join(e,"clustering",qf.NATS_CONFIG_FILES.LEAF_SERVER),r=bo.join(Kn.get(Fe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Fe.LOG_NAMES.HDB),n=Uk.get(Fe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=qf.LOG_LEVEL_FLAGS[Kn.get(Fe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Fe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==rce?"-"+n:""),script:Bk,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Fe.PROCESS_NAME_ENV_PROP]:Fe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Kn.get(Fe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Yu,i.error_file=Yu),i}a(nce,"generateNatsLeafServerConfig");function sce(){Kn.initSync();let e=bo.join(Kn.get(Fe.CONFIG_PARAMS.LOGGING_ROOT),Fe.LOG_NAMES.HDB),t={name:Fe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Fe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Fe.PROCESS_NAME_ENV_PROP]:Fe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Xae,autorestart:!1};return Kn.get(Fe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Yu,t.error_file=Yu),t}a(sce,"generateClusteringUpgradeV4ServiceConfig");function ice(){let e={[Fe.PROCESS_NAME_ENV_PROP]:Fe.PROCESS_DESCRIPTORS.RESTART_HDB};return Zm.noBootFile()&&(e[Fe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Zm.getEnvCliRootPath()),{...{name:Fe.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:vk},script:Zae}}a(ice,"generateRestart");function oce(){return{apps:[Hk()]}}a(oce,"generateAllServiceConfigs");xk.exports={generateAllServiceConfigs:oce,generateMainServerConfig:Hk,generateRestart:ice,generateNatsHubServerConfig:tce,generateNatsLeafServerConfig:nce,generateClusteringUpgradeV4ServiceConfig:sce}});var Ku=y((LDe,Xk)=>{"use strict";var st=M(),ace=ee(),Oo=Xm(),tS=nr(),yo=At(),Na=Fk(),rS=te(),zc=V(),cce=Ro(),{startWorker:kk,onMessageFromWorkers:lce}=ut(),uce=To(),PDe=require("util"),dce=require("child_process"),_ce=require("fs"),{execFile:fce}=dce,Qe;Xk.exports={enterPM2Mode:Ece,start:Ia,stop:MO,reload:qk,restart:$k,list:UO,describe:Yk,connect:No,kill:Tce,startAllServices:gce,startService:vO,getUniqueServicesList:Kk,restartAllServices:Rce,isServiceRegistered:Wk,reloadStopStart:jk,restartHdb:Vk,deleteProcess:mce,startClusteringProcesses:zk,startClusteringThreads:Jk,isHdbRestartRunning:Sce,isClusteringRunning:bce,stopClustering:Ace,reloadClustering:yce};var $f=!1;lce(e=>{e.type==="restart"&&rS.initSync(!0)});function Ece(){$f=!0}a(Ece,"enterPM2Mode");function No(){return Qe||(Qe=require("pm2")),new Promise((e,t)=>{Qe.connect((r,n)=>{r&&t(r),e(n)})})}a(No,"connect");var An,hce=10,Gk;function Ia(e,t=!1){if($f)return pce(e);let r=fce(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=An.indexOf(r);o>-1&&An.splice(o,1),!Gk&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<hce&&(_ce.existsSync(Oo.getHubConfigPath())?Ia(e):(await Oo.generateNatsConfig(!0),Ia(e),await new Promise(c=>setTimeout(c,3e3)),await Oo.removeNatsConfig(st.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Oo.removeNatsConfig(st.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=rS.get(st.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,l,d=0,u;for(;l=c.exec(i);){if(l.index&&yo.LOG_LEVEL_HIERARCHY[o]>=yo.LOG_LEVEL_HIERARCHY[u||"info"]){let f=u===yo.LOG_LEVELS.ERR||u===yo.LOG_LEVELS.WRN?zc.OUTPUTS.STDERR:zc.OUTPUTS.STDOUT;zc.logCustomLevel(u||"info",f,n,i.slice(d,l.index).trim())}let[_,E]=l;d=l.index+_.length,u=yo.LOG_LEVELS[E]}if(yo.LOG_LEVEL_HIERARCHY[o]>=yo.LOG_LEVEL_HIERARCHY[u||"info"]){let _=u===yo.LOG_LEVELS.ERR||u===yo.LOG_LEVELS.WRN?zc.OUTPUTS.STDERR:zc.OUTPUTS.STDOUT;zc.logCustomLevel(u||"info",_,n,i.slice(d).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),An=[],!An&&!t){let i=a(()=>{Gk=!0,An&&(An.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)}An.push(r)}a(Ia,"start");function pce(e){return new Promise(async(t,r)=>{try{await No()}catch(n){r(n)}Qe.start(e,(n,s)=>{n&&(Qe.disconnect(),r(n)),Qe.disconnect(),t(s)})})}a(pce,"startWithPM2");function MO(e){if(!$f){for(let t of An||[])t.name===e&&(An.splice(An.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await No()}catch(n){r(n)}Qe.stop(e,async(n,s)=>{n&&(Qe.disconnect(),r(n)),Qe.delete(e,(i,o)=>{i&&(Qe.disconnect(),r(n)),Qe.disconnect(),t(o)})})})}a(MO,"stop");function qk(e){return new Promise(async(t,r)=>{try{await No()}catch(n){r(n)}Qe.reload(e,(n,s)=>{n&&(Qe.disconnect(),r(n)),Qe.disconnect(),t(s)})})}a(qk,"reload");function $k(e){if(!$f)for(let t of An||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await No()}catch(n){r(n)}Qe.restart(e,(n,s)=>{Qe.disconnect(),t(s)})})}a($k,"restart");function mce(e){return new Promise(async(t,r)=>{try{await No()}catch(n){r(n)}Qe.delete(e,(n,s)=>{n&&(Qe.disconnect(),r(n)),Qe.disconnect(),t(s)})})}a(mce,"deleteProcess");async function Vk(){await Ia(Na.generateRestart())}a(Vk,"restartHdb");async function Sce(){let e=await UO();for(let t in e)if(e[t].name===st.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(Sce,"isHdbRestartRunning");function UO(){return new Promise(async(e,t)=>{try{await No()}catch(r){t(r)}Qe.list((r,n)=>{r&&(Qe.disconnect(),t(r)),Qe.disconnect(),e(n)})})}a(UO,"list");function Yk(e){return new Promise(async(t,r)=>{try{await No()}catch(n){r(n)}Qe.describe(e,(n,s)=>{n&&(Qe.disconnect(),r(n)),Qe.disconnect(),t(s)})})}a(Yk,"describe");function Tce(){if(!$f){for(let e of An||[])e.kill();An=[];return}return new Promise(async(e,t)=>{try{await No()}catch(r){t(r)}Qe.killDaemon((r,n)=>{r&&(Qe.disconnect(),t(r)),Qe.disconnect(),e(n)})})}a(Tce,"kill");async function gce(){try{await zk(),await Jk(),await Ia(Na.generateAllServiceConfigs())}catch(e){throw Qe?.disconnect(),e}}a(gce,"startAllServices");async function vO(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case st.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Na.generateMainServerConfig();break;case st.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Na.generateNatsIngestServiceConfig();break;case st.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Na.generateNatsReplyServiceConfig();break;case st.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Na.generateNatsHubServerConfig(),await Ia(r,t),await Oo.removeNatsConfig(e);return;case st.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Na.generateNatsLeafServerConfig(),await Ia(r,t),await Oo.removeNatsConfig(e);return;case st.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Na.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ia(r)}catch(r){throw Qe?.disconnect(),r}}a(vO,"startService");async function Kk(){try{let e=await UO(),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 Qe?.disconnect(),e}}a(Kk,"getUniqueServicesList");async function Rce(e=[]){try{let t=!1,r=await Kk();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===st.PROCESS_DESCRIPTORS.HDB?t=!0:await $k(o))}t&&await jk(st.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Qe?.disconnect(),t}}a(Rce,"restartAllServices");async function Wk(e){if(An?.find(r=>r.name===e))return!0;let t=await uce.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(Wk,"isServiceRegistered");async function jk(e){let t=rS.get(st.CONFIG_PARAMS.THREADS_COUNT)??rS.get(st.CONFIG_PARAMS.THREADS),r=await Yk(e),n=ace.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await MO(e),await vO(e)):e===st.PROCESS_DESCRIPTORS.HDB?await Vk():await qk(e)}a(jk,"reloadStopStart");var Qk;async function zk(e=!1){for(let t in st.CLUSTERING_PROCESSES){let r=st.CLUSTERING_PROCESSES[t];await vO(r,e)}}a(zk,"startClusteringProcesses");async function Jk(){Qk=kk(st.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:st.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await tS.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await tS.updateLocalStreams();let e=await cce.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===st.PRE_4_0_0_VERSION){zc.info("Starting clustering upgrade 4.0.0 process"),kk(st.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(Jk,"startClusteringThreads");async function Ace(){for(let e in st.CLUSTERING_PROCESSES)if(e!==st.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===st.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await Qk.terminate();else{let t=st.CLUSTERING_PROCESSES[e];await MO(t)}}a(Ace,"stopClustering");async function bce(){for(let e in st.CLUSTERING_PROCESSES){let t=st.CLUSTERING_PROCESSES[e];if(await Wk(t)===!1)return!1}return!0}a(bce,"isClusteringRunning");async function yce(){await Oo.generateNatsConfig(!0),await tS.reloadNATSHub(),await tS.reloadNATSLeaf(),await Oo.removeNatsConfig(st.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Oo.removeNatsConfig(st.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(yce,"reloadClustering")});var iS={};tt(iS,{compactOnStart:()=>Oce,copyDb:()=>sG});async function Oce(){Vf.notify("Running compact on start"),console.log("Running compact on start");let e=(0,BO.get)(wa.CONFIG_PARAMS.ROOTPATH),t=new Map,r=ft();try{for(let n in r){if(n==="system")continue;let s;for(let l in r[n]){s=r[n][l].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,nS.join)(e,"backup",n+".mdb"),o=(0,nS.join)(e,wa.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await Zk(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 sG(n,o),console.log("Backing up",n,"to",i),await(0,Jc.move)(s,i,{overwrite:!0})}Wu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,Jc.move)(i,s,{overwrite:!0}),await(0,Jc.remove)((0,nS.join)(e,wa.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Wu()}catch(n){Vf.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,HO.updateConfigValue)(wa.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,Jc.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Wu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await Zk(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let l=`There is a discrepancy between pre and post compact record count for database ${n}.
12
15
  Total record count before compaction: ${i}, total after: ${c}.
13
- Database backup has not been removed and can be found here: ${s}`;A_.error(l),console.error(l)}(0,NA.get)(Oo.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,Ca.remove)(s))}(0,yA.updateConfigValue)(Oo.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function hB(e){let t=await(0,TB.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function gB(e,t){console.log("copyDb start");let r=Mr()[e],n;for(let d in r){n=r[d].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,pB.open)(new mB.default(t)),c=o.openDB(Sh.INTERNAL_DBIS_NAME),l,_=0,u=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:u})){let m=h.is_hash_attribute||h.isPrimaryKey,S,g;if(m&&(S=h.compression,g=Ah(),g?h.compression=g:delete h.compression,S?.dictionary?.toString()===g?.dictionary?.toString()&&(S=null,g=null)),c.put(f,h),!(m||h.indexed))continue;let T=new SB.default(!m,m);T.encoding="binary",T.compression=S;let b=n.openDB(f,T);b.decoder=null,T.compression=g;let N=o.openDB(f,T);N.encoder=null,console.log("copying",f,"from",e,"to",t),await E(b,N,m,u)}let d=n.openDB(Sh.AUDIT_STORE_NAME,Rh);console.log("copying audit log"),E(i,d,!1,u);async function E(f,h,m,S){let g=0,T=0;for(let{key:b,value:N,version:v}of f.getRange({start:null,versions:m,transaction:S}))l=h.put(b,N,v),g++,S.openTimer&&(S.openTimer=0),T+=(b?.length||10)+N.length,_++>5e3&&(await l,console.log("copied",g,"entries",T,"bytes"),_=0);console.log("finish copying, copied",g,"entries",T,"bytes")}a(E,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{u.done(),o.close()}}var pB,mh,Ca,NA,mB,SB,Sh,Oo,TB,yA,A_,gh=be(()=>{Re();pB=require("lmdb"),mh=require("path"),Ca=require("fs-extra"),NA=G(X()),mB=G(uu()),SB=G(lu()),Sh=G(_t()),Oo=G(D());no();TB=G(Ei()),yA=G(Et()),A_=G(k());a(Qre,"compactOnStart");a(hB,"getTotalDBRecordCount");a(gB,"copyDb")});var bo=R((BOe,yB)=>{"use strict";var jre=require("minimist"),{isMainThread:CA,parentPort:IA,threadId:UOe}=require("worker_threads"),ot=D(),{PROCESS_DESCRIPTORS_VALIDATE:O_}=ot,qs=k(),DA=Y(),bh=dh(),Oh=gt(),vOe=Ze(),OB=Et(),Fs=Yc(),RB=gi(),{compactOnStart:zre}=(gh(),ae(Th)),Jre=to(),{restartWorkers:Nh,onMessageByType:Xre}=rt(),{handleHDBError:Zre,hdb_errors:ene}=ie(),{HTTP_STATUS_CODES:tne}=ene,N_=X();N_.initSync();var b_=`Restarting HarperDB. This may take up to ${ot.RESTART_TIMEOUT_MS/1e3} seconds.`,rne="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",AB="Clustering is not enabled so cannot be restarted",nne="Invalid service",Kc,xn;yB.exports={restart:bB,restartService:LA};CA&&Xre(ot.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await LA({service:e.workerType}):bB({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function bB(e){xn=Object.keys(e).length===0,Kc=await Fs.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR);let t=jre(process.argv);if(t.service){await LA(t);return}if(xn&&!Kc){console.error(rne);return}if(xn&&console.log(b_),Kc){Fs.enterPM2Mode(),qs.notify(b_);let r=Jre(Object.keys(ot.CONFIG_PARAM_MAP),!0);return DA.isEmptyOrZeroLength(Object.keys(r))||OB.updateConfigValue(void 0,void 0,r,!0,!0),sne(),b_}return CA?(qs.notify(b_),N_.get(ot.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await zre(),setTimeout(()=>{Nh()},50)):IA.postMessage({type:ot.ITC_EVENT_TYPES.RESTART}),b_}a(bB,"restart");async function LA(e){let{service:t}=e;if(ot.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw Zre(new Error,nne,tne.BAD_REQUEST,void 0,void 0,!0);if(Kc=await Fs.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR),!CA)return IA.postMessage({type:ot.ITC_EVENT_TYPES.RESTART,workerType:t}),new Promise(n=>{IA.on("message",s=>{s.type==="restart-complete"&&n()})});let r;switch(t){case O_.clustering:if(!N_.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=AB;break}xn&&console.log("Restarting clustering"),qs.notify("Restarting clustering"),await NB();break;case O_.clustering_config:case O_["clustering config"]:if(!N_.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=AB;break}xn&&console.log("Restarting clustering_config"),qs.notify("Restarting clustering_config"),await Fs.reloadClustering();break;case"custom_functions":case"custom functions":case O_.harperdb:case O_.http_workers:if(xn&&!Kc){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}xn&&console.log("Restarting http_workers"),qs.notify("Restarting http_workers"),xn?await Fs.restart(ot.HDB_PROC_DESCRIPTOR):await Nh("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(qs.error(r),xn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(LA,"restartService");async function sne(){await NB(),await Fs.restart(ot.HDB_PROC_DESCRIPTOR),await DA.async_set_timeout(2e3),N_.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await wA(),xn&&(await Oh.closeConnection(),process.exit(0))}a(sne,"restartPM2Mode");async function NB(){if(!OB.getConfigFromFile(ot.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await RB.getHDBProcessInfo()).clustering.length===0)qs.trace("Clustering not running, restart will start clustering services"),await bh.generateNatsConfig(!0),await Fs.startClusteringProcesses(),await Fs.startClusteringThreads(),await wA(),xn&&await Oh.closeConnection();else{await bh.generateNatsConfig(!0),Kc?(qs.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await Fs.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Fs.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await RB.getHDBProcessInfo()).clustering.forEach(s=>{qs.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await DA.async_set_timeout(3e3),await wA(),await Oh.updateLocalStreams(),xn&&await Oh.closeConnection(),qs.trace("Restart clustering restarting ingest and reply service threads");let t=Nh(ot.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Nh(ot.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(NB,"restartClustering");async function wA(){await bh.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await bh.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(wA,"removeNatsConfig")});var HB=R((xOe,BB)=>{"use strict";var GOe=require("lodash"),$r=D(),{handleHDBError:IB,hdb_errors:ine}=ie(),{HDB_ERROR_MSGS:one,HTTP_STATUS_CODES:ane}=ine,PA=k();BB.exports={getRolePermissions:lne};var Da=Object.create(null),cne=a(e=>({key:e,perms:{}}),"perms_template_obj"),LB=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),PB=a((e=!1,t=!1,r=!1,n=!1)=>({[$r.PERMS_CRUD_ENUM.READ]:e,[$r.PERMS_CRUD_ENUM.INSERT]:t,[$r.PERMS_CRUD_ENUM.UPDATE]:r,[$r.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),MA=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...PB(t,r,n,s)}),"table_perms_template"),wB=a((e,t=PB())=>({attribute_name:e,describe:vB(t),[y_]:t[y_],[UA]:t[UA],[vA]:t[vA]}),"attr_perms_template"),CB=a((e,t=!1)=>({attribute_name:e,describe:t,[y_]:t}),"timestamp_attr_perms_template"),{READ:y_,INSERT:UA,UPDATE:vA}=$r.PERMS_CRUD_ENUM,MB=Object.values($r.PERMS_CRUD_ENUM),UB=[y_,UA,vA];function lne(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[$r.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(Da[t]&&Da[t].key===n)return Da[t].perms;let s=une(e,r);return Da[t]?Da[t].key=n:Da[t]=cne(n),Da[t].perms=s,s}catch(r){if(!e[$r.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[$r.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<$r.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 PA.error(n),PA.debug(r),IB(new Error,one.OUTDATED_PERMS_TRANSLATION_ERROR,ane.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
14
- ${r.stack}`;throw PA.error(n),IB(new Error)}}}a(lne,"getRolePermissions");function une(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[$r.SYSTEM_SCHEMA_NAME]=n[$r.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]=_ne(t[i]);return}r[i]=LB(),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],l=t[i][o],_=dne(c,l);r[i].describe||MB.forEach(u=>{_[u]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=MA()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=MA()})}),r}a(une,"translateRolePermissions");function _ne(e){let t=LB(!0);return Object.keys(e).forEach(r=>{t.tables[r]=MA(!0,!0,!0,!0,!0)}),t}a(_ne,"createStructureUserPermissions");function dne(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,u)=>{let{attribute_name:d}=u,E=u;return $r.TIME_STAMP_NAMES.includes(d)&&(E=CB(d,u[y_])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],l=wB(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let u=i[_];u.describe=vB(u),s.attribute_permissions.push(u),c||fne(u,l)}else if(_!==o){let u;$r.TIME_STAMP_NAMES.includes(_)?u=CB(_):u=wB(_),s.attribute_permissions.push(u)}}),c||s.attribute_permissions.push(l),s.describe=DB(s),s}else return e.describe=DB(e),e}a(dne,"getTableAttrPerms");function DB(e){return MB.filter(t=>e[t]).length>0}a(DB,"getSchemaTableDescribePerm");function vB(e){return UB.filter(t=>e[t]).length>0}a(vB,"getAttributeDescribePerm");function fne(e,t){UB.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(fne,"checkForHashPerms")});var GB={};Ve(GB,{Resources:()=>yh,keyArrayToString:()=>Wc,resetResources:()=>Ene,resources:()=>No});function Ene(){return No=new yh}function Wc(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var yh,No,I_=be(()=>{ha();yh=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,l]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let u=this.get(c.slice(0,_));u&&(u.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),l=this.get(c);if(!l&&c.indexOf(".")>-1){let _=c.split(".");l=this.get(_[0])}if(l){if(l.relativeURL=t.slice(n),!l.hasSubPaths)return l;s=l}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),!s&&o.indexOf(".")>-1&&(s=this.get(o.split(".")[0])),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 it(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(Ene,"resetResources");a(Wc,"keyArrayToString")});var xB={};Ve(xB,{Headers:()=>yo,appendHeader:()=>BA});function BA(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 yo,w_=be(()=>{yo=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(BA,"appendHeader")});var C_={};Ve(C_,{authentication:()=>WB,bypassAuth:()=>Rne,login:()=>One,logout:()=>bne,start:()=>Ane});function Rne(){KB=!0}async function WB(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?Sne?mne:[]:pne?hne:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new yo([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Ih&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Ih&&o.push("Access-Control-Allow-Credentials","true")}}let l,_;if(Ih){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let m of h)if(m.startsWith(f)){let S=m.indexOf(";");l=m.slice(f.length,S===-1?m.length:S),_=await FB.get(l);break}e.session=_||(_={})}let u=a((f,h,m)=>{let S=new Qc.AuthAuditLog(f,h,Qt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=m,l&&(S.session_id=l),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Qt.AUTH_AUDIT_STATUS.SUCCESS?qB.notify(S):qB.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await dt.getUser(f,null,null),u(f,Qt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,Qc.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=La.get(n),!d){let f=n.indexOf(" "),h=n.slice(0,f),m=n.slice(f+1),S,g;try{switch(h){case"Basic":let T=atob(m),b=T.indexOf(":");S=T.slice(0,b),g=T.slice(b+1),d=S||g?await dt.getUser(S,g,e):null;break;case"Bearer":try{d=await(0,wh.validateOperationToken)(m)}catch(N){if(N.message==="invalid token")try{return await(0,wh.validateRefreshToken)(m),c({status:-1})}catch{throw N}}break}}catch(T){return gne&&(La.get(m)||(La.set(m,m),u(S,Qt.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:Pa({error:T.message},e)})}La.set(n,d),Tne&&u(d.username,Qt.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await dt.getUser(_.user,null,e):(KB&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,VB.getSuperUser)());Ih&&(e.session.update=function(f){if(!l){l=(0,$B.v4)();let m=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${l}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",m):E?.headers?.set&&E.headers.set("Set-Cookie",m)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=l,FB.put(f)},e.login=async function(f,h){e.user=await dt.getUser(f,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 E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&No.loginPath?(E.status=302,E.headers.set("Location",No.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(l){throw c(l)}function c(l){let _=o.length;if(_>0){let u=l.headers;u||(l.headers=u=new yo);for(let d=0;d<_;){let E=o[d++];u.set(E,o[d++])}}return o=null,l}a(c,"applyResponseHeaders")}function Ane({server:e,port:t}){e.http(WB,{port:t||"all"}),kB||(kB=!0,setInterval(()=>{La=new Map},qn.get(Qt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),YB.user.addListener(()=>{La=new Map}))}async function One(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 bne(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var VB,wh,$B,qn,Qt,Qc,YB,qB,hne,pne,mne,Sne,FB,Ih,KB,Tne,gne,La,kB,Ch=be(()=>{VB=G(Lr());yr();I_();wh=G(s_());Re();$B=require("uuid"),qn=G(X()),Qt=G(D()),Qc=G(k()),YB=G(bu());w_();jc();qB=(0,Qc.loggerWithTag)("auth-event");qn.initSync();hne=qn.get(Qt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),pne=qn.get(Qt.CONFIG_PARAMS.HTTP_CORS),mne=qn.get(Qt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),Sne=qn.get(Qt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),FB=St({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Ih=qn.get(Qt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,KB=qn.get(Qt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,Tne=qn.get(Qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,gne=qn.get(Qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,La=new Map;dt.onInvalidatedUser(()=>{La=new Map});a(Rne,"bypassAuth");a(WB,"authentication");a(Ane,"start");a(One,"login");a(bne,"logout")});var eH=R((zOe,ZB)=>{"use strict";var Le=require("joi"),QB=require("fs-extra"),jB=require("path"),wi=nt(),zB=X(),JB=D(),XB=k(),{hdb_errors:Nne}=ie(),{HDB_ERROR_MSGS:mr}=Nne,Ii=/^[a-zA-Z0-9-_]+$/;ZB.exports={getDropCustomFunctionValidator:Ine,setCustomFunctionValidator:wne,addComponentValidator:Pne,dropCustomFunctionProjectValidator:Mne,packageComponentValidator:Une,deployComponentValidator:vne,setComponentFileValidator:Cne,getComponentFileValidator:Lne,dropComponentFileValidator:Dne};function Dh(e,t,r){try{let n=zB.get(JB.CONFIG_PARAMS.COMPONENTSROOT),s=jB.join(n,t);return QB.existsSync(s)?e?t:r.message(mr.PROJECT_EXISTS):e?r.message(mr.NO_PROJECT):t}catch(n){return XB.error(n),r.message(mr.VALIDATION_ERR)}}a(Dh,"checkProjectExists");function D_(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(D_,"checkFilePath");function yne(e,t,r,n){try{let s=zB.get(JB.CONFIG_PARAMS.COMPONENTSROOT),i=jB.join(s,e,t,r+".js");return QB.existsSync(i)?r:n.message(mr.NO_FILE)}catch(s){return XB.error(s),n.message(mr.VALIDATION_ERR)}}a(yne,"checkFileExists");function Ine(e){let t=Le.object({project:Le.string().pattern(Ii).custom(Dh.bind(null,!0)).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME}),type:Le.string().valid("helpers","routes").required(),file:Le.string().pattern(Ii).custom(yne.bind(null,e.project,e.type)).custom(D_).required().messages({"string.pattern.base":mr.BAD_FILE_NAME})});return wi.validateBySchema(e,t)}a(Ine,"getDropCustomFunctionValidator");function wne(e){let t=Le.object({project:Le.string().pattern(Ii).custom(Dh.bind(null,!0)).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME}),type:Le.string().valid("helpers","routes").required(),file:Le.string().custom(D_).required(),function_content:Le.string().required()});return wi.validateBySchema(e,t)}a(wne,"setCustomFunctionValidator");function Cne(e){let t=Le.object({project:Le.string().pattern(Ii).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME}),file:Le.string().custom(D_).required(),payload:Le.string().allow("").optional(),encoding:Le.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return wi.validateBySchema(e,t)}a(Cne,"setComponentFileValidator");function Dne(e){let t=Le.object({project:Le.string().pattern(Ii).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME}),file:Le.string().custom(D_).optional()});return wi.validateBySchema(e,t)}a(Dne,"dropComponentFileValidator");function Lne(e){let t=Le.object({project:Le.string().required(),file:Le.string().custom(D_).required(),encoding:Le.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return wi.validateBySchema(e,t)}a(Lne,"getComponentFileValidator");function Pne(e){let t=Le.object({project:Le.string().pattern(Ii).custom(Dh.bind(null,!1)).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME})});return wi.validateBySchema(e,t)}a(Pne,"addComponentValidator");function Mne(e){let t=Le.object({project:Le.string().pattern(Ii).custom(Dh.bind(null,!0)).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME})});return wi.validateBySchema(e,t)}a(Mne,"dropCustomFunctionProjectValidator");function Une(e){let t=Le.object({project:Le.string().pattern(Ii).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME}),skip_node_modules:Le.boolean()});return wi.validateBySchema(e,t)}a(Une,"packageComponentValidator");function vne(e){let t=Le.object({project:Le.string().pattern(Ii).required().messages({"string.pattern.base":mr.BAD_PROJECT_NAME}),payload:Le.string().optional().messages({"string.pattern.base":mr.BAD_PACKAGE}),package:Le.string().optional()});return wi.validateBySchema(e,t)}a(vne,"deployComponentValidator")});var Uh=R((XOe,aH)=>{"use strict";var Lh=require("joi"),Ph=require("path"),tH=require("fs-extra"),{exec:Bne}=require("child_process"),Hne=require("util"),rH=Hne.promisify(Bne),L_=D(),{handleHDBError:zc,hdb_errors:Gne}=ie(),{HTTP_STATUS_CODES:Jc}=Gne,P_=X(),xne=nt(),Xc=k();P_.initSync();var HA=P_.get(L_.CONFIG_PARAMS.COMPONENTSROOT),nH="npm install --omit=dev --json",qne=`${nH} --dry-run`;aH.exports={installModules:$ne,auditModules:Yne,installAllRootModules:Fne,uninstallRootModule:kne,linkHarperdb:Vne};async function Fne(e=!1){await Mh(),await M_(e?"npm install --ignore-scripts":"npm install",P_.get(L_.CONFIG_PARAMS.ROOTPATH))}a(Fne,"installAllRootModules");async function kne(e){await M_(`npm uninstall ${e}`,P_.get(L_.CONFIG_PARAMS.ROOTPATH))}a(kne,"uninstallRootModule");async function Vne(){await Mh(),await M_(`npm link ${L_.PACKAGE_ROOT}`,P_.get(L_.CONFIG_PARAMS.ROOTPATH))}a(Vne,"linkHarperdb");async function M_(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await rH(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
15
- `,""))}return n&&!n.includes("Debugger listening")&&Xc.error("Error running NPM command:",e,n),Xc.trace(r,n),r?.replace(`
16
- `,"")}a(M_,"runCommand");async function $ne(e){Xc.info(`starting installModules for request: ${e}`);let t=oH(e);if(t)throw zc(t,t.message,Jc.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?qne:nH;await Mh(),await iH(r);let i={};for(let o=0,c=r.length;o<c;o++){let l=r[o];i[l]={npm_output:null,npm_error:null};let _=Ph.join(HA,l),u,d=null;try{let{stdout:E,stderr:f}=await rH(s,{cwd:_});u=E?E.replace(`
17
- `,""):null,d=f?f.replace(`
18
- `,""):null}catch(E){E.stderr?i[l].npm_error=sH(E.stderr):i[l].npm_error=E.message;continue}try{i[l].npm_output=JSON.parse(u)}catch{i[l].npm_output=u}try{i[l].npm_error=JSON.parse(d)}catch{i[l].npm_error=d}}return Xc.info(`finished installModules with response ${i}`),i}a($ne,"installModules");function sH(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
19
- `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(sH,"parseNPMStdErr");async function Yne(e){Xc.info(`starting auditModules for request: ${e}`);let t=oH(e);if(t)throw zc(t,t.message,Jc.BAD_REQUEST);let{projects:r}=e;await Mh(),await iH(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Ph.join(HA,o);n[o]={npm_output:null,npm_error:null};try{let l=await M_("npm audit --json",c);n[o].npm_output=JSON.parse(l)}catch(l){n[o].npm_error=sH(l.stderr)}}return Xc.info(`finished auditModules with response ${n}`),n}a(Yne,"auditModules");async function Mh(){try{return await M_("npm -v"),!0}catch{throw zc(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Jc.BAD_REQUEST,void 0,void 0,!0)}}a(Mh,"checkNPMInstalled");async function iH(e){if(!Array.isArray(e)||e.length===0)throw zc(new Error,"projects argument must be an array with at least 1 element",Jc.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=Ph.join(HA,i.toString());if(!await tH.pathExists(o)){t.push(i);continue}let l=Ph.join(o,"package.json");await tH.pathExists(l)||r.push(i)}if(t.length>0)throw zc(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Jc.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw zc(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Jc.BAD_REQUEST,void 0,void 0,!0)}a(iH,"checkProjectPaths");function oH(e){let t=Lh.object({projects:Lh.array().min(1).items(Lh.string()).required(),dry_run:Lh.boolean().default(!1)});return xne.validateBySchema(e,t)}a(oH,"modulesValidator")});var xA=R((ebe,dH)=>{"use strict";var Zc=require("fs-extra"),GA=require("path"),vh=k(),cH=Y(),Bh=D(),_H=X(),Kne=Et();dH.exports=Wne;async function Wne(){let e=Qne(),t=_H.get(Bh.CONFIG_PARAMS.ROOTPATH),r=GA.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Bh.PACKAGE_ROOT}},s=GA.join(t,"node_modules");await Zc.ensureDir(s);let i,o=!0,c=!1;try{i=await Zc.readJson(r)}catch(l){if(cH.isEmptyOrZeroLength(e))return;if(l.code!==Bh.NODE_ERROR_CODES.ENOENT)throw l;o=!1}if(!cH.isEmptyOrZeroLength(e)){for(let{name:l,package:_}of e){let u=await lH(_);n.dependencies[l]=u+_}if(!o){vh.notify("Installing components"),await uH(r,n,null);return}for(let{name:l,package:_}of e){let u=i.dependencies[l],d=await lH(_);if(u===void 0||u!==d+_){c=!0;break}}}for(let l in i.dependencies)n.dependencies[l]===void 0&&(vh.notify("Removing component",l),c=!0);c&&(vh.notify("Updating components."),await uH(r,n,i))}a(Wne,"installComponents");function Qne(){let e=Kne.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(Qne,"getComponentsConfig");async function lH(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":GA.extname(e)||await Zc.pathExists(e)?"file:":"github:"}a(lH,"getPkgPrefix");async function uH(e,t,r){vh.trace("npm installing components package.json",t),await Zc.writeFile(e,JSON.stringify(t,null," "));try{await Uh().installAllRootModules(_H.get(Bh.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Zc.writeFile(e,JSON.stringify(r,null," ")):await Zc.unlink(e),n}}a(uH,"installPackages")});var kA=R((nbe,pH)=>{"use strict";var Ke=require("fs-extra"),qA=require("fast-glob"),Oe=require("path"),EH=require("tar-fs"),rbe=require("uuid").v4,FA=require("normalize-path"),ks=eH(),Gt=k(),Je=D(),Ct=X(),U_=Et(),jne=Y(),{PACKAGE_ROOT:zne}=D(),{handleHDBError:jt,hdb_errors:Jne}=ie(),{basename:Xne}=require("path"),Zne=xA(),hH=X(),ese=D(),{Readable:tse}=require("stream"),{isMainThread:rse}=require("worker_threads"),{HDB_ERROR_MSGS:Ma,HTTP_STATUS_CODES:zt}=Jne,nse=Oe.join(zne,"application-template"),fH=Oe.join(Ct.get(Je.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function sse(){Gt.trace("getting custom api status");let e={};try{e={port:Ct.get(Je.CONFIG_PARAMS.HTTP_PORT),directory:Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw jt(new Error,Ma.FUNCTION_STATUS,zt.INTERNAL_SERVER_ERROR,Gt.ERR,t)}return e}a(sse,"customFunctionsStatus");function ise(){Gt.trace("getting custom api endpoints");let e={},t=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT);try{qA.sync(FA(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:qA.sync(FA(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:qA.sync(FA(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw jt(new Error,Ma.GET_FUNCTIONS,zt.INTERNAL_SERVER_ERROR,Gt.ERR,r)}return e}a(ise,"getCustomFunctions");function ose(e){e.project&&(e.project=Oe.parse(e.project).name),e.file&&(e.file=Oe.parse(e.file).name);let t=ks.getDropCustomFunctionValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);Gt.trace("getting custom api endpoint file content");let r=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Oe.join(r,n,s,i+".js");try{return Ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw jt(new Error,Ma.GET_FUNCTION,zt.INTERNAL_SERVER_ERROR,Gt.ERR,c)}}a(ose,"getCustomFunction");function ase(e){e.project&&(e.project=Oe.parse(e.project).name),e.file&&(e.file=Oe.parse(e.file).name);let t=ks.setCustomFunctionValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);Gt.trace("setting custom function file content");let r=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ke.outputFileSync(Oe.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw jt(new Error,Ma.SET_FUNCTION,zt.INTERNAL_SERVER_ERROR,Gt.ERR,c)}}a(ase,"setCustomFunction");function cse(e){e.project&&(e.project=Oe.parse(e.project).name),e.file&&(e.file=Oe.parse(e.file).name);let t=ks.getDropCustomFunctionValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);Gt.trace("dropping custom function file");let r=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ke.unlinkSync(Oe.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw jt(new Error,Ma.DROP_FUNCTION,zt.INTERNAL_SERVER_ERROR,Gt.ERR,o)}}a(cse,"dropCustomFunction");function lse(e){e.project&&(e.project=Oe.parse(e.project).name);let t=ks.addComponentValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);Gt.trace("adding component");let r=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Oe.join(r,n);return Ke.mkdirSync(s,{recursive:!0}),Ke.copySync(nse,s),`Successfully added project: ${n}`}catch(s){throw jt(new Error,Ma.ADD_FUNCTION,zt.INTERNAL_SERVER_ERROR,Gt.ERR,s)}}a(lse,"addComponent");function use(e){e.project&&(e.project=Oe.parse(e.project).name);let t=ks.dropCustomFunctionProjectValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);Gt.trace("dropping custom function project");let r=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Ct.get(Je.CONFIG_PARAMS.APPS);if(!jne.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 U_.updateConfigValue(Je.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Oe.join(r,n);return Ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw jt(new Error,Ma.DROP_FUNCTION_PROJECT,zt.INTERNAL_SERVER_ERROR,Gt.ERR,i)}}a(use,"dropCustomFunctionProject");async function _se(e){e.project&&(e.project=Oe.parse(e.project).name);let t=ks.packageComponentValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);let r=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Gt.trace("packaging component",n);let s;try{s=await Ke.realpath(Oe.join(r,n))}catch(l){if(l.code!==Je.NODE_ERROR_CODES.ENOENT)throw l;try{s=await Ke.realpath(Oe.join(Ct.get(Je.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Je.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ke.ensureDir(fH);let i=Oe.join(fH,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:l=>l.includes(Oe.join(s,"node_modules"))}),EH.pack(s,o).pipe(Ke.createWriteStream(i,{overwrite:!0})),await new Promise(l=>setTimeout(l,2e3));let c=Ke.readFileSync(i,{encoding:"base64"});return await Ke.remove(i),{project:n,payload:c}}a(_se,"packageComponent");async function dse(e){e.project&&(e.project=Oe.parse(e.project).name);let t=ks.deployComponentValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);let r=Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Gt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Oe.join(r,n),i="file:"+o,await Ke.emptyDir(o);let E=tse.from(Buffer.from(s,"base64"));await new Promise((h,m)=>{E.pipe(EH.extract(o,{finish:h})).on("error",m)});let f=await Ke.readdir(o);f.length===1&&f[0]==="package"&&(await Ke.copy(Oe.join(o,"package"),o),await Ke.remove(Oe.join(o,"package")))}if(await U_.addConfig(n,{package:i}),!s){await Zne();let E=hH.get(ese.CONFIG_PARAMS.ROOTPATH);o=Oe.join(E,"node_modules",n)}if(rse)return;let c=new Map;c.isWorker=!0;let l=(Gh(),ae(Hh)),_;l.setErrorReporter(E=>_=E);let u=Xne(o),d=l.component_errors.get(u);try{await l.loadComponent(o,c)}finally{l.component_errors.set(u,d)}if(_)throw _;return Gt.info("Installed component"),`Successfully deployed: ${n}`}a(dse,"deployComponent");async function fse(){let e=U_.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 l=await Ke.readdir(o,{withFileTypes:!0});for(let _ of l){let u=_.name;if(u.startsWith(".")||u==="node_modules")continue;let d=Oe.join(o,u);if(_.isDirectory()||_.isSymbolicLink()){let E={name:u,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await Ke.stat(d),f={name:Oe.basename(u),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(l){return Gt.warn("Error loading package",l),{error:l.toString(),entries:[]}}},"walk_dir"),n=await r(Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{name:Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT).split(Oe.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Oe.join(Ct.get(Je.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(Gh(),ae(Hh)).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(fse,"getComponents");async function Ese(e){let t=ks.getComponentFileValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);let n=U_.getConfigObj()[e.project]||e.project==="harperdb"?Oe.join(hH.get(Je.CONFIG_PARAMS.ROOTPATH),"node_modules"):Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ke.stat(Oe.join(n,e.project,e.file));return{message:await Ke.readFile(Oe.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Je.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Oe.join(e.project,e.file)}'`):i}}a(Ese,"getComponentFile");async function hse(e){let t=ks.setComponentFileValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Oe.join(Ct.get(Je.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(hse,"setComponentFile");async function pse(e){let t=ks.dropComponentFileValidator(e);if(t)throw jt(t,t.message,zt.BAD_REQUEST);let r=e.file?Oe.join(e.project,e.file):e.project,n=Oe.join(Ct.get(Je.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ke.pathExists(n)&&await Ke.remove(n),U_.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(pse,"dropComponent");pH.exports={customFunctionsStatus:sse,getCustomFunctions:ise,getCustomFunction:ose,setCustomFunction:ase,dropCustomFunction:cse,addComponent:lse,dropCustomFunctionProject:use,packageComponent:_se,deployComponent:dse,getComponents:fse,getComponentFile:Ese,setComponentFile:hse,dropComponent:pse}});var VA=R((ibe,SH)=>{"use strict";var Vs=require("joi"),mH=nt();SH.exports={readTransactionLogValidator:mse,deleteTransactionLogsBeforeValidator:Sse};function mse(e){let t=Vs.object({schema:Vs.string().required(),table:Vs.string().required(),from:Vs.date().timestamp(),to:Vs.date().timestamp(),limit:Vs.number().min(1)});return mH.validateBySchema(e,t)}a(mse,"readTransactionLogValidator");function Sse(e){let t=Vs.object({schema:Vs.string().required(),table:Vs.string().required(),timestamp:Vs.date().timestamp().required()});return mH.validateBySchema(e,t)}a(Sse,"deleteTransactionLogsBeforeValidator")});var xh=R((abe,OH)=>{"use strict";var $A=D(),v_=gt(),TH=Y(),gH=X(),RH=fi(),{handleHDBError:el,hdb_errors:Tse}=ie(),{HTTP_STATUS_CODES:tl}=Tse,{readTransactionLogValidator:gse,deleteTransactionLogsBeforeValidator:Rse}=VA(),AH="This operation relies on clustering and cannot run with it disable.",Ase="Logs successfully deleted from transaction log.",Ose="All logs successfully deleted from transaction log.";OH.exports={readTransactionLog:bse,deleteTransactionLogsBefore:Nse};async function*bse(e){let t=gse(e);if(t)throw el(t,t.message,tl.BAD_REQUEST,void 0,void 0,!0);if(!gH.get($A.CONFIG_PARAMS.CLUSTERING_ENABLED))throw el(new Error,AH,tl.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=TH.checkSchemaTableExist(r,n);if(s)throw el(new Error,s,tl.NOT_FOUND,void 0,void 0,!0);let i=RH.createNatsTableStreamName(r,n),o=await v_.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let l=Math.floor(c?.nats_timestamp/1e6);if(e.to&&l>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:l,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===$A.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(bse,"readTransactionLog");async function Nse(e){let t=Rse(e);if(t)throw el(t,t.message,tl.BAD_REQUEST,void 0,void 0,!0);if(!gH.get($A.CONFIG_PARAMS.CLUSTERING_ENABLED))throw el(new Error,AH,tl.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=TH.checkSchemaTableExist(r,n);if(i)throw el(new Error,i,tl.NOT_FOUND,void 0,void 0,!0);let o=RH.createNatsTableStreamName(r,n),{jsm:c}=await v_.getNATSReferences(),l=await v_.getStreamInfo(o),_=new Date(l.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let u=Ase,d,E=new Date(l.state.last_ts).getTime();return s>E?(d=l.state.last_seq+1,u=Ose):d=(await v_.viewStream(o,parseInt(s),1))[0].nats_sequence,await v_.purgeTableStream(r,n,{seq:d}),u}a(Nse,"deleteTransactionLogsBefore")});var NH=R((lbe,bH)=>{"use strict";var YA=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}};bH.exports=YA});var IH=R((_be,yH)=>{"use strict";var KA=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};yH.exports=KA});var QA=R((fbe,CH)=>{"use strict";var wH=NH(),yse=IH(),{HDB_ERROR_MSGS:Ise}=rn(),WA=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Ise.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 wH(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new yse(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new wH(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}};CH.exports=WA});var Vh=R((hbe,YH)=>{"use strict";var jA=Cr(),qh=ur(),kn=LE(),G_=Ei(),zA=ia(),wse=ER(),Cse=vU(),x_=Lr(),Fh=vE(),xt=k(),Dse=NR(),Lse=c_(),Pse=sA(),Mse=JE(),Use=ZE(),vse=oA(),Bse=th(),Hse=nh(),JA=ih(),Ci=Y(),Gse=M0(),XA=ah(),PH=bo(),Fn=D(),MH=HB(),xse=gi(),UH=s_(),vH=(Ch(),ae(C_)),BH=Et(),pn=kA(),qse=require("alasql"),HH=xh(),GH=Uh(),xH=QA(),{handleHDBError:Yr,hdb_errors:qH}=ie(),{HDB_ERROR_MSGS:nr,HTTP_STATUS_CODES:B_}=qH,$=new Map,FH="delete",Io="insert",Di="read",Ua="update",H_="describe",DH=G_.describeSchema.name,LH=G_.describeTable.name,kH={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},Fse="catchup",kse="handleGetJob",Vse="handleGetJobsByStartDate",kh={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},$se=[kn.createTable.name,kn.createAttribute.name,kn.dropTable.name,kn.dropAttribute.name],VH={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},j=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};$.set(jA.insert.name,new j(!1,[Io]));$.set(jA.update.name,new j(!1,[Ua]));$.set(jA.upsert.name,new j(!1,[Io,Ua]));$.set(qh.searchByConditions.name,new j(!1,[Di]));$.set(qh.searchByHash.name,new j(!1,[Di]));$.set(qh.searchByValue.name,new j(!1,[Di]));$.set(qh.search.name,new j(!1,[Di]));$.set(kn.createSchema.name,new j(!0,[]));$.set(kn.createTable.name,new j(!0,[]));$.set(kn.createAttribute.name,new j(!1,[Io]));$.set(kn.dropSchema.name,new j(!0,[]));$.set(kn.dropTable.name,new j(!0,[]));$.set(kn.dropAttribute.name,new j(!0,[]));$.set(G_.describeSchema.name,new j(!1,[Di]));$.set(G_.describeTable.name,new j(!1,[Di]));$.set(zA.deleteRecord.name,new j(!1,[FH]));$.set(x_.addUser.name,new j(!0,[]));$.set(x_.alterUser.name,new j(!0,[]));$.set(x_.dropUser.name,new j(!0,[]));$.set(x_.listUsersExternal.name,new j(!0,[]));$.set(Fh.listRoles.name,new j(!0,[]));$.set(Fh.addRole.name,new j(!0,[]));$.set(Fh.alterRole.name,new j(!0,[]));$.set(Fh.dropRole.name,new j(!0,[]));$.set(Dse.name,new j(!0,[]));$.set(Lse.name,new j(!0,[]));$.set(Pse.name,new j(!0,[]));$.set(Mse.name,new j(!0,[]));$.set(Use.name,new j(!0,[]));$.set(vse.name,new j(!0,[]));$.set(JA.setRoutes.name,new j(!0,[]));$.set(JA.getRoutes.name,new j(!0,[]));$.set(JA.deleteRoutes.name,new j(!0,[]));$.set(BH.setConfiguration.name,new j(!0,[]));$.set(Bse.clusterStatus.name,new j(!0,[]));$.set(Hse.name,new j(!0,[]));$.set(XA.getFingerprint.name,new j(!0,[]));$.set(XA.setLicense.name,new j(!0,[]));$.set(zA.deleteFilesBefore.name,new j(!0,[]));$.set(zA.deleteAuditLogsBefore.name,new j(!0,[]));$.set(PH.restart.name,new j(!0,[]));$.set(PH.restartService.name,new j(!0,[]));$.set(wse.name,new j(!0,[]));$.set(Cse.name,new j(!0,[Di]));$.set(xse.systemInformation.name,new j(!0,[]));$.set(BH.getConfiguration.name,new j(!0,[]));$.set(HH.readTransactionLog.name,new j(!0,[]));$.set(HH.deleteTransactionLogsBefore.name,new j(!0,[]));$.set(GH.installModules.name,new j(!0,[]));$.set(GH.auditModules.name,new j(!0,[]));$.set(UH.createTokens.name,new j(!1,[]));$.set(UH.refreshOperationToken.name,new j(!1,[]));$.set(vH.login.name,new j(!1,[]));$.set(vH.logout.name,new j(!1,[]));$.set(pn.customFunctionsStatus.name,new j(!0,[]));$.set(pn.getCustomFunctions.name,new j(!0,[]));$.set(pn.getComponents.name,new j(!0,[]));$.set(pn.getComponentFile.name,new j(!0,[]));$.set(pn.setComponentFile.name,new j(!0,[]));$.set(pn.dropComponent.name,new j(!0,[]));$.set(pn.getCustomFunction.name,new j(!0,[]));$.set(pn.setCustomFunction.name,new j(!0,[]));$.set(pn.dropCustomFunction.name,new j(!0,[]));$.set(pn.addComponent.name,new j(!0,[]));$.set(pn.dropCustomFunctionProject.name,new j(!0,[]));$.set(pn.packageComponent.name,new j(!0,[]));$.set(pn.deployComponent.name,new j(!0,[]));$.set(XA.getRegistrationInfo.name,new j(!1,[]));$.set(x_.userInfo.name,new j(!1,[]));$.set(G_.describeAll.name,new j(!1,[]));$.set(kse,new j(!1,[]));$.set(Vse,new j(!0,[]));$.set(Fse,new j(!0,[]));$.set(kh.CSV_DATA_LOAD,new j(!1,[Io,Ua]));$.set(kh.CSV_URL_LOAD,new j(!1,[Io,Ua]));$.set(kh.CSV_FILE_LOAD,new j(!1,[Io,Ua]));$.set(kh.IMPORT_FROM_S3,new j(!1,[Io,Ua]));$.set(VH.EXPORT_TO_S3,new j(!0,[]));$.set(VH.EXPORT_LOCAL,new j(!0,[]));$.set(Fn.VALID_SQL_OPS_ENUM.DELETE,new j(!1,[FH]));$.set(Fn.VALID_SQL_OPS_ENUM.SELECT,new j(!1,[Di]));$.set(Fn.VALID_SQL_OPS_ENUM.INSERT,new j(!1,[Io]));$.set(Fn.VALID_SQL_OPS_ENUM.UPDATE,new j(!1,[Ua]));YH.exports={verifyPerms:Kse,verifyPermsAst:Yse,verifyBulkLoadAttributePerms:Qse};function Yse(e,t,r){if(Ci.isEmptyOrZeroLength(e))throw xt.info("verify_perms_ast has an empty user parameter"),Yr(new Error);if(Ci.isEmptyOrZeroLength(t))throw xt.info("verify_perms_ast has an empty user parameter"),Yr(new Error);if(Ci.isEmptyOrZeroLength(r))throw xt.info("verify_perms_ast has a null operation parameter"),Yr(new Error);try{let n=new xH,s=new Gse(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw xt.info("No schemas defined in verifyPermsAst(), will not continue."),Yr(new Error);let c=!!t.role.permission.super_user,l=i.includes("system");if(l&&kH[r])throw Yr(new Error,nr.DROP_SYSTEM,B_.FORBIDDEN);if(c&&!l)return null;let _=MH.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof qse.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let E=s.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let u=$H(t,r,o,n);return u||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),m=eO(t.role.permission,E,d[f]);ZA(h,m,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw Yr(n)}}a(Yse,"verifyPermsAst");function Kse(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw xt.info("null required parameter in verifyPerms"),Yr(new Error,nr.DEFAULT_INVALID_REQUEST,B_.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 xH;if(Ci.isEmptyOrZeroLength(e.hdb_user.role)||Ci.isEmptyOrZeroLength(e.hdb_user.role.permission))return xt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(nr.USER_HAS_NO_PERMS(e.hdb_user.username));let l=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,u=o.has(Fn.SYSTEM_SCHEMA_NAME)||s===Fn.SYSTEM_SCHEMA_NAME;if(u&&kH[r])throw Yr(new Error,nr.DROP_SYSTEM,B_.FORBIDDEN);if(l&&!u||_===!0&&(r===kn.createSchema.name||r===kn.dropSchema.name))return null;if($se.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=MH.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===DH||r===LH){if(s===Fn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(nr.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===DH&&(!d[s]||!d[s][H_]))return c.handleInvalidItem(nr.SCHEMA_NOT_FOUND(s));if(r===LH&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][H_]))return c.handleInvalidItem(nr.TABLE_NOT_FOUND(s,i))}}let E=$H(e.hdb_user,r,o,c,n);if(E)return E;if($.get(r)&&$.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&Fn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let m=[],S=d[s].tables[i];S[Fn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(T=>T[Fn.PERMS_CRUD_ENUM.READ]).forEach(T=>{m.push(T.attribute_name)}):m=global.hdb_schema[s][i].attributes.map(g=>g.attribute),e.get_attributes=m)}let f=Wse(e),h=eO(e.hdb_user.role.permission,s,i);return ZA(f,h,r,i,s,c,n),c.getPermsResponse()}a(Kse,"verifyPerms");function $H(e,t,r,n,s){if(Ci.arrayHasEmptyValues([e,t,r]))throw xt.info("hasPermissions has an invalid parameter"),Yr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||$.get(t).requires_su))return null;if(!$.get(t))throw xt.info(`operation ${t} not found.`),Yr(new Error,nr.OP_NOT_FOUND(t),B_.BAD_REQUEST);if($.get(t)&&$.get(t).requires_su)return xt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(nr.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!o[l]||o[l][H_]===!1){n.addInvalidItem(nr.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(nr.SCHEMA_NOT_FOUND(l));continue}let _=r.get(l);for(let u of _){let d=o[l].tables[u];if(!d||d[H_]===!1)n.addInvalidItem(nr.TABLE_NOT_FOUND(l,u));else try{let E=[],f=$.get(t).perms;!Ci.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let m=f[h],S=d[m];(S==null||S===!1)&&(xt.info(`Required ${m} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(m))}E.length>0&&n.addUnauthorizedTable(l,u,E)}catch(E){let f=nr.UNKNOWN_OP_AUTH_ERROR(t,l,u);throw xt.error(f),xt.error(E),Yr(qH.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a($H,"hasPermissions");function ZA(e,t,r,n,s,i,o){if(!e||!t)throw xt.info("no attributes specified in checkAttributePerms."),Yr(new Error);let c=$.get(r).perms;if(!c||c==="")throw xt.info(`no permissions found for ${r} in checkAttributePerms().`),Yr(new Error);if(Ci.isEmptyOrZeroLength(t))return xt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let l={};for(let u of e){let d=t.get(u);if(d){if(d[H_]===!1){i.addInvalidItem(nr.ATTR_NOT_FOUND(s,n,u),s,n);continue}if(c)for(let E of c){if(Fn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Di)throw Yr(new Error,nr.SYSTEM_TIMESTAMP_PERMS_ERR,B_.FORBIDDEN);d[E]===!1&&(l[d.attribute_name]?l[d.attribute_name].push(E):l[d.attribute_name]=[E])}}else i.addInvalidItem(nr.ATTR_NOT_FOUND(s,n,u),s,n)}let _=Object.keys(l);_.length>0&&i.addUnauthorizedAttributes(_,s,n,l)}a(ZA,"checkAttributePerms");function Wse(e){let t=new Set;try{if(e.action)return t;if(e.operation===Fn.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){xt.info(r)}return t}a(Wse,"getRecordAttributes");function eO(e,t,r){let n=new Map;if(Ci.isEmpty(e))return xt.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{xt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(eO,"getAttributePermissions");function Qse(e,t,r,n,s,i,o){let c=new Set(i),l=eO(e,n,s);ZA(c,l,t,s,n,o,r)}a(Qse,"verifyBulkLoadAttributePerms")});var Yh=R((mbe,zH)=>{"use strict";zH.exports={evaluateSQL:aie,processAST:jH,convertSQLToAST:QH,checkASTPermissions:WH};var jse=Cr(),KH=require("util"),zse=KH.callbackify(jse.insert),Jse=ur().search,Xse=gM().update,Zse=KH.callbackify(Xse),eie=AM().convertDelete,wo=require("alasql"),tie=Vh(),$h=k(),rie=fE(),nie=Y(),q_=D(),{hdb_errors:sie,handleHDBError:tO}=ie(),{HTTP_STATUS_CODES:rO}=sie;rie(wo);var iie=403,oie="There was a problem performing this insert. Please check the logs and try again.",nO=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function aie(e,t){let r=e.parsed_sql_object;if(!r){r=QH(e.sql);let n,s=r.ast.statements[0];if(s instanceof wo.yy.Insert?n=s.into.databaseid:s instanceof wo.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof wo.yy.Update||s instanceof wo.yy.Delete?n=s.table.databaseid:$h.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof wo.yy.Select)&&nie.isEmptyOrZeroLength(n))return t("No schema specified",null)}jH(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(aie,"evaluateSQL");function WH(e,t){let r;try{r=tie.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(WH,"checkASTPermissions");function QH(e){let t=new nO;if(!e)throw tO(new Error,"The 'sql' parameter is missing from the request body",rO.BAD_REQUEST);try{let r=e.trim(),n=wo.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
20
- `);throw n[1]?tO(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,rO.BAD_REQUEST):tO(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",rO.BAD_REQUEST)}return t}a(QH,"convertSQLToAST");function jH(e,t,r){try{let n=cie;if(!e.bypass_auth&&!t.permissions_checked){let i=WH(e,t);if(i&&i.length>0)return r(iie,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case q_.VALID_SQL_OPS_ENUM.SELECT:n=Jse,s=t.ast.statements[0];break;case q_.VALID_SQL_OPS_ENUM.INSERT:n=lie;break;case q_.VALID_SQL_OPS_ENUM.UPDATE:n=Zse;break;case q_.VALID_SQL_OPS_ENUM.DELETE:n=eie;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(jH,"processAST");function cie(e,t){$h.info(e),t("unknown sql statement")}a(cie,"nullFunction");function lie({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=uie(i,e.values)}catch(o){return r(o)}zse(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(l){$h.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}a(lie,"convertInsert");function uie(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]]=wo.compile(`SELECT ${s.toString()} AS [${q_.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw $h.error(r),new Error(oie)}}a(uie,"createDataObjects")});var sO=R((Tbe,XH)=>{"use strict";var{S3:_ie,GetObjectCommand:die}=require("@aws-sdk/client-s3");XH.exports={getFileStreamFromS3:fie,getS3AuthObj:JH};async function fie(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await JH(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new die(r))).Body}a(fie,"getFileStreamFromS3");function JH(e,t,r){return new _ie({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(JH,"getS3AuthObj")});var Kh=R((Rbe,aG)=>{"use strict";var oO=ur(),Eie=Yh(),hie=sO(),{AsyncParser:pie,Transform:mie}=require("json2csv"),k_=require("stream"),mn=Y(),iO=require("fs-extra"),Sie=require("path"),Vn=k(),{promisify:tG}=require("util"),F_=Y(),{handleHDBError:Dt,hdb_errors:Tie}=ie(),{HDB_ERROR_MSGS:Kr,HTTP_STATUS_CODES:Lt}=Tie,{streamAsJSON:gie}=(IS(),ae(UI)),{Upload:Rie}=require("@aws-sdk/lib-storage"),ZH=["search_by_value","search_by_hash","sql","search_by_conditions"],eG=["json","csv"],rG="json",nG="csv",Aie="Successfully exported JSON locally.",Oie="Successfully exported CSV locally.",bie=1e3,Nie=oO.searchByHash,yie=oO.searchByValue,Iie=tG(Eie.evaluateSQL),wie=tG(k_.finished);aG.exports={export_to_s3:Pie,export_local:Cie,toCsvStream:sG};async function Cie(e){Vn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=iG(e);if(!mn.isEmpty(t))throw Vn.error(t),Dt(new Error,t,Lt.BAD_REQUEST,void 0,void 0,!0);if(mn.isEmpty(e.path))throw Vn.error(Kr.MISSING_VALUE("path")),Dt(new Error,Kr.MISSING_VALUE("path"),Lt.BAD_REQUEST,void 0,void 0,!0);let r=(mn.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Sie.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=mn.buildFolderPath(e.path,r);await Die(e.path);let s=await oG(e);return await Lie(n,e.format,s)}a(Cie,"export_local");async function Die(e){if(Vn.trace("in confirmPath"),mn.isEmptyOrZeroLength(e))throw Dt(new Error,`Invalid path: ${e}`,Lt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await iO.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,Vn.error(n),Dt(new Error,n,Lt.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 Vn.error(r),Dt(new Error,r,Lt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Die,"confirmPath");async function Lie(e,t,r){if(Vn.trace("in saveToLocal"),F_.isEmptyOrZeroLength(e))throw Dt(new Error,Kr.INVALID_VALUE("file_path"),Lt.BAD_REQUEST,void 0,void 0,!0);if(F_.isEmptyOrZeroLength(t))throw Dt(new Error,Kr.INVALID_VALUE("Source format"),Lt.BAD_REQUEST,void 0,void 0,!0);if(F_.isEmpty(r))throw Dt(new Error,Kr.NOT_FOUND("Data"),Lt.BAD_REQUEST,void 0,void 0,!0);if(t===rG){let n=iO.createWriteStream(e);return gie(r).pipe(n),await wie(n),{message:Aie,path:e}}else if(t===nG){let n=iO.createWriteStream(e),s=k_.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(u=>({label:u,value:u})));let c={objectMode:!0};return await new pie(i,c).fromInput(s).toOutput(n).promise(!1),{message:Oie,path:e}}throw Dt(new Error,Kr.INVALID_VALUE("format"),Lt.BAD_REQUEST)}a(Lie,"saveToLocal");async function Pie(e){if(!e.s3||Object.keys(e.s3).length===0)throw Dt(new Error,Kr.MISSING_VALUE("S3 object"),Lt.BAD_REQUEST);if(mn.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Dt(new Error,Kr.MISSING_VALUE("aws_access_key_id"),Lt.BAD_REQUEST);if(mn.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Dt(new Error,Kr.MISSING_VALUE("aws_secret_access_key"),Lt.BAD_REQUEST);if(mn.isEmptyOrZeroLength(e.s3.bucket))throw Dt(new Error,Kr.MISSING_VALUE("bucket"),Lt.BAD_REQUEST);if(mn.isEmptyOrZeroLength(e.s3.key))throw Dt(new Error,Kr.MISSING_VALUE("key"),Lt.BAD_REQUEST);if(mn.isEmptyOrZeroLength(e.s3.region))throw Dt(new Error,Kr.MISSING_VALUE("region"),Lt.BAD_REQUEST);let t=iG(e);if(!mn.isEmpty(t))throw Dt(new Error,t,Lt.BAD_REQUEST);Vn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await oG(e)}catch(l){throw Vn.error(l),l}let n,s=await hie.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new k_.PassThrough;if(e.format===nG){i=e.s3.key+".csv";let l=sG(r,r.getColumns?.());l.on("error",_=>{throw _}),l.pipe(o)}else if(e.format===rG){i=e.s3.key+".json";let l=new k_.Readable;l.pipe(o),l.on("error",d=>{throw d}),l.push("[");let _=r.length,u="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";u+=f,d!==0&&d%bie===0&&(l.push(u),u="")}u.length!==0&&l.push(u),l.push("]"),l.push(null)}else throw Dt(new Error,Kr.INVALID_VALUE("format"),Lt.BAD_REQUEST);return new Rie({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Pie,"export_to_s3");function sG(e,t){let r=k_.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 mie(n,s);return r.pipe(i)}a(sG,"toCsvStream");function iG(e){if(Vn.trace("in exportCoreValidation"),mn.isEmpty(e.format))return"format missing";if(eG.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${eG.join(", ")}`;let t=e.search_operation.operation;if(mn.isEmpty(t))return"search_operation.operation missing";if(ZH.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${ZH.join(", ")}`}a(iG,"exportCoreValidation");async function oG(e){Vn.trace("in getRecords");let t,r;if(F_.isEmpty(e.search_operation)||F_.isEmptyOrZeroLength(e.search_operation.operation))throw Dt(new Error,Kr.INVALID_VALUE("Search operation"),Lt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=yie;break;case"search_by_hash":t=Nie;break;case"search_by_conditions":t=oO.searchByConditions;break;case"sql":t=Iie;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Vn.error(r),Dt(new Error,r,Lt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(oG,"getRecords")});var pG={};Ve(pG,{contentTypes:()=>uO,findBestSerializer:()=>jh,getDeserializer:()=>Ba,registerContentHandlers:()=>_O,serialize:()=>zh,serializeMessage:()=>Pa});function Mie(e){try{return e?.[0]===123?lO(e):e}catch{return e}}function _O(e){e.register(vie,{serializers:[{regex:/^application\/json$/,serializer:nu},{regex:/^application\/cbor$/,serializer:function(t){return new va.EncoderStream($_).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Qh.Readable.from((0,$s.encodeIter)(t,$_)):(0,$s.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Wh.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,$s.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,va.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function jh(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[_,...u]=l.split(/\s*;\s*/),d=1,E={q:1};for(let h of u){let m=h.indexOf("=");E[h.substring(0,m)]=h.substring(m+1)}d=+E.q;let f=Jt.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)throw new _G.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Jt.keys()).join(", "),406);n=Jt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function zh(e,t,r){let n=lG&&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=jh(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,Li.createBrotliCompress)({params:{[Li.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Li.constants.BROTLI_MODE_TEXT:Li.constants.BROTLI_MODE_GENERIC,[Li.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>lG?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Li.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function Pa(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return V_(e);let r=t.serialize;if(r)return r(e);let n=jh(t);return r=t.serialize=n.serializer.serialize,r(e)}function Bie(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 Ba(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Jt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Jt.get(e)?.deserialize||uG(e,n);return o=>Bie(o).then(i)}return e&&Jt.get(e)?.deserialize||uG(e,n)}function uG(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 lO(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Hie(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 Wh,$s,va,Li,_G,Qh,dG,aO,cO,fG,EG,V_,lO,$_,Jt,uO,cG,hG,Uie,vie,lG,jc=be(()=>{IS();Wh=G(Kh()),$s=require("msgpackr"),va=require("cbor-x"),Li=require("zlib"),_G=G(ie()),Qh=require("stream");yr();dG=require("../index"),aO=G(X()),cO=G(D()),fG=G(require("yaml")),EG=aO.default.get(cO.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,V_=EG?zo:JSON.stringify,lO=EG?yS:JSON.parse,$_={useRecords:!1,useToJSON:!0},Jt=new Map,uO=Jt;dt.contentTypes=uO;(0,dG._assignPackageExport)("contentTypes",uO);Jt.set("application/json",{serializeStream:nu,serialize:V_,deserialize:lO,q:.8});cG=new va.Encoder($_);Jt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new va.EncoderStream($_).end(e)},serialize:cG.encode,deserialize:cG.decode,q:1});Jt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Qh.Readable.from((0,$s.encodeIter)(e,$_)):(0,$s.pack)(e)},serialize:$s.pack,deserialize:$s.unpack,q:.9});Jt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Wh.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,Wh.toCsvStream)(e,e?.getColumns?.())},q:.1});Jt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Jt.set("text/yaml",{serialize(e){return fG.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Jt.set("text/event-stream",{serializeStream:function(e){return Qh.Readable.from(Hie(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+`
21
- `),e.data){let r=e.data;typeof r=="object"&&(r=V_(r)),t+="data: "+r+`
16
+ Database backup has not been removed and can be found here: ${s}`;Vf.error(l),console.error(l)}(0,BO.get)(wa.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,Jc.remove)(s))}(0,HO.updateConfigValue)(wa.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function Zk(e){let t=await(0,nG.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function sG(e,t){console.log("copyDb start");let r=ft()[e],n;for(let _ in r){n=r[_].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,eG.open)(new tG.default(t)),c=o.openDB(sS.INTERNAL_DBIS_NAME),l,d=0,u=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:u})){let S=h.is_hash_attribute||h.isPrimaryKey,T,g;if(S&&(T=h.compression,g=aS(),g?h.compression=g:delete h.compression,T?.dictionary?.toString()===g?.dictionary?.toString()&&(T=null,g=null)),c.put(f,h),!(S||h.indexed))continue;let m=new rG.default(!S,S);m.encoding="binary",m.compression=T;let C=n.openDB(f,m);C.decoder=null,m.compression=g;let O=o.openDB(f,m);O.encoder=null,console.log("copying",f,"from",e,"to",t),await E(C,O,S,u)}let _=n.openDB(sS.AUDIT_STORE_NAME,Yf);console.log("copying audit log"),E(i,_,!1,u);async function E(f,h,S,T){let g=0,m=0;for(let{key:C,value:O,version:x}of f.getRange({start:null,versions:S,transaction:T}))l=h.put(C,O,x),g++,T.openTimer&&(T.openTimer=0),m+=(C?.length||10)+O.length,d++>5e3&&(await l,console.log("copied",g,"entries",m,"bytes"),d=0);console.log("finish copying, copied",g,"entries",m,"bytes")}a(E,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{u.done(),o.close()}}var eG,nS,Jc,BO,tG,rG,sS,wa,nG,HO,Vf,oS=Ce(()=>{De();eG=require("lmdb"),nS=require("path"),Jc=require("fs-extra"),BO=B(te()),tG=B(m_()),rG=B(p_()),sS=B(Bt()),wa=B(M());io();nG=B(uo()),HO=B(yt()),Vf=B(V());a(Oce,"compactOnStart");a(Zk,"getTotalDBRecordCount");a(sG,"copyDb")});var Ca=y((kDe,dG)=>{"use strict";var Nce=require("minimist"),{isMainThread:FO,parentPort:Wf,threadId:HDe}=require("worker_threads"),Pt=M(),{PROCESS_DESCRIPTORS_VALIDATE:ju}=Pt,vi=V(),kO=ee(),lS=Xm(),cS=nr(),xDe=At(),cG=yt(),Bi=Ku(),iG=To(),{compactOnStart:Ice}=(oS(),ne(iS)),wce=Jo(),{restartWorkers:uS,onMessageByType:Cce}=ut(),{handleHDBError:Dce,hdb_errors:Pce}=ce(),{HTTP_STATUS_CODES:Lce}=Pce,jf=te(),{sendOperationToNode:oG,getThisNodeName:Mce,monitorNodeCAs:Uce}=(hs(),ne(ma)),{getHDBNodeTable:FDe}=(Su(),ne(WB));jf.initSync();var Kf=`Restarting HarperDB. This may take up to ${Pt.RESTART_TIMEOUT_MS/1e3} seconds.`,vce="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",aG="Clustering is not enabled so cannot be restarted",Bce="Invalid service",Qu,ys;dG.exports={restart:lG,restartService:GO};FO&&Cce(Pt.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await GO({service:e.workerType}):lG({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function lG(e){ys=Object.keys(e).length===0,Qu=await Bi.isServiceRegistered(Pt.HDB_PROC_DESCRIPTOR);let t=Nce(process.argv);if(t.service){await GO(t);return}if(ys&&!Qu){console.error(vce);return}if(ys&&console.log(Kf),Qu){Bi.enterPM2Mode(),vi.notify(Kf);let r=wce(Object.keys(Pt.CONFIG_PARAM_MAP),!0);return kO.isEmptyOrZeroLength(Object.keys(r))||cG.updateConfigValue(void 0,void 0,r,!0,!0),Hce(),Kf}return FO?(vi.notify(Kf),jf.get(Pt.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await Ice(),setTimeout(()=>{uS()},50)):Wf.postMessage({type:Pt.ITC_EVENT_TYPES.RESTART}),Kf}a(lG,"restart");async function GO(e){let{service:t}=e;if(Pt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw Dce(new Error,Bce,Lce.BAD_REQUEST,void 0,void 0,!0);if(Qu=await Bi.isServiceRegistered(Pt.HDB_PROC_DESCRIPTOR),!FO){e.replicated&&Uce(),Wf.postMessage({type:Pt.ITC_EVENT_TYPES.RESTART,workerType:t}),Wf.ref(),await new Promise(s=>{Wf.on("message",i=>{i.type==="restart-complete"&&(s(),Wf.unref())})});let n;if(e.replicated){e.replicated=!1,n=[];for(let s of server.nodes){if(s.name===Mce())continue;let{job_id:i}=await oG(s,e);n.push(await new Promise((o,c)=>{let d=2400,u=setInterval(async()=>{if(d--<=0){clearInterval(u);let f=new Error("Timed out waiting for restart job to complete");f.replicated=n,c(f)}let E=(await oG(s,{operation:"get_job",id:i})).results[0];if(E.status==="COMPLETE"&&(clearInterval(u),o({node:s.name,message:E.message})),E.status==="ERROR"){clearInterval(u);let f=new Error(E.message);f.replicated=n,c(f)}},250)}))}return{replicated:n}}return}let r;switch(t){case ju.clustering:if(!jf.get(Pt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=aG;break}ys&&console.log("Restarting clustering"),vi.notify("Restarting clustering"),await uG();break;case ju.clustering_config:case ju["clustering config"]:if(!jf.get(Pt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=aG;break}ys&&console.log("Restarting clustering_config"),vi.notify("Restarting clustering_config"),await Bi.reloadClustering();break;case"custom_functions":case"custom functions":case ju.harperdb:case ju.http_workers:case ju.http:if(ys&&!Qu){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}ys&&console.log("Restarting http_workers"),vi.notify("Restarting http_workers"),ys?await Bi.restart(Pt.HDB_PROC_DESCRIPTOR):await uS("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(vi.error(r),ys&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(GO,"restartService");async function Hce(){await uG(),await Bi.restart(Pt.HDB_PROC_DESCRIPTOR),await kO.async_set_timeout(2e3),jf.get(Pt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await xO(),ys&&(await cS.closeConnection(),process.exit(0))}a(Hce,"restartPM2Mode");async function uG(){if(!cG.getConfigFromFile(Pt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await iG.getHDBProcessInfo()).clustering.length===0)vi.trace("Clustering not running, restart will start clustering services"),await lS.generateNatsConfig(!0),await Bi.startClusteringProcesses(),await Bi.startClusteringThreads(),await xO(),ys&&await cS.closeConnection();else{await lS.generateNatsConfig(!0),Qu?(vi.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await Bi.restart(Pt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Bi.restart(Pt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await iG.getHDBProcessInfo()).clustering.forEach(s=>{vi.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await kO.async_set_timeout(3e3),await xO(),await cS.updateLocalStreams(),ys&&await cS.closeConnection(),vi.trace("Restart clustering restarting ingest and reply service threads");let t=uS(Pt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=uS(Pt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(uG,"restartClustering");async function xO(){await lS.removeNatsConfig(Pt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await lS.removeNatsConfig(Pt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(xO,"removeNatsConfig")});var AG=y(($De,RG)=>{"use strict";var qDe=require("lodash"),bn=M(),{handleHDBError:_G,hdb_errors:xce}=ce(),{HDB_ERROR_MSGS:Fce,HTTP_STATUS_CODES:kce}=xce,qO=V();RG.exports={getRolePermissions:qce};var Xc=Object.create(null),Gce=a(e=>({key:e,perms:{}}),"perms_template_obj"),pG=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),mG=a((e=!1,t=!1,r=!1,n=!1)=>({[bn.PERMS_CRUD_ENUM.READ]:e,[bn.PERMS_CRUD_ENUM.INSERT]:t,[bn.PERMS_CRUD_ENUM.UPDATE]:r,[bn.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),$O=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...mG(t,r,n,s)}),"table_perms_template"),fG=a((e,t=mG())=>({attribute_name:e,describe:gG(t),[Qf]:t[Qf],[VO]:t[VO],[YO]:t[YO]}),"attr_perms_template"),EG=a((e,t=!1)=>({attribute_name:e,describe:t,[Qf]:t}),"timestamp_attr_perms_template"),{READ:Qf,INSERT:VO,UPDATE:YO}=bn.PERMS_CRUD_ENUM,SG=Object.values(bn.PERMS_CRUD_ENUM),TG=[Qf,VO,YO];function qce(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r={...global.hdb_schema};delete r[bn.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(Xc[t]&&Xc[t].key===n)return Xc[t].perms;let s=$ce(e,r);return Xc[t]?Xc[t].key=n:Xc[t]=Gce(n),Xc[t].perms=s,s}catch(r){if(!e[bn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[bn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<bn.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 qO.error(n),qO.debug(r),_G(new Error,Fce.OUTDATED_PERMS_TRANSLATION_ERROR,kce.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
17
+ ${r.stack}`;throw qO.error(n),_G(new Error)}}}a(qce,"getRolePermissions");function $ce(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[bn.SYSTEM_SCHEMA_NAME]=n[bn.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]=Vce(t[i]);return}r[i]=pG(),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],l=t[i][o],d=Yce(c,l);r[i].describe||SG.forEach(u=>{d[u]&&(r[i].describe=!0)}),r[i].tables[o]=d}else r[i].tables[o]=$O()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=$O()})}),r}a($ce,"translateRolePermissions");function Vce(e){let t=pG(!0);return Object.keys(e).forEach(r=>{t.tables[r]=$O(!0,!0,!0,!0,!0)}),t}a(Vce,"createStructureUserPermissions");function Yce(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s={...e};s.attribute_permissions=[];let i=r.reduce((d,u)=>{let{attribute_name:_}=u,E=u;return bn.TIME_STAMP_NAMES.includes(_)&&(E=EG(_,u[Qf])),d[_]=E,d},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],l=fG(o);return t.attributes.forEach(({attribute:d})=>{if(i[d]){let u=i[d];u.describe=gG(u),s.attribute_permissions.push(u),c||Kce(u,l)}else if(d!==o){let u;bn.TIME_STAMP_NAMES.includes(d)?u=EG(d):u=fG(d),s.attribute_permissions.push(u)}}),c||s.attribute_permissions.push(l),s.describe=hG(s),s}else return e.describe=hG(e),e}a(Yce,"getTableAttrPerms");function hG(e){return SG.filter(t=>e[t]).length>0}a(hG,"getSchemaTableDescribePerm");function gG(e){return TG.filter(t=>e[t]).length>0}a(gG,"getAttributeDescribePerm");function Kce(e,t){TG.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(Kce,"checkForHashPerms")});var bG={};tt(bG,{Headers:()=>Io,appendHeader:()=>KO,mergeHeaders:()=>WO});function KO(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}function WO(e,t){(typeof e.set!="function"||typeof e.has!="function")&&(e=new Io(e));for(let[r,n]of t)e.has(r)?r.toLowerCase()==="set-cookie"&&e.append?.(r,n,!0):e.set(r,n);return e}var Io,zf=Ce(()=>{Io=class extends Map{static{a(this,"Headers")}constructor(t){if(t)if(t[Symbol.iterator])super(t);else{super();for(let r in t)this.set(r,t[r])}else super()}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(KO,"appendHeader");a(WO,"mergeHeaders")});var Jf={};tt(Jf,{authentication:()=>DG,bypassAuth:()=>Zce,login:()=>tle,logout:()=>rle,start:()=>ele});function Zce(){CG=!0}async function DG(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?zce?Qce:[]:jce?Wce:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new Io([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return dS&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),dS&&o.push("Access-Control-Allow-Credentials","true")}}let l,d;if(dS){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let S of h)if(S.startsWith(f)){let T=S.indexOf(";");l=S.slice(f.length,T===-1?S.length:T),d=await yG.get(l);break}e.session=d||(d={})}let u=a((f,h,S)=>{let T=new zu.AuthAuditLog(f,h,yr.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);T.auth_strategy=S,l&&(T.session_id=l),r.referer&&(T.referer=r.referer),r.origin&&(T.origin=r.origin),h===yr.AUTH_AUDIT_STATUS.SUCCESS?jO.notify(T):jO.error(T)},"authAuditLog");if(!e.authorized&&e.mtlsConfig&&e.peerCertificate.subject&&e?._nodeRequest?.socket?.authorizationError&&jO.error("Authorization error:",e._nodeRequest.socket.authorizationError),e.mtlsConfig&&e.authorized&&e.peerCertificate.subject){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await nt.getUser(f,null,null),u(f,yr.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,zu.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let _;if(!e.user)if(n){if(_=Zc.get(n),!_){let f=n.indexOf(" "),h=n.slice(0,f),S=n.slice(f+1),T,g;try{switch(h){case"Basic":let m=atob(S),C=m.indexOf(":");T=m.slice(0,C),g=m.slice(C+1),_=T||g?await nt.getUser(T,g,e):null;break;case"Bearer":try{_=await(0,_S.validateOperationToken)(S)}catch(O){if(O.message==="invalid token")try{return await(0,_S.validateRefreshToken)(S),c({status:-1})}catch{throw O}}break}}catch(m){return Xce&&(Zc.get(S)||(Zc.set(S,S),u(T,yr.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:el({error:m.message},e)})}Zc.set(n,_),Jce&&u(_.username,yr.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=_}else d?.user?e.user=await nt.getUser(d.user,null,e):(CG&&(e.ip?.includes("127.0.0.")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,NG.getSuperUser)());dS&&(e.session.update=function(f){if(!l){l=(0,IG.v4)();let S=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${l}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",S):E?.headers?.set&&E.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")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=l,yG.put(f)},e.login=async function(f,h){e.user=await nt.getUser(f,h,e),e.session.update({user:e.user.username})},(_&&!d||d?.user?.username!==_?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&da.loginPath?(E.status=302,E.headers.set("Location",da.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(l){throw c(l)}function c(l){let d=o.length;if(d>0){let u=l.headers;u||(l.headers=u=new Io);for(let _=0;_<d;){let E=o[_++];u.set(E,o[_++])}}return o=null,l}a(c,"applyResponseHeaders")}function ele({server:e,port:t}){e.http(DG,{port:t||"all"}),OG||(OG=!0,setInterval(()=>{Zc=new Map},Os.get(yr.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),wG.user.addListener(()=>{Zc=new Map}))}async function tle(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 rle(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var NG,_S,IG,Os,yr,zu,wG,jO,Wce,jce,Qce,zce,yG,dS,CG,Jce,Xce,Zc,OG,fS=Ce(()=>{NG=B(_n());Wr();lf();_S=B(Of());De();IG=require("uuid"),Os=B(te()),yr=B(M()),zu=B(V()),wG=B(P_());zf();Ju();jO=(0,zu.loggerWithTag)("auth-event");Os.initSync();Wce=Os.get(yr.CONFIG_PARAMS.HTTP_CORSACCESSLIST),jce=Os.get(yr.CONFIG_PARAMS.HTTP_CORS),Qce=Os.get(yr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),zce=Os.get(yr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),yG=dt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),dS=Os.get(yr.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,CG=process.env.AUTHENTICATION_AUTHORIZELOCAL??Os.get(yr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,Jce=Os.get(yr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,Xce=Os.get(yr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Zc=new Map;nt.onInvalidatedUser(()=>{Zc=new Map});a(Zce,"bypassAuth");a(DG,"authentication");a(ele,"start");a(tle,"login");a(rle,"logout")});var HG=y((XDe,BG)=>{"use strict";var ye=require("joi"),PG=require("fs-extra"),LG=require("path"),Wn=St(),MG=te(),UG=M(),vG=V(),{hdb_errors:nle}=ce(),{HDB_ERROR_MSGS:Ur}=nle,wo=/^[a-zA-Z0-9-_]+$/,sle=/^[a-zA-Z0-9-_]+$/;BG.exports={getDropCustomFunctionValidator:ole,setCustomFunctionValidator:ale,addComponentValidator:dle,dropCustomFunctionProjectValidator:_le,packageComponentValidator:fle,deployComponentValidator:Ele,setComponentFileValidator:cle,getComponentFileValidator:ule,dropComponentFileValidator:lle,addSSHKeyValidator:hle,updateSSHKeyValidator:ple,deleteSSHKeyValidator:mle,setSSHKnownHostsValidator:Sle};function ES(e,t,r){try{let n=MG.get(UG.CONFIG_PARAMS.COMPONENTSROOT),s=LG.join(n,t);return PG.existsSync(s)?e?t:r.message(Ur.PROJECT_EXISTS):e?r.message(Ur.NO_PROJECT):t}catch(n){return vG.error(n),r.message(Ur.VALIDATION_ERR)}}a(ES,"checkProjectExists");function Xf(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Xf,"checkFilePath");function ile(e,t,r,n){try{let s=MG.get(UG.CONFIG_PARAMS.COMPONENTSROOT),i=LG.join(s,e,t,r+".js");return PG.existsSync(i)?r:n.message(Ur.NO_FILE)}catch(s){return vG.error(s),n.message(Ur.VALIDATION_ERR)}}a(ile,"checkFileExists");function ole(e){let t=ye.object({project:ye.string().pattern(wo).custom(ES.bind(null,!0)).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME}),type:ye.string().valid("helpers","routes").required(),file:ye.string().pattern(wo).custom(ile.bind(null,e.project,e.type)).custom(Xf).required().messages({"string.pattern.base":Ur.BAD_FILE_NAME})});return Wn.validateBySchema(e,t)}a(ole,"getDropCustomFunctionValidator");function ale(e){let t=ye.object({project:ye.string().pattern(wo).custom(ES.bind(null,!0)).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME}),type:ye.string().valid("helpers","routes").required(),file:ye.string().custom(Xf).required(),function_content:ye.string().required()});return Wn.validateBySchema(e,t)}a(ale,"setCustomFunctionValidator");function cle(e){let t=ye.object({project:ye.string().pattern(wo).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME}),file:ye.string().custom(Xf).required(),payload:ye.string().allow("").optional(),encoding:ye.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Wn.validateBySchema(e,t)}a(cle,"setComponentFileValidator");function lle(e){let t=ye.object({project:ye.string().pattern(wo).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME}),file:ye.string().custom(Xf).optional()});return Wn.validateBySchema(e,t)}a(lle,"dropComponentFileValidator");function ule(e){let t=ye.object({project:ye.string().required(),file:ye.string().custom(Xf).required(),encoding:ye.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Wn.validateBySchema(e,t)}a(ule,"getComponentFileValidator");function dle(e){let t=ye.object({project:ye.string().pattern(wo).custom(ES.bind(null,!1)).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME})});return Wn.validateBySchema(e,t)}a(dle,"addComponentValidator");function _le(e){let t=ye.object({project:ye.string().pattern(wo).custom(ES.bind(null,!0)).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME})});return Wn.validateBySchema(e,t)}a(_le,"dropCustomFunctionProjectValidator");function fle(e){let t=ye.object({project:ye.string().pattern(wo).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME}),skip_node_modules:ye.boolean()});return Wn.validateBySchema(e,t)}a(fle,"packageComponentValidator");function Ele(e){let t=ye.object({project:ye.string().pattern(wo).required().messages({"string.pattern.base":Ur.BAD_PROJECT_NAME}),payload:ye.string().optional().messages({"string.pattern.base":Ur.BAD_PACKAGE}),package:ye.string().optional(),restart:ye.boolean().optional()});return Wn.validateBySchema(e,t)}a(Ele,"deployComponentValidator");function hle(e){let t=ye.object({name:ye.string().pattern(sle).required().messages({"string.pattern.base":Ur.BAD_SSH_KEY_NAME}),key:ye.string().required(),host:ye.string().required(),hostname:ye.string().required(),known_hosts:ye.string().optional()});return Wn.validateBySchema(e,t)}a(hle,"addSSHKeyValidator");function ple(e){let t=ye.object({name:ye.string().required(),key:ye.string().required()});return Wn.validateBySchema(e,t)}a(ple,"updateSSHKeyValidator");function mle(e){let t=ye.object({name:ye.string().required()});return Wn.validateBySchema(e,t)}a(mle,"deleteSSHKeyValidator");function Sle(e){let t=ye.object({known_hosts:ye.string().required()});return Wn.validateBySchema(e,t)}a(Sle,"setSSHKnownHostsValidator")});var TS=y((ePe,$G)=>{"use strict";var hS=require("joi"),tl=require("path"),mS=require("fs-extra"),{exec:Tle}=require("child_process"),gle=require("util"),xG=gle.promisify(Tle),ed=M(),{handleHDBError:Xu,hdb_errors:Rle}=ce(),{HTTP_STATUS_CODES:Zu}=Rle,rd=te(),Ale=St(),td=V();rd.initSync();var QO=rd.get(ed.CONFIG_PARAMS.COMPONENTSROOT),FG="npm install --omit=dev --json",ble=`${FG} --dry-run`,yle=rd.get(ed.CONFIG_PARAMS.ROOTPATH),pS=tl.join(yle,"ssh");$G.exports={installModules:wle,auditModules:Cle,installAllRootModules:Ole,uninstallRootModule:Nle,linkHarperdb:Ile};async function Ole(e=!1){await SS();let t=!1,r=process.env;mS.pathExistsSync(pS)&&mS.readdirSync(pS).forEach(n=>{n.includes(".key")&&!t&&(r={GIT_SSH_COMMAND:"ssh -F "+tl.join(pS,"config")+" -o UserKnownHostsFile="+tl.join(pS,"known_hosts"),...process.env},t=!0)}),await Zf(e?"npm install --ignore-scripts":"npm install",rd.get(ed.CONFIG_PARAMS.ROOTPATH),r)}a(Ole,"installAllRootModules");async function Nle(e){await Zf(`npm uninstall ${e}`,rd.get(ed.CONFIG_PARAMS.ROOTPATH))}a(Nle,"uninstallRootModule");async function Ile(){await SS(),await Zf(`npm link ${ed.PACKAGE_ROOT}`,rd.get(ed.CONFIG_PARAMS.ROOTPATH))}a(Ile,"linkHarperdb");async function Zf(e,t=void 0,r=process.env){let n,s;try{({stdout:n,stderr:s}=await xG(e,{cwd:t,env:r}))}catch(i){throw new Error(i.stderr.replace(`
18
+ `,""))}return s&&!s.includes("Debugger listening")&&td.error("Error running NPM command:",e,s),td.trace(n,s),n?.replace(`
19
+ `,"")}a(Zf,"runCommand");async function wle(e){td.info(`starting installModules for request: ${e}`);let t=qG(e);if(t)throw Xu(t,t.message,Zu.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?ble:FG;await SS(),await GG(r);let i={};for(let o=0,c=r.length;o<c;o++){let l=r[o];i[l]={npm_output:null,npm_error:null};let d=tl.join(QO,l),u,_=null;try{let{stdout:E,stderr:f}=await xG(s,{cwd:d});u=E?E.replace(`
20
+ `,""):null,_=f?f.replace(`
21
+ `,""):null}catch(E){E.stderr?i[l].npm_error=kG(E.stderr):i[l].npm_error=E.message;continue}try{i[l].npm_output=JSON.parse(u)}catch{i[l].npm_output=u}try{i[l].npm_error=JSON.parse(_)}catch{i[l].npm_error=_}}return td.info(`finished installModules with response ${i}`),i}a(wle,"installModules");function kG(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
22
+ `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(kG,"parseNPMStdErr");async function Cle(e){td.info(`starting auditModules for request: ${e}`);let t=qG(e);if(t)throw Xu(t,t.message,Zu.BAD_REQUEST);let{projects:r}=e;await SS(),await GG(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=tl.join(QO,o);n[o]={npm_output:null,npm_error:null};try{let l=await Zf("npm audit --json",c);n[o].npm_output=JSON.parse(l)}catch(l){n[o].npm_error=kG(l.stderr)}}return td.info(`finished auditModules with response ${n}`),n}a(Cle,"auditModules");async function SS(){try{return await Zf("npm -v"),!0}catch{throw Xu(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Zu.BAD_REQUEST,void 0,void 0,!0)}}a(SS,"checkNPMInstalled");async function GG(e){if(!Array.isArray(e)||e.length===0)throw Xu(new Error,"projects argument must be an array with at least 1 element",Zu.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=tl.join(QO,i.toString());if(!await mS.pathExists(o)){t.push(i);continue}let l=tl.join(o,"package.json");await mS.pathExists(l)||r.push(i)}if(t.length>0)throw Xu(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Zu.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Xu(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Zu.BAD_REQUEST,void 0,void 0,!0)}a(GG,"checkProjectPaths");function qG(e){let t=hS.object({projects:hS.array().min(1).items(hS.string()).required(),dry_run:hS.boolean().default(!1)});return Ale.validateBySchema(e,t)}a(qG,"modulesValidator")});var JO=y((rPe,jG)=>{"use strict";var nd=require("fs-extra"),zO=require("path"),gS=V(),VG=ee(),RS=M(),WG=te(),Dle=yt();jG.exports=Ple;async function Ple(){let e=Lle(),t=WG.get(RS.CONFIG_PARAMS.ROOTPATH),r=zO.join(t,"package.json"),n={dependencies:{harperdb:"file:"+RS.PACKAGE_ROOT}},s=zO.join(t,"node_modules");nd.ensureDirSync(s);let i,o=!0,c=!1;try{i=nd.readJsonSync(r)}catch(l){if(VG.isEmptyOrZeroLength(e))return;if(l.code!==RS.NODE_ERROR_CODES.ENOENT)throw l;o=!1}if(!VG.isEmptyOrZeroLength(e)){for(let{name:l,package:d}of e){let u=YG(d);n.dependencies[l]=u+d}if(!o){gS.notify("Installing components"),await KG(r,n,null);return}for(let{name:l,package:d}of e){let u=i.dependencies[l],_=YG(d);if(u===void 0||u!==_+d){c=!0;break}}}for(let l in i.dependencies)n.dependencies[l]===void 0&&(gS.notify("Removing component",l),c=!0);c&&(gS.notify("Updating components."),await KG(r,n,i))}a(Ple,"installComponents");function Lle(){let e=Dle.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(Lle,"getComponentsConfig");function YG(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":zO.extname(e)||nd.existsSync(e)?"file:":"github:"}a(YG,"getPkgPrefix");async function KG(e,t,r){gS.trace("npm installing components package.json",t),nd.writeFileSync(e,JSON.stringify(t,null," "));try{await TS().installAllRootModules(WG.get(RS.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?nd.writeFileSync(e,JSON.stringify(r,null," ")):nd.unlinkSync(e),n}}a(KG,"installPackages")});var eN=y(XG=>{"use strict";var Ae=require("fs-extra"),XO=require("fast-glob"),Ie=require("path"),zG=require("tar-fs"),Mle=require("gunzip-maybe"),sPe=require("uuid").v4,ZO=require("normalize-path"),yn=HG(),Ft=V(),Et=M(),Jt=te(),eE=yt(),Ule=ee(),{PACKAGE_ROOT:vle}=M(),{handleHDBError:kt,hdb_errors:Ble}=ce(),{basename:Hle}=require("path"),xle=JO(),JG=te(),Fle=M(),{Readable:kle}=require("stream"),{isMainThread:Gle}=require("worker_threads"),{HDB_ERROR_MSGS:rl,HTTP_STATUS_CODES:Gt}=Ble,qle=ut(),{replicateOperation:ni}=(hs(),ne(ma)),$le=Ie.join(vle,"application-template"),QG=Ie.join(Jt.get(Et.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp"),Vle=Jt.get(Et.CONFIG_PARAMS.ROOTPATH),Da=Ie.join(Vle,"ssh"),Co=Ie.join(Da,"known_hosts");function Yle(){Ft.trace("getting custom api status");let e={};try{e={port:Jt.get(Et.CONFIG_PARAMS.HTTP_PORT),directory:Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw kt(new Error,rl.FUNCTION_STATUS,Gt.INTERNAL_SERVER_ERROR,Ft.ERR,t)}return e}a(Yle,"customFunctionsStatus");function Kle(){Ft.trace("getting custom api endpoints");let e={},t=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT);try{XO.sync(ZO(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:XO.sync(ZO(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:XO.sync(ZO(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw kt(new Error,rl.GET_FUNCTIONS,Gt.INTERNAL_SERVER_ERROR,Ft.ERR,r)}return e}a(Kle,"getCustomFunctions");function Wle(e){e.project&&(e.project=Ie.parse(e.project).name),e.file&&(e.file=Ie.parse(e.file).name);let t=yn.getDropCustomFunctionValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);Ft.trace("getting custom api endpoint file content");let r=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Ie.join(r,n,s,i+".js");try{return Ae.readFileSync(o,{encoding:"utf8"})}catch(c){throw kt(new Error,rl.GET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ft.ERR,c)}}a(Wle,"getCustomFunction");async function jle(e){e.project&&(e.project=Ie.parse(e.project).name),e.file&&(e.file=Ie.parse(e.file).name);let t=yn.setCustomFunctionValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);Ft.trace("setting custom function file content");let r=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{Ae.outputFileSync(Ie.join(r,n,s,i+".js"),o);let c=await ni(e);return c.message=`Successfully updated custom function: ${i}.js`,c}catch(c){throw kt(new Error,rl.SET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ft.ERR,c)}}a(jle,"setCustomFunction");async function Qle(e){e.project&&(e.project=Ie.parse(e.project).name),e.file&&(e.file=Ie.parse(e.file).name);let t=yn.getDropCustomFunctionValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);Ft.trace("dropping custom function file");let r=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{Ae.unlinkSync(Ie.join(r,n,s,i+".js"));let o=await ni(e);return o.message=`Successfully deleted custom function: ${i}.js`,o}catch(o){throw kt(new Error,rl.DROP_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ft.ERR,o)}}a(Qle,"dropCustomFunction");async function zle(e){e.project&&(e.project=Ie.parse(e.project).name);let t=yn.addComponentValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);Ft.trace("adding component");let r=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Ie.join(r,n);Ae.mkdirSync(s,{recursive:!0}),Ae.copySync($le,s);let i=await ni(e);return i.message=`Successfully added project: ${n}`,i}catch(s){throw kt(new Error,rl.ADD_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ft.ERR,s)}}a(zle,"addComponent");async function Jle(e){e.project&&(e.project=Ie.parse(e.project).name);let t=yn.dropCustomFunctionProjectValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);Ft.trace("dropping custom function project");let r=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Jt.get(Et.CONFIG_PARAMS.APPS);if(!Ule.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 eE.updateConfigValue(Et.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Ie.join(r,n);Ae.rmSync(i,{recursive:!0});let o=await ni(e);return o.message=`Successfully deleted project: ${n}`,o}catch(i){throw kt(new Error,rl.DROP_FUNCTION_PROJECT,Gt.INTERNAL_SERVER_ERROR,Ft.ERR,i)}}a(Jle,"dropCustomFunctionProject");async function Xle(e){e.project&&(e.project=Ie.parse(e.project).name);let t=yn.packageComponentValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let r=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ft.trace("packaging component",n);let s;try{s=await Ae.realpath(Ie.join(r,n))}catch(l){if(l.code!==Et.NODE_ERROR_CODES.ENOENT)throw l;try{s=await Ae.realpath(Ie.join(Jt.get(Et.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(d){if(d.code===Et.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ae.ensureDir(QG);let i=Ie.join(QG,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:l=>l.includes(Ie.join(s,"node_modules"))}),zG.pack(s,o).pipe(Ae.createWriteStream(i,{overwrite:!0})),await new Promise(l=>setTimeout(l,2e3));let c=Ae.readFileSync(i,{encoding:"base64"});return await Ae.remove(i),{project:n,payload:c}}a(Xle,"packageComponent");async function Zle(e){e.project&&(e.project=Ie.parse(e.project).name);let t=yn.deployComponentValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let r=Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Ft.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Ie.join(r,n),i="file:"+o,await Ae.emptyDir(o);let f=kle.from(Buffer.from(s,"base64"));await new Promise((S,T)=>{f.pipe(Mle()).pipe(zG.extract(o,{finish:S})).on("error",T)});let h=await Ae.readdir(o);h.length===1&&h[0]==="package"&&(await Ae.copy(Ie.join(o,"package"),o),await Ae.remove(Ie.join(o,"package")))}if(await eE.addConfig(n,{package:i}),!s){await xle();let f=JG.get(Fle.CONFIG_PARAMS.ROOTPATH);o=Ie.join(f,"node_modules",n)}if(Gle)return;let c=new Map;c.isWorker=!0;let l=(rE(),ne(tE)),d;l.setErrorReporter(f=>d=f);let u=Hle(o),_=l.component_errors.get(u);try{await l.loadComponent(o,c)}finally{l.component_errors.set(u,_)}if(d)throw d;Ft.info("Installed component");let E=await ni(e);return e.restart===!0?(qle.restartWorkers("http"),E.message=`Successfully deployed: ${n}, restarting HarperDB`):E.message=`Successfully deployed: ${n}`,E}a(Zle,"deployComponent");async function eue(){let e=eE.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push({...e[o],name:o})}let r=a(async(o,c)=>{try{let l=await Ae.readdir(o,{withFileTypes:!0});for(let d of l){let u=d.name;if(u.startsWith(".")||u==="node_modules")continue;let _=Ie.join(o,u);if(d.isDirectory()||d.isSymbolicLink()){let E={name:u,entries:[]};c.entries.push(E),await r(_,E)}else{let E=await Ae.stat(_),f={name:Ie.basename(u),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(l){return Ft.warn("Error loading package",l),{error:l.toString(),entries:[]}}},"walk_dir"),n=await r(Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),{name:Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT).split(Ie.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Ie.join(Jt.get(Et.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(rE(),ne(tE)).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(eue,"getComponents");async function tue(e){let t=yn.getComponentFileValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let n=eE.getConfigObj()[e.project]||e.project==="harperdb"?Ie.join(JG.get(Et.CONFIG_PARAMS.ROOTPATH),"node_modules"):Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ae.stat(Ie.join(n,e.project,e.file));return{message:await Ae.readFile(Ie.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Et.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Ie.join(e.project,e.file)}'`):i}}a(tue,"getComponentFile");async function rue(e){let t=yn.setComponentFileValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Ie.join(Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);e.payload!==void 0?(await Ae.ensureFile(n),await Ae.outputFile(n,e.payload,r)):await Ae.ensureDir(n);let s=await ni(e);return s.message="Successfully set component: "+e.file,s}a(rue,"setComponentFile");async function nue(e){let t=yn.dropComponentFileValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let r=e.file?Ie.join(e.project,e.file):e.project,n=Ie.join(Jt.get(Et.CONFIG_PARAMS.COMPONENTSROOT),r);await Ae.pathExists(n)&&await Ae.remove(n),eE.deleteConfigFromFile([e.project]);let s=await ni(e);return s.message="Successfully dropped: "+r,s}a(nue,"dropComponent");async function sue(e){let t=yn.addSSHKeyValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let{name:r,key:n,host:s,hostname:i,known_hosts:o}=e;Ft.trace("adding ssh key",r);let c=Ie.join(Da,r+".key"),l=Ie.join(Da,"config");if(await Ae.pathExists(c))throw new Error("Key already exists. Use update_ssh_key or delete_ssh_key and then add_ssh_key");await Ae.outputFile(c,n),await Ae.chmod(c,"0600");let d=`#${r}
23
+ Host ${s}
24
+ HostName ${i}
25
+ User git
26
+ IdentityFile ${c}
27
+ IdentitiesOnly yes`;await Ae.pathExists(l)?await Ae.appendFile(l,`
28
+ `+d):await Ae.outputFile(l,d);let u="";if(await Ae.pathExists(Co)||(await Ae.writeFile(Co,""),await Ae.chmod(Co,"0600")),i=="github.com"&&!(await Ae.readFile(Co,"utf8")).includes("github.com"))try{let S=(await(await fetch("https://api.github.com/meta")).json()).ssh_keys;for(let T of S)Ae.appendFile(Co,"github.com "+T+`
29
+ `)}catch{u=". Unable to get known hosts from github.com. Set your known hosts manually using set_ssh_known_hosts."}o&&await Ae.appendFile(Co,o);let _=await ni(e);return _.message=`Added ssh key: ${r}${u}`,_}a(sue,"addSSHKey");async function iue(e){let t=yn.updateSSHKeyValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let{name:r,key:n}=e;Ft.trace("updating ssh key",r);let s=Ie.join(Da,r+".key");if(!await Ae.pathExists(s))throw new Error("Key does not exist. Use add_ssh_key");await Ae.outputFile(s,n);let i=await ni(e);return i.message=`Updated ssh key: ${r}`,i}a(iue,"updateSSHKey");async function oue(e){let t=yn.deleteSSHKeyValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let{name:r}=e;Ft.trace("deleting ssh key",r);let n=Ie.join(Da,r+".key"),s=Ie.join(Da,"config");if(!await Ae.pathExists(n))throw new Error("Key does not exist");let i=await Ae.readFile(s,"utf8"),o=new RegExp(`#${r}[\\S\\s]*?IdentitiesOnly yes`,"g");i=i.replace(o,""),await Ae.outputFile(s,i),Ae.removeSync(n);let c=await ni(e);return c.message=`Deleted ssh key: ${r}`,c}a(oue,"deleteSSHKey");async function aue(e){let t=[];return await Ae.pathExists(Da)&&(await Ae.readdir(Da)).forEach(r=>{r!="known_hosts"&&r!="config"&&t.push({name:r.split(".")[0]})}),t}a(aue,"listSSHKeys");async function cue(e){let t=yn.setSSHKnownHostsValidator(e);if(t)throw kt(t,t.message,Gt.BAD_REQUEST);let{known_hosts:r}=e;await Ae.outputFile(Co,r);let n=await ni(e);return n.message="Known hosts successfully set",n}a(cue,"setSSHKnownHosts");async function lue(e){return await Ae.pathExists(Co)?{known_hosts:await Ae.readFile(Co,"utf8")}:{known_hosts:null}}a(lue,"getSSHKnownHosts");Object.assign(XG,{customFunctionsStatus:Yle,getCustomFunctions:Kle,getCustomFunction:Wle,setCustomFunction:jle,dropCustomFunction:Qle,addComponent:zle,dropCustomFunctionProject:Jle,packageComponent:Xle,deployComponent:Zle,getComponents:eue,getComponentFile:tue,setComponentFile:rue,dropComponent:nue,addSSHKey:sue,updateSSHKey:iue,deleteSSHKey:oue,listSSHKeys:aue,setSSHKnownHosts:cue,getSSHKnownHosts:lue})});var tN=y((aPe,eq)=>{"use strict";var Ns=require("joi"),ZG=St();eq.exports={readTransactionLogValidator:uue,deleteTransactionLogsBeforeValidator:due};function uue(e){let t=Ns.object({schema:Ns.string(),database:Ns.string(),table:Ns.string().required(),from:Ns.date().timestamp(),to:Ns.date().timestamp(),limit:Ns.number().min(1)});return ZG.validateBySchema(e,t)}a(uue,"readTransactionLogValidator");function due(e){let t=Ns.object({schema:Ns.string(),database:Ns.string(),table:Ns.string().required(),timestamp:Ns.date().timestamp().required()});return ZG.validateBySchema(e,t)}a(due,"deleteTransactionLogsBeforeValidator")});var yS=y((lPe,oq)=>{"use strict";var rN=M(),nE=nr(),tq=ee(),rq=te(),nq=lo(),sq=V(),{handleHDBError:AS,hdb_errors:_ue}=ce(),{HTTP_STATUS_CODES:bS}=_ue,{readTransactionLogValidator:fue,deleteTransactionLogsBeforeValidator:Eue}=tN(),iq=Hn(),hue="Logs successfully deleted from transaction log.",pue="All logs successfully deleted from transaction log.";oq.exports={readTransactionLog:mue,deleteTransactionLogsBefore:Tue};async function mue(e){let t=fue(e);if(t)throw AS(t,t.message,bS.BAD_REQUEST,void 0,void 0,!0);e.database=e.database??e.schema??"data";let r=tq.checkSchemaTableExist(e.database,e.table);if(r)throw AS(new Error,r,bS.NOT_FOUND,void 0,void 0,!0);return rq.get(rN.CONFIG_PARAMS.CLUSTERING_ENABLED)?await Sue(e):(sq.info("Reading HarperDB logs used by Plexus"),(e.from||e.to)&&(e.search_type="timestamp",e.search_values=[e.from??0],e.to&&(e.search_values[1]=e.to)),iq.readAuditLog(e))}a(mue,"readTransactionLog");async function*Sue(e){let t=nq.createNatsTableStreamName(e.database,e.table),r=await nE.viewStreamIterator(t,parseInt(e.from),e.limit);for await(let n of r){let s=Math.floor(n?.nats_timestamp/1e6);if(e.to&&s>e.to)break;let i={operation:n?.entry?.operation,user:n?.entry?.__origin?.user,timestamp:s,records:n?.entry?.records,attributes:n?.entry?.attributes};n?.entry?.operation===rN.OPERATIONS_ENUM.DELETE&&(i.hash_values=n?.entry?.hash_values),yield i}}a(Sue,"readTransactionLogNats");async function Tue(e){let t=Eue(e);if(t)throw AS(t,t.message,bS.BAD_REQUEST,void 0,void 0,!0);if(e.database=e.database??e.schema??"data",!rq.get(rN.CONFIG_PARAMS.CLUSTERING_ENABLED))return sq.info("Delete transaction logs called for Plexus"),iq.deleteAuditLogsBefore(e);let{database:r,table:n,timestamp:s}=e,i=tq.checkSchemaTableExist(r,n);if(i)throw AS(new Error,i,bS.NOT_FOUND,void 0,void 0,!0);let o=nq.createNatsTableStreamName(r,n),{jsm:c}=await nE.getNATSReferences(),l=await nE.getStreamInfo(o),d=new Date(l.state.first_ts).getTime();if(s<=d)return`No transactions exist before: ${s}`;let u=hue,_,E=new Date(l.state.last_ts).getTime();return s>E?(_=l.state.last_seq+1,u=pue):_=(await nE.viewStream(o,parseInt(s),1))[0].nats_sequence,await nE.purgeTableStream(r,n,{seq:_}),u}a(Tue,"deleteTransactionLogsBefore")});var cq=y((dPe,aq)=>{"use strict";var nN=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}};aq.exports=nN});var uq=y((fPe,lq)=>{"use strict";var sN=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};lq.exports=sN});var oN=y((hPe,_q)=>{"use strict";var dq=cq(),gue=uq(),{HDB_ERROR_MSGS:Rue}=Ln(),iN=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Rue.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 dq(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new gue(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new dq(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}};_q.exports=iN});var wS=y((TPe,Cq)=>{"use strict";var aN=un(),OS=jr(),ws=gm(),oE=uo(),cN=mc(),Aue=Ay(),bue=hx(),aE=_n(),NS=ym(),pr=V(),yue=My(),Oue=Pf(),Nue=fO(),Iue=km(),wue=pO(),Cue=mO(),Due=$m(),Pue=Ym(),lN=Km(),Do=ee(),Lue=mk(),uN=jm(),hq=Ca(),Is=M(),pq=AG(),Mue=To(),mq=Of(),Sq=(fS(),ne(Jf)),Tq=yt(),ir=eN(),Uue=require("alasql"),gq=yS(),Rq=TS(),cE=Ss(),Aq=(Wc(),ne(Kc)),bq=oN(),{handleHDBError:On,hdb_errors:yq}=ce(),{addNodeBack:mPe,removeNodeBack:SPe}=(Wc(),ne(Kc)),{HDB_ERROR_MSGS:vr,HTTP_STATUS_CODES:sE}=yq,W=new Map,Oq="delete",Pa="insert",Po="read",nl="update",iE="describe",fq=oE.describeSchema.name,Eq=oE.describeTable.name,Nq={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},vue="catchup",Bue="handleGetJob",Hue="handleGetJobsByStartDate",IS={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},xue=[ws.createTable.name,ws.createAttribute.name,ws.dropTable.name,ws.dropAttribute.name],Iq={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},J=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};W.set(aN.insert.name,new J(!1,[Pa]));W.set(aN.update.name,new J(!1,[nl]));W.set(aN.upsert.name,new J(!1,[Pa,nl]));W.set(OS.searchByConditions.name,new J(!1,[Po]));W.set(OS.searchByHash.name,new J(!1,[Po]));W.set(OS.searchByValue.name,new J(!1,[Po]));W.set(OS.search.name,new J(!1,[Po]));W.set(ws.createSchema.name,new J(!0,[]));W.set(ws.createTable.name,new J(!0,[]));W.set(ws.createAttribute.name,new J(!1,[Pa]));W.set(ws.dropSchema.name,new J(!0,[]));W.set(ws.dropTable.name,new J(!0,[]));W.set(ws.dropAttribute.name,new J(!0,[]));W.set(oE.describeSchema.name,new J(!1,[Po]));W.set(oE.describeTable.name,new J(!1,[Po]));W.set(cN.deleteRecord.name,new J(!1,[Oq]));W.set(aE.addUser.name,new J(!0,[]));W.set(aE.alterUser.name,new J(!0,[]));W.set(aE.dropUser.name,new J(!0,[]));W.set(aE.listUsersExternal.name,new J(!0,[]));W.set(NS.listRoles.name,new J(!0,[]));W.set(NS.addRole.name,new J(!0,[]));W.set(NS.alterRole.name,new J(!0,[]));W.set(NS.dropRole.name,new J(!0,[]));W.set(yue.name,new J(!0,[]));W.set(Oue.name,new J(!0,[]));W.set(Nue.name,new J(!0,[]));W.set(Iue.name,new J(!0,[]));W.set(wue.name,new J(!0,[]));W.set(Cue.name,new J(!0,[]));W.set(lN.setRoutes.name,new J(!0,[]));W.set(lN.getRoutes.name,new J(!0,[]));W.set(lN.deleteRoutes.name,new J(!0,[]));W.set(Tq.setConfiguration.name,new J(!0,[]));W.set(Due.clusterStatus.name,new J(!0,[]));W.set(Pue.name,new J(!0,[]));W.set(uN.getFingerprint.name,new J(!0,[]));W.set(uN.setLicense.name,new J(!0,[]));W.set(cN.deleteFilesBefore.name,new J(!0,[]));W.set(cN.deleteAuditLogsBefore.name,new J(!0,[]));W.set(hq.restart.name,new J(!0,[]));W.set(hq.restartService.name,new J(!0,[]));W.set(Aue.name,new J(!0,[]));W.set(bue.name,new J(!0,[Po]));W.set(Mue.systemInformation.name,new J(!0,[]));W.set(Tq.getConfiguration.name,new J(!0,[]));W.set(gq.readTransactionLog.name,new J(!0,[]));W.set(gq.deleteTransactionLogsBefore.name,new J(!0,[]));W.set(Rq.installModules.name,new J(!0,[]));W.set(Rq.auditModules.name,new J(!0,[]));W.set(cE.createCsr.name,new J(!0,[]));W.set(cE.signCertificate.name,new J(!0,[]));W.set(cE.listCertificates.name,new J(!0,[]));W.set(cE.addCertificate.name,new J(!0,[]));W.set(cE.removeCertificate.name,new J(!0,[]));W.set(Aq.addNodeBack.name,new J(!0,[]));W.set(Aq.removeNodeBack.name,new J(!0,[]));W.set(mq.createTokens.name,new J(!1,[]));W.set(mq.refreshOperationToken.name,new J(!1,[]));W.set(Sq.login.name,new J(!1,[]));W.set(Sq.logout.name,new J(!1,[]));W.set(ir.customFunctionsStatus.name,new J(!0,[]));W.set(ir.getCustomFunctions.name,new J(!0,[]));W.set(ir.getComponents.name,new J(!0,[]));W.set(ir.getComponentFile.name,new J(!0,[]));W.set(ir.setComponentFile.name,new J(!0,[]));W.set(ir.dropComponent.name,new J(!0,[]));W.set(ir.getCustomFunction.name,new J(!0,[]));W.set(ir.setCustomFunction.name,new J(!0,[]));W.set(ir.dropCustomFunction.name,new J(!0,[]));W.set(ir.addComponent.name,new J(!0,[]));W.set(ir.dropCustomFunctionProject.name,new J(!0,[]));W.set(ir.packageComponent.name,new J(!0,[]));W.set(ir.deployComponent.name,new J(!0,[]));W.set(ir.addSSHKey.name,new J(!0,[]));W.set(ir.updateSSHKey.name,new J(!0,[]));W.set(ir.deleteSSHKey.name,new J(!0,[]));W.set(ir.listSSHKeys.name,new J(!0,[]));W.set(ir.setSSHKnownHosts.name,new J(!0,[]));W.set(ir.getSSHKnownHosts.name,new J(!0,[]));W.set(uN.getRegistrationInfo.name,new J(!1,[]));W.set(aE.userInfo.name,new J(!1,[]));W.set(oE.describeAll.name,new J(!1,[]));W.set(Bue,new J(!1,[]));W.set(Hue,new J(!0,[]));W.set(vue,new J(!0,[]));W.set(IS.CSV_DATA_LOAD,new J(!1,[Pa,nl]));W.set(IS.CSV_URL_LOAD,new J(!1,[Pa,nl]));W.set(IS.CSV_FILE_LOAD,new J(!1,[Pa,nl]));W.set(IS.IMPORT_FROM_S3,new J(!1,[Pa,nl]));W.set(Iq.EXPORT_TO_S3,new J(!0,[]));W.set(Iq.EXPORT_LOCAL,new J(!0,[]));W.set(Is.VALID_SQL_OPS_ENUM.DELETE,new J(!1,[Oq]));W.set(Is.VALID_SQL_OPS_ENUM.SELECT,new J(!1,[Po]));W.set(Is.VALID_SQL_OPS_ENUM.INSERT,new J(!1,[Pa]));W.set(Is.VALID_SQL_OPS_ENUM.UPDATE,new J(!1,[nl]));Cq.exports={verifyPerms:kue,verifyPermsAst:Fue,verifyBulkLoadAttributePerms:que};function Fue(e,t,r){if(Do.isEmptyOrZeroLength(e))throw pr.info("verify_perms_ast has an empty user parameter"),On(new Error);if(Do.isEmptyOrZeroLength(t))throw pr.info("verify_perms_ast has an empty user parameter"),On(new Error);if(Do.isEmptyOrZeroLength(r))throw pr.info("verify_perms_ast has a null operation parameter"),On(new Error);try{let n=new bq,s=new Lue(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw pr.info("No schemas defined in verifyPermsAst(), will not continue."),On(new Error);let c=!!t.role.permission.super_user,l=i.includes("system");if(l&&Nq[r])throw On(new Error,vr.DROP_SYSTEM,sE.FORBIDDEN);if(c&&!l)return null;let d=pq.getRolePermissions(t.role);t.role.permission=d,!c&&e instanceof Uue.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(d));for(let _=0;_<i.length;_++){let E=s.getTablesBySchemaName(i[_]);E&&o.set(i[_],E)}let u=wq(t,r,o,n);return u||(o.forEach((_,E)=>{for(let f=0;f<_.length;f++){let h=s.getAttributesBySchemaTableName(E,_[f]),S=_N(t.role.permission,E,_[f]);dN(h,S,r,_[f],E,n)}}),n.getPermsResponse())}catch(n){throw On(n)}}a(Fue,"verifyPermsAst");function kue(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw pr.info("null required parameter in verifyPerms"),On(new Error,vr.DEFAULT_INVALID_REQUEST,sE.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 bq;if(Do.isEmptyOrZeroLength(e.hdb_user.role)||Do.isEmptyOrZeroLength(e.hdb_user.role.permission))return pr.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(vr.USER_HAS_NO_PERMS(e.hdb_user.username));let l=!!e.hdb_user.role.permission.super_user,d=e.hdb_user.role.permission.structure_user,u=o.has(Is.SYSTEM_SCHEMA_NAME)||s===Is.SYSTEM_SCHEMA_NAME;if(u&&Nq[r])throw On(new Error,vr.DROP_SYSTEM,sE.FORBIDDEN);if(l&&!u||d===!0&&(r===ws.createSchema.name||r===ws.dropSchema.name))return null;if(xue.indexOf(r)>=0&&(d===!0||Array.isArray(d)))return d===!0||d.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let _=pq.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=_,r===fq||r===Eq){if(s===Is.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(vr.SCHEMA_PERM_ERROR(s));if(!_.super_user){if(r===fq&&(!_[s]||!_[s][iE]))return c.handleInvalidItem(vr.SCHEMA_NOT_FOUND(s));if(r===Eq&&(!_[s]||!_[s].tables[i]||!_[s].tables[i][iE]))return c.handleInvalidItem(vr.TABLE_NOT_FOUND(s,i))}}let E=wq(e.hdb_user,r,o,c,n);if(E)return E;if(W.get(r)&&W.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&Is.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let S=[],T=_[s].tables[i];T[Is.PERMS_CRUD_ENUM.READ]&&(T.attribute_permissions.length>0?T.attribute_permissions.filter(m=>m[Is.PERMS_CRUD_ENUM.READ]).forEach(m=>{S.push(m.attribute_name)}):S=global.hdb_schema[s][i].attributes.map(g=>g.attribute),e.get_attributes=S)}let f=Gue(e),h=_N(e.hdb_user.role.permission,s,i);return dN(f,h,r,i,s,c,n),c.getPermsResponse()}a(kue,"verifyPerms");function wq(e,t,r,n,s){if(Do.arrayHasEmptyValues([e,t,r]))throw pr.info("hasPermissions has an invalid parameter"),On(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||W.get(t).requires_su))return null;if(!W.get(t))throw pr.info(`operation ${t} not found.`),On(new Error,vr.OP_NOT_FOUND(t),sE.BAD_REQUEST);if(W.get(t)&&W.get(t).requires_su)return pr.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(vr.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!o[l]||o[l][iE]===!1){n.addInvalidItem(vr.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(vr.SCHEMA_NOT_FOUND(l));continue}let d=r.get(l);for(let u of d){let _=o[l].tables[u];if(!_||_[iE]===!1)n.addInvalidItem(vr.TABLE_NOT_FOUND(l,u));else try{let E=[],f=W.get(t).perms;!Do.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let S=f[h],T=_[S];(T==null||T===!1)&&(pr.info(`Required ${S} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(S))}E.length>0&&n.addUnauthorizedTable(l,u,E)}catch(E){let f=vr.UNKNOWN_OP_AUTH_ERROR(t,l,u);throw pr.error(f),pr.error(E),On(yq.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(wq,"hasPermissions");function dN(e,t,r,n,s,i,o){if(!e||!t)throw pr.info("no attributes specified in checkAttributePerms."),On(new Error);let c=W.get(r).perms;if(!c||c==="")throw pr.info(`no permissions found for ${r} in checkAttributePerms().`),On(new Error);if(Do.isEmptyOrZeroLength(t))return pr.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let l={};for(let u of e){let _=t.get(u);if(_){if(_[iE]===!1){i.addInvalidItem(vr.ATTR_NOT_FOUND(s,n,u),s,n);continue}if(c)for(let E of c){if(Is.TIME_STAMP_NAMES.includes(_.attribute_name)&&E!==Po)throw On(new Error,vr.SYSTEM_TIMESTAMP_PERMS_ERR,sE.FORBIDDEN);_[E]===!1&&(l[_.attribute_name]?l[_.attribute_name].push(E):l[_.attribute_name]=[E])}}else i.addInvalidItem(vr.ATTR_NOT_FOUND(s,n,u),s,n)}let d=Object.keys(l);d.length>0&&i.addUnauthorizedAttributes(d,s,n,l)}a(dN,"checkAttributePerms");function Gue(e){let t=new Set;try{if(e.action)return t;if(e.operation===Is.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){pr.info(r)}return t}a(Gue,"getRecordAttributes");function _N(e,t,r){let n=new Map;if(Do.isEmpty(e))return pr.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{pr.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(_N,"getAttributePermissions");function que(e,t,r,n,s,i,o){let c=new Set(i),l=_N(e,n,s);dN(c,l,t,s,n,o,r)}a(que,"verifyBulkLoadAttributePerms")});var DS=y((RPe,Uq)=>{"use strict";Uq.exports={evaluateSQL:tde,processAST:Mq,convertSQLToAST:Lq,checkASTPermissions:Pq};var $ue=un(),Dq=require("util"),Vue=Dq.callbackify($ue.insert),Yue=jr().search,Kue=M0().update,Wue=Dq.callbackify(Kue),jue=v0().convertDelete,La=require("alasql"),Que=wS(),CS=V(),zue=Bp(),Jue=ee(),lE=M(),{hdb_errors:Xue,handleHDBError:fN}=ce(),{HTTP_STATUS_CODES:EN}=Xue;zue(La);var Zue=403,ede="There was a problem performing this insert. Please check the logs and try again.",hN=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function tde(e,t){let r=e.parsed_sql_object;if(!r){r=Lq(e.sql);let n,s=r.ast.statements[0];if(s instanceof La.yy.Insert?n=s.into.databaseid:s instanceof La.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof La.yy.Update||s instanceof La.yy.Delete?n=s.table.databaseid:CS.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof La.yy.Select)&&Jue.isEmptyOrZeroLength(n))return t("No schema specified",null)}Mq(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(tde,"evaluateSQL");function Pq(e,t){let r;try{r=Que.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Pq,"checkASTPermissions");function Lq(e){let t=new hN;if(!e)throw fN(new Error,"The 'sql' parameter is missing from the request body",EN.BAD_REQUEST);try{let r=e.trim(),n=La.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
30
+ `);throw n[1]?fN(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,EN.BAD_REQUEST):fN(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",EN.BAD_REQUEST)}return t}a(Lq,"convertSQLToAST");function Mq(e,t,r){try{let n=rde;if(!e.bypass_auth&&!t.permissions_checked){let i=Pq(e,t);if(i&&i.length>0)return r(Zue,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case lE.VALID_SQL_OPS_ENUM.SELECT:n=Yue,s=t.ast.statements[0];break;case lE.VALID_SQL_OPS_ENUM.INSERT:n=nde;break;case lE.VALID_SQL_OPS_ENUM.UPDATE:n=Wue;break;case lE.VALID_SQL_OPS_ENUM.DELETE:n=jue;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(Mq,"processAST");function rde(e,t){CS.info(e),t("unknown sql statement")}a(rde,"nullFunction");function nde({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=sde(i,e.values)}catch(o){return r(o)}Vue(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(l){CS.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}a(nde,"convertInsert");function sde(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]]=La.compile(`SELECT ${s.toString()} AS [${lE.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw CS.error(r),new Error(ede)}}a(sde,"createDataObjects")});var pN=y((bPe,Bq)=>{"use strict";var{S3:ide,GetObjectCommand:ode}=require("@aws-sdk/client-s3");Bq.exports={getFileStreamFromS3:ade,getS3AuthObj:vq};async function ade(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await vq(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new ode(r))).Body}a(ade,"getFileStreamFromS3");function vq(e,t,r){return new ide({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(vq,"getS3AuthObj")});var PS=y((OPe,Yq)=>{"use strict";var SN=jr(),cde=DS(),lde=pN(),{AsyncParser:ude,Transform:dde}=require("json2csv"),dE=require("stream"),jn=ee(),mN=require("fs-extra"),_de=require("path"),Cs=V(),{promisify:Fq}=require("util"),uE=ee(),{handleHDBError:or,hdb_errors:fde}=ce(),{HDB_ERROR_MSGS:Nn,HTTP_STATUS_CODES:ar}=fde,{streamAsJSON:Ede}=(lR(),ne(KD)),{Upload:hde}=require("@aws-sdk/lib-storage"),Hq=["search_by_value","search_by_hash","sql","search_by_conditions"],xq=["json","csv"],kq="json",Gq="csv",pde="Successfully exported JSON locally.",mde="Successfully exported CSV locally.",Sde=1e3,Tde=SN.searchByHash,gde=SN.searchByValue,Rde=Fq(cde.evaluateSQL),Ade=Fq(dE.finished);Yq.exports={export_to_s3:Nde,export_local:bde,toCsvStream:qq};async function bde(e){Cs.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=$q(e);if(!jn.isEmpty(t))throw Cs.error(t),or(new Error,t,ar.BAD_REQUEST,void 0,void 0,!0);if(jn.isEmpty(e.path))throw Cs.error(Nn.MISSING_VALUE("path")),or(new Error,Nn.MISSING_VALUE("path"),ar.BAD_REQUEST,void 0,void 0,!0);let r=(jn.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(_de.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=jn.buildFolderPath(e.path,r);await yde(e.path);let s=await Vq(e);return await Ode(n,e.format,s)}a(bde,"export_local");async function yde(e){if(Cs.trace("in confirmPath"),jn.isEmptyOrZeroLength(e))throw or(new Error,`Invalid path: ${e}`,ar.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await mN.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,Cs.error(n),or(new Error,n,ar.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 Cs.error(r),or(new Error,r,ar.BAD_REQUEST,void 0,void 0,!0)}return!0}a(yde,"confirmPath");async function Ode(e,t,r){if(Cs.trace("in saveToLocal"),uE.isEmptyOrZeroLength(e))throw or(new Error,Nn.INVALID_VALUE("file_path"),ar.BAD_REQUEST,void 0,void 0,!0);if(uE.isEmptyOrZeroLength(t))throw or(new Error,Nn.INVALID_VALUE("Source format"),ar.BAD_REQUEST,void 0,void 0,!0);if(uE.isEmpty(r))throw or(new Error,Nn.NOT_FOUND("Data"),ar.BAD_REQUEST,void 0,void 0,!0);if(t===kq){let n=mN.createWriteStream(e);return Ede(r).pipe(n),await Ade(n),{message:pde,path:e}}else if(t===Gq){let n=mN.createWriteStream(e),s=dE.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(u=>({label:u,value:u})));let c={objectMode:!0};return await new ude(i,c).fromInput(s).toOutput(n).promise(!1),{message:mde,path:e}}throw or(new Error,Nn.INVALID_VALUE("format"),ar.BAD_REQUEST)}a(Ode,"saveToLocal");async function Nde(e){if(!e.s3||Object.keys(e.s3).length===0)throw or(new Error,Nn.MISSING_VALUE("S3 object"),ar.BAD_REQUEST);if(jn.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw or(new Error,Nn.MISSING_VALUE("aws_access_key_id"),ar.BAD_REQUEST);if(jn.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw or(new Error,Nn.MISSING_VALUE("aws_secret_access_key"),ar.BAD_REQUEST);if(jn.isEmptyOrZeroLength(e.s3.bucket))throw or(new Error,Nn.MISSING_VALUE("bucket"),ar.BAD_REQUEST);if(jn.isEmptyOrZeroLength(e.s3.key))throw or(new Error,Nn.MISSING_VALUE("key"),ar.BAD_REQUEST);if(jn.isEmptyOrZeroLength(e.s3.region))throw or(new Error,Nn.MISSING_VALUE("region"),ar.BAD_REQUEST);let t=$q(e);if(!jn.isEmpty(t))throw or(new Error,t,ar.BAD_REQUEST);Cs.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await Vq(e)}catch(l){throw Cs.error(l),l}let n,s=await lde.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new dE.PassThrough;if(e.format===Gq){i=e.s3.key+".csv";let l=qq(r,r.getColumns?.());l.on("error",d=>{throw d}),l.pipe(o)}else if(e.format===kq){i=e.s3.key+".json";let l=new dE.Readable;l.pipe(o),l.on("error",_=>{throw _}),l.push("[");let d=r.length,u="";for(let[_,E]of r.entries()){let f=_===d-1?JSON.stringify(E):JSON.stringify(E)+",";u+=f,_!==0&&_%Sde===0&&(l.push(u),u="")}u.length!==0&&l.push(u),l.push("]"),l.push(null)}else throw or(new Error,Nn.INVALID_VALUE("format"),ar.BAD_REQUEST);return new hde({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Nde,"export_to_s3");function qq(e,t){let r=dE.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 dde(n,s);return r.pipe(i)}a(qq,"toCsvStream");function $q(e){if(Cs.trace("in exportCoreValidation"),jn.isEmpty(e.format))return"format missing";if(xq.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${xq.join(", ")}`;let t=e.search_operation.operation;if(jn.isEmpty(t))return"search_operation.operation missing";if(Hq.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Hq.join(", ")}`}a($q,"exportCoreValidation");async function Vq(e){Cs.trace("in getRecords");let t,r;if(uE.isEmpty(e.search_operation)||uE.isEmptyOrZeroLength(e.search_operation.operation))throw or(new Error,Nn.INVALID_VALUE("Search operation"),ar.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=gde;break;case"search_by_hash":t=Tde;break;case"search_by_conditions":t=SN.searchByConditions;break;case"sql":t=Rde;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Cs.error(r),or(new Error,r,ar.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(Vq,"getRecords")});var t$={};tt(t$,{contentTypes:()=>AN,findBestSerializer:()=>US,getDeserializer:()=>il,registerContentHandlers:()=>bN,serialize:()=>EE,serializeMessage:()=>el});function Ide(e){try{return e?.[0]===123?RN(e):e}catch{return e}}function bN(e){e.register(Cde,{serializers:[{regex:/^application\/json$/,serializer:c_},{regex:/^application\/cbor$/,serializer:function(t){return new sl.EncoderStream(fE).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?MS.Readable.from((0,Hi.encodeIter)(t,fE)):(0,Hi.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,LS.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Hi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,sl.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function US(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[d,...u]=l.split(/\s*;\s*/),_=1,E={q:1};for(let h of u){let S=h.indexOf("=");E[h.substring(0,S)]=h.substring(S+1)}_=+E.q;let f=Or.get(d);if(f){let h=(f.q||1)*_;h>s&&(n=f,i=f.type||d,s=h,o=E)}}if(!n){if(r)throw new Qq.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Or.keys()).join(", "),406);n=Or.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function EE(e,t,r){let n=Wq&&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=US(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&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),Xq.default.warn?.(`Error serializing error ${t?.url||t}: ${l}`),l)),e.getColumns=c}let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Lo.createBrotliCompress)({params:{[Lo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Lo.constants.BROTLI_MODE_TEXT:Lo.constants.BROTLI_MODE_GENERIC,[Lo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>Wq?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Lo.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function el(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return _E(e);let r=t.serialize;if(r)return r(e);let n=US(t);return r=t.serialize=n.serializer.serialize,r(e)}function Dde(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 il(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Or.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Or.get(e)?.deserialize||jq(e,n);return o=>Dde(o).then(i)}return e&&Or.get(e)?.deserialize||jq(e,n)}function jq(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 RN(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Pde(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 LS,Hi,sl,Lo,Qq,MS,zq,TN,gN,Jq,Xq,Zq,_E,RN,fE,Or,AN,Kq,e$,wde,Cde,Wq,Ju=Ce(()=>{lR();LS=B(PS()),Hi=require("msgpackr"),sl=require("cbor-x"),Lo=require("zlib"),Qq=B(ce()),MS=require("stream");Wr();zq=B(no()),TN=B(te()),gN=B(M()),Jq=B(require("yaml")),Xq=B(du()),Zq=TN.default.get(gN.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,_E=Zq?oc:JSON.stringify,RN=Zq?cR:JSON.parse,fE={useRecords:!1,useToJSON:!0},Or=new Map,AN=Or;nt.contentTypes=AN;(0,zq._assignPackageExport)("contentTypes",AN);Or.set("application/json",{serializeStream:c_,serialize:_E,deserialize(e){return RN(e)},q:.8});Kq=new sl.Encoder(fE);Or.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new sl.EncoderStream(fE).end(e)},serialize:Kq.encode,deserialize:Kq.decode,q:1});Or.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?MS.Readable.from((0,Hi.encodeIter)(e,fE)):(0,Hi.pack)(e)},serialize:Hi.pack,deserialize:Hi.unpack,q:.9});Or.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,LS.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,LS.toCsvStream)(e,e?.getColumns?.())},q:.1});Or.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Or.set("text/yaml",{serialize(e){return Jq.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Or.set("text/event-stream",{serializeStream:function(e){return MS.Readable.from(Pde(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+`
31
+ `),e.data){let r=e.data;typeof r=="object"&&(r=_E(r)),t+="data: "+r+`
22
32
  `}return e.id&&(t+="id: "+e.id+`
23
33
  `),e.retry&&(t+="retry: "+e.retry+`
24
34
  `),t+`
25
- `}else return typeof e=="object"?`data: ${V_(e)}
35
+ `}else return typeof e=="object"?`data: ${_E(e)}
26
36
 
27
37
  `:`data: ${e}
28
38
 
29
- `},compressible:!1,q:.8});Jt.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()}});hG={type:"application/json",serializeStream:nu,serialize:V_,deserialize:Mie,q:.5};Jt.set("*/*",hG);Jt.set("",hG);a(Mie,"tryJSONParse");a(_O,"registerContentHandlers");Uie=require("fastify-plugin"),vie=Uie(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=jh(n.raw);s.type(c),s.serializer(function(l){return(o.serializeStream||o.serialize)(l,{headers:{set:(_,u)=>{s.header(_,u)}}})})}),r()},{name:"content-type-negotiation"});a(jh,"findBestSerializer");lG=aO.default.get(cO.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(zh,"serialize");a(Pa,"serializeMessage");a(Bie,"streamToBuffer");a(Ba,"getDeserializer");a(uG,"deserializerUnknownType");a(Hie,"transformIterable")});function EO(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=_(l);for(let f=1;f<e.length;f++){let h=e[f],m=_(h);d=d.concat(m)}let E=new Set;return d.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let d=_(l),E=u(e.slice(1),!0,l.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?EO(d.conditions,d.operator,r,n,s,i,o,c):sl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function u(d,E,f){return d.map((h,m)=>{if(h.conditions){let T=h.operator==="or",b=u(h.conditions,!T,f);return T?(N,v)=>b.some(U=>U(N,v)):(N,v)=>b.every(U=>U(N,v))}let S=(h.attribute||h[0])===r.primaryKey,g=W_(h,r,i,c,S,f);return E&&m<d.length-1&&f&&(f=Kie(r.primaryStore,h.estimated_count,f)),g}).filter(Boolean)}a(u,"mapConditionsToFilters")}function sl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(Array.isArray(o)){let T=o[0],b=Mi(n.attributes,T);if(b.relationship){if(o.length<2)throw new Sn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let N=b.definition?.tableClass||b.elements?.definition?.tableClass,v=new Map,U=sl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,N,s,v);if(b.relationship.to){i[o[0]]=v;let F=!!Mi(N.attributes,b.relationship.to)?.elements;U=kie(U,b,N.primaryStore,F,v)}if(b.relationship.from){let F=a(M=>sl({attribute:b.relationship.from,value:M},t,r,n,s,v),"searchEntry");b.elements?(i[o[0]]=v,U=Vie(U,b,N.primaryStore,v,F)):U=U.flatMap(F)}return U}else if(o.length===1)o=o[0];else throw new Sn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,u,d,E;c instanceof Date&&(c=c.getTime());let f;switch(hO[l]||l){case"lt":_=!0,u=c;break;case"le":_=!0,u=c,d=!0;break;case"gt":_=c,E=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,u=c.slice(0),u[u.length-1]=Ys.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),u=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),u=c[1],u instanceof Date&&(u=u.getTime()),d=!0;break;case"equals":case void 0:_=c,u=c,d=!0;break;case"ne":if(c===null){_=c,E=!0;break}case"sort":case"contains":case"ends_with":_=!0,f=!0;break;default:throw new Sn.ClientError(`Unknown query comparator "${l}"`)}let h,m=o===n.primaryKey||o==null;if(typeof _=="string"&&_.length>$n.MAX_SEARCH_KEY_LENGTH&&(_=_.slice(0,$n.MAX_SEARCH_KEY_LENGTH)+$n.OVERFLOW_MARKER,E=!1,h=W_(e,n,null,i,m)),typeof u=="string"&&u.length>$n.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,$n.MAX_SEARCH_KEY_LENGTH)+$n.OVERFLOW_MARKER,d=!0,h=h??W_(e,n,null,i,m)),r){let T=_;_=u,u=T,T=!E,E=!d,d=T}let S=m?n.primaryStore:n.indices[o];if(!S||S.isIndexing||f||c===null&&!S.indexNulls){if(s===!1&&!S)throw new Sn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Sn.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(S?.isIndexing)throw new Sn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!S.indexNulls)throw new Sn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(h=h??W_(e,n,null,i,m),!h)throw new Sn.ClientError(`Unknown search operator ${e.comparator}`)}let g={start:_,end:u,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:m,transaction:t,reverse:r};if(m){let T=S.getRange(g).map(h?function({key:b,value:N}){return this.isSync?N&&h(N)?b:Co.SKIP:new Promise((v,U)=>setImmediate(()=>{try{v(N&&h(N)?b:Co.SKIP)}catch(F){U(F)}}))}:b=>b.value==null?Co.SKIP:b);return T.hasEntries=!0,T}else return S?S.getRange(g).map(h?function({key:T,value:b}){let N;return typeof T=="string"&&T.length>$n.MAX_SEARCH_KEY_LENGTH?N=n.primaryStore.get(b):N={[o]:T},this.isSync?h(N)?b:Co.SKIP:new Promise((v,U)=>setImmediate(()=>{try{v(h(N)?b:Co.SKIP)}catch(F){U(F)}}))}:({value:T})=>T):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:T,value:b}){return this.isSync?b&&h(b)?T:Co.SKIP:new Promise((N,v)=>setImmediate(()=>{try{N(b&&h(b)?T:Co.SKIP)}catch(U){v(U)}}))})}function Mi(e,t){if(Array.isArray(t))if(t.length>1){let r=Mi(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Mi(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 kie(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let l=t.relationship.to,_=a((u,d)=>{let E=u;Array.isArray(u)&&(E=Es(u),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),u!==E&&(f.key=u)},"add_entry");for(let u of e){let d=u.value??r.get(u.key??u),E=d?.[l];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],u);else _(E,u)}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 Vie(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let _=Es(l.value);if(!c.has(_))return c.add(_),l}if(!i){let _=new Map;n.fromRecord=u=>u[t.relationship.from]?.filter?.(d=>_.has(Es(d)));for(let u of e){if(n.filters){let d=r.get(u);if(n.filters.some(E=>!E(d)))continue}_.set(Es(u),u)}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 W_(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=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 u=c[0],d=Mi(t.attributes,u),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[u],h=W_({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},E,r,f?.[u]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let m=t.propertyResolvers?.[u],S,g=a((T,b)=>{let N,v;if(m){if(m.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let F of h.idFilter.idSet)e={attribute:m.from,value:F};S=_(m.from,h.idFilter,!0,!0)}else S=_(m.from,h.idFilter,!1,!0);let U=S(T);return S.idFilter&&(g.idFilter=S.idFilter),U}v=m(T,r,b),N=v?.value}else N=T[u];return N?Array.isArray(N)?N.some(h):h(N,v):!1},"recordFilter");return g}}switch(l instanceof Date&&(l=l.getTime()),hO[o]||o){case $n.SEARCH_TYPES.EQUALS:case void 0:return _(c,u=>u===l,!0);case"contains":return _(c,u=>u?.toString().includes(l));case"ends_with":return _(c,u=>u?.toString().endsWith(l));case"starts_with":return _(c,u=>typeof u=="string"&&u.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],_(c,u=>{if(!Array.isArray(u))return!1;for(let d=0,E=l.length;d<E;d++)if(u[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),_(c,u=>(0,Ys.compareKeys)(u,l[0])>=0&&(0,Ys.compareKeys)(u,l[1])<=0,!0);case"gt":return _(c,u=>(0,Ys.compareKeys)(u,l)>0);case"ge":return _(c,u=>(0,Ys.compareKeys)(u,l)>=0);case"lt":return _(c,u=>(0,Ys.compareKeys)(u,l)<0);case"le":return _(c,u=>(0,Ys.compareKeys)(u,l)<=0);case"ne":return _(c,u=>(0,Ys.compareKeys)(u,l)!==0);case"sort":return()=>!0;default:throw new Sn.ClientError(`Unknown query comparator "${o}"`)}function _(u,d,E,f){let h;E=E&&!s&&t?.indices[u]&&i>3,E&&(e.estimated_count==null&&Xh(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let m=0,S=3;function g(T){let b=T[u],N;if(typeof b!="object"||!b||f?N=d(b):Array.isArray(b)?N=b.some(d):b instanceof Date&&(N=d(b.getTime())),E&&(S++,!N&&!g.idFilter&&++m/S*(i-S)>h)){let v=sl(e,r.transaction.getReadTxn(),!1,t).map(Es),U=new Set(v);g.idFilter=F=>U.has(Es(F)),g.idFilter.idSet=U}return N}return a(g,"recordFilter"),s&&(g.idFilter=d),g}a(_,"attributeComparator")}function Xh(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/Pi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=hO[n]||n,n===$n.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=Mi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Xh(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Pi(e.indices[i.relationship.from])/(Pi(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=Pi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=qie*Pi(e.primaryStore)+1:n==="between"?r.estimated_count=xie*Pi(e.primaryStore)+1:n==="sort"?r.estimated_count=Pi(e.primaryStore)+1:r.estimated_count=Gie*Pi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Zh(e){if(e)if(Do=e,rl.lastIndex=0,$ie.test(e))try{let t=Y_(new nl,"");if(Wr!==Do.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 ${Wr} in '${Do}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Y_(e,t){let r=rl,n,s,i,o,c,l=decodeURIComponent,_;for(;n=r.exec(Do);){Wr=r.lastIndex;let[,u,d]=n;if(o){if(u)throw new SyntaxError(`expected operator, but encountered '${u}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(u.length<=2)i=u;else throw new SyntaxError(`invalid FIQL operator ${u}`);l=dO}else{if(l=decodeURIComponent,i="equals",!u)throw new SyntaxError("attribute must be specified before equality comparator");s=K_(u)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Fie[d],l=fO[i]?dO:decodeURIComponent,!u)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=K_(u);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:l(u)};i==="eq"&&mG(h,u),Jh(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(K_(u)),s=void 0;break;case"(":rl.lastIndex=Wr;let f=Y_(u?[]:new nl,")");switch(u){case"":Jh(e,_),e.conditions.push(f);break;case"limit":switch(f.length){case 1:e.limit=+f[0];break;case 2:e.offset=+f[0],e.limit=f[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(f[0])&&f.length===1&&!f[0].name?(e.select=f[0],e.select.asArray=!0):f.length===1?e.select=f[0]:f.length===2&&f[1]===""?e.select=f.slice(0,1):e.select=f;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=SG(f);break;default:throw new SyntaxError(`unknown query function call ${u}`)}Do[Wr]===","?r.lastIndex=++Wr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!u)throw new SyntaxError("property sets must have a defined parent property name");rl.lastIndex=Wr,E=Y_([],"}"),E.name=u,e.push(E),Do[Wr]===","?r.lastIndex=++Wr:o=!0;break;case"[":rl.lastIndex=Wr,u?(E=Y_(new nl,"]"),E.name=u):E=Y_(e.conditions?new nl:[],"]"),e.conditions?(Jh(e,_),e.conditions.push(E),s=null):e.push(E),Do[Wr]===","?r.lastIndex=++Wr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(u)};i==="eq"&&mG(h,u),Jh(e,_),e.conditions.push(h)}else if(u)throw new SyntaxError("no attribute or comparison specified")}else(u||e.length>0&&c)&&e.push(K_(u));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?Yie:rl,r.lastIndex=Wr),Wr===Do.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Jh(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 K_(e){return e.indexOf(".")>-1?e.split(".").map(K_):decodeURIComponent(e)}function dO(e){if(e==="null")return null;if(e.indexOf("/")>-1){let t=e.split("/"),r=new il(t.length);for(let n=0,s=t.length;n<s;n++)r[n]=dO(t[n]);return r}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(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Sn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function mG(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Sn.ClientError("wildcard can only be used at the end of a string")}function SG(e){let t=TG(e[0]);return e.length>1&&(t.next=SG(e.slice(1))),t}function TG(e){if(Array.isArray(e)){let t=TG(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 Es(e){return Array.isArray(e)?e.join("\0"):e}function Pi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function Kie(e,t,r){return t*r/Pi(e)}var Sn,$n,Ys,Co,Gie,xie,qie,Fie,fO,hO,$ie,rl,Yie,Wr,Do,nl,ep=be(()=>{Sn=G(ie()),$n=G(_t()),Ys=require("ordered-binary"),Co=require("lmdb");Mn();Gie=.3,xie=.1,qie=.05,Fie={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},fO={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(EO,"executeConditions");a(sl,"searchByIndex");a(Mi,"findAttribute");a(kie,"joinTo");a(Vie,"joinFrom");hO={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(W_,"filterByType");a(Xh,"estimateCondition");$ie=/[()[\]|!<>.]|(=\w*=)/,rl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Yie=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Zh,"parseQuery");a(Y_,"parseBlock");a(Jh,"assignOperator");a(K_,"decodeProperty");a(dO,"typedDecoding");a(mG,"wildcardDecoding");a(SG,"toSortObject");a(TG,"toSortEntry");nl=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(Es,"flattenKey");a(Pi,"estimatedEntryCount");a(Kie,"intersectionEstimate")});function bG(e){let t={openapi:Wie,info:{title:"HarperDB HTTP REST interface",version:(0,OG.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:l}=n.Resource;if(c=c??"id",!c)continue;let _={},u=[];if(o)for(let{type:b,name:N,elements:v,relationship:U,definition:F}of o){if(U)b==="array"?_[N]={type:"array",items:{$ref:Lo+v.type}}:_[N]={$ref:Lo+b};else{let M=F??v?.definition;if(M){if(!t.components.schemas[M.type]){let W={};M.properties.forEach(z=>{W[z.name]=new TO(pO[z.type],z.type)}),t.components.schemas[M.type]=new AG(W)}b==="array"?_[N]={type:"array",items:{$ref:Lo+M.type}}:_[N]={$ref:Lo+M.type}}else b==="array"?v.type==="Any"||v.type=="ID"?_[N]={type:"array",items:{format:v.type}}:_[N]={type:"array",items:new TO(pO[v.type],v.type)}:b==="Any"||b=="ID"?_[N]={format:b}:_[N]=new TO(pO[b],b)}u.push(new gO(N,"query",_[N]))}let d=Object.keys(_),E=new gO(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new gO("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new AG(_);let h=l.post!==Resource.prototype.post||l.update,m=typeof l.put=="function",S=typeof l.get=="function",g=typeof l.delete=="function",T="/"+s+"/";h&&(t.paths[T]={},t.paths[T].post=new Qie(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[T]||(t.paths[T]={}),t.paths[T].get=new mO(u,r,{200:new SO({$ref:Lo+i})},"search for records by the specified property name and value pairs")),g&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new RG(u,r,"delete all the records that match the provided query",{204:new gG})),T="/"+s+"/{"+c+"}",S&&(t.paths[T]={},t.paths[T].get=new mO([E],r,{200:new SO({$ref:Lo+i})},"retrieve a record by its primary key")),m&&(t.paths[T]||(t.paths[T]={}),t.paths[T].put=new jie([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),g&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new RG([E],r,"delete a record with the given primary key",{204:new gG})),S&&f.schema.enum.length>0&&(T="/"+s+"/{"+c+"}.{property}",t.paths[T]={},t.paths[T].get=new mO([E,f],r,{200:new SO({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function Qie(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Lo+e}}}},this.security=t,this.responses={200:{description:RO,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function mO(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function SO(e){this.description=RO,this.content={"application/json":{schema:e}}}function gG(){this.description="successfully processed request, no content returned to client"}function jie(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Lo+r}}}},this.responses={200:{description:RO}}}function RG(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function AG(e){this.type="object",this.properties=e}function TO(e,t){this.type=e,this.format=t}function gO(e,t,r){this.name=e,this.in=t,this.schema=r}var OG,Wie,pO,Lo,RO,NG=be(()=>{OG=G(Ri()),Wie="3.0.3",pO={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Lo="#/components/schemas/",RO="successful operation";a(bG,"generateJsonApi");a(Qie,"Post");a(mO,"Get");a(SO,"Response200");a(gG,"Response204");a(jie,"Put");a(RG,"Delete");a(AG,"ResourceSchema");a(TO,"Type");a(gO,"Parameter")});var rp={};Ve(rp,{start:()=>Xie});async function Jie(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Zh(e);let s=new yo;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==yG){let h=tp.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let l=r["cache-control"];if(l){l=l.toLowerCase();let h=l.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),l.includes("only-if-cached")&&(e.onlyIfCached=!0),l.includes("no-cache")&&(e.noCache=!0),l.includes("no-store")&&(e.noCacheStore=!0),l.includes("stale-if-error")&&(e.staleIfError=!0),l.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await it(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Ba(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new ol.ClientError(h,400)}if(e.authorize=!0,i===yG&&n==="GET"){if(e?.user?.role?.permission?.super_user)return bG(tp);throw new ol.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 ol.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new ol.ServerError(`Method ${n} is not recognized`,501)}}),u=200,d;if(_==null)u=n==="GET"||n==="HEAD"?404:204,AO.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){zie[0]=d;let h=String.fromCharCode(34,(sr[0]&63)+62,(sr[0]>>6)+(sr[1]<<2&63)+62,(sr[1]>>4)+(sr[2]<<4&63)+62,(sr[2]>>2)+62,(sr[3]&63)+62,(sr[3]>>6)+(sr[4]<<2&63)+62,(sr[4]>>4)+(sr[5]<<4&63)+62,(sr[5]>>2)+62,(sr[6]&63)+62,(sr[6]>>6)+(sr[7]<<2&63)+62,34),m=r["if-none-match"];m&&h==m?(_?.onDone&&_.onDone(),u=304,_=void 0):s.setIfNone("ETag",h),AO.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(u=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:u,headers:s,body:void 0},f=_?.wasLoadedFromSource?.();return f!==void 0&&(E.wasCacheMiss=f,!f&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(E.body=zh(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?Ha.warn(i):Ha.info(i):Ha.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=zh(i.contentType?i:i.toString(),e,o),o}}function Xie(e){AO=e,!IG&&(IG=!0,tp=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Jie(t,r)},e),e.server.ws(async(t,r,n)=>{Q_++;let s=new ts;wG||(wG=!0,Yu(l=>{Q_>0&&l.push({metric:"ws-connections",connections:Q_,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ha.warn(l)});let o;t.on("message",a(function(_){o||(o=Ba(r.requestedContentType??r.headers.asObject["content-type"],!1));let u=o(_);s.push(u)},"message"));let c;t.on("close",()=>{Q_--,fn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),_=tp.getMatch(l);if(fn(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,vr(h=>({count:h.count,total:Q_}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let u={url:_.relativeURL,async:!0},d=_.Resource;c=(await it(r,()=>d.connect(u,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=Pa(f.value,r);t.send(h),vr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){t.close(Zie[l.statusCode]||1011,l.toString()),t.close("login failed")}t.close()},e))}var Ha,ol,sr,zie,AO,yG,IG,tp,wG,Q_,Zie,CG=be(()=>{jc();Ti();Ha=G(k()),ol=G(ie());ep();tu();ha();w_();NG();sr=new Uint8Array(8),zie=new Float64Array(sr.buffer,0,1),AO={},yG="openapi";a(Jie,"http");Q_=0;a(Xie,"start");Zie={401:3e3,403:3003}});var OO=R((qbe,DG)=>{var{recordAction:np,recordActionBinary:eoe}=(Ti(),ae(Ku)),toe=require("fastify-plugin"),roe=200;DG.exports=toe(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(),l=s.request.routeOptions,_,u,d;l.config?.isOperation?(_=n.body?.operation,u="operation"):(_=l.url,u="fastify-route",d=l.method),np(o,"duration",_,d,u),eoe(s.raw.statusCode<400,"success",_,d,u);let E=roe;i?.pipe?(i.on("data",S=>{E+=S.length}),i.on("end",()=>{np(performance.now()-c,"transfer",_,d,u),np(E,"bytes-sent",_,d,u)})):(E+=i?.length||0,np(E,"bytes-sent",_,d,u));let f=o.toFixed(3),h=s.getHeader("Server-Timing"),m=`db;dur=${f}`;s.header("Server-Timing",h?`${h}, ${m}`:m)}),r()},{name:"hdb-request-time"})});var CO=R((Vbe,UG)=>{var ap=require("clone"),cp=nt(),noe=Y(),ip=D(),Fbe=k(),bO=require("fs"),yO=require("joi"),{string:op}=yO.types(),{hdb_errors:soe,handleHDBError:sp}=ie(),{HDB_ERROR_MSGS:kbe,HTTP_STATUS_CODES:NO}=soe,{common_validators:al}=Ls(),LG=" is required",ioe=["insert","update","upsert"],IO={database:{presence:!1,format:al.schema_format,length:al.schema_length},schema:{presence:!1,format:al.schema_format,length:al.schema_length},table:{presence:!0,format:al.schema_format,length:al.schema_length},action:{inclusion:{within:ioe,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},ooe={schema:op.required(),table:op.required(),action:op.valid("insert","update","upsert")},{AWS_ACCESS_KEY:aoe,AWS_SECRET:coe,AWS_BUCKET:loe,AWS_FILE_KEY:uoe,REGION:_oe}=ip.S3_BUCKET_AUTH_KEYS,doe={s3:{presence:!0},[`s3.${aoe}`]:{presence:!0,type:"String"},[`s3.${coe}`]:{presence:!0,type:"String"},[`s3.${loe}`]:{presence:!0,type:"String"},[`s3.${uoe}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${_oe}`]:{presence:!0,type:"String"}},PG=ap(IO);PG.data.presence={message:LG};var MG=ap(IO);MG.file_path.presence={message:LG};var foe=Object.assign(ap(IO),doe),wO=ap(ooe);wO.csv_url=op.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();wO.passthrough_headers=yO.object();function Eoe(e){let t=cp.validateObject(e,PG);return lp(e,t)}a(Eoe,"dataObject");function hoe(e){let t=cp.validateBySchema(e,yO.object(wO));return lp(e,t)}a(hoe,"urlObject");function poe(e){let t=cp.validateObject(e,MG);return lp(e,t)}a(poe,"fileObject");function moe(e){let t=cp.validateObject(e,foe);return lp(e,t)}a(moe,"s3FileObject");function lp(e,t){if(!t){let r=noe.checkGlobalSchemaTable(e.schema,e.table);if(r)return sp(new Error,r,NO.BAD_REQUEST);if(e.operation===ip.OPERATIONS_ENUM.CSV_FILE_LOAD)try{bO.accessSync(e.file_path,bO.constants.R_OK|bO.constants.F_OK)}catch(n){return n.code===ip.NODE_ERROR_CODES.ENOENT?sp(n,`No such file or directory ${n.path}`,NO.BAD_REQUEST):n.code===ip.NODE_ERROR_CODES.EACCES?sp(n,`Permission denied ${n.path}`,NO.BAD_REQUEST):sp(n)}}return t}a(lp,"postValidateChecks");UG.exports={dataObject:Eoe,urlObject:hoe,fileObject:poe,s3FileObject:moe}});var DO=R((Ybe,vG)=>{"use strict";var j_=k(),up=D();async function Soe(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===up.OPERATIONS_ENUM.INSERT||t.operation===up.OPERATIONS_ENUM.UPDATE||t.operation===up.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===up.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(j_.info(i.message),i):i.http_resp_msg?(j_.error(`Error calling operation: ${e.name}`),j_.error(i.http_resp_msg),i):(j_.error(`Error calling operation: ${e.name}`),j_.error(i),i)}}a(Soe,"callOperationFunctionAsAwait");vG.exports={callOperationFunctionAsAwait:Soe}});var HG=R((Wbe,BG)=>{"use strict";var LO=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}},PO=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};BG.exports={BulkLoadFileObject:LO,BulkLoadDataObject:PO}});var xG=R((jbe,GG)=>{"use strict";var MO=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};GG.exports=MO});var xO=R((tNe,rx)=>{"use strict";var _p=Cr(),fp=CO(),Toe=require("needle"),hs=D(),Jbe=Ze(),cl=Y(),{handleHDBError:ht,hdb_errors:QG}=ie(),{HTTP_STATUS_CODES:ir,HDB_ERROR_MSGS:qt,CHECK_LOGS_WRAPPER:xa}=QG,ll=k(),UO=require("papaparse");cl.promisifyPapaParse();var ps=require("fs-extra"),goe=require("path"),{chain:qG}=require("stream-chain"),FG=require("stream-json/streamers/StreamArray"),kG=require("stream-json/utils/Batch"),VG=require("stream-chain/utils/comp"),{finished:$G}=require("stream"),Roe=X(),jG=DO(),Aoe=sO(),{BulkLoadFileObject:BO,BulkLoadDataObject:Ooe}=HG(),HO=QA(),{verifyBulkLoadAttributePerms:zG}=Vh(),Xbe=xG(),Zbe=gt(),eNe=fi(),{databases:boe}=(Re(),ae($e)),{coerceType:Noe}=(Ep(),ae(qO)),YG="No records parsed from csv file.",Ga=`${Roe.get("HDB_ROOT")}/tmp`,{schema_regex:yoe}=Ls(),KG=1024*1024*2,WG=5e3,Ioe={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};rx.exports={csvDataLoad:woe,csvURLLoad:Coe,csvFileLoad:Doe,importFromS3:Loe};async function woe(e,t){let r=fp.dataObject(e);if(r)throw ht(r,r.message,ir.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=ZG(e.schema,e.table),i=UO.parse(e.data,{header:!0,skipEmptyLines:!0,transform:vO.bind(null,s),dynamicTyping:!1}),o=new HO;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&zG(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 ht(new Error,c,ir.BAD_REQUEST,void 0,void 0,!0);let l=new Ooe(e.action,e.schema,e.table,i.data);return n=await jG.callOperationFunctionAsAwait(ex,l,null),n.message===YG?YG:tx(n.records,n.number_written)}catch(s){throw qa(s)}}a(woe,"csvDataLoad");async function Coe(e){let t=fp.urlObject(e);if(t)throw ht(t,t.message,ir.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Ga}/${r}`;try{await Poe(e,r)}catch(s){throw ll.error(qt.DOWNLOAD_FILE_ERR(r)+" - "+s),ht(s,xa(qt.DOWNLOAD_FILE_ERR(r)))}try{let s=new BO(this.job_operation_function.name,e.action,e.schema,e.table,n,hs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await GO(s);return await dp(n),i}catch(s){throw await dp(n),qa(s)}}a(Coe,"csvURLLoad");async function Doe(e){let t=fp.fileObject(e);if(t)throw ht(t,t.message,ir.BAD_REQUEST,void 0,void 0,!0);let r=new BO(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,hs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await GO(r)}catch(n){throw qa(n)}}a(Doe,"csvFileLoad");async function Loe(e){let t=fp.s3FileObject(e);if(t)throw ht(t,t.message,ir.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=goe.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Ga}/${s}`;let i=new BO(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Moe(s,e);let o=await GO(i);return await dp(r),o}catch(n){throw await dp(r),qa(n)}}a(Loe,"importFromS3");async function Poe(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Toe("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 ht(n,s,n.statusCode,hs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}voe(r,e.csv_url),await Uoe(t,r.raw)}a(Poe,"downloadCSVFile");async function Moe(e,t){try{let r=`${Ga}/${e}`;await ps.mkdirp(Ga),await ps.writeFile(`${Ga}/${e}`,"",{flag:"a+"});let n=await ps.createWriteStream(r),s=await Aoe.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(){ll.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw ll.error(qt.S3_DOWNLOAD_ERR+" - "+r),ht(r,xa(qt.S3_DOWNLOAD_ERR))}}a(Moe,"downloadFileFromS3");async function Uoe(e,t){try{await ps.mkdirp(Ga),await ps.writeFile(`${Ga}/${e}`,t)}catch(r){throw ll.error(qt.WRITE_TEMP_FILE_ERR),ht(r,xa(qt.DEFAULT_BULK_LOAD_ERR))}}a(Uoe,"writeFileToTempFolder");async function dp(e){if(e)try{await ps.access(e),await ps.unlink(e)}catch{ll.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(dp,"deleteTempFile");function voe(e,t){if(e.statusCode!==QG.HTTP_STATUS_CODES.OK)throw ht(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,ir.BAD_REQUEST);if(!Ioe[e.headers["content-type"]])throw ht(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,ir.BAD_REQUEST);if(!e.raw)throw ht(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,ir.BAD_REQUEST)}a(voe,"validateURLResponse");async function GO(e){try{let t;switch(e.file_type){case hs.VALID_S3_FILE_TYPES.CSV:t=await Boe(e);break;case hs.VALID_S3_FILE_TYPES.JSON:t=await Hoe(e);break;default:throw ht(new Error,qt.DEFAULT_BULK_LOAD_ERR,ir.BAD_REQUEST,hs.LOG_LEVELS.ERROR,qt.INVALID_FILE_EXT_ERR(e))}return tx(t.records,t.number_written)}catch(t){throw qa(t)}}a(GO,"fileLoad");async function JG(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 _p.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&zG(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=ht(c);r(l)}}a(JG,"validateChunk");async function XG(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;cl.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!cl.isEmpty(c)&&!cl.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await jG.callOperationFunctionAsAwait(ex,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=ht(c,xa(qt.INSERT_CSV_ERR),ir.INTERNAL_SERVER_ERROR,hs.LOG_LEVELS.ERROR,qt.INSERT_CSV_ERR+" - "+c);r(l)}}a(XG,"insertChunk");async function Boe(e){let t={records:0,number_written:0},r=ZG(e.schema,e.table);try{let n=new HO,s=ps.createReadStream(e.file_path,{highWaterMark:KG});s.setEncoding("utf8"),await UO.parsePromise(s,JG.bind(null,e,n),vO.bind(null,r));let i=n.getPermsResponse();if(i)throw ht(new Error,i,ir.BAD_REQUEST);return s=ps.createReadStream(e.file_path,{highWaterMark:KG}),s.setEncoding("utf8"),await UO.parsePromise(s,XG.bind(null,e,t),vO.bind(null,r)),s.destroy(),t}catch(n){throw ht(n,xa(qt.PAPA_PARSE_ERR),ir.INTERNAL_SERVER_ERROR,hs.LOG_LEVELS.ERROR,qt.PAPA_PARSE_ERR+n)}}a(Boe,"callPapaParse");function ZG(e,t){let r=boe[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Noe(i,s));return n}a(ZG,"createTransformMap");function vO(e,t,r){let n=e.get(r);return n?n(t):cl.autoCast(t)}a(vO,"typeFunction");async function Hoe(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new HO,s=qG([ps.createReadStream(e.file_path,{encoding:"utf-8"}),FG.withParser(),c=>c.value,new kG({batchSize:WG}),VG(async c=>{await JG(e,n,r,c)})]);await new Promise((c,l)=>{$G(s,_=>{_?l(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ht(new Error,i,ir.BAD_REQUEST);let o=qG([ps.createReadStream(e.file_path,{encoding:"utf-8"}),FG.withParser(),c=>c.value,new kG({batchSize:WG}),VG(async c=>{await XG(e,t,r,c)})]);return await new Promise((c,l)=>{$G(o,_=>{_?l(_):c()}),o.resume()}),t}catch(n){throw ht(n,xa(qt.INSERT_JSON_ERR),ir.INTERNAL_SERVER_ERROR,hs.LOG_LEVELS.ERROR,qt.INSERT_JSON_ERR+n)}}a(Hoe,"insertJson");async function ex(e){let t={};try{e.data&&e.data.length>0&&Goe(e.data[0])?t=await xoe(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",ll.info(t.message))}catch(r){throw qa(r)}return t}a(ex,"callBulkFileLoad");function Goe(e){let t=Object.keys(e);for(let r of t)if(!yoe.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Goe,"validateColumnNames");async function xoe(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=_p.insert;break;case"update":i=_p.update;break;case"upsert":i=_p.upsert;break;default:throw ht(new Error,qt.INVALID_ACTION_PARAM_ERR(n),ir.BAD_REQUEST,hs.LOG_LEVELS.ERROR,qt.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 u=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][u])>=0&&e.splice(d,1)}let l=cl.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:o.new_attributes}}catch(o){throw qa(o)}}a(xoe,"bulkFileLoad");function tx(e,t){return`successfully loaded ${t} of ${e} records`}a(tx,"buildResponseMsg");function qa(e){return ht(e,xa(qt.DEFAULT_BULK_LOAD_ERR),ir.INTERNAL_SERVER_ERROR,hs.LOG_LEVELS.ERROR,qt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(qa,"buildTopLevelErrMsg")});var sx=R((nNe,nx)=>{"use strict";var FO=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};nx.exports=FO});var ax=R((iNe,ox)=>{"use strict";var qoe=D(),ix=require("moment"),Foe=require("uuid").v4,kO=class{static{a(this,"JobObject")}constructor(){this.id=Foe(),this.type=void 0,this.start_datetime=ix().valueOf(),this.created_datetime=ix().valueOf(),this.end_datetime=void 0,this.status=qoe.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};ox.exports=kO});var VO=R((aNe,hx)=>{"use strict";var koe=require("uuid").v4,dx=Cr(),fx=ur(),Voe=as(),$oe=Nc(),Yoe=sx(),et=D(),Koe=ax(),Woe=GE(),Yn=k(),Qoe=mu(),ul=Y(),{promisify:joe}=require("util"),Fa=require("moment"),zoe=Yh(),hp=CO(),cx=ST(),{deleteTransactionLogsBeforeValidator:Joe}=VA(),{handleHDBError:lx,hdb_errors:Xoe}=ie(),{HTTP_STATUS_CODES:ux}=Xoe,_x=fx.searchByValue,Zoe=fx.searchByHash,eae=dx.insert,tae=joe(zoe.evaluateSQL),rae=dx.update;hx.exports={addJob:iae,updateJob:aae,handleGetJob:nae,handleGetJobsByStartDate:sae,getJobById:Ex};async function nae(e){try{let t=await Ex(e.id);return ul.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 Yn.error("There was an error getting job",t),new Error(r)}}a(nae,"handleGetJob");async function sae(e){try{let t=await oae(e);if(Yn.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=Fa(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Fa(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 Yn.error(r),new Error(r)}}a(sae,"handleGetJobsByStartDate");async function iae(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||ul.isEmptyOrZeroLength(e.operation)){let u="job parameter is invalid";return Yn.info(u),t.error=u,t}if(!et.JOB_TYPE_ENUM[e.operation])return Yn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case et.OPERATIONS_ENUM.CSV_FILE_LOAD:n=hp.fileObject(e);break;case et.OPERATIONS_ENUM.CSV_URL_LOAD:n=hp.urlObject(e);break;case et.OPERATIONS_ENUM.CSV_DATA_LOAD:n=hp.dataObject(e);break;case et.OPERATIONS_ENUM.IMPORT_FROM_S3:n=hp.s3FileObject(e);break;case et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=cx(e,"date");break;case et.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=cx(e,"timestamp");break;case et.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Joe(e);break;case et.OPERATIONS_ENUM.RESTART_SERVICE:if(et.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw lx(new Error,"Invalid service",ux.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw lx(n,n.message,ux.BAD_REQUEST,void 0,void 0,!0);let s=new Koe;s.type=e.operation===et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Voe(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await _x(i))}catch(u){let d=`There was an error inserting a new job: ${u}`;return Yn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=koe();try{o=await _x(i)}catch(u){let d=`There was an error inserting a new job: ${u}`;return Yn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Yn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new Qoe(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await eae(l)}catch(u){return Yn.error(`There was an error inserting a job for job type: ${e.operation} -- ${u}`),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 u=`Created a job with type ${s.type} and id ${s.id}`;t.message=u,t.createdJob=s,t.success=!0,Yn.trace(u)}return t}a(iae,"addJob");async function oae(e){let t=Fa(e.from_date,Fa.ISO_8601),r=Fa(e.to_date,Fa.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 Yoe(n,e.hdb_user);try{return await tae(s)}catch(i){throw Yn.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(oae,"getJobsInDateRange");async function Ex(e){if(ul.isEmptyOrZeroLength(e))return ul.errorizeMessage("Invalid job ID specified.");let t=new $oe(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Zoe(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Yn.error(n),ul.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(Ex,"getJobById");async function aae(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(ul.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===et.JOB_STATUS_ENUM.COMPLETE||e.status===et.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Fa().valueOf());let t=new Woe(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await rae(t),r}a(aae,"updateJob")});var Ox=R((lNe,Ax)=>{"use strict";var px=Y(),Ft=D(),cae=require("moment"),pp=xO(),z_=k(),mx=VO(),Sx=Kh(),Tx=ia(),gx=rt(),lae=xh(),uae=bo(),{parentPort:_ae,isMainThread:Rx}=require("worker_threads"),{onMessageByType:dae}=rt(),$O=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function fae(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(px.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(px.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Ft.JOB_TYPE_ENUM.csv_file_load:await Ks(e,pp.csvFileLoad);break;case Ft.JOB_TYPE_ENUM.csv_url_load:await Ks(e,pp.csvURLLoad);break;case Ft.JOB_TYPE_ENUM.csv_data_load:await Ks(e,pp.csvDataLoad);break;case Ft.JOB_TYPE_ENUM.import_from_s3:await Ks(e,pp.importFromS3);break;case Ft.JOB_TYPE_ENUM.empty_trash:break;case Ft.JOB_TYPE_ENUM.export_local:await Ks(e,Sx.export_local);break;case Ft.JOB_TYPE_ENUM.export_to_s3:await Ks(e,Sx.export_to_s3);break;case Ft.JOB_TYPE_ENUM.delete_files_before:case Ft.JOB_TYPE_ENUM.delete_records_before:await Ks(e,Tx.deleteFilesBefore);break;case Ft.JOB_TYPE_ENUM.delete_audit_logs_before:await Ks(e,Tx.deleteAuditLogsBefore);break;case Ft.JOB_TYPE_ENUM.delete_transaction_logs_before:await Ks(e,lae.deleteTransactionLogsBefore);break;case Ft.JOB_TYPE_ENUM.restart_service:return await Ks(e,uae.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(fae,"parseMessage");async function Ks(e,t){try{e.job.status=Ft.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=cae().valueOf(),await mx.updateJob(e.job),await Eae(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):z_.error(`There was an error running ${t.name} job with id ${e.job.id}`),z_.error(n),e.job.message=n,e.job.status=Ft.JOB_STATUS_ENUM.ERROR;try{await mx.updateJob(e.job)}catch(s){throw z_.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Ks,"runJob");async function Eae(e){z_.trace("launching job thread:",e),Rx?gx.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Ft.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})}):_ae.postMessage({type:Ft.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(Eae,"launchJobThread");Rx&&dae(Ft.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{gx.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Ft.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`})})}catch(r){z_.error(r)}});Ax.exports={parseMessage:fae,RunnerMessage:$O}});var Nx=R((_Ne,bx)=>{"use strict";var YO=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};bx.exports=YO});var kx=R((fNe,JO)=>{"use strict";var Rp=ur(),QO=Yh(),mp=xO(),Ui=LE(),Sp=Ei(),X_=ia(),hae=ER(),J_=Lr(),Tp=vE(),or=kA(),gp=k(),pae=NR(),mae=c_(),yx=sA(),Sae=JE(),Tae=ZE(),gae=oA(),Rae=th(),Aae=nh(),KO=ih(),Ix=Kh(),Oae=Vh(),jO=VO(),V=D(),{hdb_errors:ed,handleHDBError:Z_}=ie(),{HTTP_STATUS_CODES:wx}=ed,WO=ah(),Cx=bo(),Gx=require("util"),_l=Cr(),bae=Bn(),Nae=gi(),Dx=Ox(),Lx=s_(),Px=(Ch(),ae(C_)),Mx=Et(),Ux=xh(),vx=Uh(),{setServerUtilities:yae}=(Ep(),ae(qO)),{CONTEXT:Iae}=(Mn(),ae(fg)),{_assignPackageExport:wae}=require("../index"),{transformReq:Cae}=Y(),{server:Dae}=(yr(),ae(jo)),Sr=gp.loggerWithTag("operation"),Lae=DO(),Bx=Rp.searchByHash,Pae=Rp.searchByValue,Mae=Gx.promisify(Rp.search),Uae=Gx.promisify(QO.evaluateSQL),vae={[V.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[V.OPERATIONS_ENUM.CREATE_TABLE]:!0,[V.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[V.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[V.OPERATIONS_ENUM.DROP_TABLE]:!0,[V.OPERATIONS_ENUM.DROP_SCHEMA]:!0},K=Nx();async function xx(e,t){try{if(e.body.operation!=="read_log"&&(gp.log_level===V.LOG_LEVELS.INFO||gp.log_level===V.LOG_LEVELS.DEBUG||gp.log_level===V.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;Sr.info(o)}}catch(n){Sr.error(n)}let r=await Lae.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return vae[e.body.operation]&&bae.setSchemaDataToGlobal(n=>{n&&Sr.error(n)}),r}a(xx,"processLocalTransaction");var Hx=Hae();JO.exports={chooseOperation:qx,getOperationFunction:Fx,operation:zO,processLocalTransaction:xx};yae(JO.exports);Dae.operation=zO;function qx(e){let t;try{t=Fx(e)}catch(s){throw Sr.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=QO.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=QO.checkASTPermissions(e,i);if(o)throw Sr.error(`${wx.FORBIDDEN} from operation ${e.operation}`),Sr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Z_(new Error,o,ed.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==V.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==V.OPERATIONS_ENUM.LOGIN&&e.operation!==V.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=Oae.verifyPerms(i,s);if(o)throw Sr.error(`${wx.FORBIDDEN} from operation ${e.operation}`),Sr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Z_(new Error,o,ed.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw Z_(s,"There was an error when trying to choose an operation path")}return r}a(qx,"chooseOperation");function Fx(e){if(Sr.trace(`getOperationFunction with operation: ${e.operation}`),Hx.has(e.operation))return Hx.get(e.operation);throw Z_(new Error,ed.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),ed.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(Fx,"getOperationFunction");wae("operation",zO);function zO(e,t){e.hdb_user=this[Iae]?.user,e.bypass_auth=!t;let r=qx(e);return xx({body:e},r)}a(zO,"operation");async function Bae(e){Sr.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[V.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case V.OPERATIONS_ENUM.INSERT:o=await _l.insert(i);break;case V.OPERATIONS_ENUM.UPDATE:o=await _l.update(i);break;case V.OPERATIONS_ENUM.UPSERT:o=await _l.upsert(i);break;case V.OPERATIONS_ENUM.DELETE:o=await X_.deleteRecord(i);break;default:Sr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Sr.info("Invalid operation in transaction"),Sr.error(o)}}a(Bae,"catchup");async function ms(e){Cae(e);let t,r;try{r=await jO.addJob(e),t=r.createdJob,Sr.info("addJob result",r);let n=new Dx.RunnerMessage(t,e);return{message:await Dx.parseMessage(n)??`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 Sr.error(s),Z_(n,s)}}a(ms,"executeJob");function Hae(){let e=new Map;return e.set(V.OPERATIONS_ENUM.INSERT,new K(_l.insert)),e.set(V.OPERATIONS_ENUM.UPDATE,new K(_l.update)),e.set(V.OPERATIONS_ENUM.UPSERT,new K(_l.upsert)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new K(Rp.searchByConditions)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_HASH,new K(Bx)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_ID,new K(Bx)),e.set(V.OPERATIONS_ENUM.SEARCH_BY_VALUE,new K(Pae)),e.set(V.OPERATIONS_ENUM.SEARCH,new K(Mae)),e.set(V.OPERATIONS_ENUM.SQL,new K(Uae)),e.set(V.OPERATIONS_ENUM.CSV_DATA_LOAD,new K(ms,mp.csvDataLoad)),e.set(V.OPERATIONS_ENUM.CSV_FILE_LOAD,new K(ms,mp.csvFileLoad)),e.set(V.OPERATIONS_ENUM.CSV_URL_LOAD,new K(ms,mp.csvURLLoad)),e.set(V.OPERATIONS_ENUM.IMPORT_FROM_S3,new K(ms,mp.importFromS3)),e.set(V.OPERATIONS_ENUM.CREATE_SCHEMA,new K(Ui.createSchema)),e.set(V.OPERATIONS_ENUM.CREATE_DATABASE,new K(Ui.createSchema)),e.set(V.OPERATIONS_ENUM.CREATE_TABLE,new K(Ui.createTable)),e.set(V.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new K(Ui.createAttribute)),e.set(V.OPERATIONS_ENUM.DROP_SCHEMA,new K(Ui.dropSchema)),e.set(V.OPERATIONS_ENUM.DROP_DATABASE,new K(Ui.dropSchema)),e.set(V.OPERATIONS_ENUM.DROP_TABLE,new K(Ui.dropTable)),e.set(V.OPERATIONS_ENUM.DROP_ATTRIBUTE,new K(Ui.dropAttribute)),e.set(V.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new K(Sp.describeSchema)),e.set(V.OPERATIONS_ENUM.DESCRIBE_DATABASE,new K(Sp.describeSchema)),e.set(V.OPERATIONS_ENUM.DESCRIBE_TABLE,new K(Sp.describeTable)),e.set(V.OPERATIONS_ENUM.DESCRIBE_ALL,new K(Sp.describeAll)),e.set(V.OPERATIONS_ENUM.DELETE,new K(X_.deleteRecord)),e.set(V.OPERATIONS_ENUM.ADD_USER,new K(J_.addUser)),e.set(V.OPERATIONS_ENUM.ALTER_USER,new K(J_.alterUser)),e.set(V.OPERATIONS_ENUM.DROP_USER,new K(J_.dropUser)),e.set(V.OPERATIONS_ENUM.LIST_USERS,new K(J_.listUsersExternal)),e.set(V.OPERATIONS_ENUM.LIST_ROLES,new K(Tp.listRoles)),e.set(V.OPERATIONS_ENUM.ADD_ROLE,new K(Tp.addRole)),e.set(V.OPERATIONS_ENUM.ALTER_ROLE,new K(Tp.alterRole)),e.set(V.OPERATIONS_ENUM.DROP_ROLE,new K(Tp.dropRole)),e.set(V.OPERATIONS_ENUM.USER_INFO,new K(J_.userInfo)),e.set(V.OPERATIONS_ENUM.READ_LOG,new K(pae)),e.set(V.OPERATIONS_ENUM.ADD_NODE,new K(mae)),e.set(V.OPERATIONS_ENUM.UPDATE_NODE,new K(yx)),e.set(V.OPERATIONS_ENUM.SET_NODE_REPLICATION,new K(yx)),e.set(V.OPERATIONS_ENUM.REMOVE_NODE,new K(Sae)),e.set(V.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new K(Tae)),e.set(V.OPERATIONS_ENUM.PURGE_STREAM,new K(gae)),e.set(V.OPERATIONS_ENUM.SET_CONFIGURATION,new K(Mx.setConfiguration)),e.set(V.OPERATIONS_ENUM.CLUSTER_STATUS,new K(Rae.clusterStatus)),e.set(V.OPERATIONS_ENUM.CLUSTER_NETWORK,new K(Aae)),e.set(V.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new K(KO.setRoutes)),e.set(V.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new K(KO.getRoutes)),e.set(V.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new K(KO.deleteRoutes)),e.set(V.OPERATIONS_ENUM.EXPORT_TO_S3,new K(ms,Ix.export_to_s3)),e.set(V.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new K(ms,X_.deleteFilesBefore)),e.set(V.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new K(ms,X_.deleteFilesBefore)),e.set(V.OPERATIONS_ENUM.EXPORT_LOCAL,new K(ms,Ix.export_local)),e.set(V.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new K(jO.handleGetJobsByStartDate)),e.set(V.OPERATIONS_ENUM.GET_JOB,new K(jO.handleGetJob)),e.set(V.OPERATIONS_ENUM.GET_FINGERPRINT,new K(WO.getFingerprint)),e.set(V.OPERATIONS_ENUM.SET_LICENSE,new K(WO.setLicense)),e.set(V.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new K(WO.getRegistrationInfo)),e.set(V.OPERATIONS_ENUM.RESTART,new K(Cx.restart)),e.set(V.OPERATIONS_ENUM.RESTART_SERVICE,new K(ms,Cx.restartService)),e.set(V.OPERATIONS_ENUM.CATCHUP,new K(Bae)),e.set(V.OPERATIONS_ENUM.SYSTEM_INFORMATION,new K(Nae.systemInformation)),e.set(V.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new K(ms,X_.deleteAuditLogsBefore)),e.set(V.OPERATIONS_ENUM.READ_AUDIT_LOG,new K(hae)),e.set(V.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new K(Lx.createTokens)),e.set(V.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new K(Lx.refreshOperationToken)),e.set(V.OPERATIONS_ENUM.LOGIN,new K(Px.login)),e.set(V.OPERATIONS_ENUM.LOGOUT,new K(Px.logout)),e.set(V.OPERATIONS_ENUM.GET_CONFIGURATION,new K(Mx.getConfiguration)),e.set(V.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new K(or.customFunctionsStatus)),e.set(V.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new K(or.getCustomFunctions)),e.set(V.OPERATIONS_ENUM.GET_COMPONENT_FILE,new K(or.getComponentFile)),e.set(V.OPERATIONS_ENUM.GET_COMPONENTS,new K(or.getComponents)),e.set(V.OPERATIONS_ENUM.SET_COMPONENT_FILE,new K(or.setComponentFile)),e.set(V.OPERATIONS_ENUM.DROP_COMPONENT,new K(or.dropComponent)),e.set(V.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new K(or.getCustomFunction)),e.set(V.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new K(or.setCustomFunction)),e.set(V.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new K(or.dropCustomFunction)),e.set(V.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new K(or.addComponent)),e.set(V.OPERATIONS_ENUM.ADD_COMPONENT,new K(or.addComponent)),e.set(V.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new K(or.dropCustomFunctionProject)),e.set(V.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new K(or.packageComponent)),e.set(V.OPERATIONS_ENUM.PACKAGE_COMPONENT,new K(or.packageComponent)),e.set(V.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new K(or.deployComponent)),e.set(V.OPERATIONS_ENUM.DEPLOY_COMPONENT,new K(or.deployComponent)),e.set(V.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new K(Ux.readTransactionLog)),e.set(V.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new K(ms,Ux.deleteTransactionLogsBefore)),e.set(V.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new K(vx.installModules)),e.set(V.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new K(vx.auditModules)),e.set(V.OPERATIONS_ENUM.GET_BACKUP,new K(Ui.getBackup)),e}a(Hae,"initializeOperationFunctionMap")});var Op=R((hNe,Yx)=>{"use strict";var XO=D(),Gae=Y(),td=k(),{handleHDBError:ZO,hdb_errors:Ap}=ie(),{isMainThread:xae}=require("worker_threads"),{Readable:qae}=require("stream"),Vx=require("os"),Fae=require("util"),kae=vR(),Vae=Fae.promisify(kae.authorize),$x=kx(),{createGzip:$ae,constants:Yae}=require("zlib");function Kae(e){let t=`Found an uncaught exception with message: ${e.message}. ${Vx.EOL}Stack: ${e.stack} ${Vx.EOL}Terminating ${xae?"HDB":"thread"}.`;console.error(t),td.fatal(t),process.exit(1)}a(Kae,"handleServerUncaughtException");function Wae(e,t,r){if(td[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:Ap.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(Wae,"serverErrorHandler");function Qae(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=ZO(new Error,"Invalid JSON.",Ap.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Gae.isEmpty(e.body.operation)){let n=ZO(new Error,"Request body must include an 'operation' property.",Ap.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(Qae,"reqBodyValidationHandler");function jae(e,t,r){let n;e.body.operation!==XO.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==XO.OPERATIONS_ENUM.LOGIN&&e.body.operation!==XO.OPERATIONS_ENUM.LOGOUT?Vae(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{td.warn(s),td.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(ZO(s,i,Ap.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(jae,"authHandler");async function zae(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=$x.chooseOperation(e.body);let s=await $x.processLocalTransaction(e,n);if(s instanceof qae&&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($ae({level:Yae.Z_BEST_SPEED})))}return s}catch(s){throw td.error(s),s}}a(zae,"handlePostRequest");Yx.exports={authHandler:jae,handlePostRequest:zae,handleServerUncaughtException:Kae,serverErrorHandler:Wae,reqBodyValidationHandler:Qae}});var jx=R((mNe,Qx)=>{"use strict";var Jae=require("fastify-plugin"),{handlePostRequest:Kx,authHandler:Xae,reqBodyValidationHandler:Zae}=Op();async function ece(e){e.decorate("hdbCore",{preValidation:[Zae,Xae],request:t=>Wx(Kx(t,response)),requestWithoutAuthentication:(t,r)=>Wx(Kx(t,r,!0))})}a(ece,"hdbCore");async function Wx(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(Wx,"convertAsyncIterators");Qx.exports=Jae(ece)});var Xx=R((gNe,Jx)=>{"use strict";var TNe=require("fs"),eb=X();eb.initSync();var{CONFIG_PARAMS:zx}=D(),tce=1024*1024*1024;function rce(e){let t=eb.get(zx.HTTP_TIMEOUT),r=eb.get(zx.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:tce,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(rce,"getServerOptions");Jx.exports=rce});var tq=R((ANe,eq)=>{"use strict";var tb=X();tb.initSync();var{CONFIG_PARAMS:Zx}=D();function nce(){let e=tb.get(Zx.HTTP_CORSACCESSLIST),t=tb.get(Zx.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(nce,"getCORSOptions");eq.exports=nce});var sq=R((bNe,nq)=>{"use strict";var rq=X();rq.initSync();var sce=D();function ice(){return rq.get(sce.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(ice,"getHeaderTimeoutConfig");nq.exports=ice});var nb={};Ve(nb,{customFunctionsServer:()=>cce,ready:()=>Tq,start:()=>ace});function ace(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){vi||(vi=Sq(t),dt.http((await vi).server));let o=await vi,c=(0,rb.dirname)(s),l=(0,rb.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!iq.has(c)){iq.add(c);try{o.register(uce(c,l))}catch(_){if(_.message==="Root plugin has already booted")We.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:Tq}}async function cce(){try{We.info("In Custom Functions Fastify server"+process.cwd()),We.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),We.debug(`Custom Functions server process ${process.pid} starting up.`),await lce();let e=_q.get(dq.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=vi=await Sq(e)}catch(r){throw We.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw We.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){We.error(`Custom Functions ${process.pid} Error: ${e}`),We.error(e),process.exit(1)}}async function lce(){try{We.info("Custom Functions starting configuration."),await fq.setUsersToGlobal(),We.info("Custom Functions completed configuration.")}catch(e){We.error(e)}}function uce(e,t){return async function(r){try{We.info("Custom Functions starting buildRoutes"),We.trace("Loading fastify routes folder "+e),(0,oq.existsSync)(e)&&r.register(uq.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:We.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?We.error(s.message):s&&We.error(s),o()})}catch(n){We.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function Sq(e){We.info("Custom Functions starting buildServer.");let t=(0,Eq.default)(e),r=(0,aq.default)(t);r.server.headersTimeout=(0,pq.default)(),r.setErrorHandler(mq.serverErrorHandler);let n=(0,hq.default)();return n&&r.register(cq.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),o()}),r.register(lq.default),await r.register(oce),await r.after(),_O(r),We.info("Custom Functions completed buildServer."),r}function Tq(){if(vi)return vi.then?vi.then(e=>e.ready()):vi.ready()}var rb,oq,aq,cq,lq,uq,_q,dq,We,oce,fq,Eq,hq,pq,mq,vi,iq,gq=be(()=>{rb=require("path"),oq=require("fs"),aq=G(require("fastify")),cq=G(require("@fastify/cors")),lq=G(OO()),uq=G(require("@fastify/autoload")),_q=G(X()),dq=G(D()),We=G(k()),oce=G(jx()),fq=G(Lr()),Eq=G(Xx()),hq=G(tq()),pq=G(sq()),mq=G(Op());jc();yr();iq=new Set;a(ace,"start");a(cce,"customFunctionsServer");a(lce,"setUp");a(uce,"buildRouteFolder");a(Sq,"buildServer");a(Tq,"ready")});var sb={};Ve(sb,{start:()=>_ce});function _ce(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,Nq.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){Aq||(Aq=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=Rq.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,Oq.default)(s,(0,bq.realpathSync)(o))}}return i(s)},{runFirst:!0})),Rq.set(r,n)}}}var Oq,bq,Nq,Rq,Aq,yq=be(()=>{Oq=G(require("send")),bq=require("fs"),Nq=G(require("serve-static")),Rq=new Map;a(_ce,"start")});var cb={};Ve(cb,{Request:()=>ib,createReuseportFd:()=>bp});var Iq,ib,ob,ab,bp,Np=be(()=>{Iq=require("os"),ib=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 ab(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 ob(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},ob=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)}},ab=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,Iq.platform)()!="win32"&&(bp=require("node-unix-socket").createReuseportFd)});var Sb=R(Po=>{"use strict";var{isMainThread:_b,parentPort:nd,threadId:yp}=require("worker_threads"),{Socket:dce,createServer:fce}=require("net"),{createServer:Ece,IncomingMessage:hce}=require("http"),{createServer:pce}=require("https"),{readFileSync:mce,unlinkSync:wq,existsSync:Sce}=require("fs"),kt=k(),ke=X(),pt=D(),{server:Cp}=(yr(),ae(jo)),{WebSocketServer:Tce}=require("ws"),{createSecureContext:gce,createServer:Rce}=require("node:tls"),{getTicketKeys:Pq,restartNumber:Ace,getWorkerIndex:sd}=rt(),{Headers:Mq,appendHeader:Oce}=(w_(),ae(xB)),{recordAction:rd,recordActionBinary:bce}=(Ti(),ae(Ku)),{Request:Uq,createReuseportFd:Cq}=(Np(),ae(cb)),{checkMemoryLimit:Nce}=la(),{X509Certificate:yce}=require("crypto"),vq=require("tls"),Ice=vq.createSecureContext,dl;vq.createSecureContext=function(e){return dl||Ice(e)};var Bq=ke.get(pt.CONFIG_PARAMS.THREADS_DEBUG);if(Bq){let e;if(_b)e=ke.get(pt.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){kt.info("Could not close debugger",t)}});else{let t=ke.get(pt.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&sd()>=0&&(e=t+sd())}if(e){let t=ke.get(pt.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=ke.get(pt.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){kt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&_b)try{require("inspector").open(9229)}catch(e){Ace<=1&&kt.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:LNe,CONFIG_PARAMS:wce}=pt;ke.initSync();var Cce=ke.get(wce.HTTP_SESSIONAFFINITY),Ws={};Po.registerServer=hb;Po.httpServer=pb;Po.deliverSocket=Eb;Po.startServers=Hq;Po.when_components_loaded=null;Po.createSNICallback=mb;Cp.http=pb;Cp.request=Mce;Cp.socket=Uce;Cp.ws=vce;var lb={},Ip={},Dce,Bi={},wp={},Lce=[],db=[];function Hq(){return Po.when_components_loaded=Dp().loadRootComponents(!0).then(()=>{nd?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)Eb(n,r,s);else if(t.requestId)Pce(t);else if(t.type===pt.ITC_EVENT_TYPES.SHUTDOWN){kt.trace("received shutdown request",yp);for(let i in Ws){let o=Ws[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),u=0,d=setInterval(()=>{u++;let E=u>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}u===1?kt.info(`Closing ${f.length} idle connections`):E&&kt.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,m=f.length;h<m;h++){let S=f[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
30
- Connection: close\r
31
- \r
32
- `))}},25).unref()}o.close?.(()=>{if(ke.get(pt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&sd()==0)try{wq(ke.get(pt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,yp),o.cantCleanupProperly||kt.warn("Had to forcefully exit the thread",yp),process.exit(0)},5e3).unref()})}if(Bq||process.env.DEV_MODE)try{require("inspector").close()}catch(i){kt.info("Could not close debugger",i)}}}).ref();let e=[];if(Cq&&!Cce)for(let t in Ws){let r=Ws[t];if(isNaN(t)&&sd()==0){Sce(t)&&wq(t),e.push(new Promise((i,o)=>{r.listen({path:t},()=>{i(),kt.info("Domain socket listening on "+t)}).on("error",o)}));continue}let n=ke.get(pt.CONFIG_PARAMS.HTTP_THREADRANGE);if(n){let i=typeof n=="string"?n.split("-"):n,o=sd();if(o<i[0]||o>i[1])continue}let s;try{s=Cq(+t,"::")}catch(i){console.error(`Unable to bind to port ${t}`,i);continue}e.push(new Promise((i,o)=>{r.listen({fd:s},()=>{i(),kt.trace("Listening on port "+t,yp)}).on("error",o)}))}Promise.all(e).then(()=>{nd?.postMessage({type:pt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(Hq,"startServers");_b||Hq();function Eb(e,t,r){let n=e?.read?e:new dce({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Ws[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=Ws[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(kt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(Eb,"deliverSocket");var Dq=new Map;function Pce(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=Dq.get(s),r){case"connection":i=Eb(void 0,t),Dq.set(s,i),i.write=(c,l,_)=>(nd.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,l,_)=>(nd.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),nd.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(Pce,"proxyRequest");function hb(e,t,r=!0){!+t&&t!==ke.get(pt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(ke.get(pt.CONFIG_PARAMS.HTTP_PORT),10));let n=Ws[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",Lq),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else Ws[t]=e;e.on("unhandled",Lq)}a(hb,"registerServer");function Gq(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=[],ke.get(pt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:ke.get(pt.CONFIG_PARAMS.HTTP_PORT),secure:ke.get(pt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),ke.get(pt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:ke.get(pt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&ke.get(pt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:ke.get(pt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(Gq,"getPorts");function pb(e,t){for(let{port:r,secure:n}of Gq(t))xq(r,n,t?.isOperationsServer),typeof e=="function"?db[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,hb(e,r,!1)),wp[r]=fb(db,r),Dce=fb(Lce,r)}a(pb,"httpServer");function xq(e,t,r){if(!Bi[e]){let n=r?"operationsApi_network":"http",s={noDelay:!0,keepAliveTimeout:ke.get(n+"_keepAliveTimeout"),headersTimeout:ke.get(n+"_headersTimeout"),requestTimeout:ke.get(n+"_timeout")},i=ke.get(n+"_mtls"),o=ke.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let l=ke.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:Pq(),maxHeaderSize:ke.get(pt.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:mb(l)})}let c=Nce();Bi[e]=(t?pce:Ece)(s,async(l,_)=>{try{let d=performance.now(),E=new Uq(l,_);r&&(E.isOperationsServer=!0);let f=await wp[e](E);if(!f){if(E._nodeResponse.statusCode)return;f=qq(E)}if(c?f.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):f.headers?.set?.("Server","HarperDB"),f.status===-1){for(let v of f.headers||[])_.setHeader(v[0],v[1]);return l.baseRequest=E,_.baseResponse=f,Bi[e].emit("unhandled",l,_)}let h=f.status||200,m=performance.now(),S=m-d,g=f.body,T;if(!f.handlesHeaders){let v=f.headers||new Mq;g?g.length>=0&&(typeof g=="string"?v.set("Content-Length",Buffer.byteLength(g)):v.set("Content-Length",g.length),T=!0):(v.set("Content-Length","0"),T=!0);let U=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(U+=", miss"),Oce(v,"Server-Timing",U,!0),_.writeHead(h,v&&(v[Symbol.iterator]?Array.from(v):v)),T&&_.end(g)}let b=E.handlerPath,N=E.method;if(rd(S,"duration",b,N,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),bce(h<400,"success",b,N),!T)if(g?.pipe){g.pipe(_),g.destroy&&_.on("close",()=>{g.destroy()});let v=0;g.on("data",U=>{v+=U.length}),g.on("end",()=>{rd(performance.now()-m,"transfer",b,N),rd(v,"bytes-sent",b,N)})}else g?.then?g.then(v=>{_.end(v)},u):_.end(g)}catch(d){u(d)}function u(d){let E=d.headers;_.writeHead(d.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),_.end(d.toString()),d.statusCode?d.statusCode===500?kt.warn(d):kt.info(d):kt.error(d)}a(u,"onError")}),i&&(Bi[e].mtlsConfig=i),t&&(Bi[e].on("secureConnection",l=>{l._parent.startTime&&rd(performance.now()-l._parent.startTime,"tls-handshake",e),rd(l.isSessionReused(),"tls-reused",e)}),Bi[e].isSecure=!0,s.SNICallback(null,(l,_)=>{try{dl=_,_&&Bi[e].setSecureContext(_.options)}finally{dl=null}})),hb(Bi[e],e)}return Bi[e]}a(xq,"getHTTPServer");function fb(e,t){let r=qq;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(fb,"makeCallbackChain");function qq(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new Mq}}a(qq,"unhandled");function Mce(e,t){pb(e,{requestOnly:!0,...t})}a(Mce,"onRequest");function Uce(e,t){let r;if(t.securePort){let n=Object.assign({},ke.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={noDelay:!0,rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:mb(n)};r=Rce(s,e),s.SNICallback(null,(i,o)=>{try{dl=o,o&&r.setSecureContext(o.options)}finally{dl=null}}),Ws[t.securePort]=r}return t.port&&(r=fce({noDelay:!0},e),Ws[t.port]=r),r}a(Uce,"onSocket");Object.defineProperty(hce.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 vce(e,t){let r;for(let{port:n,secure:s}of Gq(t)){Ip[n]||(Ip[n]=new Tce({server:r=xq(n,s)}),Ip[n].on("connection",async(c,l)=>{try{let _=new Uq(l);_.isWebSocket=!0;let u=wp[n](_),d=l.headers["sec-websocket-protocol"]||"",E=lb[n];if(d){let f;for(let h=0;h<E.length;h++){let m=E[h];m.protocol===d&&(f=!0,m.listener(c,_,u))}if(f)return}for(let f=0;f<E.length;f++){let h=E[f];h.protocol||h.listener(c,_,u)}}catch(_){kt.warn("Error handling WebSocket connection",_)}}),Ip[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=lb[n];o||(o=lb[n]=[]),o.push({listener:e,protocol:i}),wp[n]=fb(db,n)}return r}a(vce,"onWebSocket");function Lq(e,t){t.writeHead(404),t.end(`Not found
33
- `)}a(Lq,"defaultNotFound");function ub(e){return e.startsWith("-----BEGIN")?e:mce(e)}a(ub,"readPEM");function mb(e){let t=[];for(let i=0;e[i];i++)t.push(e[i]);t.length||t.push(e);let r=new Map,n,s=!1;for(let i of t){let o=ub(i.privateKey),c=ub(i.certificate),l=i.certificateAuthority&&ub(i.certificateAuthority);if(!o||!c)throw new Error("Missing private key or certificate for secure server");let _={ciphers:i.ciphers,ca:l,ticketKeys:Pq()},u=gce(_);u.options=_,_.instantiatedContext=u,u.context.setCert(c),u.context.setKey(o,void 0),_.cert=c,_.key=o,u.certStart=c.slice(0,100).toString(),n||(n=u);let d=new yce(c),E=i.hostname??i.host??i.hostnames??i.hosts??(d.subjectAltName?d.subjectAltName.split(",").map(f=>{let h=f.indexOf(":");return f.slice(h+1)}):[d.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(E)||(E=[E]);for(let f of E)f?(f[0]==="*"&&(s=!0,f=f.slice(1)),r.has(f)||r.set(f,u)):kt.error("No hostname found for certificate at",i.certificate)}return(i,o)=>{let c=i;for(;;){let l=r.get(c);if(l)return kt.debug("Found certificate for",i,l.certStart),o(null,l);if(s&&c){let _=c.indexOf(".",1);_<0?c="":c=c.slice(_)}else break}kt.debug("No certificate found to match",i,"using the first certificate"),o(null,n)}}a(mb,"createSNICallback")});var jq={};Ve(jq,{startHTTPThreads:()=>Hce,startSocketServer:()=>Ob,updateWorkerIdleness:()=>Qq});async function Hce(e=2,t){if(t)Rb(0,1,!0);else{let{loadRootComponents:r}=Dp();if(e===0)return(0,Qs.setMainIsWorker)(!0),await Sb().startServers(),Promise.resolve([]);await r()}Wq();for(let r=0;r<e;r++)Rb(r,e);return Promise.all(Kq)}function Wq(){let e=(0,$q.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),gb=setInterval(()=>{Mp.notify(e)},Bce).unref())}function Rb(e,t=1,r){if(Tb++,(0,Qs.startWorker)("server/threads/threadServer.js",{name:ml.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(_){_.type===ml.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});Kq.push(s),await s,fl.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=Pp.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=fl.indexOf(n);o>-1&&fl.splice(o,1)}if(a(i,"removeWorker"),El){let o=El;El=[];for(let c of o)Yq[c.localPort](null,c)}}}),r){let n=setInterval(()=>{Ab?Ab=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Qs.shutdownWorkers)(),Tb=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function Ob(e=0,t){if(typeof e=="string")try{(0,Up.existsSync)(e)&&(0,Up.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Gce:r=xce(t):r=bb;let n=(0,hl.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=Yq[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),Ab=!0,r(o,(c,l)=>{if(!c){if(Fq){let u=o._socket||new hl.Socket({handle:o,writable:!0,readable:!0});Fq.deliverSocket(u,e,l),u.resume()}else Tb>0?(El.length===0&&setTimeout(()=>{El.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,El.push(o)):(console.log("start up a dynamic thread to handle request"),Rb(0));vr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:l});else{let u=o._socket||new hl.Socket({handle:o,writable:!0,readable:!0});kce(u,c,e)}vr(!0,"socket-routed")})};let s=ma();Mp.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 bb(e,t){let r,n=0;for(let s of fl){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=Lp)return Lp=i,t(r);n=i}Lp=0,t(r)}function Gce(e,t){let r={};e.getpeername(r);let n=r.address,s=pl.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);bb(e,o=>{pl.set(n,{worker:o,lastUsed:i}),t(o)})}function xce(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new hl.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let l=o.toString("latin1").match(t)?.[1],_=pl.get(l),u=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=u,s(_.worker);bb(n,d=>{pl.set(l,{worker:d,lastUsed:u}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Qq(){Lp=0;for(let e of fl)e.expectedIdle=e.recentELU.idle+qce,e.requests=1;fl.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function kce(e,t,r){let n=Fce++;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(),Pp.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")),Pp.delete(n)),s.event=="destroy"&&(e.destroy(),Pp.delete(n))})}var Qs,hl,ml,Mp,Up,Vq,$q,fl,El,Yq,Fq,Tb,Kq,gb,Bce,Ab,Lp,kq,pl,qce,Pp,Fce,Nb=be(()=>{Qs=G(rt()),hl=require("net"),ml=G(D()),Mp=G(k()),Up=require("fs");Ti();Vq=require("worker_threads"),$q=G(la()),fl=[],El=[],Yq=[],Tb=0,Kq=[];Vq.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,Qs.onMessageFromWorkers)(e=>{e.type===ml.ITC_EVENT_TYPES.RESTART&&gb&&(clearInterval(gb),Wq())}));Bce=6e5;a(Hce,"startHTTPThreads");a(Wq,"licenseWarning");a(Rb,"startHTTPWorker");a(Ob,"startSocketServer");Lp=0;a(bb,"findMostIdleWorker");kq=36e5,pl=new Map;a(Gce,"findByRemoteAddressAffinity");a(xce,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of pl)r.lastUsed+kq<e&&pl.delete(t)},kq).unref();qce=1e3;a(Qq,"updateWorkerIdleness");(0,Qs.setMonitorListener)(Qq);Pp=new Map,Fce=1;a(kce,"proxySocket")});var Zq=R((FNe,Xq)=>{"use strict";var Vce=require("cluster"),ka=X();ka.initSync();var Jq=D(),BNe=require("util"),Hi=k(),HNe=require("fs"),$ce=require("fastify"),GNe=ma(),Yce=require("@fastify/cors"),Kce=require("@fastify/compress"),Wce=require("@fastify/static"),Qce=OO(),jce=require("path"),{PACKAGE_ROOT:zce}=D(),Jce=Bn(),Xce=Y(),Zce=Lr(),ele=la(),{server:tle}=(yr(),ae(jo)),{node_request_key:xNe}=(Np(),ae(cb)),{authHandler:rle,handlePostRequest:nle,serverErrorHandler:sle,reqBodyValidationHandler:ile}=Op(),qNe=require("net"),{registerContentHandlers:ole}=(jc(),ae(pG)),ale=6e4,cle=1024*1024*1024,lle="TRUE",{CONFIG_PARAMS:id}=Jq,Sl;Xq.exports={hdbServer:zq,start:zq};async function zq(e){try{Hi.info("In Fastify server"+process.cwd()),Hi.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Hi.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Vce.isMaster,await ule();let t=e.securePort>0;Sl=_le(t),await Sl.ready(),e||(e={}),e.isOperationsServer=!0;try{tle.http(Sl.server,e),Sl.server.closeIdleConnections||await Sl.listen({port:0,host:"::"})}catch(r){throw Sl.close(),Hi.error(r),Hi.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Hi.fatal(t),process.exit(1)}}a(zq,"operationsServer");async function ule(){Hi.trace("Configuring HarperDB process."),Jce.setSchemaDataToGlobal(),await Zce.setUsersToGlobal(),await ele.getLicense()}a(ule,"setUp");function _le(e){Hi.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=dle(e),r=$ce(t);r.server.headersTimeout=Ele(),r.setErrorHandler(sle);let n=fle();n&&r.register(Yce,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,_){r.server.emit("unhandled",l.raw,_.raw)}),c()}),r.register(Qce),r.register(Kce),r.register(Wce,{root:jce.join(zce,"studio/build-local")}),ole(r);let s=ka.get(Jq.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Xce.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[ile,rle],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),nle(i,o)}),r.get("/health",()=>"HarperDB is running."),Hi.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(_le,"buildServer");function dle(e){let t=ka.get(id.OPERATIONSAPI_NETWORK_TIMEOUT),r=ka.get(id.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:cle,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(dle,"getServerOptions");function fle(){let e=ka.get(id.OPERATIONSAPI_NETWORK_CORS),t=ka.get(id.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===lle)&&(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(fle,"getCORSOpts");function Ele(){return ka.get(id.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??ale}a(Ele,"getHeaderTimeoutConfig")});var Lb={};Ve(Lb,{disableNATS:()=>ple,publishToStream:()=>Hp,setNATSReplicator:()=>yb,setPublishToStream:()=>mle,setSubscription:()=>Db,start:()=>hle});function hle(){od.default.get(ad.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Tle()}function ple(e=!0){sF=e}function mle(e,t){Hp=e,Db=t}function Tle(){if(sF||process.env._DISABLE_NATS)return;let e=Mr(),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];yb(s,r,i)}}Pb((r,n)=>{yb(r.tableName,r.databaseName,r),n&&oF(r)}),!eF&&(eF=!0)}function yb(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 er{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){oF(i)}static subscribe(){let i=new ts;return Db(t,e,i),i}static subscribeOnThisThread(i){return i<(od.default.get(ad.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Sle)}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 vp(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=iF;return i}a(n,"getNATSTransaction")}function oF(e){let t=od.default.get(ad.default.CONFIG_PARAMS.CLUSTERING_NODENAME);Hp(`${wb.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,Cb.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 tF,wb,Cb,rF,nF,od,ad,Bp,sF,Hp,Db,Sle,iF,eF,vp,Ib,aF=be(()=>{Re();Mn();tF=G(gt()),wb=G(Ze()),Cb=G(fi());tu();rF=G(rR()),nF=G(Nr()),od=G(X()),ad=G(D()),Bp=G(k());a(hle,"start");a(ple,"disableNATS");Hp=tF.publishToStream,Db=rF.setSubscription;a(mle,"setPublishToStream");Sle=2;a(Tle,"assignReplicationSource");a(yb,"setNATSReplicator");a(oF,"publishSchema");vp=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=od.default.get(ad.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],l,_;for(let u of i){let d=u.table,E=u.operation=="put"?"upsert":u.operation;l||(Bp.trace(`Sending transaction event ${E}`),_=l={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,E!=="delete"&&E!=="invalidate"&&(l.records=o)),l.table===d&&l.operation===E?(o.push(u.record),c.push(u.id)):_=_.next={operation:E,table:d,id:u.id,record:u.record},u.expiresAt&&(_.expiresAt=u.expiresAt)}l&&n.push(Hp(`${wb.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,Cb.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(u=>{throw Bp.error("An error has occurred trying to replicate transaction",l,u),u.statusCode=504,u}))}return Promise.all(n)}},Ib=class extends vp{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,nF.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};iF=new Ib});async function dF({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await Mb.get(e,{returnNonexistent:!0});i=new Bb(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await Mb.get(e);o&&o.delete()}i=new xp(e,t)}return n&&(n.id=e,n.user={username:t?.username},cd.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function Ub(){return Gp++,Gp>65500&&(Gp=1),Gp}function vb(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=No.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 it(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var lF,Mo,uF,_F,cF,Mb,cd,Gp,xp,Bb,fF=be(()=>{Re();I_();lF=G(Nr()),Mo=G(k());ha();uF=G(rt()),_F=G(Sb());yr();cF=100,Mb=St({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"}]}}]}),cd=St({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,uF.getWorkerIndex)()===0&&(async()=>{await _F.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of cd.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await dt.getUser(r.user.username));try{await vb(r,t,r)}catch{(0,Mo.warn)("Failed to publish will",t)}cd.delete(e.id)}})();a(dF,"getSession");Gp=1;a(Ub,"getNextMessageId");xp=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;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("?"),l,_;if(c>-1?(l=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 u=this.subscriptions.find(g=>g.topic===s),d;u?(d=i>0,u.end(),this.subscriptions.splice(this.subscriptions.indexOf(u),1)):d=i===2;let E={search:l,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Mo.trace)("Resuming subscription from",s,"from",o);let f=No.getMatch(_);if(!f){let g=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw g.statusCode=404,g}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let g=E.url.slice(1);if(g.indexOf("#")>-1&&g.indexOf("#")!==g.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,g.indexOf("+")===g.length-1)E.onlyChildren=!0,E.url="/"+g.slice(0,g.length-1);else{let T=g.split("/"),b;for(let U=0;U<T.length;U++)if(T[U].indexOf("+")>-1)if(T[U]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let N=!0;T[T.length-1]==="#"&&(T.length--,N=!1),b&&(n=a(U=>{let F=U.id;if(!Array.isArray(F)||N&&F.length!==T.length)return!1;for(let M=0;M<T.length;M++)if(T[M]!=="+"&&T[M]!==F[M])return!1;return!0},"filter"));let v=T.indexOf("+");E.url="/"+(v>-1?T.slice(0,v):T).concat("").join("/")}}let h=f.path,m=f.Resource,S=await it(E,async()=>{let g=this.createContext();g.topic=s,g.retainHandling=i;let T=await m.subscribe(E,g);if(!T)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!T[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let b=(async()=>{for await(let N of T)try{let v;if(N.type&&N.type!=="put"&&N.type!=="delete"&&N.type!=="message"&&N.type!=="patch"||n&&!n(N))continue;r?(N.topic=s,v=this.needsAcknowledge(N)):(N.acknowledge?.(),v=Ub());let U=N.id;if(Array.isArray(U)&&(U=Wc(U)),U==null&&(U=""),await this.listener(h+"/"+U,N.value,v,t)===!1)break;this.awaitingAcks?.size>cF?await new Promise(M=>setTimeout(M,this.awaitingAcks.size-cF)):await new Promise(setImmediate)}catch(v){(0,Mo.warn)(v)}})();return T});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=Ub();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 vb(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){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();it(r,async()=>{try{if(!t){let n=await cd.get(this.sessionId);n?.doesExist()&&await vb(n,n.data,r)}}finally{await cd.delete(this.sessionId)}}).catch(n=>{(0,Mo.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(vb,"publish");Bb=class extends xp{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=Ub(),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);if(!r)return;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,Mo.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,lF.getNextMonotonicTime)()),(0,Mo.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),Mb.put(this.sessionRecord)}}});var Gb={};Ve(Gb,{bypassAuth:()=>gle,start:()=>Rle});function gle(){SF=!0}function Rle({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new mF.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,l=r?.mtls;return n&&(c=e.ws((_,u,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),ar.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=hF(_,h=>{_.send(h)},u,Promise.resolve(d).then(()=>u?.user),o);_.on("message",E),_.on("close",f),_.on("error",h=>{ar.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let u;if(o.events.emit("connection",_),ar.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),l){if(_.authorized)try{let f=l.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{u=await e.getUser(f,null,null),(0,Tl.get)(cr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&Fp.notify({username:u?.username,status:cr.AUTH_AUDIT_STATUS.SUCCESS,type:cr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Tl.get)(cr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&Fp.error({username:f,status:cr.AUTH_AUDIT_STATUS.FAILURE,type:cr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else ar.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),ar.error(f)}else if(l.required)return ar.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!u&&SF&&_.remoteAddress.includes("127.0.0.1")&&(u=await(0,pF.getSuperUser)(),ar.debug("Auto-authorizing local connection",u?.username));let{onMessage:d,onClose:E}=hF(_,f=>_.write(f),null,u,o);_.on("data",d),_.on("close",E),_.on("error",f=>{ar.info("Socket error",f)})},{port:t,securePort:s,mtls:l})),c}function hF(e,t,r,n,s){EF||(EF=!0,Yu(d=>{qp>0&&d.push({metric:"mqtt-connections",connections:qp,byThread:!0})}));let i;qp++;let o,c={protocolVersion:4},l=(0,kp.parser)({protocolVersion:5});function _(d){l.parse(d)}a(_,"onMessage");function u(){qp--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),fn(!1,"connection","mqtt","disconnect"),ar.debug("MQTT connection was closed",e.remoteAddress))}return a(u,"onClose"),l.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;let E=d.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;vr(d.length,"bytes-received",h,S(d),"mqtt");try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await dt.getUser(d.username,d.password.toString(),r),(0,Tl.get)(cr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&Fp.notify({username:n?.username,status:cr.AUTH_AUDIT_STATUS.SUCCESS,type:cr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Tl.get)(cr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&Fp.error({username:d.username,status:cr.AUTH_AUDIT_STATUS.FAILURE,type:cr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),fn(!1,"connection","mqtt","connect"),m({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),fn(!1,"connection","mqtt","connect"),m({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let M=e.deserialize||(e.deserialize=Ba(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=dF({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return ar.error(M),s.events.emit("auth-failed",d,e,M),fn(!1,"connection","mqtt","connect"),m({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),fn(!0,"connection","mqtt","connect"),m({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,W,z,J)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",M);let le=M.indexOf("/",1),ue=le>0?M.slice(0,le):M;m({cmd:"publish",topic:M,payload:g(W),messageId:z||Math.floor(Math.random()*1e8),qos:J.qos},ue);let Ee=e._socket??e;return Ee.writableNeedDrain?new Promise(Ge=>Ee.once("drain",Ge)):!Ee.closed}catch(le){return ar.error(le),o?.disconnect(),s.sessions.delete(o),!1}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let T=[];for(let M of d.subscriptions){let W;try{W=(await o.addSubscription(M,M.qos>=1)).qos||0}catch(z){s.events.emit("error",z,e,M,o),ar.error(z),W=c.protocolVersion<5?128:z.statusCode===403?135:z.statusCode===404?143:128}T.push(W)}await o.committed,m({cmd:"suback",granted:T,messageId:d.messageId});break;case"unsubscribe":{let M=[];for(let W of d.unsubscriptions)M.push(o.removeSubscription(W)?0:17);m({cmd:"unsuback",granted:M,messageId:d.messageId});break}case"pubrel":m({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let b=d.qos===2?"pubrec":"puback",N=e.deserialize||(e.deserialize=Ba(r?.headers.get?.("content-type"))),U=(d.payload?.length||0)>0?N(d.payload):void 0,F;try{F=await o.publish(d,U)}catch(M){s.events.emit("error",M,e,d,o),ar.warn(M),d.qos>0&&m({cmd:b,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&m({cmd:b,messageId:d.messageId,reasonCode:F===!1?144:0},d.topic);break;case"pubrec":m({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":m({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),fn(!0,"connection","mqtt","disconnect"),ar.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(T){s.events.emit("error",T,e,d,o),ar.error(T),m({cmd:"disconnect"})}function m(T,b){let N=(0,kp.generate)(T,c);t(N),vr(N.length,"bytes-sent",b,S(T),"mqtt")}a(m,"sendPacket");function S(T){return T.qos>0?T.cmd+",qos="+T.qos:T.cmd}a(S,"packetMethodName");function g(T){return Pa(T,r)}a(g,"serialize")}),l.on("error",d=>{ar.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:_,onClose:u}}var kp,pF,Tl,cr,Hb,mF,Fp,ar,SF,EF,qp,TF=be(()=>{kp=require("mqtt-packet");fF();pF=G(Lr());jc();Ti();yr();Tl=G(X()),cr=G(D()),Hb=G(k()),mF=require("events"),Fp=(0,Hb.loggerWithTag)("auth-event"),ar=(0,Hb.loggerWithTag)("mqtt"),SF=(0,Tl.get)(cr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(gle,"bypassAuth");a(Rle,"start");qp=0;a(hF,"onSocket")});var Hh={};Ve(Hh,{component_errors:()=>Rl,loadComponent:()=>Vp,loadComponentDirectories:()=>wF,setErrorReporter:()=>Nle});function wF(e,t){t&&(qb=t),e&&(Fb=e);let r=[];if((0,tt.existsSync)(xb)){let s=(0,tt.readdirSync)(xb,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,at.join)(xb,o);r.push(Vp(c,qb,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(Vp(n,qb,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{IF=!0})}function Nle(e){ld=e}async function Vp(e,t,r,n,s,i){let o=(0,tt.realpathSync)(e);if(!RF.has(o)){RF.set(o,!0),s&&(Fb=s);try{let c;n&&(Rl=new Map);let l=(0,at.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,tt.existsSync)(l)?c=n?(0,yF.getConfigObj)():(0,AF.parseDocument)((0,tt.readFileSync)(l,"utf8"),{simpleKeys:!0}).toJSON():c=kb;let _=(0,at.join)(e,"node_modules","harperdb");try{Va.isMainThread&&(n||(0,tt.existsSync)(_)&&(0,tt.realpathSync)(Ol.PACKAGE_ROOT)!==(0,tt.realpathSync)(_))&&((0,tt.rmSync)(_,{recursive:!0,force:!0}),(0,tt.existsSync)((0,at.join)(e,"node_modules"))||(0,tt.mkdirSync)((0,at.join)(e,"node_modules")),(0,tt.symlinkSync)(Ol.PACKAGE_ROOT,_,"dir"))}catch(E){gl.default.error("Error symlinking harperdb module",E)}let u=[],d=n;for(let E in c){let f=c[E];if(Rl.set(n?E:(0,at.basename)(e),!1),!f)continue;let h,m=f.package;try{if(m){let N=e,v;for(;!(0,tt.existsSync)(v=(0,at.join)(N,"node_modules",E));)if(N=(0,at.dirname)(N),N.length<(0,NF.getHdbBasePath)().length){v=null;break}if(v)h=await Vp(v,t,r,!1),d=!0;else throw new Error(`Unable to find package ${E}:${m}`)}else h=ble[E];if(!h)continue;u.push(h);let S=a(N=>(N.origin=r,St(N)),"ensureTable"),g=f.network||(f.port||f.securePort)&&f,T=g?.securePort||g?.https&&g.port,b=!g?.https&&g?.port;if(Va.isMainThread&&(h=await h.startOnMainThread?.({server:dt,ensureTable:S,port:b,securePort:T,resources:t,...f})||h,n&&g))for(let N of[b,T])try{if(+N&&!gF.includes(N)){let v=Vb.get(Ol.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);v&&gl.default.warn("Session affinity is not recommended and may cause memory leaks"),(v||!bp)&&(gF.push(N),Ob(N,v))}}catch(v){console.error("Error listening on socket",N,v,E)}if(t.isWorker&&(h=await h.start?.({server:dt,ensureTable:S,port:b,securePort:T,resources:t,...f})||h),Fb.set(h,!0),(h.handleFile||h.handleDirectory)&&f.files){if(f.files.includes(".."))throw(0,bF.handleHDBError)("Can not reference parent directories");let N=(0,at.join)(e,f.files).replace(/\\/g,"/"),v=N.indexOf("/*");if(v>-1&&f.files!==kb[E]?.files&&!(0,tt.existsSync)(N.slice(0,v)))throw new Error(`The path '${N.slice(0,v)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let U=(0,at.basename)(e),F=f.path||"/";F=F.startsWith("/")?F:F.startsWith("./")?"/"+U+F.slice(2):F==="."?"/"+U:"/"+U+"/"+F;let M,W,z;if(f.root){let le=f.root;le.startsWith("/")&&(le=le.slice(1)),le.endsWith("/")&&(le=le.slice(0,-1)),le+="/",W=(0,at.join)(e,le)}else(z=N.indexOf("/*"))>-1&&(W=N.slice(0,z+1),M=(0,at.relative)(e,W));let J=!1;if(Va.isMainThread&&h.setupDirectory&&(J=await h.setupDirectory?.(F,W,t)),t.isWorker&&h.handleDirectory&&(J=await h.handleDirectory?.(F,W,t)),J)continue;for(let le of await(0,OF.default)(N,{onlyFiles:!1,objectMode:!0})){let{path:ue,dirent:Ee}=le;d=!0;let Ge=(0,at.relative)(e,ue).replace(/\\/g,"/");if(M)if(Ge.startsWith(M))Ge=Ge.slice(M.length+1);else throw new Error(`The root path '${f.root}' does not reference a valid part of the file path '${Ge}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let we=F+(F.endsWith("/")?"":"/")+Ge;try{if(Ee.isFile()){let xe=await Ole(ue);Va.isMainThread&&await h.setupFile?.(xe,we,ue,t),t.isWorker&&await h.handleFile?.(xe,we,ue,t)}else Va.isMainThread&&await h.setupDirectory?.(we,ue,t),t.isWorker&&await h.handleDirectory?.(we,ue,t)}catch(xe){xe.message=`Could not load ${Ee.isFile()?"file":"directory"} '${ue}'${f.module?" using '"+f.module+"'":""} for application '${e}' due to: ${xe.message}`,ld?.(xe),((0,Al.getWorkerIndex)()===0?console:gl.default).error(xe),t.set(f.path||"/",new ud(xe)),Rl.set(n?E:(0,at.basename)(e),xe.message)}}}}catch(S){S.message=`Could not load component '${E}' for application '${(0,at.basename)(e)}' due to: ${S.message}`,ld?.(S),((0,Al.getWorkerIndex)()===0?console:gl.default).error(S),t.set(f.path||"/",new ud(S),null,!0),Rl.set(n?E:(0,at.basename)(e),S.message)}}if(Va.isMainThread&&!IF&&i&&(0,Al.watchDir)(e,async()=>wF()),c.extensionModule)return await uf((0,at.join)(e,c.extensionModule));if(!d&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;ld?.(new Error(E)),((0,Al.getWorkerIndex)()===0?console:gl.default).error(E),Rl.set((0,at.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,ld?.(c),t.set("",new ud(c))}}}var tt,at,Va,AF,Vb,Ol,OF,Al,gl,bF,NF,Ale,yF,Ole,xb,Fb,IF,qb,Rl,ble,kb,gF,RF,ld,ud,Gh=be(()=>{tt=require("fs"),at=require("path"),Va=require("worker_threads"),AF=require("yaml"),Vb=G(X()),Ol=G(D());AI();yI();II();CG();gq();yq();OF=G(require("fast-glob")),Al=G(rt()),gl=G(k());gS();yr();bF=G(ie());Mn();Re();Nb();NF=G(X()),Ale=G(Zq());Ch();aF();TF();yF=G(Et());Np();({readFile:Ole}=tt.promises),xb=Vb.get(Ol.CONFIG_PARAMS.COMPONENTSROOT),Fb=new Map,Rl=new Map;a(wF,"loadComponentDirectories");ble={REST:rp,rest:rp,graphqlSchema:TS,jsResource:AS,fastifyRoutes:nb,login:bS,static:sb,operationsApi:Ale,customFunctions:{},http:{},clustering:Lb,authentication:C_,mqtt:Gb},kb={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(kb,"static",{value:{files:"web/**"}});gF=[],RF=new Map;a(Nle,"setErrorReporter");a(Vp,"loadComponent");ud=class extends er{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 Dp=R((Eye,DF)=>{var{isMainThread:CF}=require("worker_threads"),{getTables:yle}=(Re(),ae($e)),{loadComponentDirectories:Ile,loadComponent:wle}=(Gh(),ae(Hh)),{resetResources:Cle}=(I_(),ae(GB)),Dle=xA(),Lle=Et(),{dirname:Ple}=require("path"),{getConnection:Mle}=gt(),Ule=X(),vle=D(),$b=new Map;async function Ble(e=!1){!CF&&Ule.get(vle.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Mle();try{CF&&await Dle()}catch(n){console.error(n)}let t=Cle();yle(),t.isWorker=e,await wle(Ple(Lle.getConfigFilePath()),t,"hdb",!0,$b),await Ile($b,t);let r=[];for(let[n]of $b)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Ble,"loadRootComponents");DF.exports.loadRootComponents=Ble});var rt=R((pye,vo)=>{"use strict";var{Worker:Hle,MessageChannel:Gle,parentPort:js,isMainThread:jb,threadId:xle,workerData:Gi}=require("worker_threads"),{PACKAGE_ROOT:qle}=D(),{join:UF,isAbsolute:Fle,extname:kle}=require("path"),{server:vF}=(yr(),ae(jo)),{watch:Vle,readdir:$le}=require("fs/promises"),{totalmem:LF}=require("os"),_d=D(),BF=X(),xi=k(),{randomBytes:Yle}=require("crypto"),{_assignPackageExport:Kle}=require("../index"),Wle=D(),PF=1024*1024,Uo=[],Kn=[],Qle=50,zb=1e4,jle="restart",HF="request_thread_info",GF="resource_report",xF="thread_info",qF="added-port",zle="ack",Yb;Kle("threads",Kn);vo.exports={startWorker:Kb,restartWorkers:Xb,shutdownWorkers:tue,workers:Uo,setMonitorListener:lue,onMessageFromWorkers:rue,onMessageByType:WF,broadcast:sue,broadcastWithAcknowledgement:oue,setChildListenerByType:eue,getWorkerIndex:FF,getWorkerCount:kF,getTicketKeys:$F,setMainIsWorker:Xle,setTerminateTimeout:Jle,restartNumber:Gi?.restartNumber||1};Kn.onMessageByType=WF;Kn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Kn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var Jb;function Jle(e){zb=e}a(Jle,"setTerminateTimeout");function FF(){return Gi?Gi.workerIndex:Jb?0:void 0}a(FF,"getWorkerIndex");function kF(){return Gi?Gi.workerCount:Jb?1:void 0}a(kF,"getWorkerCount");function Xle(e){Jb=e}a(Xle,"setMainIsWorker");var VF=1,$p;function $F(){return $p||($p=jb?Yle(48):Gi.ticketKeys,$p)}a($F,"getTicketKeys");Object.defineProperty(vF,"workerIndex",{get(){return FF()}});Object.defineProperty(vF,"workerCount",{get(){return kF()}});var YF={[HF](e,t){aue(t)},[GF](e,t){cue(t,e)}};function Kb(e,t={}){let r=process.constrainedMemory?.()||LF();r=Math.min(r,LF(),2e4*PF);let n=BF.get(_d.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/PF/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Kn){let _=new Gle;_.existingPort=l,i.push(_),o.push(_.port2)}kle(e)||(e+=".js");let c=new Hle(Fle(e)?e:UF(qle,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:VF=t.threadCount,name:t.name,restartNumber:vo.exports.restartNumber,ticketKeys:$F()},transferList:o},t));for(let{port1:l,existingPort:_}of i)_.postMessage({type:qF,port:l,threadId:c.threadId},[l]);return Kp(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>Kb(e,t),c.on("error",l=>{xi.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Uo.splice(Uo.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Qle?(t.unexpectedRestarts=c.unexpectedRestarts+1,Kb(e,t)):xi.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{YF[l.type]?.(l,c)}),Uo.push(c),_ue(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(Kb,"startWorker");var Zle=[_d.THREAD_TYPES.HTTP];async function Xb(e=null,t=Math.max(VF>3,1),r=!0){if(jb){if(r){let{loadRootComponents:o}=Dp();await o()}vo.exports.restartNumber++,t<1&&(t=t*Uo.length);let n=[],s=[];for(let o of Uo.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;xi.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:vo.exports.restartNumber,type:_d.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Zle.indexOf(o.name)>-1,l=new Promise(_=>{let u=setTimeout(()=>o.terminate(),zb*2).unref();o.on("exit",()=>{clearTimeout(u),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),_()})});if(n.push(l),c&&r){let _=o.startCopy(),u=new Promise(d=>{let E=a(f=>{f.type===Wle.ITC_EVENT_TYPES.CHILD_STARTED&&(xi.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(u)),_.off("message",E))},"startListener");xi.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(u),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}=bo();r&&(e==="http"||!e)&&BF.get(_d.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else js.postMessage({type:jle,workerType:e})}a(Xb,"restartWorkers");function eue(e,t){YF[e]=t}a(eue,"setChildListenerByType");function tue(e){return Xb(e,1/0,!1)}a(tue,"shutdownWorkers");var KF=[];function rue(e){KF.push(e)}a(rue,"onMessageFromWorkers");var Wb=new Map;function WF(e,t){let r=Wb.get(e);r||Wb.set(e,r=[]),r.push(t)}a(WF,"onMessageByType");var nue=10;async function sue(e){let t=0;for(let r of Kn)try{r.postMessage(e),t++>nue&&(t=0,await new Promise(setImmediate))}catch(n){xi.error("Unable to send message to worker",n)}}a(sue,"broadcast");var Yp=new Map,iue=1;function oue(e){return new Promise(t=>{let r=0;for(let n of Kn)try{let s=iue++,i=a(()=>{Yp.delete(s),--r===0&&t(),n!==js&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,Yp.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of Yp)o.port===n&&o()})),n.postMessage(e),r++}catch(s){xi.error("Unable to send message to worker",s)}r===0&&t()})}a(oue,"broadcastWithAcknowledgement");function aue(e){e.postMessage({type:xF,workers:QF()})}a(aue,"sendThreadInfo");function QF(){let e=Date.now();return Uo.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(QF,"getChildWorkerInfo");function cue(e,t){e.resources=t,e.resources.updated=Date.now()}a(cue,"recordResourceReport");var Qb;function lue(e){Qb=e}a(lue,"setMonitorListener");var uue=1e3,MF=!1;function _ue(){MF||(MF=!0,setInterval(()=>{for(let e of Uo){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}Qb&&Qb()},uue).unref())}a(_ue,"startMonitoring");var due=1e3;if(js){Kp(js);for(let e=0,t=Gi.addPorts.length;e<t;e++){let r=Gi.addPorts[e];r.threadId=Gi.addThreadIds[e],Kp(r)}setInterval(()=>{let e=process.memoryUsage();js.postMessage({type:GF,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},due).unref(),Yb=a(()=>new Promise((e,t)=>{js.on("message",r),js.postMessage({type:HF});function r(n){n.type===xF&&(js.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else Yb=QF;vo.exports.getThreadInfo=Yb;function Kp(e,t){Kn.push(e),e.on("message",r=>{if(r.type===qF)r.port.threadId=r.threadId,Kp(r.port);else if(r.type===zle){let n=Yp.get(r.id);n&&n()}else{for(let s of KF)s(r,e);let n=Wb.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){xi.error(i)}}}).on("close",()=>{Kn.splice(Kn.indexOf(e),1)}).on("exit",()=>{Kn.splice(Kn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(Kp,"addPort");if(jb){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await $le(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(UF(s,o.name));try{for await(let{filename:o}of Vle(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await Xb(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");vo.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else js.on("message",async e=>{let{type:t}=e;t===_d.ITC_EVENT_TYPES.SHUTDOWN&&(vo.exports.restartNumber=e.restartNumber,js.unref(),setTimeout(()=>{xi.warn("Thread did not voluntarily terminate",xle),process.exit(0)},zb).unref())})});var LP={};Ve(LP,{AUDIT_STORE_OPTIONS:()=>Rh,createAuditEntry:()=>hf,openAuditStore:()=>zp,readAuditEntry:()=>Yt,setAuditRetention:()=>Eue,transactionKeyEncoder:()=>nk});function zp(e){let t=e.auditStore=e.openDB(ek.AUDIT_STORE_NAME,Rh);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=Wp){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c;try{for(let{key:l,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-Zb})){if((_[0]&15)===rN){let u=Yt(_),d=u.tableId;r[d]?.(u.recordId)}if(c=t.remove(l),await new Promise(setImmediate),++o>=fue){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,Zb/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,jp.getWorkerIndex)()===(0,jp.getWorkerCount)()-1&&s(Wp),t}function Eue(e,t=Wp){Zb=e,Wp=t}function hf(e,t,r,n,s,i,o){let c=sk[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let l=1;n&&(n>1?bl.setFloat64(0,n):Wn.set(qS),l=9),E(0),E(t),d(r),bl.setFloat64(l,e),l+=8,s?d(s):Wn[l++]=0,Wn[n?8:0]=c;let u=Wn.subarray(0,l);if(o)return Buffer.concat([u,o]);return u;function d(f){let h=l;l+=1,l=(0,Nl.writeKey)(f,Wn,l);let m=l-h-1;m>127?m>16383?(sN.error("Key or username was too large for audit entry",f),l=h+1,Wn[h]=0):(Wn.copyWithin(h+2,h+1,l),bl.setUint16(h,m|32768),l++):Wn[h]=m}function E(f){f<128?Wn[l++]=f:f<16384?(bl.setUint16(l,f|32768),l+=2):f<1056964608?(bl.setUint32(l,f|3221225472),l+=4):(Wn[l]=255,bl.setUint32(l+1,f),l+=5)}}function Yt(e){try{let t=e.dataView||(e.dataView=new nN(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,l=t.position+=o,_=t.readFloat64();o=t.readInt();let u=t.position,d=t.position+=o;return{type:sk[n&7],tableId:i,get recordId(){return ZF(e,c,l)},version:_,previousLocalTime:r,get user(){return d>u?ZF(e,u,d):void 0},getValue(E,f,h){if(n&eN||n&tN&&!f)return E.decoder.decode(e.subarray(t.position));if(n&tN&&h)return iN(E.getEntry(this.recordId),h,E)}}}catch(t){return sN.error("Reading audit entry error",t,e),{}}}function ZF(e,t,r){let n=e.subarray(t,r);return(0,Nl.readKey)(n,0,r-t)}var Nl,Qp,ek,tk,jp,rk,sN,Wn,bl,nk,Rh,Zb,fue,Wp,eN,tN,jF,rN,zF,JF,XF,sk,nN,no=be(()=>{Nl=require("ordered-binary"),Qp=G(X()),ek=G(_t()),tk=G(D()),jp=G(rt()),rk=G(Y());cu();sN=G(k());Jp();(0,Qp.initSync)();Wn=Buffer.alloc(1024),bl=new DataView(Wn.buffer,Wn.byteOffset,1024),nk={writeKey(e,t,r){return e===au?(t.set(au,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Nl.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,Nl.readKey)(e,t,r)}},Rh={encoding:"binary",keyEncoder:nk},Zb=(0,rk.convertToMS)((0,Qp.get)(tk.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,fue=1e3,Wp=1e4;a(zp,"openAuditStore");a(Eue,"setAuditRetention");eN=16,tN=32,jF=1,rN=2,zF=3,JF=4,XF=5,sk={put:jF|eN,[jF]:"put",delete:rN,[rN]:"delete",message:zF|eN,[zF]:"message",invalidate:JF,[JF]:"invalidate",patch:XF|tN,[XF]:"patch"};a(hf,"createAuditEntry");a(Yt,"readAuditEntry");nN=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(ZF,"readKeySafely")});var oN={};Ve(oN,{add:()=>Xp,applyReverse:()=>ik,getRecordAtTime:()=>iN,rebuildUpdateBefore:()=>Zp});function Xp(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function Zp(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,Xp(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function ik(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=hue[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=ok}}function iN(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let l=n.get(i),_=Yt(l);switch(_.type){case"put":s=_.getValue(r);break;case"patch":ik(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let l in s)s[l]===ok&&(o[l]=!0,c++);for(;c>0&&i>0;){let l=n.get(i),_=Yt(l),u;switch(_.type){case"put":u=_.getValue(r);break;case"patch":u=_.getValue(r);break}for(let d in u)o[d]&&(s[d]=u[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let l in o)s[l]=null;return s}var hue,ok,Jp=be(()=>{no();a(Xp,"add");Xp.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};hue={add:Xp};a(Zp,"rebuildUpdateBefore");a(ik,"applyReverse");ok={};a(iN,"getRecordAtTime")});function Tn(e){return e[Pt]||(e[Pt]=Object.create(null))}function sm(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,l,_;if(o.resolve)_={get(){return o.resolve(this,this[Ie])},set(u){return o.set(this,u)},configurable:!0};else{switch(o.type){case"String":l=a(function(u){if(!(typeof u=="string"||u==null&&o.nullable!==!1))throw new Qn.ClientError(`${c} must be a string, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"ID":l=a(function(u){if(!(typeof u=="string"||u?.length>0&&u.every?.(d=>typeof d=="string")||u==null&&o.nullable!==!1))throw new Qn.ClientError(`${c} must be a string, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"Float":case"Number":l=a(function(u){let d=u?.__op__?u.value:u;if(!(typeof d=="number"||u==null&&o.nullable!==!1))throw new Qn.ClientError(`${c} must be a number, attempt to assign ${d}`);Tn(this)[c]=u},"set");break;case"Int":l=a(function(u){let d=u?.__op__?u.value:u;if(!(d>>0===d||u==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),u?.__op__?u.value=d:u=d;else throw new Qn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"Long":l=a(function(u){let d=u?.__op__?u.value:u;if(!(Math.round(d)===u&&Math.abs(d)<=9007199254740992||u==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),u?.__op__?u.value=d:u=d;else throw new Qn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"BigInt":l=a(function(u){let d=u?.__op__?u.value:u;if(!(typeof d=="bigint"||u==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),u?.__op__?u.value=d:u=d;else throw new Qn.ClientError(`${c} must be a number, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"Boolean":l=a(function(u){if(!(typeof u=="boolean"||u==null&&o.nullable!==!1))throw new Qn.ClientError(`${c} must be a boolean, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"Date":l=a(function(u){if(!(u instanceof Date||u==null&&o.nullable!==!1))if(typeof u=="string"||typeof u=="number")u=new Date(u);else throw new Qn.ClientError(`${c} must be a Date, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"Bytes":l=a(function(u){if(!(u instanceof Uint8Array||u==null&&o.nullable!==!1))throw new Qn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${u}`);Tn(this)[c]=u},"set");break;case"Any":case void 0:l=a(function(u){Tn(this)[c]=u},"set");break;default:l=a(function(u){if(!(typeof u=="object"||u==null&&o.nullable!==!1))throw new Qn.ClientError(`${c} must be an object, attempt to assign ${u}`);Tn(this)[c]=u},"set")}_={get(){let u=this[Pt];if(u&&c in u){let E=u[c];if(E?.__op__){let f=this[pe]?.[c];return E.update(f)}return E}let d=this[pe]?.[c];if(d&&typeof d=="object"){let E=ck(d,o);if(E)return u||(u=this[Pt]=Object.create(null)),u[c]=E}return d},set:l,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 l=this[Pt];return l?.[o]!==void 0?l[o]:this[pe]?.[o]}),i("set",function(o,c){let l=n[o];if(l)return l.set.call(this,c);if(t.sealed)throw new Qn.ClientError("Can not add a property to a sealed table schema");Tn(this)[o]=c}),i("deleteProperty",function(o){Tn(this)[o]=void 0}),i("toJSON",function(){let o=this[Pt],c;for(let _ in o){c||(c=Object.assign({},this[pe]));let u=o[_];if(u?.__op__){let d=c[_];u=u.update(d)}c[_]=u}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[pe])),Object.assign(c,this)),c||this[pe]}),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 ck(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?.[pe])throw new Error("Can not track an already tracked object, check for circular references");this[pe]=s}},sm(r,t)),new r(e)):new em(e);case Array:let n=new rm(e.length);n[pe]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=ck(o,t?.elements)),n[s]=o}return n;default:return e}}function uE(e){let t=e[Pt],r;for(let s in t){r||(r=Object.assign({},e[pe]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=uE(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[pe])),Object.assign(r,e)),r||e[pe]}function Ya(e,t=e[Pt]){let r;if(ak.call(e,pe)&&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=Ya(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[pe]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=oN[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Ya(s);r[n]=s}return r?Object.freeze(r):ak.call(e,pe)?e[pe]:e}function tm(e){let t=e[pe];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[$a]||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?.[pe]===s){if(tm(i))return!0}else return!0}}else{let r=e[Pt];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[pe]===i){if(tm(s))return!0}else return!0}else return!0}}return!1}var Qn,Pt,em,ak,$a,rm,nm,_E=be(()=>{Mn();Qn=G(ie());Jp();Pt=Symbol("own-data");a(Tn,"getChanges");a(sm,"assignTrackedAccessors");a(ck,"trackObject");em=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[pe])throw new Error("Can not track an already tracked object, check for circular references");this[pe]=t}};sm(em,{});a(uE,"collapseData");ak=Object.prototype.hasOwnProperty;a(Ya,"deepFreeze");a(tm,"hasChanges");$a=Symbol.for("has-array-changes"),rm=class extends Array{static{a(this,"TrackedArray")}[$a];constructor(t){super(t)}splice(...t){return this[$a]=!0,super.splice(...t)}push(...t){return this[$a]=!0,super.push(...t)}pop(){return this[$a]=!0,super.pop()}unshift(...t){return this[$a]=!0,super.unshift(...t)}shift(){return this[$a]=!0,super.shift()}};rm.prototype.constructor=Array;nm=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var fg={};Ve(fg,{CONTEXT:()=>Ie,ID_PROPERTY:()=>Ue,IS_COLLECTION:()=>Ss,MultiPartId:()=>il,RECORD_PROPERTY:()=>pe,Resource:()=>er,snake_case:()=>mue,transformForSelect:()=>om});function mue(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function lk(e,t){if(dd=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(dd=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new il;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){dd=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function gn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,_,u;if(r?(o?(u=i,o=o[Ie]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(u=s,c=u[this.primaryKey]??null,o=i[Ie]||i):u=i:(u=s,c=u[Ue]??u[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ie]||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(l=s,s[Symbol.iterator]){c=[],_=!0;for(let f of s){if(typeof f=="object"&&f)break;c.push(f)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let m=this.parseQuery(c.slice(f+1));l?l=Object.assign(m,l):l=m,c=c.slice(0,f)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=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(l?.ensureLoaded!=null||l?.async||_?(d=Object.assign({},t),l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),_&&(d.isCollection=!0)):d=t,o.transaction){let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)}else return it(o,()=>{let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)},d);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,l,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,u,o):f.allowUpdate(o.user,u,o):t.type==="create"?f.allowCreate(o.user,u,o):f.allowDelete(o.user,l,o);if(h?.then)return h.then(m=>{if(!m)throw new im(o.user);return typeof u?.then=="function"?u.then(S=>e(f,l,o,S)):e(f,l,o,u)});if(!h)throw new im(o.user)}return typeof u?.then=="function"?u.then(h=>e(f,l,o,h)):e(f,l,o,u)}a(E,"authorizeActionOnResource")}}function Rn(e,t){let r=new dk.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 aN(e,t,r){let n=e[pe];if(n){let s=e[Pt];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 om(e,t){let r=t?.propertyResolvers,n=t[Ie],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):aN(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let _=[],u=i(aN(l,r,n));for(let d of e)_.push(u(d));return _},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(E=>E&&typeof E=="object"?c(E):E);let _={},u=i(aN(l,r,n)),d;for(let E of e){let f=u(E);f===void 0&&o&&(f=null),f?.then?(d||(d=[]),d.push(f.then(h=>_[E.name||E]=h))):_[E.name||E]=f}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 l=s[c.name];if(!l){let u=r[c.name]?.definition?.tableClass;l=s[c.name]=om(c.select||c,u)}let _=o(c.name);return l(_)}else return o(c);else return c}}a(i,"handleProperty")}var uk,_k,dk,Ie,Ue,Ss,pe,pue,er,im,dd,il,Mn=be(()=>{uk=require("crypto");tu();_k=require("../index"),dk=G(ie());_E();ha();ep();Ie=Symbol.for("context"),Ue=Symbol.for("primary-key"),Ss=Symbol("is-collection"),pe=Symbol("stored-record"),pue={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},er=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ue]=t;let n=r?.[Ie];this[Ie]=n!==void 0?n:r||null}static get=gn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let _=om(l,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=gn(function(t,r,n,s){if(Array.isArray(s)&&t[Ss]){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,_=l.getResource(c[l.primaryKey],n,{async:!0});_.then?i.push(_.then(u=>u.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Rn(t,"put")},{hasContent:!0,type:"update"});static patch=gn(function(t,r,n,s){return t.patch?t.patch(s,r):Rn(t,"patch")},{hasContent:!0,type:"update"});static delete=gn(function(t,r,n,s){return t.delete?t.delete(r):Rn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,uk.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),n||(n={}),it(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Rn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=gn(function(t,r,n,s){return t.invalidate?t.invalidate(r):Rn(t,"delete")},{hasContent:!1,type:"update"});static post=gn(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=gn(function(t,r,n,s){return t.connect?t.connect(s,r):Rn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=gn(function(t,r,n,s){return t.subscribe?t.subscribe(r):Rn(t,"subscribe")},{type:"read"});static publish=gn(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.publish?t.publish(s,r):Rn(t,"publish")},{hasContent:!0,type:"create"});static search=gn(function(t,r,n,s){let i=t.search?t.search(r):Rn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=om(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=gn(function(t,r,n,s){return t.search?t.search(s,r):Rn(t,"search")},{hasContent:!0,type:"read"});static copy=gn(function(t,r,n,s){return t.copy?t.copy(s,r):Rn(t,"copy")},{type:"create"});static move=gn(function(t,r,n,s){return t.move?t.move(s,r):Rn(t,"move")},{type:"delete"});post(t){if(this[Ss])return this.constructor.create(this[Ue],t,this[Ie]);Rn(this,"post")}static isCollection(t){return t?.[Ss]}static coerceId(t){return t}static parseQuery(t){return Zh(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&&pue[o];if(c)r.requestedContentType=c;else if(n)n.property=o;else return{query:{property:o},id:lk(t,this),isCollection:dd}}let i=lk(t,this);return dd?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ie],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 l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let _=l.asMap.get(t);if(s=_?.find(u=>u.constructor===c),s)return s;_||l.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=l.find(_=>_[Ue]===t&&_.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let _=new Map;for(let u of l){let d=u[Ue],E=_.get(d);E?E.push(u):_.set(d,[u])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Ss]=!0),s}subscribe(t){return new ts}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new ts}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[Ie]}};er.prototype[Ie]=null;(0,_k._assignPackageExport)("Resource",er);a(mue,"snake_case");im=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(lk,"pathToId");il=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(gn,"transactional");a(Rn,"missingMethod");a(aN,"selectFromObject");a(om,"transformForSelect")});function hk(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=Ek,Sue(e.primaryStore,e.auditStore)):(c=fk,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{pk(fk[i])})));let l=c[i]||(c[i]=[]);l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now());let _=l[o];_||(_=l[o]=new Map,_.envs=l,_.tableId=o,_.store=e.primaryStore),t=Wc(t);let u=new lN(r);u.startTime=n;let d=_.get(t);return d?d.push(u):(_.set(t,d=[u]),d.tables=_,d.key=t),u.subscriptions=d,u}function pk(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Yt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l,_=Wc(i.recordId),u=0;do{let d=o.get(_);if(d){for(let f of d)if(!(u>0&&!(f.includeDescendants&&!(f.onlyChildren&&u>1)))){if(f.startTime>=n){(0,cN.info)("omitting",c,f.startTime,n);continue}try{let h;f.supportsTransactions&&f.txnInProgress!==i.version&&(h=!0,f.txnInProgress||(r?r.push(f):r=[f]),f.txnInProgress=i.version),f.listener(c,i,n,h)}catch(h){console.error(h),(0,cN.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,u++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Sue(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let l=Ek[s];if(!l)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now(),pk(l),r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var cN,fk,Ek,lN,mk=be(()=>{cN=G(k());tu();I_();no();fk=Object.create(null),Ek=Object.create(null);a(hk,"addSubscription");lN=class extends ts{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(pk,"notifyFromTransactionData");a(Sue,"listenToCommits")});var qO={};Ve(qO,{coerceType:()=>am,makeTable:()=>um,setServerUtilities:()=>Iue,updateResource:()=>cm});function um(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:_,dbisDB:u,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:m}=e,{attributes:S}=e;S||(S=[]);let g=VS(i,n,l),T=0,b,N,v={},U=Promise.resolve(),F,M,W;for(let Q of S)(Q.assignCreatedTime||Q.name==="__createdtime__")&&(F=Q),(Q.assignUpdatedTime||Q.name==="__updatedtime__")&&(M=Q),Q.expiresAt&&(W=Q),Q.isPrimaryKey&&(v=Q);let z,J=[],le=[],ue=1,Ee=2,Ge={},we={},xe=864e5,Wd,Qd,zi,_y=!1,jm,zm,nY=i.getRange({start:!1,end:!1}).constructor,sY=10,iY=6;h&&Ey();class Xe extends er{static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=F;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=u;static schemaDefined=_;static sourcedFrom(p,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(p.intermediateSource=!0,this.sources.unshift(p)):this.sources.push(p),N=p.get&&(!p.get.reliesOnPrototype||p.prototype.get);let L=a(P=>{let y=this.sources.slice(0,-1);if(y=y.filter(B=>B[P]&&(!B[P].reliesOnPrototype||B.prototype[P])),y.length>0)if(y.length===1){let B=y[0];return(q,C,x)=>{if(q?.source!==B)return B[P](C,x,q)}}else return(B,q,C)=>{let x=[];for(let H of y){if(B?.source===H)break;x.push(H[P](q,C,B))}return Promise.all(x)}},"getApplyToIntermediateSource"),O=this.sources[this.sources.length-1],I=a(P=>{if(O[P]&&(!O[P].reliesOnPrototype||O.prototype[P]))return(y,B,q)=>{if(!y?.source)return O[P](B,q,y)}},"getApplyToCanonicalSource");return Ge={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish")},we={put:L("put"),patch:L("patch"),delete:L("delete"),publish:L("publish"),invalidate:L("invalidate")},(async()=>{let P=!1,y=a(async(B,q)=>{let C=B.value,x=B.table?ft[c][B.table]:Xe;if(c===gs.SYSTEM_SCHEMA_NAME&&(B.table===gs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||B.table===gs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(P=!0),B.id===void 0&&(B.id=C[x.primaryKey],B.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(B));B.source=p;let H=await x.getResource(B.id,q,yl);switch(B.type){case"put":return H._writeUpdate(C,!0,yl);case"patch":return H._writeUpdate(C,!1,yl);case"delete":return H._writeDelete(yl);case"publish":return H._writePublish(C,yl);case"invalidate":return H.invalidate(yl);default:ct.error("Unknown operation",B.type,B.id)}},"writeUpdate");try{let B=p.subscribe;B&&m==null&&(m=!0);let q=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Wa.getWorkerIndex)()):(0,Wa.getWorkerIndex)()===0,C=B&&q&&await p.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let x;for await(let H of C)try{if(!(H.type==="transaction"?H.writes[0]:H)){ct.error("Bad subscription event",H);continue}if(H.source=p,x)if(H.beginTxn)x.resolve();else{y(H,x);continue}if(H.type==="end_txn")continue;let de=it(H,()=>{if(H.type==="transaction"){let se=[];for(let Be of H.writes)try{se.push(y(Be,H))}catch(_e){throw _e.message+=" writing "+JSON.stringify(Be)+" of event "+JSON.stringify(H),_e}return Promise.all(se)}else if(H.type==="define_schema"){let se=this.attributes.slice(0),Be;for(let _e of H.attributes)se.find(Pe=>Pe.name===_e.name)||(se.push(_e),Be=!0);Be&&(St({table:s,database:c,attributes:se,origin:"cluster"}),Td.signalSchemaChange(new gd.SchemaEventMsg(process.pid,gs.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return H.beginTxn?(x=H,y(H,H),new Promise(se=>{x.resolve=se})):y(H,H)});P&&(await de,Td.signalUserChange(new gd.UserEventMsg(process.pid))),H.onCommit&&(de?.then?de.then(H.onCommit):H.onCommit())}catch(ee){ct.error("error in subscription handler",ee)}}}catch(B){ct.error(B)}})(),this}static getResource(p,A,L){let O=super.getResource(p,A,L);if(p!=null){ql(p);try{if(O.hasOwnProperty(pe))return O;if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let I=!L?.async||i.cache?.get(p),P=Zn(A),y=P.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Jm(p,A,{transaction:y},I,B=>{if(B?cm(O,B):O[pe]=null,A.onlyIfCached&&A.noCacheStore){if(!O.doesExist())throw new An.ServerError("Entry is not cached",504)}else if(L?.ensureLoaded){let q=Xm(p,B,A,O);if(q)return P?.disregardReadTxn(),O[uN]=!0,dN(q,C=>(cm(O,C),O))}return O})}catch(I){throw I.message.includes("Unable to serialize object")&&(I.message+=": "+JSON.stringify(p)),I}}return O}ensureLoaded(){let p=Xm(this[Ue],this[Qr],this[Ie]);if(p)return this[uN]=!0,dN(p,A=>{this[Qr]=A,this[pe]=A.value,this[md]=A.version})}static setTTLExpiration(p){if(typeof p=="number")E=p*1e3,f||(f=0);else if(p&&typeof p=="object")E=p.expiration*1e3,f=(p.eviction||0)*1e3,xe=p.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");xe=xe||(E+f)/4,eS()}static enableAuditing(p=!0){h=p,p&&Ey(),Xe.audit=p}static coerceId(p){return p===""?null:am(p,v)}static async dropTable(){if(delete ft[c][s],c===o){for(let p of S)u.remove(Xe.tableName+"/"+p.name),r[p.name]?.drop();u.remove(Xe.tableName+"/"),i.drop(),await u.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));Td.signalSchemaChange(new gd.SchemaEventMsg(process.pid,gs.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(p){if(typeof p=="string")return this.getProperty(p);if(this[Ss])return this.search(p);if(this[Ue]===null){if(p?.conditions)return this.search(p);let A=Xe.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(p?.property)return this.getProperty(p.property);if(this.doesExist()||p?.ensureLoaded===!1||this[Ie]?.returnNonexistent)return this}allowRead(p,A){let L=zd(p);if(L?.read){if(L.isSuperUser)return!0;let O=L.attribute_permissions,I=A?.select;if(O?.length>0||_y&&I){if(A||(A={}),I){let P=O?.length>0&&_N(O,"read");A.select=I.map(y=>{let B=y.name||y;if(!P||P[B]){let q=zi[B]?.definition?.tableClass;if(q){if(y.name||(y={name:y}),!q.prototype.allowRead.call(null,p,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else A.select=O.filter(P=>P.read&&!zi[P.attribute_name]).map(P=>P.attribute_name);return A}else return!0}}allowUpdate(p,A){let L=zd(p);if(L?.update){let O=L.attribute_permissions;if(O?.length>0){let I=_N(O,"update");for(let P in A)if(!I[P])return!1;for(let P of O){let y=P.attribute_name;!P.update&&!(y in A)&&(A[y]=this.getProperty(y))}}return!0}}allowCreate(p,A){if(this[Ss]){let L=zd(p);if(L?.insert){let O=L.attribute_permissions;if(O?.length>0){let I=_N(O,"insert");for(let P in A)if(!I[P])return!1}else return!0}}else return this.allowUpdate(p,{})}allowDelete(p){return zd(p)?.delete}update(p,A){if(!Zn(this[Ie]))throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let O;return typeof p=="object"&&p&&(A?(Object.isFrozen(p)&&(p=Object.assign({},p)),this[pe]={},this[Pt]=p):(O=this[Pt],O&&(p=Object.assign(O,p)),this[Pt]=O=p)),this._writeUpdate(this[Pt],A),this}addTo(p,A){if(typeof A=="number"||typeof A=="bigint")this[fd]===Tk?this.set(p,(+this.getProperty(p)||0)+A):(this[fd]||this.update(),this.set(p,new nm(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(p,A){if(typeof A=="number")return this.addTo(p,-A);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Qr]}invalidate(p){let A=this[Ie],L=this[Ue];ql(L),Zn(this[Ie]).addWrite({key:L,store:i,invalidated:!0,entry:this[Qr],nodeName:this[Ie]?.nodeName,before:Ge.invalidate?.bind(this,A,L),beforeIntermediate:we.invalidate?.bind(this,A,L),commit:(I,P)=>{if(P?.version>I)return;let y=null;for(let B in r)y||(y={}),y[B]=this.getProperty(B);g(L,y,this[Qr],I,Ed,h,this[Ie],0,"invalidate")}})}static evict(p,A,L){let O=this.Source,I;if(!((N||h)&&(!A||(I=i.getEntry(p),!I||!A)||I.version!==L))){if(N){if(i.hasLock(p,I.version))return;let P;for(let y in r)P||(P={}),P[y]=A[y];if(P)return g(p,P,I,L,hd,null,null,0,null,!0)}return i.ifVersion(p,L,()=>{jd(p,A,null)}),h?g(p,null,I,L,hd,null,null,0,null,!0):i.remove(p,L)}}lock(){throw new Error("Not yet implemented")}static operation(p,A){return p.table||=s,p.schema||=c,yk.operation(p,A)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,A,L){let O=this[Ie],I=Zn(O),P=this[Ue];ql(P);let y=this[Qr];this[fd]=A?Tk:bue;let B={key:P,store:i,entry:y,nodeName:O?.nodeName,validate:q=>{p||(p=this[Pt]),A||p&&tm(this[Pt]===p?this:p)?O?.source||(I.checkOverloaded(),this.validate(p,!A),M&&(p[M.name]=M.type==="Date"?new Date(q):M.type==="String"?new Date(q).toISOString():q),A&&(t&&p[t]!==P&&(p[t]=P),F&&(y?.value?p[F.name]=y?.value[F.name]:p[F.name]=F.type==="Date"?new Date(q):F.type==="String"?new Date(q).toISOString():q),p=Ya(p))):I.removeWrite(B)},before:A?Ge.put?()=>Ge.put(O,P,p):null:Ge.patch?()=>Ge.patch(O,P,p):Ge.put?()=>Ge.put(O,P,Ya(this)):null,beforeIntermediate:A?we.put?()=>we.put(O,P,p):null:we.patch?()=>we.patch(O,P,p):we.put?()=>we.put(O,P,Ya(this)):null,commit:(q,C,x)=>{if(x){if(O&&C?.version>(O.lastModified||0)&&(O.lastModified=C.version),this[Qr]=C,C?.value?.[pe])throw new Error("Can not assign a record to a record, check for circular references");A||(this[pe]=C?.value??null)}this[Pt]=void 0,this[md]=q;let H=C?.value,ee=p;if(this[fd]=0,C?.version>=q)if(h){let _e=C.localTime,Pe=C.version;for(;ee&&(_e>q||Pe>=q&&_e>0);){let re=l.get(_e);if(!re)break;let Z=Yt(re);if(Pe=Z.version,Pe>q){if(Z.type==="patch"){let ge=Z.getValue(i);ee=Zp(ee,ge)}else if(Z.type==="put"||Z.type==="delete")return}else if(Pe===q)return;_e=Z.previousLocalTime}}else{if(A)return;ee=Zp(ee,H)}let de;if(A?de=ee:(this[pe]=H,de=A?ee:Ya(this,ee)),this[pe]=de,de?.[pe])throw new Error("Can not assign a record to a record, check for circular references");let se;A||(se=p),jd(P,H,de);let Be=A?"put":"patch";g(P,de,C,q,0,h,O,O.expiresAt||(E?E+Date.now():0),Be,!1,se)}};I.addWrite(B)}async delete(p){if(typeof p=="string")return this.deleteProperty(p);if(this[Ss]){for await(let A of this.search(p))(await Xe.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(p);return}return this[pe]?this._writeDelete(p):!1}_writeDelete(p){let A=Zn(this[Ie]),L=this[Ue];ql(L);let O=this[Ie];return A.addWrite({key:L,store:i,resource:this,nodeName:O?.nodeName,before:Ge.delete?.bind(this,O,L),beforeIntermediate:we.delete?.bind(this,O,L),commit:(I,P,y)=>{let B=P?.value;y&&(O&&P?.version>(O.lastModified||0)&&(O.lastModified=P.version),cm(this,P)),!(P?.version>I)&&(jd(this[Ue],B),ct.trace("Write delete entry",L,I),h||m?(g(L,null,this[Qr],I,0,h,this[Ie],0,"delete"),h||eS()):i.remove(this[Ue]))}}),!0}search(p){let A=this[Ie],L=Zn(A);if(!p)throw new Error("No query provided");let O=p.conditions;O?O.length===void 0&&(O=O[Symbol.iterator]?Array.from(O):[O]):O=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this[Ue]&&(O=[{attribute:null,comparator:"prefix",value:this[Ue]}].concat(O));let I,P={};function y(Z,ge){let qe;switch(ge){case"and":case void 0:if(Z.length<1)throw new Error('An "and" operator requires at least one condition');qe=!0;break;case"or":if(Z.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+ge)}let ys=qe&&{},Ji;for(let je of Z){if(je.conditions){je.conditions=y(je.conditions,je.operator);continue}let Xt=je[0]??je.attribute,Ln=Xt==null?v:Mi(S,Xt);if(Ln){if(qe){let Is=Es(Xt),Zt=ys[Is];Zt?(Zt.push(je),Ji=!0):ys[Is]=[je]}(Ln.type||fO[je.comparator])&&(je[1]===void 0?je.value=q(je.value,Ln):je[1]=q(je[1],Ln))}else if(Xt!=null)throw(0,An.handleHDBError)(new Error,`${Xt} is not a defined attribute`,404)}if(p.enforceExecutionOrder)return Z;if(Ji)for(let je in ys){let Xt=ys[je],Ln=Xt.length;if(Ln>1)for(let Is=0;Is<Ln;Is++){let Zt=Xt[Is];if(Zt.comparator==="ge"||Zt.comparator==="greater_than_equal")for(let Xi=0;Xi<Ln;Xi++){let ac=Xt[Xi];(ac.comparator==="le"||ac.comparator==="less_than_equal")&&(Zt.comparator="between",Zt.value=[Zt.value,ac.value],Z.splice(Z.indexOf(ac),1))}if(Zt.comparator==="equals"||!Zt.comparator){for(let Xi=0;Xi<Ln;Xi++)if(Xi!==Is){let ac=Xt[Xi];Z.splice(Z.indexOf(ac),1)}break}}}return Z}a(y,"prepareConditions");function B(Z,ge){if(p.enforceExecutionOrder)return Z;for(let qe of Z)qe.conditions&&(qe.conditions=B(qe.conditions,qe.operator));return Z.length>1&&ge!=="or"?(0,Nk.sortBy)(Z,Xh(Xe)):Z}a(B,"orderConditions");function q(Z,ge){return Array.isArray(Z)?Z.map(qe=>am(qe,ge)):am(Z,ge)}a(q,"coerceTypedValues");let C=p.operator;(O.length>0||C)&&(O=y(O,C));let x=typeof p.sort=="object"&&p.sort,H;if(x&&C!=="or"){let Z=x.attribute;if(I=O.find(ge=>Es(ge.attribute)===Es(Z)),!I){let ge=Mi(S,Z);if(!ge)throw(0,An.handleHDBError)(new Error,`${Array.isArray(Z)?Z.join("."):Z} is not a defined attribute`,404);if(ge.indexed)I={attribute:Z,comparator:"sort"},O.push(I);else if(O.length===0&&!p.allowFullScan)throw(0,An.handleHDBError)(new Error,`${Array.isArray(Z)?Z.join("."):Z} is not indexed and not combined with any other conditions`,404)}I&&(I.descending=!!x.descending)}O=B(O,C),x&&(I&&O[0]===I?x.next&&(H={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(I&&O.splice(O.indexOf(I),1),H=x));let ee=p.select;if(O.length===0&&(O=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:O,operator:C,postOrdering:H,selectApplied:!!ee};let de=L.useReadTxn(),se=EO(O,C,Xe,de,p,A,(Z,ge)=>dy(Z,ee,A,de,ge),P),Be=p.ensureLoaded!==!1;H||(se=re(se));let _e=Xe.transformEntryForSelect(ee,A,de,P,Be,!0),Pe=Xe.transformToOrderedSelect(se,ee,H,de,A,_e);function re(Z){return p.offset||p.limit!==void 0?Z.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0):Z}return a(re,"applyOffset"),H&&(Pe=re(Pe)),Pe.onDone=()=>{Pe.onDone=null,L.doneReadTxn()},Pe.selectApplied=!0,Pe.getColumns=()=>{if(ee){let Z=[];for(let ge of ee)ge==="*"?Z.push(...S.map(qe=>qe.name)):Z.push(ge.name||ge);return Z}return S.map(Z=>Z.name)},Pe}static transformToOrderedSelect(p,A,L,O,I,P){let y=new nY;if(L){p=dy(p,A,O,I,null);let B;y.iterate=function(){let C,x=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),H,ee=L.dbOrderedAttribute,de,se,Be=!0;function _e(re){let Z=re.next&&_e(re.next),ge=re.descending;return(qe,ys)=>{let Ji=Zm(qe,re.attribute,O),je=Zm(ys,re.attribute,O),Xt=ge?(0,Qa.compareKeys)(je,Ji):(0,Qa.compareKeys)(Ji,je);return Xt===0?Z?.(qe,ys)||0:Xt}}a(_e,"createComparator");let Pe=_e(L);return{async next(){let re;if(C)if(re=C.next(),re.done){if(H)return y.onDone&&y.onDone(),re}else return{value:await P.call(this,re.value)};B=[],de&&B.push(de);do if(re=await x.next(),re.done){if(H=!0,B.length)break;return y.onDone&&y.onDone(),re}else{let Z=re.value;if(Z?.then&&(Z=await Z),ee){let ge=Zm(Z,ee,O);if(Be)Be=!1,se=ge;else if(ge!==se){se=ge,de=Z;break}}B.push(Z)}while(!0);return L.isGrouped,B.sort(Pe),C=B[Symbol.iterator](),re=C.next(),re.done?(y.onDone&&y.onDone(),re):{value:await P.call(this,re.value)}},return(){y.onDone&&y.onDone(),x.return()},throw(){y.onDone&&y.onDone(),x.throw()}}};let q=a(C=>{if(typeof A=="object"&&Array.isArray(C.attribute))for(let x=0;x<A.length;x++){let H=A[x],ee;if(H.name===C.attribute[0]){for(ee=H.sort||(H.sort={});ee.next;)ee=ee.next;ee.attribute=C.attribute.slice(1),ee.descending=C.descending}else H===C.attribute[0]&&(A[x]=ee={name:H,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&q(C.next)},"applySortingOnSelect");q(L)}else y.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),y=y.map(P);return y}static transformEntryForSelect(p,A,L,O,I,P){if(p&&(p===t||p?.length===1&&p[0]===t)){let C=a(x=>(A?.transaction?.stale&&(A.transaction.stale=!1),x?.key??x),"transform");return p===t?C:p.asArray?x=>[C(x)]:x=>({[t]:C(x)})}let y;I&&N&&!p?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(y=!0);let B,q=a(function(C){let x;if(A?.transaction?.stale&&(A.transaction.stale=!1),C!=null){if(jm=C,x=C.value||C.deref?.(),!x&&(C.key===void 0||C.deref)){if(C=Jm(C.key??C,A,{transaction:L,lazy:p?.length<4},this.isSync,H=>H),C?.then)return C.then(q.bind(this));x=C?.value}if(y&&(C.metadataFlags&(Ed|hd)||C.expiresAt&&C.expiresAt<Date.now())){let H=Xm(C.key??C,C,A);if(H?.then)return H.then(q)}}if(x==null)return P?Ka.SKIP:x;if(p&&!(p[0]==="*"&&p.length===1)){let H,ee=a((se,Be)=>{let _e;typeof se=="object"?_e=se.name:_e=se;let Pe=zi?.[_e],re;if(Pe){let Z=O?.[_e];if(Z)if(Z.hasMappings){let qe=Pe.from?x[Pe.from]:Es(C.key);re=Z.get(qe),re||(re=[])}else re=Z.fromRecord?.(x);else re=Pe(x,A,C);let ge=a(qe=>{if(qe&&typeof qe=="object"){let ys=Pe.definition?.tableClass||Xe;B||(B={});let Ji=B[_e]||(B[_e]=ys.transformEntryForSelect(_e===se?null:se.select||(Array.isArray(se)?se:null),A,L,Z,I));if(Array.isArray(qe)){let je=[],Xt=ys.transformToOrderedSelect(qe,se.select,typeof se.sort=="object"&&se.sort,A,L,Ji)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ln=a(Zt=>{for(;!Zt.done;){if(Zt?.then)return Zt.then(Ln);je.push(Zt.value),Zt=Xt.next()}Be(je,_e)},"nextValue"),Is=Ln(Xt.next());Is&&(H||(H=[]),H.push(Is));return}else if(qe=Ji.call(this,qe),qe?.then){H||(H=[]),H.push(qe.then(je=>Be(je,_e)));return}}Be(qe,_e)},"handleResolvedValue");re?.then?(H||(H=[]),H.push(re.then(ge))):ge(re);return}else re=x[_e],re&&typeof re=="object"&&_e!==se&&(re=Xe.transformEntryForSelect(se.select||se,A,L,null)({value:re}));Be(re,_e)},"selectAttribute"),de;if(typeof p=="string")ee(p,se=>{de=se});else if(Array.isArray(p))if(p.asArray)de=[],p.forEach((se,Be)=>{se==="*"?p[Be]=x:ee(se,_e=>de[Be]=_e)});else{de={};let se=p.forceNulls;for(let Be of p)if(Be==="*")for(let _e in x)de[_e]=x[_e];else ee(Be,(_e,Pe)=>{_e===void 0&&se&&(_e=null),de[Pe]=_e})}else throw new An.ClientError("Invalid select"+p);return H?Promise.all(H).then(()=>de):de}return x},"transform");return q}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");h||St({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),p||(p={});let A=!p.rawEvents,L=[],O=hk(Xe,this[Ue]??null,function(P,y,B,q){try{let C=y.getValue?.(i,A);if(!C&&y.type==="patch"&&A){let H=i.getEntry(P);H?.version===y.version?C=H.value:C=y.getValue?.(i,!0,B),y.type="put"}let x={id:P,timestamp:B,value:C,version:y.version,type:y.type,beginTxn:q};L?L.push(x):this.send(x)}catch(C){ct.error(C)}},p.startTime||0,p),I=(async()=>{this[Ss]&&(O.includeDescendants=!0,p.onlyChildren&&(O.onlyChildren=!0)),p.supportsTransactions&&(O.supportsTransactions=!0);let P=this[Ue],y=p.previousCount;y>1e3&&(y=1e3);let B=p.startTime;if(this[Ss]){if(B){if(y)throw new An.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:q,value:C}of l.getRange({start:B,exclusiveStart:!0,snapshot:!1})){let x=Yt(C);if(x.tableId!==n)continue;let H=x.recordId;if(P==null||Ok(P,H)){let ee=x.getValue(i,A,q);if(O.send({id:H,timestamp:q,value:ee,version:x.version,type:x.type}),O.queue?.length>Rk&&await O.waitForDrain()===!1)return}O.startTime=q}}else if(y){let q=[];for(let{key:C,value:x}of l.getRange({start:"z",end:!1,reverse:!0}))try{let H=Yt(x);if(H.tableId!==n)continue;let ee=H.recordId;if(P==null||Ok(P,ee)){let de=H.getValue(i,A,C);if(q.push({id:ee,timestamp:C,value:de,version:H.version,type:H.type}),--y<=0)break}}catch(H){ct.error("Error getting history entry",C,H)}for(let C=q.length;C>0;)O.send(q[--C]);q[0]&&(O.startTime=q[0].timestamp)}else if(!p.omitCurrent){for(let{key:q,value:C,version:x,localTime:H}of i.getRange({start:P??!1,end:P==null?void 0:[P,Qa.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(C&&(O.send({id:q,timestamp:H,value:C,version:x,type:"put"}),O.queue?.length>Rk&&await O.waitForDrain()===!1))return}}else{y&&!B&&(B=0);let q=this[Qr]?.localTime;if(q===kS&&(i.cache?.delete(P),this[Qr]=i.getEntry(P),ct.trace("re-retrieved record",q,this[Qr]?.localTime),q=this[Qr]?.localTime),ct.trace("Subscription from",B,"from",P,q),B<q){let C=[],x=q;do{let H=l.get(x);if(H){p.omitCurrent=!0;let ee=Yt(H),de=ee.getValue(i,A,x);A&&(ee.type="put"),C.push({id:P,value:de,timestamp:x,...ee}),x=ee.previousLocalTime}else break;y&&y--}while(x>B&&y!==0);for(let H=C.length;H>0;)O.send(C[--H]);O.startTime=q}!p.omitCurrent&&this.doesExist()&&O.send({id:P,timestamp:q,value:this[pe],version:this[md],type:"put"})}for(let q of L)O.send(q);L=null})();return p.listener&&O.on("data",p.listener),O}doesExist(){return!!(this[pe]||this[fd])}publish(p,A){this._writePublish(p,A)}_writePublish(p,A){let L=Zn(this[Ie]),O=this[Ue]||null;ql(O);let I=this[Ie];L.addWrite({key:O,store:i,entry:this[Qr],nodeName:I?.nodeName,validate:()=>{I?.source||(L.checkOverloaded(),this.validate(p))},before:Ge.publish?.bind(this,I,O,p),beforeIntermediate:we.publish?.bind(this,I,O,p),commit:(P,y,B)=>{y===void 0&&m&&!h&&eS(),g(O,y?.value??null,y,y?.version||P,0,!0,I,y?.expiresAt,"message",!1,p)}})}validate(p,A){let L,O=a((I,P,y)=>{if(P.type&&I!=null)if(A&&I.__op__&&(I=I.value),P.properties){typeof I!="object"&&(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be an object${P.type?" ("+P.type+")":""}`);let B=P.properties;for(let q=0,C=B.length;q<C;q++){let x=B[q],H=O(I[x.name],x,y+"."+x.name);H&&(I[x.name]=H)}if(P.sealed&&I!=null&&typeof I=="object")for(let q in I)B.find(C=>C.name===q)||(L||(L=[])).push(`Property ${q} is not allowed within object in property ${y}`)}else switch(P.type){case"Int":(typeof I!="number"||I>>0!==I)&&(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof I!="number"||!(Math.floor(I)===I&&Math.abs(I)<=9007199254740992))&&(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof I!="number"&&(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a number`);break;case"ID":typeof I=="string"||I?.length>0&&I.every?.(B=>typeof B=="string")||(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a string, or an array of strings`);break;case"String":typeof I!="string"&&(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a string`);break;case"Boolean":typeof I!="boolean"&&(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a boolean`);break;case"Date":if(!(I instanceof Date)){if(typeof I=="string"||typeof I=="number")return new Date(I);(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a Date`)}break;case"BigInt":if(typeof I!="bigint"){if(typeof I=="string"||typeof I=="number")return BigInt(I);(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a bigint`)}break;case"Bytes":I instanceof Uint8Array||(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(I)){if(P.elements)for(let B=0,q=I.length;B<q;B++){let C=I[B],x=O(C,P.elements,y+"[*]");x&&(I[B]=x)}}else(L||(L=[])).push(`Value ${Ts(I)} in property ${y} must be a Buffer or Uint8Array`);break}P.nullable===!1&&I==null&&(L||(L=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let I=0,P=S.length;I<P;I++){let y=S[I];if(!y.relationship&&(!A||y.name in p)){let B=O(p[y.name],y,y.name);B&&(p[y.name]=B)}}if(d)for(let I in p)S.find(P=>P.name===I)||(L||(L=[])).push(`Property ${I} is not allowed`);if(L)throw new An.ClientError(L.join(". "))}getUpdatedTime(){return this[md]}wasLoadedFromSource(){return N?!!this[uN]:void 0}static async addAttributes(p){let A=S.slice(0);for(let L of p){if(!L.name)throw new An.ClientError("Attribute name is required");if(L.name.match(/[`/]/))throw new An.ClientError("Attribute names cannot include backticks or forward slashes");A.push(L)}return St({table:s,database:c,schemaDefined:_,attributes:A}),Xe.indexingOperation}static async removeAttributes(p){let A=S.filter(L=>!p.includes(L.name));return St({table:s,database:c,schemaDefined:_,attributes:A}),Xe.indexingOperation}static getRecordCount(p){let A=i.getStats().entryCount,L=1e3/2,O=performance.now(),I=Math.floor(A/2),P=p?.exactCount,y=0,B=0,q;for(let{value:C}of i.getRange({start:!0,lazy:!0}))if(C!=null&&y++,B++,!P&&B<I&&performance.now()-O>L){q=B;break}if(q){let C=y;y=0;for(let{value:re}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:q}))re!=null&&y++;let x=q*2,H=(y+C)/x,ee=Math.pow((y-C+1)/q/2,2)+H*(1-H)/x,de=Math.max(Math.sqrt(ee)*A,1),se=Math.round(H*A),Be=Math.max(se-1.96*de,y+C),_e=Math.min(se+1.96*de,A),Pe=Math.pow(10,Math.round(Math.log10(de)));return Pe>se&&(Pe=Pe/10),y=Math.round(se/Pe)*Pe,{recordCount:y,estimatedRange:[Math.round(Be),Math.round(_e)]}}return{recordCount:y}}static updatedAttributes(){zi=this.propertyResolvers={$id:(p,A,L)=>({value:L.key}),$updatedtime:(p,A,L)=>L.version,$record:(p,A,L)=>L?{value:p}:p};for(let p of this.attributes){p.resolve=null;let A=p.relationship;if(A)if(p.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),_y=!0,A.to)p.elements?.definition?(zi[p.name]=p.resolve=(L,O,I)=>{let P=L[A.from?A.from:t],y=p.elements.definition.tableClass;return I?sl({attribute:A.to,value:P},Zn(O).getReadTxn(),!1,y,!1).asArray:y.search([{attribute:A.to,value:P}],O).asArray},p.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},p.resolve.definition=p.elements.definition,A.from&&(p.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${p.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let L=p.definition||p.elements?.definition;L?(zi[p.name]=p.resolve=(O,I,P)=>{let y=O[A.from];if(y!==void 0){if(p.elements){let B,q=y.map(C=>{let x=P?L.tableClass.primaryStore.getEntry(C,{transaction:Zn(I).getReadTxn()}):L.tableClass.get(C,I);return x?.then&&(B=!0),x});return A.filterMissing?B?Promise.all(q).then(C=>C.filter(bk)):q.filter(bk):B?Promise.all(q):q}return P?L.tableClass.primaryStore.getEntry(y,{transaction:Zn(I).getReadTxn()}):L.tableClass.get(y,I)}},p.set=(O,I)=>{if(Array.isArray(I)){let P=I.map(y=>y[Ue]||y[L.tableClass.primaryKey]);O[A.from]=P}else{let P=I[Ue]||I[L.tableClass.primaryKey];O[A.from]=P}},p.resolve.definition=p.definition||p.elements?.definition,p.resolve.from=A.from):console.error(`The relationship property "${p.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${p.name}" in table "${s}" must use either "from" or "to" arguments`)}sm(this,this)}static async deleteHistory(p=0){let A;for(let{key:L,value:O}of l.getRange({start:0,end:p}))await pd(),Yt(O).tableId===n&&(A=l.remove(L));await A}static async*getHistory(p=0,A=1/0){for(let{key:L,value:O}of l.getRange({start:p,end:A})){await pd();let I=Yt(O);I.tableId===n&&(yield{id:I.recordId,localTime:L,version:I.version,type:I.type,value:I.getValue(i,!0,L),user:I.user})}}static async getHistoryOfRecord(p){let A=[];if(p==null)throw new Error("An id is required");let L=i.getEntry(p);if(!L)return A;let O=L.localTime;if(!O)throw new Error("The entry does not have a local audit time");let I=0;do{await pd();let P=l.get(O);if(P){let y=Yt(P);A.push({id:y.recordId,localTime:O,version:y.version,type:y.type,value:y.getValue(i,!0,O),user:y.user}),O=y.previousLocalTime}else break}while(I<1e3&&O);return A.reverse()}static cleanup(){z?.remove()}}Xe.updatedAttributes();let oY=Xe.prototype;return oY[Oue]=!0,E&&Xe.setTTLExpiration(E/1e3),W&&aY(),Xe;function jd(Q,p,A){let L;for(let O in r){let I=r[O],P=I.isIndexing,y=A?.[O],B=p?.[O];if(y===B&&!P)continue;L=!0;let q=I.indexNulls,C=(0,Sd.getIndexedValues)(y,q),x=(0,Sd.getIndexedValues)(B,q);if(x?.length>0){let H=new Set(x);if(C=C?C.filter(ee=>{if(H.has(ee))H.delete(ee);else return!0}):[],x=Array.from(H),(x.length>0||C.length>0)&&Sk){let ee=x.concat(C).map(de=>({key:de,value:Q}));I.prefetch(ee,Ak)}for(let ee=0,de=x.length;ee<de;ee++)I.remove(x[ee],Q)}else C?.length>0&&Sk&&I.prefetch(C.map(H=>({key:H,value:Q})),Ak);if(C)for(let H=0,ee=C.length;H<ee;H++)I.put(C[H],Q)}return L}a(jd,"updateIndices");function ql(Q){switch(typeof Q){case"number":return!0;case"string":if(Q.length<659)return!0;if(Q.length>gk)throw new Error("Primary key size is too large: "+Q.length);break;case"object":if(Q===null)return!0;break;case"bigint":if(Q<2n**64n&&Q>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof Q)}if((0,Qa.writeKey)(Q,Nue,0)>gk)throw new Error("Primary key size is too large: "+Q.length);return!0}a(ql,"checkValidId");function Jm(Q,p,A,L,O){let I=a(()=>{if(p?.transaction?.stale&&(p.transaction.stale=!1),A.transaction?.isDone)return O(null,Q);let P=i.getEntry(Q,A);return P&&p&&(P?.version>(p.lastModified||0)&&(p.lastModified=P.version),P?.localTime&&!p.lastRefreshed&&(p.lastRefreshed=P.localTime)),O(P,Q)},"whenPrefetched");return L?I():ue>0?(ue--,I()):new Promise((P,y)=>{ue===0?(ue--,i.prefetch([Q],()=>{B(),q()})):(J.push(Q),le.push(q),J.length>iY&&(ue--,B()));function B(){if(J.length>0){let C=le;i.prefetch(J,()=>{ue===-1?B():ue++;for(let x of C)x()}),J=[],le=[],Ee>2&&Ee--}else ue=Ee,Ee<sY&&Ee++}a(B,"prefetch");function q(){try{P(I())}catch(C){y(C)}}a(q,"load")})}a(Jm,"loadLocalRecord");function zd(Q){if(!Q?.role)return;let p=Q.role.permission;if(p.super_user)return yue;let A=p[c],L,O=A?.tables;if(O)return O[s];if(c==="data"&&(L=p[s])&&!L.tables)return L}a(zd,"getTablePermissions");function Xm(Q,p,A,L){if(N){let O;if(A.noCache?O=!0:(p?(!p.value||p.metadataFlags&(Ed|hd)||p.expiresAt&&p.expiresAt<Date.now())&&(O=!0):O=!0,fn(!O,"cache-hit",s)),O){let I=fy(Q,p,A).then(P=>(P?.value?.[pe]&&ct.error("Can not assign a record with a record property"),A&&(P?.version>(A.lastModified||0)&&(A.lastModified=P.version),A.lastRefreshed=Date.now()),P));if(A?.onlyIfCached||p?.value&&L?.allowStaleWhileRevalidate?.(p,Q)){if(I.catch(P=>ct.warn(P)),A?.onlyIfCached&&!L.doesExist())throw new An.ServerError("Entry is not cached",504);return}else return I}}}a(Xm,"ensureLoadedFromSource");function Zn(Q){let p=Q?.transaction;if(p){if(!p.lmdbDb)return p.lmdbDb=i,p;do{if(p.lmdbDb?.path===i.path)return p;let A=p.next;if(!A)return p=p.next=new Ea,p.lmdbDb=i,p;p=A}while(!0)}else return new cE}a(Zn,"txnForContext");function Zm(Q,p,A){if(!Q)return;jm=Q;let L=Q.value||Q.deref?.()||(jm=i.getEntry(Q.key))?.value;if(typeof p=="object"){let I=zi,P=L;for(let y=0,B=p.length;y<B;y++){let q=p[y],C=I?.[q];P=C&&P?C(P,A,!0)?.value:P?.[q],I=C?.definition?.tableClass?.propertyResolvers}return P}let O=zi[p];return O?O(L,A):L[p]}a(Zm,"getAttributeValue");function dy(Q,p,A,L,O){let I=O?.length,P={transaction:L,lazy:I>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},y;function B(q,C){let x=q?.value;if(!x)return Ka.SKIP;for(let H=0;H<I;H++)if(!y?.includes(H)&&!O[H](x,q))return Ka.SKIP;return C!==void 0&&(q.key=C),q}if(a(B,"processEntry"),I>0||!Q.hasEntries){let q=Q.map(C=>{if(y=null,typeof C=="object"&&C?.key!==void 0)return I>0?B(C):C;if(C==null)return Ka.SKIP;for(let x=0;x<I;x++){let ee=O[x].idFilter;if(ee){if(!ee(C))return Ka.SKIP;y||(y=[]),y.push(x)}}return Jm(C,A,P,!1,B)});return Array.isArray(Q)&&(q=q.filter(C=>C!==Ka.SKIP)),q.hasEntries=!0,q}return Q}a(dy,"transformToEntries");async function fy(Q,p,A){let L=p?.metadataFlags,O=p?.version,I,P;if(!i.attemptLock(Q,O,()=>{clearTimeout(P);let C=i.getEntry(Q);!C||!C.value||C.metadataFlags&(Ed|hd)?I(fy(Q,i.getEntry(Q),A)):I(C)}))return new Promise(C=>{I=C,P=setTimeout(()=>{i.unlock(Q,O)},Aue)});let y=p?.value,B={requestContext:A,replacingRecord:y,replacingVersion:O,noCacheStore:!1,source:null,resourceCache:A?.resourceCache},q=A?.responseHeaders;return new Promise((C,x)=>{let H;dN(it(B,async ee=>{let de=performance.now(),se,Be,_e;try{for(let ge of Xe.sources)if(ge.get&&(!ge.get.reliesOnPrototype||ge.prototype.get)&&(B.source=ge,se=await ge.get(Q,B),se))break;_e=L&Ed;let re=B.lastModified||_e&&O;Be=_e||re>O||!y,re||(re=(0,Sd.getNextMonotonicTime)());let Z=performance.now()-de;if(vr(Z,"cache-resolution",s),q&&BA(q,"Server-Timing",`cache-resolve;dur=${Z.toFixed(2)}`,!0),ee.timestamp=re,E&&!B.expiresAt&&(B.expiresAt=Date.now()+E),se){if(typeof se!="object")throw new Error("Only objects can be cached and stored in tables");typeof se.toJSON=="function"&&(se=se.toJSON()),t&&se[t]!==Q&&(se[t]=Q)}H=!0,C({version:re,value:se})}catch(re){re.message+=` while resolving record ${Q} for ${s}`,y&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(C({version:O,value:y}),ct.trace(re.message,"(returned stale record)")):x(re),B.transaction.abort();return}if(A?.noCacheStore||B.noCacheStore){B.transaction.abort();return}Zn(B).addWrite({key:Q,store:i,entry:p,nodeName:"source",commit:(re,Z)=>{if(Z?.version!==O)return;let ge=jd(Q,y,se);se?(we.put?.(B,Q,se),g(Q,se,Z,re,0,h&&Be||null,B,B.expiresAt,"put",!!_e)):(we.delete?.(B,Q),h||m?g(Q,null,Z,re,0,h&&Be||null,B,0,"delete",!!_e):i.remove(Q,O))}})}),()=>{i.unlock(Q,O)},ee=>{i.unlock(Q,O),H&&ct.error("Error committing cache update",ee)})})}a(fy,"getFromSource");function eS(){if(xe!==Wd&&(Wd=xe,(0,Wa.getWorkerIndex)()===(0,Wa.getWorkerCount)()-1)){if(Qd&&clearTimeout(Qd),!xe)return;let Q=new Date;Q.setMonth(0),Q.setDate(1),Q.setHours(0),Q.setMinutes(0),Q.setSeconds(0);let p=Math.ceil((Date.now()-Q.getTime())/xe)*xe+Q.getTime(),A=a(L=>{ct.trace(`Scheduled next cleanup scan at ${new Date(L)}ms`),Qd=setTimeout(()=>U=U.then(async()=>{if(A(Math.max(L+xe,Date.now())),i.rootStore.status!=="open"){clearTimeout(Qd);return}let O=50,I=new Array(O),P=0;ct.trace(`Starting cleanup scan for ${s}`);try{let y=0;for(let{key:B,value:q,version:C,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let H;q===null&&!h&&C+Rue<Date.now()?H=i.remove(B,C):x&&x+f<Date.now()&&(H=Xe.evict(B,q,C),y++),H&&(await I[P],I[P]=H.catch(ee=>{ct.error("Cleanup error",ee)}),++P>=O&&(P=0)),await pd()}ct.trace(`Finished cleanup scan for ${s}, evicted ${y} entries`)}catch(y){ct.trace(`Error in cleanup scan for ${s}:`,y)}}),Math.min(L-Date.now(),2147483647)).unref()},"startNextTimer");A(p)}}a(eS,"scheduleCleanup");function Ey(){z=l?.addDeleteRemovalCallback(n,Q=>{let p=i.getEntry(Q);p?.value===null&&i.remove(Q,p.version)})}a(Ey,"addDeleteRemoval");function aY(){(0,Wa.getWorkerIndex)()===0&&setInterval(async()=>{if(!zm){zm=!0;try{let Q=W.name,p=r[Q];if(!p)throw new Error(`expiresAt attribute ${W} must be indexed`);for(let A of p.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let L of p.getValues(A)){let O=i.getEntry(L);O?.value?O.value[Q]<Date.now()&&Xe.evict(L,O.value,O.version):i.ifVersion(L,O?.version,()=>p.remove(A,L))}await pd()}}catch(Q){ct.error("Error in evicting old records",Q)}finally{zm=!1}}},gue).unref()}a(aY,"runRecordExpirationEviction")}function _N(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 Ak(){}function Iue(e){yk=e}function am(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;switch(r){case"Int":case"Long":return e==="null"?null:parseInt(e);case"Float":return e==="null"?null:parseFloat(e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":return isNaN(e)?e==="null"?null:(wue.test(e)||(e+="Z"),new Date(e)):new Date(+e);case void 0:case"Any":return(0,lm.autoCast)(e);default:return e}}function Ok(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 dN(e,t,r){return e?.then?e.then(t,r):t(e)}function cm(e,t){e[Qr]=t,e[pe]=t?.value??null,e[md]=t?.version}function bk(e){return e!=null}function Ts(e){try{return JSON.stringify(e)}catch{return e}}var gs,Ka,Sd,Nk,Rd,An,Td,gd,ct,Qa,Wa,lm,Tue,yk,gue,Rue,Sk,Aue,md,Oue,Qr,fd,Tk,bue,uN,yl,Ed,hd,Nue,gk,Rk,yue,eIe,wue,pd,Ep=be(()=>{gs=G(D()),Ka=require("lmdb"),Sd=G(Nr()),Nk=require("lodash");Mn();vg();Rd=G(X());mk();An=G(ie()),Td=G(hi()),gd=G(os());Re();ep();ct=G(k());_E();ha();Qa=require("ordered-binary"),Wa=G(rt());no();lm=G(Y());cu();Ti();Jp();w_();Tue=new Uint8Array(9);Tue[8]=192;gue=6e4,Rue=864e5;Rd.initSync();Sk=Rd.get(gs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Aue=1e4,md=Symbol.for("version"),Oue=Symbol.for("incremental-update"),Qr=Symbol("entry"),fd=Symbol("is-saving"),Tk=1,bue=2,uN=Symbol("loaded-from-source"),yl={isNotification:!0,ensureLoaded:!1},Ed=1,hd=8,Nue=Buffer.allocUnsafeSlow(8192),gk=1978,Rk=100,yue={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},eIe=(0,lm.convertToMS)(Rd.get(gs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(um,"makeTable");a(_N,"attributesAsObject");a(Ak,"noop");a(Iue,"setServerUtilities");wue=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(am,"coerceType");a(Ok,"isDescendantId");pd=a(()=>new Promise(setImmediate),"rest");a(dN,"when");a(cm,"updateResource");a(bk,"exists");a(Ts,"stringify")});var $e={};Ve($e,{database:()=>Ic,databases:()=>ft,dropDatabase:()=>qg,dropTableMeta:()=>Mue,getDatabases:()=>Mr,getDefaultCompression:()=>Ah,getTables:()=>Cue,onUpdatedTable:()=>Pb,readMetaDb:()=>Ad,resetDatabases:()=>R_,table:()=>St,tables:()=>nn});function Cue(){return hm||Mr(),nn||{}}function Mr(){if(hm)return ft;hm=!0,Cl=new Map;let e=(0,Ot.getHdbBasePath)()&&(0,lt.join)((0,Ot.getHdbBasePath)(),Vt.DATABASES_DIR_NAME),t=(0,Ot.get)(Vt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Ot.get)(Vt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,On.existsSync)(e)?e:(0,lt.join)((0,Ot.getHdbBasePath)(),Vt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,On.existsSync)(e))for(let r of(0,On.readdirSync)(e,{withFileTypes:!0})){let n=(0,lt.basename)(r.name,".mdb");r.isFile()&&(0,lt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Ad((0,lt.join)(e,r.name),null,n)}if((0,On.existsSync)((0,wl.getBaseSchemaPath)())){for(let r of(0,On.readdirSync)((0,wl.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,lt.join)((0,wl.getBaseSchemaPath)(),r.name),s=(0,lt.join)((0,wl.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,On.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,lt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,lt.join)(s,i.name);Ad((0,lt.join)(n,i.name),(0,lt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,On.existsSync)(s))for(let o of(0,On.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,lt.extname)(o.name).toLowerCase()===".mdb"&&Ad((0,lt.join)(s,o.name),(0,lt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],l=(0,lt.join)(c.path,(0,lt.basename)(o+".mdb"));(0,On.existsSync)(l)&&Ad(l,o,r,null,!0)}}for(let r in ft){let n=Cl.get(r);if(n){let s=ft[r];r.includes("delete")&&jn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(jn.trace(`delete table class ${i}`),delete s[i])}else if(delete ft[r],r==="data"){for(let s in nn)delete nn[s];delete nn[pm]}}return Cl=null,ft}}function R_(){hm=!1;for(let[,e]of Bo)e.needsDeletion=!0;Mr();for(let[e,t]of Bo)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Bo.delete(e));return ft}function Ad(e,t,r=hN,n,s){let i=new fN.default(e,!1);try{let o=Bo.get(e);o?o.needsDeletion=!1:(o=(0,dm.open)(i),Bo.set(e,o));let c=new ja.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(_m.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,On.existsSync)(n)&&(i.path=n,_=(0,dm.open)(i),_.isLegacy=!0):_=zp(o));let u=Dk(r),d=u[pm],E=new Map;for(let{key:f,value:h}of l.getRange({start:!1})){let[m,S]=f.toString().split("/");S===""?S=h.name:S||(S=m,m=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(m);let g=E.get(m);g||E.set(m,g={attributes:[]}),(S==null||h.is_hash_attribute)&&(g.primary=h),S!=null&&g.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:m,primary:S}=h;if(!S){for(let J of m)if(J.is_hash_attribute||J.isPrimaryKey){S=J;break}if(!S){jn.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(m)}`);continue}}let g=u[f],T={},b=[],N,v,U=typeof S.audit=="boolean"?S.audit:(0,Ot.get)(Vt.CONFIG_PARAMS.LOGGING_AUDITLOG),F=S.trackDeletes,M=S.expiration,W=S.eviction,z=S.sealed;if(g)T=g.indices,b=g.attributes,g.schemaVersion++;else{N=S.tableId,N?N>=(l.get(Il)||0)&&l.putSync(Il,N+1):(S.tableId=N=l.get(Il),N||(N=1),l.putSync(Il,N+1),l.putSync(S.key,S));let J=new ja.default(!S.is_hash_attribute,S.is_hash_attribute);if(J.compression=S.compression,J.compression){let le=(0,Ot.get)(Vt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||Ck;J.compression.threshold=le}v=pf(o.openDB(S.key,J)),v.rootStore=o,v.tableId=N}for(let J of m){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!T[J.name]){let ue=new ja.default(!J.is_hash_attribute,J.is_hash_attribute);T[J.name]=o.openDB(J.key,ue),T[J.name].indexNulls=J.indexNulls}let le=b.find(ue=>ue.name===J.name);le?b.splice(b.indexOf(le),1,J):b.push(J)}}catch(le){jn.error("Error trying to update attribute",J,b,T,le)}}if(!g){g=Lk(u,f,um({primaryStore:v,auditStore:_,audit:U,sealed:z,expirationMS:M&&M*1e3,evictionMS:W&&W*1e3,trackDeletes:F,tableName:f,tableId:N,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:T,attributes:m,schemaDefined:S.schemaDefined,dbisDB:l})),g.schemaVersion=1;for(let J of pN)J(g)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Dk(e){let t=ft[e];if(t||(e==="data"?t=ft[e]=nn:e==="system"?Object.defineProperty(ft,"system",{value:t=Object.create(null),configurable:!0}):t=ft[e]=Object.create(null)),Cl&&!Cl.has(e)){let r=new Set;t[pm]=r,Cl.set(e,r)}return t}function Lk(e,t,r){return e[t]=r,r}function Ic({database:e,table:t}){e||(e=hN),Mr();let r=Dk(e),n=(0,lt.join)((0,Ot.getHdbBasePath)(),Vt.DATABASES_DIR_NAME),s=(0,Ot.get)(Vt.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,Ot.get)(Vt.CONFIG_PARAMS.STORAGE_PATH)||((0,On.existsSync)(n)?n:(0,lt.join)((0,Ot.getHdbBasePath)(),Vt.LEGACY_DATABASES_DIR_NAME));let o=(0,lt.join)(n,(i?t:e)+".mdb"),c=Bo.get(o);if(!c){let l=new fN.default(o,!1);c=(0,dm.open)(l),Bo.set(o,c)}return c}async function qg(e){if(!ft[e])throw new Error("Schema does not exist");let t=ft[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Bo.delete(r.path),r.status==="open"&&(await r.close(),await Od.remove(r.path));if(r||(r=Ic({database:e,table:null}),r.status==="open"&&(await r.close(),await Od.remove(r.path))),e==="data"){for(let n in nn)delete nn[n];delete nn[pm]}delete ft[e]}function St({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:l,schemaDefined:_,origin:u}){t||(t=hN);let d=Ic({database:t,table:e}),E=ft[t],f=E?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,m,S,g;_==null&&(_=!0);let T=new ja.default(!1);for(let M of i)M.attribute&&!M.name?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let b,N;if(f){if(h=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=d.auditStore;M||(M=zp(d)),m=i.find(le=>le.isPrimaryKey)||{},h=m.name,m.is_hash_attribute=!0,m.schemaDefined=_,m.compression=Ah(),l&&(m.trackDeletes=!0),o=m.audit=typeof o=="boolean"?o:(0,Ot.get)(Vt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(m.expiration=r),n&&(m.eviction=n),typeof c=="boolean"&&(m.sealed=c),u&&(m.origins?m.origins.includes(u)||m.origins.push(u):m.origins=[u]),jn.trace(`${e} table loading, opening primary store`);let W=new ja.default(!1,!0);W.compression=m.compression;let z=e+"/",J=pf(d.openDB(z,W));J.rootStore=d,g=d.dbisDb=d.openDB(_m.INTERNAL_DBIS_NAME,T),J.tableId=g.get(Il),J.tableId||(J.tableId=1),g.putSync(Il,J.tableId+1),m.tableId=J.tableId,f=Lk(E,e,um({primaryStore:J,auditStore:M,audit:o,sealed:c,trackDeletes:l,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:g})),f.schemaVersion=1,b=!0,F(),g.put(z,m)}S=f.indices,g=g||(d.dbisDb=d.openDB(_m.INTERNAL_DBIS_NAME,T)),f.dbisDB=g;let v=[];for(let{key:M,value:W}of g.getRange({start:!0})){let[z,J]=M.toString().split("/");if(J===""&&(J=W.name),J){if(z!==e)continue}else J=z;if(!i.find(ue=>ue.name===J)?.indexed&&W.indexed&&!W.isPrimaryKey){F(),b=!0,g.remove(M);let ue=f.indices[z];ue&&v.push(ue)}}let U=[];try{for(let M of i||[]){if(M.relationship)continue;let W=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:W,configurable:!0});let z=g.get(W);if(M.isPrimaryKey){if(z=z||g.get(W=e+"/")||{},o!==f.audit||c!==c||(+r||void 0)!==(+z.expiration||void 0)||(+n||void 0)!==(+z.eviction||void 0)){let le=Object.assign({},z);typeof o=="boolean"&&(o&&f.enableAuditing(o),le.audit=o),r&&(le.expiration=+r),n&&(le.eviction=+n),c!==void 0&&(le.sealed=c),b=!0,F(),g.put(W,le)}continue}z?.attribute&&!z.name&&(z.indexed=!0);let J=!z||z.type!==M.type||z.indexed!==M.indexed||z.nullable!==M.nullable||JSON.stringify(z.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(z.elements)!==JSON.stringify(M.elements);if(M.indexed){let le=new ja.default(!0,!1),ue=d.openDB(W,le);(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<bd.workerData?.restartNumber)&&(b=!0,F(),z=g.get(W),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<bd.workerData?.restartNumber)&&(b=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=z?.lastIndexedKey||!1,M.indexingPID=process.pid,ue.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ue}),U.push(M))),g.put(W,M)),z?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ue.indexNulls=M.indexNulls,S[M.name]=ue}else J&&(b=!0,F(),g.put(W,M))}}finally{N&&N()}if(b&&(f.schemaVersion++,f.updatedAttributes()),jn.trace(`${e} table loading, running index`),U.length>0||v.length>0?f.indexingOperation=Pue(f,U,v):b&&fm.signalSchemaChange(new Em.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=u,b)for(let M of pN)M(f,u!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),jn.trace(`${e} table loaded`),f;function F(){N||d.transactionSync(()=>({then(M){N=M}}))}a(F,"startTxn")}async function Pue(e,t,r){try{let n=e.schemaVersion;await fm.signalSchemaChange(new Em.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let l of r)s=l.drop();let i,o=0,c=t.length;if(await new Promise(l=>setImmediate(l)),c>0){let l=0;for(let{key:_,value:u,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(u){if(l++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,m=(0,Ik.getIndexedValues)(u[h]);if(m)for(let S=0,g=m.length;S<g;S++)f.dbi.put(m[S],_)}}),s.then(()=>l--,E=>{l--,jn.error(E)}),bd.workerData&&bd.workerData.restartNumber!==wk.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}l>Due?await s:l>Lue&&await new Promise(E=>setImmediate(E))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await fm.signalSchemaChange(new Em.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){jn.error("Error in indexing",n)}}function Mue({table:e,database:t}){let r=Ic({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 Pb(e){pN.push(e)}function Ah(){let e=(0,Ot.get)(Vt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,Ot.get)(Vt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,Ot.get)(Vt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||Ck,n={startingOffset:32};return t&&(n.dictionary=Od.readFileSync(t)),r&&(n.threshold=r),e&&n}var Ot,_m,dm,lt,On,wl,ja,fN,Vt,Od,EN,Ik,fm,Em,bd,jn,wk,hN,pm,Ck,nn,ft,Il,pN,hm,Bo,Cl,Due,Lue,Re=be(()=>{Ot=G(X()),_m=G(_t()),dm=require("lmdb"),lt=require("path"),On=require("fs"),wl=G(ze());Ep();ja=G(lu()),fN=G(uu()),Vt=G(D()),Od=G(require("fs-extra")),EN=require("../index"),Ik=G(Nr()),fm=G(hi()),Em=G(os()),bd=require("worker_threads"),jn=G(k()),wk=G(rt());no();cu();hN="data",pm=Symbol("defined-tables"),Ck=((0,Ot.get)(Vt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,Ot.initSync)();nn=Object.create(null),ft=Object.create(null);(0,EN._assignPackageExport)("databases",ft);(0,EN._assignPackageExport)("tables",nn);Il=Symbol.for("next-table-id"),pN=[],Bo=new Map;a(Cue,"getTables");a(Mr,"getDatabases");a(R_,"resetDatabases");a(Ad,"readMetaDb");a(Dk,"ensureDB");a(Lk,"setTable");a(Ic,"database");a(qg,"dropDatabase");a(St,"table");Due=1e3,Lue=10;a(Pue,"runIndexing");a(Mue,"dropTableMeta");a(Pb,"onUpdatedTable");a(Ah,"getDefaultCompression")});var Y=R((lIe,Yk)=>{"use strict";var Ho=require("path"),Bk=require("fs-extra"),jr=k(),Pk=require("fs-extra"),mm=require("os"),Uue=require("net"),vue=require("recursive-iterator"),mt=D(),Bue=fS(),Mk=require("papaparse"),Sm=require("moment"),{inspect:Hue}=require("util"),Uk=require("is-number"),cIe=require("lodash"),Gue=require("minimist"),xue=require("https"),que=require("http"),{hdb_errors:Tm}=ie(),Fue=/^((\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)))$/,Hk=require("util").promisify(setTimeout),kue=100,Vue=5,$ue="",Yue=4,vk={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Yk.exports={isEmpty:bn,isEmptyOrZeroLength:zs,arrayHasEmptyValues:Que,arrayHasEmptyOrZeroLengthValues:jue,buildFolderPath:zue,isBoolean:Gk,errorizeMessage:Kue,stripFileExtension:Xue,autoCast:Zue,autoCastJSON:xk,autoCastJSONDeep:SN,removeDir:e_e,compareVersions:t_e,isCompatibleDataVersion:r_e,escapeRawValue:n_e,unescapeValue:s_e,stringifyProps:i_e,timeoutPromise:a_e,isClusterOperation:l_e,getClusterUser:__e,checkGlobalSchemaTable:u_e,getHomeDir:Fk,getPropsFilePath:o_e,promisifyPapaParse:d_e,removeBOM:kk,createEventPromise:f_e,checkProcessRunning:E_e,checkSchemaTableExist:h_e,checkSchemaExists:Vk,checkTableExists:$k,getStartOfTomorrowInSeconds:p_e,getLimitKey:m_e,isObject:Jue,isNotEmptyAndHasValue:Wue,autoCasterIsNumberCheck:qk,backtickASTSchemaItems:S_e,isPortTaken:c_e,createForkArgs:T_e,autoCastBoolean:g_e,async_set_timeout:Hk,getTableHashAttribute:R_e,doesSchemaExist:A_e,doesTableExist:O_e,stringifyObj:b_e,ms_to_time:N_e,changeExtension:y_e,getEnvCliRootPath:TN,noBootFile:I_e,httpRequest:w_e,transformReq:C_e,convertToMS:D_e,PACKAGE_ROOT:mt.PACKAGE_ROOT};function Kue(e){return e instanceof Error?e:new Error(e)}a(Kue,"errorizeMessage");function bn(e){return e==null}a(bn,"isEmpty");function Wue(e){return!bn(e)&&(e||e===0||e===""||Gk(e))}a(Wue,"isNotEmptyAndHasValue");function zs(e){return bn(e)||e.length===0||e.size===0}a(zs,"isEmptyOrZeroLength");function Que(e){if(bn(e))return!0;for(let t=0;t<e.length;t++)if(bn(e[t]))return!0;return!1}a(Que,"arrayHasEmptyValues");function jue(e){if(zs(e))return!0;for(let t=0;t<e.length;t++)if(zs(e[t]))return!0;return!1}a(jue,"arrayHasEmptyOrZeroLengthValues");function zue(...e){try{return e.join(Ho.sep)}catch{console.error(e)}}a(zue,"buildFolderPath");function Gk(e){return bn(e)?!1:e===!0||e===!1}a(Gk,"isBoolean");function Jue(e){return bn(e)?!1:typeof e=="object"}a(Jue,"isObject");function Xue(e){return zs(e)?$ue:e.slice(0,-Yue)}a(Xue,"stripFileExtension");function Zue(e){return bn(e)||e===""||typeof e!="string"?e:vk[e]!==void 0?vk[e]:qk(e)===!0?Number(e):Fue.test(e)?new Date(e):e}a(Zue,"autoCast");function xk(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(xk,"autoCastJSON");function SN(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=SN(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=SN(r);n!==r&&(e[t]=n)}return e}else return xk(e)}a(SN,"autoCastJSONDeep");function qk(e){if(e.startsWith("0.")&&Uk(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Uk(e))}a(qk,"autoCasterIsNumberCheck");async function e_e(e){if(zs(e))throw new Error(`Directory path: ${e} does not exist`);try{await Pk.emptyDir(e),await Pk.remove(e)}catch(t){throw jr.error(`Error removing files in ${e} -- ${t}`),t}}a(e_e,"removeDir");function t_e(e,t){if(zs(e)){jr.info("Invalid current version sent as parameter.");return}if(zs(t)){jr.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("."),l=Math.min(o.length,c.length);for(let _=0;_<l;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(t_e,"compareVersions");function r_e(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(r_e,"isCompatibleDataVersion");function n_e(e){if(bn(e))return e;let t=String(e);return t==="."?mt.UNICODE_PERIOD:t===".."?mt.UNICODE_PERIOD+mt.UNICODE_PERIOD:t.replace(mt.FORWARD_SLASH_REGEX,mt.UNICODE_FORWARD_SLASH)}a(n_e,"escapeRawValue");function s_e(e){if(bn(e))return e;let t=String(e);return t===mt.UNICODE_PERIOD?".":t===mt.UNICODE_PERIOD+mt.UNICODE_PERIOD?"..":String(e).replace(mt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(s_e,"unescapeValue");function i_e(e,t){if(bn(e))return jr.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+mm.EOL}!zs(n)&&n[0]===";"?r+=" "+n+s+mm.EOL:zs(n)||(r+=n+"="+s+mm.EOL)}catch{jr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(i_e,"stringifyProps");function Fk(){let e;try{e=mm.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Fk,"getHomeDir");function o_e(){let e=Ho.join(Fk(),mt.HDB_HOME_DIR_NAME,mt.BOOT_PROPS_FILE_NAME);return Bk.existsSync(e)||(e=Ho.join(__dirname,"../","hdb_boot_properties.file")),e}a(o_e,"getPropsFilePath");function a_e(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(a_e,"timeoutPromise");async function c_e(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Uue.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(c_e,"isPortTaken");function l_e(e){try{return mt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){jr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(l_e,"isClusterOperation");function u_e(e,t){let r=(Re(),ae($e)).getDatabases();if(!r[e])return Tm.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return Tm.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(u_e,"checkGlobalSchemaTable");function __e(e,t){if(bn(t)){jr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(bn(e)||zs(e)){jr.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){jr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){jr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(__e,"getClusterUser");function d_e(){Mk.parsePromise=function(e,t,r){return new Promise(function(n,s){Mk.parse(e,{header:!0,transformHeader:kk,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(d_e,"promisifyPapaParse");function kk(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(kk,"removeBOM");function f_e(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;jr.info(`Got cluster status event response: ${Hue(s)}`);try{i.cancel()}catch{jr.error("Error trying to cancel timeout.")}n(s)})})}a(f_e,"createEventPromise");async function E_e(e){let t=!0,r=0;do await Hk(kue*r++),(await Bue.findPs(e)).length>0&&(t=!1);while(t&&r<Vue);if(t)throw new Error(`process ${e} was not started`)}a(E_e,"checkProcessRunning");function h_e(e,t){let r=Vk(e);if(r)return r;let n=$k(e,t);if(n)return n}a(h_e,"checkSchemaTableExist");function Vk(e){let{getDatabases:t}=(Re(),ae($e));if(!t()[e])return Tm.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Vk,"checkSchemaExists");function $k(e,t){let{getDatabases:r}=(Re(),ae($e));if(!r()[e][t])return Tm.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a($k,"checkTableExists");function p_e(){let e=Sm().utc().add(1,mt.MOMENT_DAYS_TAG).startOf(mt.MOMENT_DAYS_TAG).unix(),t=Sm().utc().unix();return e-t}a(p_e,"getStartOfTomorrowInSeconds");function m_e(){return Sm().utc().format("DD-MM-YYYY")}a(m_e,"getLimitKey");function S_e(e){try{let t=new vue(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){jr.error("Got an error back ticking items."),jr.error(t)}}a(S_e,"backtickASTSchemaItems");function T_e(e){return[e]}a(T_e,"createForkArgs");function g_e(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(g_e,"autoCastBoolean");function R_e(e,t){let{getDatabases:r}=(Re(),ae($e)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(R_e,"getTableHashAttribute");function A_e(e){let{getDatabases:t}=(Re(),ae($e));return t()[e]!==void 0}a(A_e,"doesSchemaExist");function O_e(e,t){let{getDatabases:r}=(Re(),ae($e));return r()[e]?.[t]!==void 0}a(O_e,"doesTableExist");function b_e(e){try{return JSON.stringify(e)}catch{return e}}a(b_e,"stringifyObj");function N_e(e){let t=Sm.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(N_e,"ms_to_time");function y_e(e,t){let r=Ho.basename(e,Ho.extname(e));return Ho.join(Ho.dirname(e),r+t)}a(y_e,"changeExtension");function TN(){if(process.env[mt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[mt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Gue(process.argv);if(e[mt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[mt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(TN,"getEnvCliRootPath");var mN;function I_e(){if(mN)return mN;let e=TN();if(TN()&&Bk.pathExistsSync(Ho.join(e,mt.HDB_CONFIG_FILE)))return mN=!0,!0}a(I_e,"noBootFile");function w_e(e,t){let r;return e.protocol==="http:"?r=que:r=xue,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",l=>{c.body+=l}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(w_e,"httpRequest");function C_e(e){if(!e.schema&&!e.database){e.schema=mt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(C_e,"transformReq");function D_e(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(D_e,"convertToMS")});var X=R((_Ie,zk)=>{"use strict";var gN=require("fs-extra"),za=require("path"),Kk=require("os"),L_e=require("properties-reader"),yd=k(),Nd=Y(),fe=D(),gm=Et(),P_e="Error initializing environment manager",Rm="BOOT_PROPS_FILE_PATH",Wk=!1,M_e={[fe.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[fe.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[fe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},qi={};zk.exports={BOOT_PROPS_FILE_PATH:Rm,getHdbBasePath:U_e,setHdbBasePath:v_e,get:Qk,initSync:H_e,setProperty:ve,initTestEnvironment:x_e,setCloneVar:G_e};function U_e(){return qi[fe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(U_e,"getHdbBasePath");function v_e(e){qi[fe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(v_e,"setHdbBasePath");function Qk(e){let t=gm.getConfigValue(e);return t===void 0?qi[e]:t}a(Qk,"get");function ve(e,t){M_e[e]&&(qi[e]=t),gm.updateConfigObject(e,t)}a(ve,"setProperty");function B_e(){let e;try{e=Nd.getPropsFilePath(),gN.accessSync(e,gN.constants.F_OK|gN.constants.R_OK),Wk=!0;let t=L_e(e);return qi[fe.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(fe.HDB_SETTINGS_NAMES.INSTALL_USER),qi[fe.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(fe.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),qi[Rm]=e,!0}catch{return yd.trace(`Environment manager found no properties file at ${e}`),!1}}a(B_e,"doesPropFileExist");function H_e(e=!1){try{(Wk||B_e()||Nd.noBootFile())&&!jk&&(gm.initConfig(e),qi[fe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=gm.getConfigValue(fe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){yd.error(P_e),yd.error(t),console.error(t),process.exit(1)}}a(H_e,"initSync");var jk=!1;function G_e(e){jk=e}a(G_e,"setCloneVar");function x_e(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,l=za.join(__dirname,"../../","unitTests");qi[Rm]=za.join(l,"hdb_boot_properties.file"),ve(fe.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,za.join(l,"settings.test")),ve(fe.HDB_SETTINGS_NAMES.INSTALL_USER,Kk.userInfo()?Kk.userInfo().username:void 0),ve(fe.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),ve(fe.HDB_SETTINGS_NAMES.LOG_PATH_KEY,za.join(l,"envDir","log")),ve(fe.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),ve(fe.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),ve(fe.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),ve(fe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,za.join(l,"envDir")),ve(fe.CONFIG_PARAMS.STORAGE_PATH,za.join(l,"envDir")),s&&(ve(fe.CONFIG_PARAMS.HTTP_SECUREPORT,Qk(fe.CONFIG_PARAMS.HTTP_PORT)),ve(fe.CONFIG_PARAMS.HTTP_PORT,null)),ve(fe.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),ve(fe.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),ve(fe.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Nd.isEmpty(i)?!1:i),ve(fe.CONFIG_PARAMS.HTTP_CORS,Nd.isEmpty(i)?!1:i),ve(fe.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),ve(fe.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),ve(fe.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),ve(fe.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),ve(fe.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,za.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),ve(fe.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Nd.isEmpty(c)?!1:c),o&&(ve("CORS_ACCESSLIST",o),ve(fe.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(ve(fe.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),ve(fe.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(ve(fe.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),ve(fe.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(ve(fe.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),ve(fe.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Rm}. Please check your boot props and settings files`;yd.fatal(r),yd.error(t)}}a(x_e,"initTestEnvironment")});var Zk=R((fIe,Xk)=>{"use strict";var Om=X();Om.initSync();var Am=D(),{httpRequest:q_e}=Y(),F_e=require("path"),Jk=require("fs-extra"),k_e=require("yaml"),V_e={describe_table:!0,describe_all:!0,describe_database:!0,list_users:!0,list_roles:!0,drop_role:!0,add_user:!0,alter_user:!0,drop_user:!0,restart_service:!0,restart:!0,create_database:!0,drop_database:!0,create_table:!0,drop_table:!0,create_attribute:!0,drop_attribute:!0,search_by_id:!0,delete:!0,search_by_value:!0,csv_file_load:!0,csv_url_load:!0,cluster_get_routes:!0,cluster_network:!0,cluster_status:!0,remove_node:!0,add_component:!0,deploy_component:!0,package_component:!0,drop_component:!0,get_components:!0,get_component_file:!0,set_component_file:!0,registration_info:!0,get_fingerprint:!0,set_license:!0,get_job:!0,search_jobs_by_start_date:!0,read_log:!0,read_transaction_log:!0,read_audit_log:!0,delete_transaction_logs_before:!0,purge_stream:!0,delete_records_before:!0,install_node_modules:!0,set_configuration:!0,get_configuration:!0,create_authentication_tokens:!0,refresh_operation_token:!0,system_information:!0,sql:!0};Xk.exports={cliOperations:Y_e,buildRequest:$_e};function $_e(){let e={};for(let t of process.argv){if(V_e[t]){e.operation=t;continue}if(t.includes("=")){let[r,...n]=t.split("=");n=n.join("=");try{n=JSON.parse(n)}catch{}e[r]=n}}return e}a($_e,"buildRequest");async function Y_e(e){await Jk.exists(F_e.join(Om.get(Am.CONFIG_PARAMS.ROOTPATH),Am.HDB_PID_FILE))||(console.error("HarperDB must be running to perform this operation"),process.exit()),await Jk.exists(Om.get(Am.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))||(console.error("No domain socket found, unable to perform this operation"),process.exit());try{let t=await q_e({method:"POST",protocol:"http:",socketPath:Om.get(Am.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),headers:{"Content-Type":"application/json"}},e);t=JSON.parse(t.body),e.json?console.log(JSON.stringify(t,null,2)):console.log(k_e.stringify(t).trim())}catch(t){let r="Error: ";t?.response?.data?.error?r+=t.response.data.error:t?.response?.data?r+=t?.response?.data:r+=t.message,console.error(r)}}a(Y_e,"cliOperations")});var rV=R((hIe,tV)=>{"use strict";var eV=require("semver/functions/major"),K_e=ma(),RN=process.versions&&process.versions.node?process.versions.node:void 0;tV.exports=W_e;function W_e(){let e=K_e.engines["minimum-node"];if(RN&&eV(RN)<eV(e))return{error:`The minimum version of Node.js HarperDB supports is: ${e}, the currently installed Node.js version is: ${RN}. Please install a version of Node.js that is withing the defined range.`}}a(W_e,"checkNodeVersion")});var ON=R((mIe,nV)=>{"use strict";var Id=X();Id.initSync();var Dl=require("fs-extra"),AN=require("path"),Ll=D(),Q_e=require("crypto"),j_e=require("uuid").v4;nV.exports=z_e;function z_e(){if(Id.getHdbBasePath()!==void 0){let e=AN.join(Id.getHdbBasePath(),Ll.LICENSE_KEY_DIR_NAME,Ll.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=AN.join(Id.getHdbBasePath(),Ll.LICENSE_KEY_DIR_NAME,Ll.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=AN.join(Id.getHdbBasePath(),Ll.LICENSE_KEY_DIR_NAME,Ll.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Dl.accessSync(r),Dl.accessSync(e),Dl.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=j_e(),i=Q_e.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Dl.writeFileSync(r,s),Dl.writeFileSync(e,i.privateKey),Dl.writeFileSync(t,i.publicKey)}else throw n}}}a(z_e,"checkJWTTokenExist")});var iV=R((TIe,sV)=>{"use strict";var bN=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};sV.exports={HdbInfoInsertObject:bN}});var cV=R((RIe,aV)=>{"use strict";var oV=D(),NN=class{static{a(this,"UpgradeObject")}constructor(t,r){this[oV.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[oV.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};aV.exports={UpgradeObject:NN}});var bm=R((OIe,uV)=>{"use strict";var zn=require("prompt"),Pl=require("chalk"),lV=k(),Rs=require("os"),yN=to(),IN=["yes","y"];async function J_e(e){let t=`${Rs.EOL}`+Pl.bold.green("Your current HarperDB version requires that we complete an update process.")+`${Rs.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Rs.EOL}${Rs.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${Rs.EOL}`;zn.override=yN(["CONFIRM_UPGRADE"]),zn.start(),zn.message=t;let r={properties:{CONFIRM_UPGRADE:{description:Pl.magenta(`${Rs.EOL}[CONFIRM_UPGRADE] Do you want to upgrade your HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n;try{n=await zn.get([r])}catch(s){return lV.error("There was an error when prompting user about an upgrade."),lV.error(s),!1}return IN.includes(n.CONFIRM_UPGRADE)}a(J_e,"forceUpdatePrompt");async function X_e(e){let t=`${Rs.EOL}`+Pl.bold.green(`Your installed HarperDB version is older than the version used to create your data. Downgrading is not recommended as it is not tested and guaranteed to work. However, if you need to downgrade, and a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Rs.EOL}`);zn.override=yN(["CONFIRM_DOWNGRADE"]),zn.start(),zn.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:Pl.magenta(`${Rs.EOL}[CONFIRM_DOWNGRADE] Do you want to proceed with using your downgraded HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n=await zn.get([r]);return IN.includes(n.CONFIRM_DOWNGRADE)}a(X_e,"forceDowngradePrompt");async function Z_e(){let e=`${Rs.EOL}`+Pl.bold.green("We now require a Certifacte Authority certificate. HarperDB can generate all new certificates for you (your existing certificates will be backed up) or you can keep any existing certificates and add your own CA certificate. To add your own CA certificate set the <certificateAuthority> parameter in harperdb-config.yaml");zn.override=yN(["GENERATE_CERTS"]),zn.start(),zn.message=e;let t={properties:{GENERATE_CERTS:{description:Pl.magenta(`${Rs.EOL}[GENERATE_CERTS] Do you want HarperDB to generate all new certificates? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"yes",required:!0}}},r=await zn.get([t]);return IN.includes(r.GENERATE_CERTS)}a(Z_e,"upgradeCertsPrompt");uV.exports={forceUpdatePrompt:J_e,forceDowngradePrompt:X_e,upgradeCertsPrompt:Z_e}});var CN=R((NIe,_V)=>{"use strict";var wN=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};_V.exports=wN});var fV=R((LIe,dV)=>{"use strict";var ede=Y(),tde=Et(),IIe=k(),wIe=require("path"),CIe=require("fs"),DIe=D();dV.exports={getOldPropsValue:rde};function rde(e,t,r=!1){let n=t.getRaw(e);return ede.isNotEmptyAndHasValue(n)?n:r?tde.getDefaultConfig(e):""}a(rde,"getOldPropsValue")});var mV=R((MIe,pV)=>{"use strict";var Go=require("path"),xo=require("fs-extra"),nde=require("properties-reader"),sde=CN(),Mt=k(),{getOldPropsValue:Qe}=fV(),{HDB_SETTINGS_NAMES:oe,CONFIG_PARAMS:Ja}=D(),Xa=Et(),Nm=X(),EV=Y(),Js=D(),DN=new sde("3.1.0"),hV=[];function ide(){let e=nde(Nm.get(oe.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),Mt.info(t);let r=` ;Settings for the HarperDB process.
39
+ `},compressible:!1,q:.8});Or.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()}});e$={type:"application/json",serializeStream:c_,serialize:_E,deserialize:Ide,q:.5};Or.set("*/*",e$);Or.set("",e$);a(Ide,"tryJSONParse");a(bN,"registerContentHandlers");wde=require("fastify-plugin"),Cde=wde(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=US(n.raw);s.type(c),s.serializer(function(l){let d;if(typeof l=="object"&&l&&(l[Symbol.iterator]||l[Symbol.asyncIterator])&&o.serializeStream){if(l.mapError){let u=l.getColumns;l=l.mapError(_=>(_.toJSON=()=>({error:_.name,message:_.message,..._.partialObject}),_)),l.getColumns=u}d=o.serializeStream}else d=o.serialize;return d(l,{headers:{set:(u,_)=>{s.header(u,_)}}})})}),r()},{name:"content-type-negotiation"});a(US,"findBestSerializer");Wq=TN.default.get(gN.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(EE,"serialize");a(el,"serializeMessage");a(Dde,"streamToBuffer");a(il,"getDeserializer");a(jq,"deserializerUnknownType");a(Pde,"transformIterable")});function NN(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let _=d(l);for(let f=1;f<e.length;f++){let h=e[f],S=d(h);_=_.concat(S)}let E=new Set;return _.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let _=d(l),E=u(e.slice(1),!0,l.estimated_count);return E.length>0?o(_,E):_}function d(_){return _.conditions?NN(_.conditions,_.operator,r,n,s,i,o,c):od(_,n,_.descending||s.reverse===!0,r,s.allowFullScan,c)}a(d,"executeCondition");function u(_,E,f){return _.map((h,S)=>{if(h.conditions){let m=h.operator==="or",C=u(h.conditions,!m,f);return m?(O,x)=>C.some(F=>F(O,x)):(O,x)=>C.every(F=>F(O,x))}let T=(h.attribute||h[0])===r.primaryKey,g=mE(h,r,i,c,T,f);return E&&S<_.length-1&&f&&(f=kde(r.primaryStore,h.estimated_count,f)),g}).filter(Boolean)}a(u,"mapConditionsToFilters")}function od(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(Array.isArray(o)){let m=o[0],C=Fi(n.attributes,m);if(C.relationship){if(o.length<2)throw new Qn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let O=C.definition?.tableClass||C.elements?.definition?.tableClass,x=new Map,F=od({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,O,s,x);if(C.relationship.to){i[o[0]]=x;let Y=!!Fi(O.attributes,C.relationship.to)?.elements;F=Bde(F,C,O.primaryStore,Y,x)}if(C.relationship.from){let Y=a($=>od({attribute:C.relationship.from,value:$},t,r,n,s,x),"searchEntry");C.elements?(i[o[0]]=x,F=Hde(F,C,O.primaryStore,x,Y)):F=F.flatMap(Y)}return F}else if(o.length===1)o=o[0];else throw new Qn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let d,u,_,E;c instanceof Date&&(c=c.getTime());let f;switch(IN[l]||l){case"lt":d=!0,u=c;break;case"le":d=!0,u=c,_=!0;break;case"gt":d=c,E=!0;break;case"ge":d=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],d=c,u=c.slice(0),u[u.length-1]=xi.MAXIMUM_KEY;break;case"starts_with":d=c.toString(),u=c+"\uFFFF";break;case"between":d=c[0],d instanceof Date&&(d=d.getTime()),u=c[1],u instanceof Date&&(u=u.getTime()),_=!0;break;case"equals":case void 0:d=c,u=c,_=!0;break;case"ne":if(c===null){d=c,E=!0;break}case"sort":case"contains":case"ends_with":d=!0,f=!0;break;default:throw new Qn.ClientError(`Unknown query comparator "${l}"`)}let h,S=o===n.primaryKey||o==null;if(typeof d=="string"&&d.length>Ds.MAX_SEARCH_KEY_LENGTH&&(d=d.slice(0,Ds.MAX_SEARCH_KEY_LENGTH)+Ds.OVERFLOW_MARKER,E=!1,h=mE(e,n,null,i,S)),typeof u=="string"&&u.length>Ds.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,Ds.MAX_SEARCH_KEY_LENGTH)+Ds.OVERFLOW_MARKER,_=!0,h=h??mE(e,n,null,i,S)),r){let m=d;d=u,u=m,m=!E,E=!_,_=m}let T=S?n.primaryStore:n.indices[o];if(!T||T.isIndexing||f||c===null&&!T.indexNulls){if(s===!1&&!T)throw new Qn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Qn.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(T?.isIndexing)throw new Qn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!T.indexNulls)throw new Qn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(h=h??mE(e,n,null,i,S),!h)throw new Qn.ClientError(`Unknown search operator ${e.comparator}`)}let g={start:d,end:u,inclusiveEnd:_,exclusiveStart:E,values:!0,versions:S,transaction:t,reverse:r};if(S){let m=T.getRange(g).map(h?function({key:C,value:O}){return this?.isSync?O&&h(O)?C:Ma.SKIP:new Promise((x,F)=>setImmediate(()=>{try{x(O&&h(O)?C:Ma.SKIP)}catch(Y){F(Y)}}))}:C=>C.value==null&&!(C.metadataFlags&(ki|va))?Ma.SKIP:C);return m.hasEntries=!0,m}else return T?T.getRange(g).map(h?function({key:m,value:C}){let O;return typeof m=="string"&&m.length>Ds.MAX_SEARCH_KEY_LENGTH?O=n.primaryStore.get(C):O={[o]:m},this.isSync?h(O)?C:Ma.SKIP:new Promise((x,F)=>setImmediate(()=>{try{x(h(O)?C:Ma.SKIP)}catch(Y){F(Y)}}))}:({value:m})=>m):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:m,value:C}){return this.isSync?C&&h(C)?m:Ma.SKIP:new Promise((O,x)=>setImmediate(()=>{try{O(C&&h(C)?m:Ma.SKIP)}catch(F){x(F)}}))})}function Fi(e,t){if(Array.isArray(t))if(t.length>1){let r=Fi(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Fi(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 Bde(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let l=t.relationship.to,d=a((u,_)=>{let E=u;Array.isArray(u)&&(E=si(u),o=!0);let f=s.get(E);f?f.push(_):s.set(E,f=[_]),u!==E&&(f.key=u)},"add_entry");for(let u of e){let _=u.value??r.get(u.key??u),E=_?.[l];if(E!=null&&!s.filters?.some(f=>!f(_)))if(n)for(let f=0;f<E.length;f++)d(E[f],u);else d(E,u)}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}},return(){if(i?.return)return i.return()}}}})}function Hde(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let d=si(l.value);if(!c.has(d))return c.add(d),l}if(!i){let d=new Map;n.fromRecord=u=>u[t.relationship.from]?.filter?.(_=>d.has(si(_)));for(let u of e){if(n.filters){let _=r.get(u);if(n.filters.some(E=>!E(_)))continue}d.set(si(u),u)}return i=d.values()[Symbol.iterator](),this.next()}do{let d=i.next();return d.done?d:(o=s(d.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function mE(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=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 u=c[0],_=Fi(t.attributes,u),E=_.definition?.tableClass||_.elements.definition?.tableClass,f=n?.[u],h=mE({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},E,r,f?.[u]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let S=t.propertyResolvers?.[u],T,g=a((m,C)=>{let O,x;if(S){if(S.from&&h.idFilter){if(!T)if(h.idFilter.idSet?.size===1){for(let Y of h.idFilter.idSet)e={attribute:S.from,value:Y};T=d(S.from,h.idFilter,!0,!0)}else T=d(S.from,h.idFilter,!1,!0);let F=T(m);return T.idFilter&&(g.idFilter=T.idFilter),F}x=S(m,r,C),O=x?.value}else O=m[u];return O?Array.isArray(O)?O.some(h):h(O,x):!1},"recordFilter");return g}}switch(l instanceof Date&&(l=l.getTime()),IN[o]||o){case Ds.SEARCH_TYPES.EQUALS:case void 0:return d(c,u=>u===l,!0);case"contains":return d(c,u=>u?.toString().includes(l));case"ends_with":return d(c,u=>u?.toString().endsWith(l));case"starts_with":return d(c,u=>typeof u=="string"&&u.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],d(c,u=>{if(!Array.isArray(u))return!1;for(let _=0,E=l.length;_<E;_++)if(u[_]!==l[_])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),d(c,u=>(0,xi.compareKeys)(u,l[0])>=0&&(0,xi.compareKeys)(u,l[1])<=0,!0);case"gt":return d(c,u=>(0,xi.compareKeys)(u,l)>0);case"ge":return d(c,u=>(0,xi.compareKeys)(u,l)>=0);case"lt":return d(c,u=>(0,xi.compareKeys)(u,l)<0);case"le":return d(c,u=>(0,xi.compareKeys)(u,l)<=0);case"ne":return d(c,u=>(0,xi.compareKeys)(u,l)!==0);case"sort":return()=>!0;default:throw new Qn.ClientError(`Unknown query comparator "${o}"`)}function d(u,_,E,f){let h;E=E&&!s&&t?.indices[u]&&i>3,E&&(e.estimated_count==null&&BS(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let S=0,T=3;function g(m){let C=m[u],O;if(typeof C!="object"||!C||f?O=_(C):Array.isArray(C)?O=C.some(_):C instanceof Date&&(O=_(C.getTime())),E&&(T++,!O&&!g.idFilter&&++S/T*(i-T)>h)){let x=od(e,r.transaction.getReadTxn(),!1,t).map(si),F=new Set(x);g.idFilter=Y=>F.has(si(Y)),g.idFilter.idSet=F}return O}return a(g,"recordFilter"),s&&(g.idFilter=_),g}a(d,"attributeComparator")}function BS(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/Mo(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=IN[n]||n,n===Ds.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=Fi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=BS(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Mo(e.indices[i.relationship.from])/(Mo(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=Mo(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Ude*Mo(e.primaryStore)+1:n==="between"?r.estimated_count=Mde*Mo(e.primaryStore)+1:n==="sort"?r.estimated_count=Mo(e.primaryStore)+1:r.estimated_count=Lde*Mo(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function HS(e){if(e)if(Ua=e,sd.lastIndex=0,xde.test(e))try{let t=hE(new id,"");if(In!==Ua.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 ${In} in '${Ua}'`,t}else return new URLSearchParams(e)}function hE(e,t){let r=sd,n,s,i,o,c,l=decodeURIComponent,d;for(;n=r.exec(Ua);){In=r.lastIndex;let[,u,_]=n;if(o){if(u)throw new SyntaxError(`expected operator, but encountered '${u}'`);o=!1,c=!1}else c=!0;let E;switch(_){case"=":if(s){if(u.length<=2)i=u;else throw new SyntaxError(`invalid FIQL operator ${u}`);l=yN}else{if(l=decodeURIComponent,i="equals",!u)throw new SyntaxError("attribute must be specified before equality comparator");s=pE(u)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=vde[_],l=ON[i]?yN:decodeURIComponent,!u)throw new SyntaxError(`attribute must be specified before comparator ${_}`);s=pE(u);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${_[0]?"'"+_[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${_?"'"+_+"'":"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:l(u)};i==="eq"&&r$(h,u),vS(e,d),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(pE(u)),s=void 0;break;case"(":sd.lastIndex=In;let f=hE(u?[]:new id,")");switch(u){case"":vS(e,d),e.conditions.push(f);break;case"limit":switch(f.length){case 1:e.limit=+f[0];break;case 2:e.offset=+f[0],e.limit=f[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(f[0])&&f.length===1&&!f[0].name?(e.select=f[0],e.select.asArray=!0):f.length===1?e.select=f[0]:f.length===2&&f[1]===""?e.select=f.slice(0,1):e.select=f;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=n$(f);break;default:throw new SyntaxError(`unknown query function call ${u}`)}Ua[In]===","?r.lastIndex=++In:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!u)throw new SyntaxError("property sets must have a defined parent property name");sd.lastIndex=In,E=hE([],"}"),E.name=u,e.push(E),Ua[In]===","?r.lastIndex=++In:o=!0;break;case"[":sd.lastIndex=In,u?(E=hE(new id,"]"),E.name=u):E=hE(e.conditions?new id:[],"]"),e.conditions?(vS(e,d),e.conditions.push(E),s=null):e.push(E),Ua[In]===","?r.lastIndex=++In:o=!0;break;case")":case"]":case"}":if(t===_[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(u)};i==="eq"&&r$(h,u),vS(e,d),e.conditions.push(h)}else if(u)throw new SyntaxError("no attribute or comparison specified")}else(u||e.length>0&&c)&&e.push(pE(u));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${_[0]}'`):new SyntaxError(`unexpected token '${_[0]}'`);default:throw new SyntaxError(`unexpected operator '${_}'`)}if(t!==")"&&(r=s?Fde:sd,r.lastIndex=In),In===Ua.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function vS(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 pE(e){return e.indexOf(".")>-1?e.split(".").map(pE):decodeURIComponent(e)}function yN(e){if(e==="null")return null;if(e.indexOf("/")>-1){let t=e.split("/"),r=new ad(t.length);for(let n=0,s=t.length;n<s;n++)r[n]=yN(t[n]);return r}if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return r[0]==="$"?parseInt(r.slice(1),36):+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Qn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function r$(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Qn.ClientError("wildcard can only be used at the end of a string")}function n$(e){let t=s$(e[0]);return e.length>1&&(t.next=n$(e.slice(1))),t}function s$(e){if(Array.isArray(e)){let t=s$(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 si(e){return Array.isArray(e)?e.join("\0"):e}function Mo(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function kde(e,t,r){return t*r/Mo(e)}var Qn,Ds,xi,Ma,Lde,Mde,Ude,vde,ON,IN,xde,sd,Fde,In,Ua,id,ol,SE=Ce(()=>{Qn=B(ce()),Ds=B(Bt()),xi=require("ordered-binary"),Ma=require("lmdb");TE();ls();Lde=.3,Mde=.1,Ude=.05,vde={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},ON={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(NN,"executeConditions");a(od,"searchByIndex");a(Fi,"findAttribute");a(Bde,"joinTo");a(Hde,"joinFrom");IN={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(mE,"filterByType");a(BS,"estimateCondition");xde=/[()[\]|!<>.]|(=\w*=)/,sd=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Fde=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(HS,"parseQuery");a(hE,"parseBlock");a(vS,"assignOperator");a(pE,"decodeProperty");a(yN,"typedDecoding");a(r$,"wildcardDecoding");a(n$,"toSortObject");a(s$,"toSortEntry");id=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(si,"flattenKey");a(Mo,"estimatedEntryCount");a(kde,"intersectionEstimate");ol=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});function l$(e){let t={openapi:Gde,info:{title:"HarperDB HTTP REST interface",version:(0,c$.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||n.Resource.isError)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:l}=n.Resource;if(c=c??"id",!c)continue;let d={},u=[];if(o)for(let{type:C,name:O,elements:x,relationship:F,definition:Y}of o){if(F)C==="array"?d[O]={type:"array",items:{$ref:Ba+x.type}}:d[O]={$ref:Ba+C};else{let $=Y??x?.definition;if($){if(!t.components.schemas[$.type]){let Z={};$.properties.forEach(Q=>{Z[Q.name]=new PN(wN[Q.type],Q.type)}),t.components.schemas[$.type]=new a$(Z)}C==="array"?d[O]={type:"array",items:{$ref:Ba+$.type}}:d[O]={$ref:Ba+$.type}}else C==="array"?x.type==="Any"||x.type=="ID"?d[O]={type:"array",items:{format:x.type}}:d[O]={type:"array",items:new PN(wN[x.type],x.type)}:C==="Any"||C=="ID"?d[O]={format:C}:d[O]=new PN(wN[C],C)}u.push(new LN(O,"query",d[O]))}let _=Object.keys(d),E=new LN(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new LN("property","path",{enum:_});f.required=!0,t.components.schemas[i]=new a$(d);let h=l.post!==Resource.prototype.post||l.update,S=typeof l.put=="function",T=typeof l.get=="function",g=typeof l.delete=="function",m="/"+s+"/";h&&(t.paths[m]={},t.paths[m].post=new qde(i,r,"create a new record auto-assigning a primary key")),T&&(t.paths[m]||(t.paths[m]={}),t.paths[m].get=new CN(u,r,{200:new DN({$ref:Ba+i})},"search for records by the specified property name and value pairs")),g&&(t.paths[m]||(t.paths[m]={}),t.paths[m].delete=new o$(u,r,"delete all the records that match the provided query",{204:new i$})),m="/"+s+"/{"+c+"}",T&&(t.paths[m]={},t.paths[m].get=new CN([E],r,{200:new DN({$ref:Ba+i})},"retrieve a record by its primary key")),S&&(t.paths[m]||(t.paths[m]={}),t.paths[m].put=new $de([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),g&&(t.paths[m]||(t.paths[m]={}),t.paths[m].delete=new o$([E],r,"delete a record with the given primary key",{204:new i$})),T&&f.schema.enum.length>0&&(m="/"+s+"/{"+c+"}.{property}",t.paths[m]={},t.paths[m].get=new CN([E,f],r,{200:new DN({enum:_})},"used to retrieve the specified property of the specified record"))}return t}function qde(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ba+e}}}},this.security=t,this.responses={200:{description:MN,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function CN(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function DN(e){this.description=MN,this.content={"application/json":{schema:e}}}function i$(){this.description="successfully processed request, no content returned to client"}function $de(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ba+r}}}},this.responses={200:{description:MN}}}function o$(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function a$(e){this.type="object",this.properties=e}function PN(e,t){this.type=e,this.format=t}function LN(e,t,r){this.name=e,this.in=t,this.schema=r}var c$,Gde,wN,Ba,MN,u$=Ce(()=>{c$=B(go()),Gde="3.0.3",wN={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ba="#/components/schemas/",MN="successful operation";a(l$,"generateJsonApi");a(qde,"Post");a(CN,"Get");a(DN,"Response200");a(i$,"Response204");a($de,"Put");a(o$,"Delete");a(a$,"ResourceSchema");a(PN,"Type");a(LN,"Parameter")});var FS={};tt(FS,{start:()=>Kde});async function Yde(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&HS(e);let i=new Io;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==d$){let T=xS.getMatch(o,n?"sse":"rest");if(!T)return t(e);e.handlerPath=T.path,c=new ol(T.relativeURL),c.async=!0,l=T.Resource}let d=r["cache-control"];if(d){let T=E$(d);for(let g of T)switch(g.name){case"max-age":e.expiresAt=g.value*1e3+Date.now();break;case"only-if-cached":e.onlyIfCached=!0;break;case"no-cache":e.noCache=!0;break;case"no-store":e.noCacheStore=!0;break;case"stale-if-error":e.staleIfError=!0;break;case"must-revalidate":e.mustRevalidate=!0;break}}let u=r["x-replicate-to"];if(u){let T=E$(u).map(g=>(g.next?.name==="confirm"&&g.next.value>=0&&(e.replicatedConfirmation=+g.next.value),g.name));e.replicateTo=T.length===1&&+T[0]>=0?+T[0]:T[0]==="*"?void 0:T}let _=await wt(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=il(r["content-type"],!0)(e.body,e.headers)}catch(T){throw new cd.ClientError(T,400)}if(e.authorize=!0,o===d$&&s==="GET"){if(e?.user?.role?.permission?.super_user)return l$(xS);throw new cd.ServerError("Forbidden",403)}switch(s){case"GET":case"HEAD":return l.get(c,e);case"POST":return l.post(c,e.data,e);case"PUT":return l.put(c,e.data,e);case"DELETE":return l.delete(c,e);case"PATCH":return l.patch(c,e.data,e);case"OPTIONS":i.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(c,e.data,e);case"COPY":return l.copy(c,r.destination,e);case"MOVE":return l.move(c,r.destination,e);case"BREW":throw new cd.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new cd.ServerError(`Method ${s} is not recognized`,501)}}),E=200,f;if(_==null)E=s==="GET"||s==="HEAD"?404:204,UN.lastModified&&e.lastModified&&i.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else{if(_.status>0&&_.headers)return _.headers=WO(_.headers,i),_.data!==void 0&&(_.body=EE(_.data,e,_)),_;if(f=e.lastModified){Vde[0]=f;let T=String.fromCharCode(34,(Br[0]&63)+62,(Br[0]>>6)+(Br[1]<<2&63)+62,(Br[1]>>4)+(Br[2]<<4&63)+62,(Br[2]>>2)+62,(Br[3]&63)+62,(Br[3]>>6)+(Br[4]<<2&63)+62,(Br[4]>>4)+(Br[5]<<4&63)+62,(Br[5]>>2)+62,(Br[6]&63)+62,(Br[6]>>6)+(Br[7]<<2&63)+62,34),g=r["if-none-match"];g&&T==g?(_?.onDone&&_.onDone(),E=304,_=void 0):i.setIfNone("ETag",T),UN.lastModified&&i.setIfNone("Last-Modified",new Date(f).toUTCString())}}e.createdResource&&(E=201),e.newLocation&&i.setIfNone("Location",e.newLocation);let h={status:E,headers:i,body:void 0},S=_?.wasLoadedFromSource?.();return S!==void 0&&(h.wasCacheMiss=S,!S&&f&&i.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||f))/1e3))),_!==void 0&&(h.body=EE(_,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?al.warn(o):al.info(o):al.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.setIfNone("Allow",o.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:o.statusCode||500,headers:i,body:void 0};return c.body=EE(o.contentType?o:o.toString(),e,c),c}}function Kde(e){UN=e,!_$&&(_$=!0,xS=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Yde(t,r)},e),e.server.ws(async(t,r,n)=>{gE++;let s=new Mn;f$||(f$=!0,X_(l=>{gE>0&&l.push({metric:"ws-connections",connections:gE,byThread:!0})}));let i;t.on("error",l=>{i=!0,al.warn(l)});let o;t.on("message",a(function(d){o||(o=il(r.requestedContentType??r.headers.asObject["content-type"],!1));let u=o(d);s.push(u)},"message"));let c;t.on("close",()=>{gE--,Vn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),d=xS.getMatch(l,"ws");if(Vn(!!d,"connection","ws","connect"),d){r.handlerPath=d.path,Rr(h=>({count:h.count,total:gE}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let u=new ol(d.relativeURL),_=d.Resource;c=(await wt(r,()=>_.connect(u,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=el(f.value,r);t.send(h),Rr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){t.close(Wde[l.statusCode]||1011,l.toString())}t.close()},e))}function E$(e){return e.split(/\s*,\s*/).map(r=>{let n,s=r.split(/\s*;\s*/),i;for(;i=s.pop();)if(i.includes("=")){let[o,c]=i.split(/\s*=\s*/);n={name:o.toLowerCase(),value:c,next:n}}else n={name:i.toLowerCase(),next:n};return n})}var al,cd,Br,Vde,UN,d$,_$,xS,f$,gE,Wde,h$=Ce(()=>{Ju();Ci();al=B(V()),cd=B(ce());SE();kl();Ic();zf();u$();SE();Br=new Uint8Array(8),Vde=new Float64Array(Br.buffer,0,1),UN={},d$="openapi";a(Yde,"http");gE=0;a(Kde,"start");Wde={401:3e3,403:3003};a(E$,"parseHeaderValue")});var vN=y((KPe,p$)=>{var{recordAction:kS,recordActionBinary:jde}=(Ci(),ne(Z_)),Qde=require("fastify-plugin"),zde=200;p$.exports=Qde(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(),l=s.request.routeOptions,d,u,_;l.config?.isOperation?(d=n.body?.operation,u="operation"):(d=l.url,u="fastify-route",_=l.method),kS(o,"duration",d,_,u),jde(s.raw.statusCode<400,"success",d,_,u);let E=zde;i?.pipe?(i.on("data",T=>{E+=T.length}),i.on("end",()=>{kS(performance.now()-c,"transfer",d,_,u),kS(E,"bytes-sent",d,_,u)})):(E+=i?.length||0,kS(E,"bytes-sent",d,_,u));let f=o.toFixed(3),h=s.getHeader("Server-Timing"),S=`db;dur=${f}`;s.header("Server-Timing",h?`${h}, ${S}`:S)}),r()},{name:"hdb-request-time"})});var GN=y((QPe,g$)=>{var VS=require("clone"),YS=St(),Jde=ee(),qS=M(),WPe=V(),BN=require("fs"),xN=require("joi"),{string:$S}=xN.types(),{hdb_errors:Xde,handleHDBError:GS}=ce(),{HDB_ERROR_MSGS:jPe,HTTP_STATUS_CODES:HN}=Xde,{common_validators:ld}=Ri(),m$=" is required",Zde=["insert","update","upsert"],FN={database:{presence:!1,format:ld.schema_format,length:ld.schema_length},schema:{presence:!1,format:ld.schema_format,length:ld.schema_length},table:{presence:!0,format:ld.schema_format,length:ld.schema_length},action:{inclusion:{within:Zde,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},e_e={schema:$S.required(),table:$S.required(),action:$S.valid("insert","update","upsert")},{AWS_ACCESS_KEY:t_e,AWS_SECRET:r_e,AWS_BUCKET:n_e,AWS_FILE_KEY:s_e,REGION:i_e}=qS.S3_BUCKET_AUTH_KEYS,o_e={s3:{presence:!0},[`s3.${t_e}`]:{presence:!0,type:"String"},[`s3.${r_e}`]:{presence:!0,type:"String"},[`s3.${n_e}`]:{presence:!0,type:"String"},[`s3.${s_e}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${i_e}`]:{presence:!0,type:"String"}},S$=VS(FN);S$.data.presence={message:m$};var T$=VS(FN);T$.file_path.presence={message:m$};var a_e=Object.assign(VS(FN),o_e),kN=VS(e_e);kN.csv_url=$S.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();kN.passthrough_headers=xN.object();function c_e(e){let t=YS.validateObject(e,S$);return KS(e,t)}a(c_e,"dataObject");function l_e(e){let t=YS.validateBySchema(e,xN.object(kN));return KS(e,t)}a(l_e,"urlObject");function u_e(e){let t=YS.validateObject(e,T$);return KS(e,t)}a(u_e,"fileObject");function d_e(e){let t=YS.validateObject(e,a_e);return KS(e,t)}a(d_e,"s3FileObject");function KS(e,t){if(!t){let r=Jde.checkGlobalSchemaTable(e.schema,e.table);if(r)return GS(new Error,r,HN.BAD_REQUEST);if(e.operation===qS.OPERATIONS_ENUM.CSV_FILE_LOAD)try{BN.accessSync(e.file_path,BN.constants.R_OK|BN.constants.F_OK)}catch(n){return n.code===qS.NODE_ERROR_CODES.ENOENT?GS(n,`No such file or directory ${n.path}`,HN.BAD_REQUEST):n.code===qS.NODE_ERROR_CODES.EACCES?GS(n,`Permission denied ${n.path}`,HN.BAD_REQUEST):GS(n)}}return t}a(KS,"postValidateChecks");g$.exports={dataObject:c_e,urlObject:l_e,fileObject:u_e,s3FileObject:d_e}});var qN=y((JPe,R$)=>{"use strict";var RE=V(),WS=M();async function __e(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===WS.OPERATIONS_ENUM.INSERT||t.operation===WS.OPERATIONS_ENUM.UPDATE||t.operation===WS.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===WS.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(RE.info(i.message),i):i.http_resp_msg?(RE.error(`Error calling operation: ${e.name}`),RE.error(i.http_resp_msg),i):(RE.error(`Error calling operation: ${e.name}`),RE.error(i),i)}}a(__e,"callOperationFunctionAsAwait");R$.exports={callOperationFunctionAsAwait:__e}});var b$=y((ZPe,A$)=>{"use strict";var $N=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}},VN=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};A$.exports={BulkLoadFileObject:$N,BulkLoadDataObject:VN}});var O$=y((tLe,y$)=>{"use strict";var YN=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};y$.exports=YN});var JN=y((aLe,q$)=>{"use strict";var jS=un(),zS=GN(),f_e=require("needle"),ii=M(),nLe=At(),ud=ee(),{handleHDBError:qt,hdb_errors:U$}=ce(),{HTTP_STATUS_CODES:Hr,HDB_ERROR_MSGS:mr,CHECK_LOGS_WRAPPER:ll}=U$,dd=V(),KN=require("papaparse");ud.promisifyPapaParse();var oi=require("fs-extra"),E_e=require("path"),{chain:N$}=require("stream-chain"),I$=require("stream-json/streamers/StreamArray"),w$=require("stream-json/utils/Batch"),C$=require("stream-chain/utils/comp"),{finished:D$}=require("stream"),h_e=te(),v$=qN(),p_e=pN(),{BulkLoadFileObject:jN,BulkLoadDataObject:m_e}=b$(),QN=oN(),{verifyBulkLoadAttributePerms:B$}=wS(),sLe=O$(),iLe=nr(),oLe=lo(),{databases:S_e}=(De(),ne(at)),{coerceType:T_e}=(TE(),ne(XN)),P$="No records parsed from csv file.",cl=`${h_e.get("HDB_ROOT")}/tmp`,{schema_regex:g_e}=Ri(),L$=1024*1024*2,M$=5e3,R_e={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};q$.exports={csvDataLoad:A_e,csvURLLoad:b_e,csvFileLoad:y_e,importFromS3:O_e};async function A_e(e,t){let r=zS.dataObject(e);if(r)throw qt(r,r.message,Hr.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=F$(e.schema,e.table),i=KN.parse(e.data,{header:!0,skipEmptyLines:!0,transform:WN.bind(null,s),dynamicTyping:!1}),o=new QN;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&B$(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 qt(new Error,c,Hr.BAD_REQUEST,void 0,void 0,!0);let l=new m_e(e.action,e.schema,e.table,i.data);return n=await v$.callOperationFunctionAsAwait(k$,l,null),n.message===P$?P$:G$(n.records,n.number_written)}catch(s){throw ul(s)}}a(A_e,"csvDataLoad");async function b_e(e){let t=zS.urlObject(e);if(t)throw qt(t,t.message,Hr.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${cl}/${r}`;try{await N_e(e,r)}catch(s){throw dd.error(mr.DOWNLOAD_FILE_ERR(r)+" - "+s),qt(s,ll(mr.DOWNLOAD_FILE_ERR(r)))}try{let s=new jN(this.job_operation_function.name,e.action,e.schema,e.table,n,ii.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await zN(s);return await QS(n),i}catch(s){throw await QS(n),ul(s)}}a(b_e,"csvURLLoad");async function y_e(e){let t=zS.fileObject(e);if(t)throw qt(t,t.message,Hr.BAD_REQUEST,void 0,void 0,!0);let r=new jN(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,ii.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await zN(r)}catch(n){throw ul(n)}}a(y_e,"csvFileLoad");async function O_e(e){let t=zS.s3FileObject(e);if(t)throw qt(t,t.message,Hr.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=E_e.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${cl}/${s}`;let i=new jN(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await I_e(s,e);let o=await zN(i);return await QS(r),o}catch(n){throw await QS(r),ul(n)}}a(O_e,"importFromS3");async function N_e(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await f_e("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 qt(n,s,n.statusCode,ii.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}C_e(r,e.csv_url),await w_e(t,r.raw)}a(N_e,"downloadCSVFile");async function I_e(e,t){try{let r=`${cl}/${e}`;await oi.mkdirp(cl),await oi.writeFile(`${cl}/${e}`,"",{flag:"a+"});let n=await oi.createWriteStream(r),s=await p_e.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(){dd.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw dd.error(mr.S3_DOWNLOAD_ERR+" - "+r),qt(r,ll(mr.S3_DOWNLOAD_ERR))}}a(I_e,"downloadFileFromS3");async function w_e(e,t){try{await oi.mkdirp(cl),await oi.writeFile(`${cl}/${e}`,t)}catch(r){throw dd.error(mr.WRITE_TEMP_FILE_ERR),qt(r,ll(mr.DEFAULT_BULK_LOAD_ERR))}}a(w_e,"writeFileToTempFolder");async function QS(e){if(e)try{await oi.access(e),await oi.unlink(e)}catch{dd.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(QS,"deleteTempFile");function C_e(e,t){if(e.statusCode!==U$.HTTP_STATUS_CODES.OK)throw qt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Hr.BAD_REQUEST);if(!R_e[e.headers["content-type"]])throw qt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Hr.BAD_REQUEST);if(!e.raw)throw qt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Hr.BAD_REQUEST)}a(C_e,"validateURLResponse");async function zN(e){try{let t;switch(e.file_type){case ii.VALID_S3_FILE_TYPES.CSV:t=await D_e(e);break;case ii.VALID_S3_FILE_TYPES.JSON:t=await P_e(e);break;default:throw qt(new Error,mr.DEFAULT_BULK_LOAD_ERR,Hr.BAD_REQUEST,ii.LOG_LEVELS.ERROR,mr.INVALID_FILE_EXT_ERR(e))}return G$(t.records,t.number_written)}catch(t){throw ul(t)}}a(zN,"fileLoad");async function H$(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 jS.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&B$(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=qt(c);r(l)}}a(H$,"validateChunk");async function x$(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;ud.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!ud.isEmpty(c)&&!ud.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(d=>c.add(d))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await v$.callOperationFunctionAsAwait(k$,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=qt(c,ll(mr.INSERT_CSV_ERR),Hr.INTERNAL_SERVER_ERROR,ii.LOG_LEVELS.ERROR,mr.INSERT_CSV_ERR+" - "+c);r(l)}}a(x$,"insertChunk");async function D_e(e){let t={records:0,number_written:0},r=F$(e.schema,e.table);try{let n=new QN,s=oi.createReadStream(e.file_path,{highWaterMark:L$});s.setEncoding("utf8"),await KN.parsePromise(s,H$.bind(null,e,n),WN.bind(null,r));let i=n.getPermsResponse();if(i)throw qt(new Error,i,Hr.BAD_REQUEST);return s=oi.createReadStream(e.file_path,{highWaterMark:L$}),s.setEncoding("utf8"),await KN.parsePromise(s,x$.bind(null,e,t),WN.bind(null,r)),s.destroy(),t}catch(n){throw qt(n,ll(mr.PAPA_PARSE_ERR),Hr.INTERNAL_SERVER_ERROR,ii.LOG_LEVELS.ERROR,mr.PAPA_PARSE_ERR+n)}}a(D_e,"callPapaParse");function F$(e,t){let r=S_e[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>T_e(i,s));return n}a(F$,"createTransformMap");function WN(e,t,r){let n=e.get(r);return n?n(t):ud.autoCast(t)}a(WN,"typeFunction");async function P_e(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new QN,s=N$([oi.createReadStream(e.file_path,{encoding:"utf-8"}),I$.withParser(),c=>c.value,new w$({batchSize:M$}),C$(async c=>{await H$(e,n,r,c)})]);await new Promise((c,l)=>{D$(s,d=>{d?l(d):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw qt(new Error,i,Hr.BAD_REQUEST);let o=N$([oi.createReadStream(e.file_path,{encoding:"utf-8"}),I$.withParser(),c=>c.value,new w$({batchSize:M$}),C$(async c=>{await x$(e,t,r,c)})]);return await new Promise((c,l)=>{D$(o,d=>{d?l(d):c()}),o.resume()}),t}catch(n){throw qt(n,ll(mr.INSERT_JSON_ERR),Hr.INTERNAL_SERVER_ERROR,ii.LOG_LEVELS.ERROR,mr.INSERT_JSON_ERR+n)}}a(P_e,"insertJson");async function k$(e){let t={};try{e.data&&e.data.length>0&&L_e(e.data[0])?t=await M_e(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",dd.info(t.message))}catch(r){throw ul(r)}return t}a(k$,"callBulkFileLoad");function L_e(e){let t=Object.keys(e);for(let r of t)if(!g_e.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(L_e,"validateColumnNames");async function M_e(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=jS.insert;break;case"update":i=jS.update;break;case"upsert":i=jS.upsert;break;default:throw qt(new Error,mr.INVALID_ACTION_PARAM_ERR(n),Hr.BAD_REQUEST,ii.LOG_LEVELS.ERROR,mr.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 u=global.hdb_schema[t][r].hash_attribute,_=e.length;for(;_--;)o.skipped_hashes.indexOf(e[_][u])>=0&&e.splice(_,1)}let l=ud.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:o.new_attributes}}catch(o){throw ul(o)}}a(M_e,"bulkFileLoad");function G$(e,t){return`successfully loaded ${t} of ${e} records`}a(G$,"buildResponseMsg");function ul(e){return qt(e,ll(mr.DEFAULT_BULK_LOAD_ERR),Hr.INTERNAL_SERVER_ERROR,ii.LOG_LEVELS.ERROR,mr.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(ul,"buildTopLevelErrMsg")});var V$=y((lLe,$$)=>{"use strict";var ZN=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};$$.exports=ZN});var W$=y((dLe,K$)=>{"use strict";var U_e=M(),Y$=require("moment"),v_e=require("uuid").v4,eI=class{static{a(this,"JobObject")}constructor(){this.id=v_e(),this.type=void 0,this.start_datetime=Y$().valueOf(),this.created_datetime=Y$().valueOf(),this.end_datetime=void 0,this.status=U_e.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};K$.exports=eI});var tI=y((fLe,tV)=>{"use strict";var B_e=require("uuid").v4,X$=un(),Z$=jr(),H_e=zs(),x_e=su(),F_e=V$(),Ot=M(),k_e=W$(),G_e=Im(),Ps=V(),q_e=y_(),_d=ee(),{promisify:$_e}=require("util"),dl=require("moment"),V_e=DS(),JS=GN(),j$=eA(),{deleteTransactionLogsBeforeValidator:Y_e}=tN(),{handleHDBError:Q$,hdb_errors:K_e}=ce(),{HTTP_STATUS_CODES:z$}=K_e,J$=Z$.searchByValue,W_e=Z$.searchByHash,j_e=X$.insert,Q_e=$_e(V_e.evaluateSQL),z_e=X$.update;tV.exports={addJob:Z_e,updateJob:tfe,handleGetJob:J_e,handleGetJobsByStartDate:X_e,getJobById:eV};async function J_e(e){try{let t=await eV(e.id);return _d.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 Ps.error("There was an error getting job",t),new Error(r)}}a(J_e,"handleGetJob");async function X_e(e){try{let t=await efe(e);if(Ps.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=dl(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=dl(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 Ps.error(r),new Error(r)}}a(X_e,"handleGetJobsByStartDate");async function Z_e(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||_d.isEmptyOrZeroLength(e.operation)){let u="job parameter is invalid";return Ps.info(u),t.error=u,t}if(!Ot.JOB_TYPE_ENUM[e.operation])return Ps.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Ot.OPERATIONS_ENUM.CSV_FILE_LOAD:n=JS.fileObject(e);break;case Ot.OPERATIONS_ENUM.CSV_URL_LOAD:n=JS.urlObject(e);break;case Ot.OPERATIONS_ENUM.CSV_DATA_LOAD:n=JS.dataObject(e);break;case Ot.OPERATIONS_ENUM.IMPORT_FROM_S3:n=JS.s3FileObject(e);break;case Ot.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Ot.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=j$(e,"date");break;case Ot.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=j$(e,"timestamp");break;case Ot.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Y_e(e);break;case Ot.OPERATIONS_ENUM.RESTART_SERVICE:if(Ot.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw Q$(new Error,"Invalid service",z$.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw Q$(n,n.message,z$.BAD_REQUEST,void 0,void 0,!0);let s=new k_e;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 H_e(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await J$(i))}catch(u){let _=`There was an error inserting a new job: ${u}`;return Ps.error(_),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=B_e();try{o=await J$(i)}catch(u){let _=`There was an error inserting a new job: ${u}`;return Ps.error(_),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Ps.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new q_e(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),d;try{d=await j_e(l)}catch(u){return Ps.error(`There was an error inserting a job for job type: ${e.operation} -- ${u}`),t.success=!1,t}if(d.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let u=`Created a job with type ${s.type} and id ${s.id}`;t.message=u,t.createdJob=s,t.success=!0,Ps.trace(u)}return t}a(Z_e,"addJob");async function efe(e){let t=dl(e.from_date,dl.ISO_8601),r=dl(e.to_date,dl.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 F_e(n,e.hdb_user);try{return await Q_e(s)}catch(i){throw Ps.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(efe,"getJobsInDateRange");async function eV(e){if(_d.isEmptyOrZeroLength(e))return _d.errorizeMessage("Invalid job ID specified.");let t=new x_e(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await W_e(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Ps.error(n),_d.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(eV,"getJobById");async function tfe(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(_d.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=dl().valueOf());let t=new G_e(Ot.SYSTEM_SCHEMA_NAME,Ot.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await z_e(t),r}a(tfe,"updateJob")});var lV=y((hLe,cV)=>{"use strict";var rV=ee(),Sr=M(),rfe=require("moment"),XS=JN(),AE=V(),nV=tI(),sV=PS(),iV=mc(),oV=ut(),nfe=yS(),sfe=Ca(),{parentPort:ife,isMainThread:aV}=require("worker_threads"),{onMessageByType:ofe}=ut(),rI=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function afe(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(rV.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(rV.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Sr.JOB_TYPE_ENUM.csv_file_load:await Gi(e,XS.csvFileLoad);break;case Sr.JOB_TYPE_ENUM.csv_url_load:await Gi(e,XS.csvURLLoad);break;case Sr.JOB_TYPE_ENUM.csv_data_load:await Gi(e,XS.csvDataLoad);break;case Sr.JOB_TYPE_ENUM.import_from_s3:await Gi(e,XS.importFromS3);break;case Sr.JOB_TYPE_ENUM.empty_trash:break;case Sr.JOB_TYPE_ENUM.export_local:await Gi(e,sV.export_local);break;case Sr.JOB_TYPE_ENUM.export_to_s3:await Gi(e,sV.export_to_s3);break;case Sr.JOB_TYPE_ENUM.delete_files_before:case Sr.JOB_TYPE_ENUM.delete_records_before:await Gi(e,iV.deleteFilesBefore);break;case Sr.JOB_TYPE_ENUM.delete_audit_logs_before:await Gi(e,iV.deleteAuditLogsBefore);break;case Sr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Gi(e,nfe.deleteTransactionLogsBefore);break;case Sr.JOB_TYPE_ENUM.restart_service:return await Gi(e,sfe.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(afe,"parseMessage");async function Gi(e,t){try{e.job.status=Sr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=rfe().valueOf(),await nV.updateJob(e.job),await cfe(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=Sr.JOB_STATUS_ENUM.ERROR;try{await nV.updateJob(e.job)}catch(s){throw AE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Gi,"runJob");async function cfe(e){AE.trace("launching job thread:",e),aV?oV.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Sr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`}}):ife.postMessage({type:Sr.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(cfe,"launchJobThread");aV&&ofe(Sr.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{oV.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:{...process.env,[Sr.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`}})}catch(r){AE.error(r)}});cV.exports={parseMessage:afe,RunnerMessage:rI}});var dV=y((mLe,uV)=>{"use strict";var nI=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};uV.exports=nI});var CV=y((gLe,lI)=>{"use strict";var nT=jr(),oI=DS(),ZS=JN(),Uo=gm(),eT=uo(),OE=mc(),lfe=Ay(),bE=_n(),tT=ym(),Lt=eN(),rT=V(),ufe=My(),dfe=Pf(),_V=fO(),_fe=km(),ffe=pO(),Efe=mO(),hfe=$m(),pfe=Ym(),sI=Km(),fV=PS(),mfe=wS(),aI=tI(),q=M(),{hdb_errors:IE,handleHDBError:NE}=ce(),{HTTP_STATUS_CODES:EV}=IE,iI=jm(),hV=Ca(),OV=require("util"),fd=un(),Sfe=_s(),Tfe=To(),pV=lV(),mV=Of(),SV=(fS(),ne(Jf)),TV=yt(),gV=yS(),RV=TS(),{setServerUtilities:gfe}=(TE(),ne(XN)),{CONTEXT:TLe}=(ls(),ne(zA)),{_assignPackageExport:Rfe}=no(),{transformReq:Afe}=ee(),{server:bfe}=(Wr(),ne(ic)),tn=rT.loggerWithTag("operation"),yE=Ss(),AV=(Wc(),ne(Kc)),yfe=qN(),bV=nT.searchByHash,Ofe=nT.searchByValue,Nfe=OV.promisify(nT.search),Ife=OV.promisify(oI.evaluateSQL),wfe={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},j=dV();async function NV(e,t){try{if(e.body.operation!=="read_log"&&(rT.log_level===q.LOG_LEVELS.INFO||rT.log_level===q.LOG_LEVELS.DEBUG||rT.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;tn.info(o)}}catch(n){tn.error(n)}let r=await yfe.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return wfe[e.body.operation]&&Sfe.setSchemaDataToGlobal(n=>{n&&tn.error(n)}),r}a(NV,"processLocalTransaction");var yV=Dfe();lI.exports={chooseOperation:IV,getOperationFunction:wV,operation:cI,processLocalTransaction:NV};gfe(lI.exports);bfe.operation=cI;function IV(e){let t;try{t=wV(e)}catch(s){throw tn.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=oI.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=oI.checkASTPermissions(e,i);if(o)throw tn.error(`${EV.FORBIDDEN} from operation ${e.operation}`),tn.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),NE(new Error,o,IE.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=mfe.verifyPerms(i,s);if(o)throw tn.error(`${EV.FORBIDDEN} from operation ${e.operation}`),tn.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),NE(new Error,o,IE.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw NE(s,"There was an error when trying to choose an operation path")}return r}a(IV,"chooseOperation");function wV(e){if(tn.trace(`getOperationFunction with operation: ${e.operation}`),yV.has(e.operation))return yV.get(e.operation);throw NE(new Error,IE.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),IE.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(wV,"getOperationFunction");Rfe("operation",cI);function cI(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=IV(e);return NV({body:e},n)}a(cI,"operation");async function Cfe(e){tn.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await fd.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await fd.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await fd.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await OE.deleteRecord(i);break;default:tn.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){tn.info("Invalid operation in transaction"),tn.error(o)}}a(Cfe,"catchup");async function ai(e){Afe(e);let t,r;try{r=await aI.addJob(e),t=r.createdJob,tn.info("addJob result",r);let n=new pV.RunnerMessage(t,e);return{message:await pV.parseMessage(n)??`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 tn.error(s),NE(n,s)}}a(ai,"executeJob");function Dfe(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new j(fd.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new j(fd.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new j(fd.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new j(nT.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new j(bV)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new j(bV)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new j(Ofe)),e.set(q.OPERATIONS_ENUM.SEARCH,new j(Nfe)),e.set(q.OPERATIONS_ENUM.SQL,new j(Ife)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new j(ai,ZS.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new j(ai,ZS.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new j(ai,ZS.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new j(ai,ZS.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new j(Uo.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new j(Uo.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new j(Uo.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new j(Uo.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new j(Uo.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new j(Uo.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new j(Uo.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new j(Uo.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new j(eT.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new j(eT.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new j(eT.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new j(eT.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new j(OE.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new j(bE.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new j(bE.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new j(bE.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new j(bE.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new j(tT.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new j(tT.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new j(tT.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new j(tT.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new j(bE.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new j(ufe)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new j(dfe)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new j(_V)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new j(_V)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new j(_fe)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new j(ffe)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new j(Efe)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new j(TV.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new j(hfe.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new j(pfe)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new j(sI.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new j(sI.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new j(sI.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new j(ai,fV.export_to_s3)),e.set(q.OPERATIONS_ENUM.CREATE_CSR,new j(yE.createCsr)),e.set(q.OPERATIONS_ENUM.SIGN_CERTIFICATE,new j(yE.signCertificate)),e.set(q.OPERATIONS_ENUM.LIST_CERTIFICATES,new j(yE.listCertificates)),e.set(q.OPERATIONS_ENUM.ADD_CERTIFICATES,new j(yE.addCertificate)),e.set(q.OPERATIONS_ENUM.REMOVE_CERTIFICATE,new j(yE.removeCertificate)),e.set(q.OPERATIONS_ENUM.ADD_NODE_BACK,new j(AV.addNodeBack)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE_BACK,new j(AV.removeNodeBack)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new j(ai,OE.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new j(ai,OE.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new j(ai,fV.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new j(aI.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new j(aI.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new j(iI.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new j(iI.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new j(iI.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new j(hV.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new j(ai,hV.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new j(Cfe)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new j(Tfe.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new j(ai,OE.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new j(lfe)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new j(mV.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new j(mV.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new j(SV.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new j(SV.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new j(TV.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new j(Lt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new j(Lt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new j(Lt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new j(Lt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new j(Lt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new j(Lt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new j(Lt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new j(Lt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new j(Lt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new j(Lt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new j(Lt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new j(Lt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new j(Lt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new j(Lt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new j(Lt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new j(Lt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new j(gV.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new j(ai,gV.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new j(RV.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new j(RV.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new j(Uo.getBackup)),e.set(q.OPERATIONS_ENUM.ADD_SSH_KEY,new j(Lt.addSSHKey)),e.set(q.OPERATIONS_ENUM.UPDATE_SSH_KEY,new j(Lt.updateSSHKey)),e.set(q.OPERATIONS_ENUM.DELETE_SSH_KEY,new j(Lt.deleteSSHKey)),e.set(q.OPERATIONS_ENUM.LIST_SSH_KEYS,new j(Lt.listSSHKeys)),e.set(q.OPERATIONS_ENUM.SET_SSH_KNOWN_HOSTS,new j(Lt.setSSHKnownHosts)),e.set(q.OPERATIONS_ENUM.GET_SSH_KNOWN_HOSTS,new j(Lt.getSSHKnownHosts)),e}a(Dfe,"initializeOperationFunctionMap")});var iT=y((ALe,LV)=>{"use strict";var uI=M(),Pfe=ee(),wE=V(),{handleHDBError:dI,hdb_errors:sT}=ce(),{isMainThread:Lfe}=require("worker_threads"),{Readable:Mfe}=require("stream"),DV=require("os"),Ufe=require("util"),vfe=$y(),Bfe=Ufe.promisify(vfe.authorize),PV=CV(),{createGzip:Hfe,constants:xfe}=require("zlib");function Ffe(e){let t=`Found an uncaught exception with message: ${e.message}. ${DV.EOL}Stack: ${e.stack} ${DV.EOL}Terminating ${Lfe?"HDB":"thread"}.`;console.error(t),wE.fatal(t),process.exit(1)}a(Ffe,"handleServerUncaughtException");function kfe(e,t,r){if(wE[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:sT.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(kfe,"serverErrorHandler");function Gfe(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=dI(new Error,"Invalid JSON.",sT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Pfe.isEmpty(e.body.operation)){let n=dI(new Error,"Request body must include an 'operation' property.",sT.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(Gfe,"reqBodyValidationHandler");function qfe(e,t,r){let n;e.body.operation!==uI.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==uI.OPERATIONS_ENUM.LOGIN&&e.body.operation!==uI.OPERATIONS_ENUM.LOGOUT?Bfe(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{wE.warn(s),wE.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(dI(s,i,sT.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(qfe,"authHandler");async function $fe(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=PV.chooseOperation(e.body);let s=await PV.processLocalTransaction(e,n);if(s instanceof Mfe&&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(Hfe({level:xfe.Z_BEST_SPEED})))}return s}catch(s){throw wE.error(s),s}}a($fe,"handlePostRequest");LV.exports={authHandler:qfe,handlePostRequest:$fe,handleServerUncaughtException:Ffe,serverErrorHandler:kfe,reqBodyValidationHandler:Gfe}});var BV=y((yLe,vV)=>{"use strict";var Vfe=require("fastify-plugin"),{handlePostRequest:MV,authHandler:Yfe,reqBodyValidationHandler:Kfe}=iT();async function Wfe(e){e.decorate("hdbCore",{preValidation:[Kfe,Yfe],request:t=>UV(MV(t,response)),requestWithoutAuthentication:(t,r)=>UV(MV(t,r,!0))})}a(Wfe,"hdbCore");async function UV(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(UV,"convertAsyncIterators");vV.exports=Vfe(Wfe)});var FV=y((ILe,xV)=>{"use strict";var NLe=require("fs"),_I=te();_I.initSync();var{CONFIG_PARAMS:HV}=M(),jfe=1024*1024*1024;function Qfe(e){let t=_I.get(HV.HTTP_TIMEOUT),r=_I.get(HV.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:jfe,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Qfe,"getServerOptions");xV.exports=Qfe});var qV=y((CLe,GV)=>{"use strict";var fI=te();fI.initSync();var{CONFIG_PARAMS:kV}=M();function zfe(){let e=fI.get(kV.HTTP_CORSACCESSLIST),t=fI.get(kV.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(zfe,"getCORSOptions");GV.exports=zfe});var YV=y((PLe,VV)=>{"use strict";var $V=te();$V.initSync();var Jfe=M();function Xfe(){return $V.get(Jfe.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Xfe,"getHeaderTimeoutConfig");VV.exports=Xfe});var hI={};tt(hI,{customFunctionsServer:()=>tEe,ready:()=>o1,start:()=>eEe});function eEe(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){vo||(vo=i1(t),nt.http((await vo).server));let o=await vo,c=(0,EI.dirname)(s),l=(0,EI.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!KV.has(c)){KV.add(c);try{o.register(nEe(c,l))}catch(d){if(d.message==="Root plugin has already booted")ht.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw d}}},ready:o1}}async function tEe(){try{ht.info("In Custom Functions Fastify server"+process.cwd()),ht.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),ht.debug(`Custom Functions server process ${process.pid} starting up.`),await rEe();let e=XV.get(ZV.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=vo=await i1(e)}catch(r){throw ht.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw ht.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){ht.error(`Custom Functions ${process.pid} Error: ${e}`),ht.error(e),process.exit(1)}}async function rEe(){try{ht.info("Custom Functions starting configuration."),await e1.setUsersToGlobal(),ht.info("Custom Functions completed configuration.")}catch(e){ht.error(e)}}function nEe(e,t){return async function(r){try{ht.info("Custom Functions starting buildRoutes"),ht.trace("Loading fastify routes folder "+e),(0,WV.existsSync)(e)&&r.register(JV.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:ht.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?ht.error(s.message):s&&ht.error(s),o()})}catch(n){ht.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function i1(e){ht.info("Custom Functions starting buildServer.");let t=(0,t1.default)(e),r=(0,jV.default)(t);r.server.headersTimeout=(0,n1.default)(),r.setErrorHandler(s1.serverErrorHandler);let n=(0,r1.default)();return n&&r.register(QV.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),o()}),r.register(zV.default),await r.register(Zfe),await r.after(),bN(r),ht.info("Custom Functions completed buildServer."),r}function o1(){if(vo)return vo.then?vo.then(e=>e.ready()):vo.ready()}var EI,WV,jV,QV,zV,JV,XV,ZV,ht,Zfe,e1,t1,r1,n1,s1,vo,KV,a1=Ce(()=>{EI=require("path"),WV=require("fs"),jV=B(require("fastify")),QV=B(require("@fastify/cors")),zV=B(vN()),JV=B(require("@fastify/autoload")),XV=B(te()),ZV=B(M()),ht=B(V()),Zfe=B(BV()),e1=B(_n()),t1=B(FV()),r1=B(qV()),n1=B(YV()),s1=B(iT());Ju();Wr();KV=new Set;a(eEe,"start");a(tEe,"customFunctionsServer");a(rEe,"setUp");a(nEe,"buildRouteFolder");a(i1,"buildServer");a(o1,"ready")});var pI={};tt(pI,{start:()=>sEe});function sEe(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,_1.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){l1||(l1=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=c1.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,u1.default)(s,(0,d1.realpathSync)(o))}}return i(s)},{runFirst:!0})),c1.set(r,n)}}}var u1,d1,_1,c1,l1,f1=Ce(()=>{u1=B(require("send")),d1=require("fs"),_1=B(require("serve-static")),c1=new Map;a(sEe,"start")});var gI={};tt(gI,{Request:()=>mI,createReuseportFd:()=>oT});var E1,mI,SI,TI,oT,aT=Ce(()=>{E1=require("os"),mI=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 TI(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 SI(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},SI=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)}},TI=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,E1.platform)()!="win32"&&(oT=require("node-unix-socket").createReuseportFd)});var AI=y((xLe,h1)=>{"use strict";var CE=te();CE.initSync();var Ed=require("fs-extra"),RI=require("path"),hd=M(),iEe=require("crypto"),oEe=require("uuid").v4;h1.exports=aEe;function aEe(){if(CE.getHdbBasePath()!==void 0){let e=RI.join(CE.getHdbBasePath(),hd.LICENSE_KEY_DIR_NAME,hd.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=RI.join(CE.getHdbBasePath(),hd.LICENSE_KEY_DIR_NAME,hd.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=RI.join(CE.getHdbBasePath(),hd.LICENSE_KEY_DIR_NAME,hd.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Ed.accessSync(r),Ed.accessSync(e),Ed.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=oEe(),i=iEe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Ed.writeFileSync(r,s),Ed.writeFileSync(e,i.privateKey),Ed.writeFileSync(t,i.publicKey)}else throw n}}}a(aEe,"checkJWTTokenExist")});var m1=y((kLe,p1)=>{"use strict";var bI=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};p1.exports={HdbInfoInsertObject:bI}});var g1=y((qLe,T1)=>{"use strict";var S1=M(),yI=class{static{a(this,"UpgradeObject")}constructor(t,r){this[S1.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[S1.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};T1.exports={UpgradeObject:yI}});var cT=y((VLe,A1)=>{"use strict";var Ls=require("prompt"),pd=require("chalk"),R1=V(),ci=require("os"),OI=Jo(),NI=["yes","y"];async function cEe(e){let t=`${ci.EOL}`+pd.bold.green("Your current HarperDB version requires that we complete an update process.")+`${ci.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${ci.EOL}${ci.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${ci.EOL}`;Ls.override=OI(["CONFIRM_UPGRADE"]),Ls.start(),Ls.message=t;let r={properties:{CONFIRM_UPGRADE:{description:pd.magenta(`${ci.EOL}[CONFIRM_UPGRADE] Do you want to upgrade your HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n;try{n=await Ls.get([r])}catch(s){return R1.error("There was an error when prompting user about an upgrade."),R1.error(s),!1}return NI.includes(n.CONFIRM_UPGRADE)}a(cEe,"forceUpdatePrompt");async function lEe(e){let t=`${ci.EOL}`+pd.bold.green(`Your installed HarperDB version is older than the version used to create your data. Downgrading is not recommended as it is not tested and guaranteed to work. However, if you need to downgrade, and a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${ci.EOL}`);Ls.override=OI(["CONFIRM_DOWNGRADE"]),Ls.start(),Ls.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:pd.magenta(`${ci.EOL}[CONFIRM_DOWNGRADE] Do you want to proceed with using your downgraded HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n=await Ls.get([r]);return NI.includes(n.CONFIRM_DOWNGRADE)}a(lEe,"forceDowngradePrompt");async function uEe(){let e=`${ci.EOL}`+pd.bold.green("We now require a Certifacte Authority certificate. HarperDB can generate all new certificates for you (your existing certificates will be backed up) or you can keep any existing certificates and add your own CA certificate. To add your own CA certificate set the <certificateAuthority> parameter in harperdb-config.yaml");Ls.override=OI(["GENERATE_CERTS"]),Ls.start(),Ls.message=e;let t={properties:{GENERATE_CERTS:{description:pd.magenta(`${ci.EOL}[GENERATE_CERTS] Do you want HarperDB to generate all new certificates? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"yes",required:!0}}},r=await Ls.get([t]);return NI.includes(r.GENERATE_CERTS)}a(uEe,"upgradeCertsPrompt");A1.exports={forceUpdatePrompt:cEe,forceDowngradePrompt:lEe,upgradeCertsPrompt:uEe}});var wI=y((KLe,b1)=>{"use strict";var II=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};b1.exports=II});var O1=y((XLe,y1)=>{"use strict";var dEe=ee(),_Ee=yt(),jLe=V(),QLe=require("path"),zLe=require("fs"),JLe=M();y1.exports={getOldPropsValue:fEe};function fEe(e,t,r=!1){let n=t.getRaw(e);return dEe.isNotEmptyAndHasValue(n)?n:r?_Ee.getDefaultConfig(e):""}a(fEe,"getOldPropsValue")});var C1=y((eMe,w1)=>{"use strict";var Ha=require("path"),xa=require("fs-extra"),EEe=require("properties-reader"),hEe=wI(),cr=V(),{getOldPropsValue:pt}=O1(),{HDB_SETTINGS_NAMES:Ee,CONFIG_PARAMS:_l}=M(),fl=yt(),lT=te(),N1=ee(),qi=M(),CI=new hEe("3.1.0"),I1=[];function pEe(){let e=EEe(lT.get(Ee.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),cr.info(t);let r=` ;Settings for the HarperDB process.
34
40
 
35
41
  ;The directory selected during install where the database files reside.
36
- ${oe.HDB_ROOT_KEY} = ${Qe(oe.HDB_ROOT_KEY,e)}
42
+ ${Ee.HDB_ROOT_KEY} = ${pt(Ee.HDB_ROOT_KEY,e)}
37
43
  ;The port the HarperDB REST interface will listen on.
38
- ${oe.SERVER_PORT_KEY} = ${Qe(oe.SERVER_PORT_KEY,e)}
44
+ ${Ee.SERVER_PORT_KEY} = ${pt(Ee.SERVER_PORT_KEY,e)}
39
45
  ;Set to true to enable HTTPS on the HarperDB REST endpoint. Requires a valid certificate and key.
40
- ${oe.HTTP_SECURE_ENABLED_KEY} = ${Qe(oe.HTTP_SECURE_ENABLED_KEY,e)}
46
+ ${Ee.HTTP_SECURE_ENABLED_KEY} = ${pt(Ee.HTTP_SECURE_ENABLED_KEY,e)}
41
47
  ;The path to the SSL certificate used when running with HTTPS enabled.
42
- ${oe.CERT_KEY} = ${Qe(oe.CERT_KEY,e)}
48
+ ${Ee.CERT_KEY} = ${pt(Ee.CERT_KEY,e)}
43
49
  ;The path to the SSL private key used when running with HTTPS enabled.
44
- ${oe.PRIVATE_KEY_KEY} = ${Qe(oe.PRIVATE_KEY_KEY,e)}
50
+ ${Ee.PRIVATE_KEY_KEY} = ${pt(Ee.PRIVATE_KEY_KEY,e)}
45
51
  ;Set to true to enable Cross Origin Resource Sharing, which allows requests across a domain.
46
- ${oe.CORS_ENABLED_KEY} = ${Qe(oe.CORS_ENABLED_KEY,e)}
52
+ ${Ee.CORS_ENABLED_KEY} = ${pt(Ee.CORS_ENABLED_KEY,e)}
47
53
  ;Allows for setting allowable domains with CORS. Comma separated list.
48
- ${oe.CORS_WHITELIST_KEY} = ${Qe(oe.CORS_WHITELIST_KEY,e)}
54
+ ${Ee.CORS_WHITELIST_KEY} = ${pt(Ee.CORS_WHITELIST_KEY,e)}
49
55
  ;Length of time in milliseconds after which a request will timeout. Defaults to 120,000 ms (2 minutes).
50
- ${oe.SERVER_TIMEOUT_KEY} = ${Qe(oe.SERVER_TIMEOUT_KEY,e,!0)}
56
+ ${Ee.SERVER_TIMEOUT_KEY} = ${pt(Ee.SERVER_TIMEOUT_KEY,e,!0)}
51
57
  ;The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response. Defaults to 5,000 ms (5 seconds).
52
- ${oe.SERVER_KEEP_ALIVE_TIMEOUT_KEY} = ${Qe(oe.SERVER_KEEP_ALIVE_TIMEOUT_KEY,e,!0)}
58
+ ${Ee.SERVER_KEEP_ALIVE_TIMEOUT_KEY} = ${pt(Ee.SERVER_KEEP_ALIVE_TIMEOUT_KEY,e,!0)}
53
59
  ;Limit the amount of time the parser will wait to receive the complete HTTP headers.. Defaults to 60,000 ms (1 minute).
54
- ${oe.SERVER_HEADERS_TIMEOUT_KEY} = ${Qe(oe.SERVER_HEADERS_TIMEOUT_KEY,e,!0)}
60
+ ${Ee.SERVER_HEADERS_TIMEOUT_KEY} = ${pt(Ee.SERVER_HEADERS_TIMEOUT_KEY,e,!0)}
55
61
  ;Define whether to log to file or not.
56
- ${oe.LOG_TO_FILE} = ${Xa.getDefaultConfig(Ja.LOGGING_FILE)}
62
+ ${Ee.LOG_TO_FILE} = ${fl.getDefaultConfig(_l.LOGGING_FILE)}
57
63
  ;Define whether to log to stdout/stderr or not. NOTE HarperDB must run in foreground in order to receive the std stream from HarperDB.
58
- ${oe.LOG_TO_STDSTREAMS} = ${Xa.getDefaultConfig(Ja.LOGGING_STDSTREAMS)}
64
+ ${Ee.LOG_TO_STDSTREAMS} = ${fl.getDefaultConfig(_l.LOGGING_STDSTREAMS)}
59
65
  ;Set to control amount of logging generated. Accepted levels are trace, debug, warn, error, fatal.
60
- ${oe.LOG_LEVEL_KEY} = ${Qe(oe.LOG_LEVEL_KEY,e)}
66
+ ${Ee.LOG_LEVEL_KEY} = ${pt(Ee.LOG_LEVEL_KEY,e)}
61
67
  ;The path where log files will be written. If there is no file name included in the path, the log file will be created by default as 'hdb_log.log'
62
- ${oe.LOG_PATH_KEY} = ${Qe(oe.LOG_PATH_KEY,e)}
68
+ ${Ee.LOG_PATH_KEY} = ${pt(Ee.LOG_PATH_KEY,e)}
63
69
  ;Set to true to enable daily log file rotations - each log file name will be prepended with YYYY-MM-DD.
64
- ${oe.LOG_DAILY_ROTATE_KEY} = ${Qe(oe.LOG_DAILY_ROTATE_KEY,e)}
70
+ ${Ee.LOG_DAILY_ROTATE_KEY} = ${pt(Ee.LOG_DAILY_ROTATE_KEY,e)}
65
71
  ;Set the number of daily log files to maintain when LOG_DAILY_ROTATE is enabled. If no integer value is set, no limit will be set for
66
72
  ;daily log files which may consume a large amount of storage depending on your log settings.
67
- ${oe.LOG_MAX_DAILY_FILES_KEY} = ${Qe(oe.LOG_MAX_DAILY_FILES_KEY,e)}
73
+ ${Ee.LOG_MAX_DAILY_FILES_KEY} = ${pt(Ee.LOG_MAX_DAILY_FILES_KEY,e)}
68
74
  ;The environment used by NodeJS. Setting to production will be the most performant, settings to development will generate more logging.
69
- ${oe.PROPS_ENV_KEY} = ${Qe(oe.PROPS_ENV_KEY,e)}
75
+ ${Ee.PROPS_ENV_KEY} = ${pt(Ee.PROPS_ENV_KEY,e)}
70
76
  ;This allows self signed certificates to be used in clustering. This is a security risk
71
77
  ;as clustering will not validate the cert, so should only be used internally.
72
78
  ;The HDB install creates a self signed certificate, if you use that cert this must be set to true.
73
- ${oe.ALLOW_SELF_SIGNED_SSL_CERTS} = ${Qe(oe.ALLOW_SELF_SIGNED_SSL_CERTS,e,!0)}
79
+ ${Ee.ALLOW_SELF_SIGNED_SSL_CERTS} = ${pt(Ee.ALLOW_SELF_SIGNED_SSL_CERTS,e,!0)}
74
80
  ;Set the max number of processes HarperDB will start. This can also be limited by number of cores and licenses.
75
- ${oe.MAX_HDB_PROCESSES} = ${Qe(oe.MAX_HDB_PROCESSES,e)}
81
+ ${Ee.MAX_HDB_PROCESSES} = ${pt(Ee.MAX_HDB_PROCESSES,e)}
76
82
  ;Set to true to enable clustering. Requires a valid enterprise license.
77
- ${oe.CLUSTERING_ENABLED_KEY} = ${Qe(oe.CLUSTERING_ENABLED_KEY,e,!0)}
83
+ ${Ee.CLUSTERING_ENABLED_KEY} = ${pt(Ee.CLUSTERING_ENABLED_KEY,e,!0)}
78
84
  ;The port that will be used for HarperDB clustering.
79
- ${oe.CLUSTERING_PORT_KEY} = ${Qe(oe.CLUSTERING_PORT_KEY,e)}
85
+ ${Ee.CLUSTERING_PORT_KEY} = ${pt(Ee.CLUSTERING_PORT_KEY,e)}
80
86
  ;The name of this node in your HarperDB cluster topology. This must be a value unique from the rest of your cluster node names.
81
- ${oe.CLUSTERING_NODE_NAME_KEY} = ${Qe(oe.CLUSTERING_NODE_NAME_KEY,e)}
87
+ ${Ee.CLUSTERING_NODE_NAME_KEY} = ${pt(Ee.CLUSTERING_NODE_NAME_KEY,e)}
82
88
  ;The user used to connect to other instances of HarperDB, this user must have a role of cluster_user.
83
- ${oe.CLUSTERING_USER_KEY} = ${Qe(oe.CLUSTERING_USER_KEY,e)}
89
+ ${Ee.CLUSTERING_USER_KEY} = ${pt(Ee.CLUSTERING_USER_KEY,e)}
84
90
  ;Defines if this instance does not record transactions. Note, if Clustering is enabled and Transaction Log is disabled your nodes will not catch up.
85
- ${oe.DISABLE_TRANSACTION_LOG_KEY} = ${Qe(oe.DISABLE_TRANSACTION_LOG_KEY,e,!0)}
91
+ ${Ee.DISABLE_TRANSACTION_LOG_KEY} = ${pt(Ee.DISABLE_TRANSACTION_LOG_KEY,e,!0)}
86
92
  ;Defines the length of time an operation token will be valid until it expires. Example values: https://github.com/vercel/ms
87
- ${oe.OPERATION_TOKEN_TIMEOUT_KEY} = ${Qe(oe.OPERATION_TOKEN_TIMEOUT_KEY,e,!0)}
93
+ ${Ee.OPERATION_TOKEN_TIMEOUT_KEY} = ${pt(Ee.OPERATION_TOKEN_TIMEOUT_KEY,e,!0)}
88
94
  ;Defines the length of time a refresh token will be valid until it expires. Example values: https://github.com/vercel/ms
89
- ${oe.REFRESH_TOKEN_TIMEOUT_KEY} = ${Qe(oe.REFRESH_TOKEN_TIMEOUT_KEY,e,!0)}
95
+ ${Ee.REFRESH_TOKEN_TIMEOUT_KEY} = ${pt(Ee.REFRESH_TOKEN_TIMEOUT_KEY,e,!0)}
90
96
  ;The port the IPC server will run on.
91
- ${oe.IPC_SERVER_PORT} = ${Xa.getDefaultConfig(Ja.IPC_NETWORK_PORT)}
97
+ ${Ee.IPC_SERVER_PORT} = ${fl.getDefaultConfig(_l.IPC_NETWORK_PORT)}
92
98
  ;Run HDB in the foreground.
93
- ${oe.RUN_IN_FOREGROUND} = ${Xa.getDefaultConfig(Ja.OPERATIONSAPI_FOREGROUND)}
99
+ ${Ee.RUN_IN_FOREGROUND} = ${fl.getDefaultConfig(_l.OPERATIONSAPI_FOREGROUND)}
94
100
  ;Set to true to enable custom API endpoints. Requires a valid enterprise license.
95
- ${oe.CUSTOM_FUNCTIONS_ENABLED_KEY} = ${Xa.getDefaultConfig(Ja.CUSTOMFUNCTIONS_ENABLED)}
101
+ ${Ee.CUSTOM_FUNCTIONS_ENABLED_KEY} = ${fl.getDefaultConfig(_l.CUSTOMFUNCTIONS_ENABLED)}
96
102
  ;The port used to access the custom functions server.
97
- ${oe.CUSTOM_FUNCTIONS_PORT_KEY} = ${Xa.getDefaultConfig(Ja.HTTP_PORT)}
103
+ ${Ee.CUSTOM_FUNCTIONS_PORT_KEY} = ${fl.getDefaultConfig(_l.HTTP_PORT)}
98
104
  ;The path to the folder containing HarperDB custom function files.
99
- ${oe.CUSTOM_FUNCTIONS_DIRECTORY_KEY} = ${Go.join(Qe(oe.HDB_ROOT_KEY,e),"custom_functions")}
105
+ ${Ee.CUSTOM_FUNCTIONS_DIRECTORY_KEY} = ${Ha.join(pt(Ee.HDB_ROOT_KEY,e),"custom_functions")}
100
106
  ;Set the max number of processes HarperDB will start for the Custom Functions server
101
- ${oe.MAX_CUSTOM_FUNCTION_PROCESSES} = ${Xa.getDefaultConfig(Ja.HTTP_THREADS)}
102
- `,n=Nm.get("settings_path"),s=Go.dirname(n),i=Go.join(s,"3_1_0_upgrade_settings.bak");try{Mt.info(`Backing up old settings file to: ${i}`),xo.copySync(n,i)}catch(c){throw Mt.error(c),console.error("There was a problem writing the backup for the old settings file. Please check the log for details."),c}try{Mt.info("New settings file values for 3.1.0 upgrade:",r),Mt.info(`Creating new/upgraded settings file at '${n}'`),xo.writeFileSync(n,r),Mt.info("Updating env variables with new settings values")}catch(c){throw console.error("There was a problem writing the new settings file. Please check the log for details."),Mt.error("Attempting to reset the settings file to its original state. Use the '.bak' file if this fails."),Mt.error(c),xo.copySync(i,n),c}Nm.initSync();let o="New settings file for 3.1.0 upgrade successfully created.";return console.log(o),Mt.info(o),o}a(ide,"updateSettingsFile_3_1_0");function ode(){let e=Go.join(EV.getHomeDir(),Js.HDB_HOME_DIR_NAME,Js.LICENSE_KEY_DIR_NAME,Js.LICENSE_FILE_NAME),t=Go.join(EV.getHomeDir(),Js.HDB_HOME_DIR_NAME,Js.LICENSE_KEY_DIR_NAME,Js.REG_KEY_FILE_NAME),r=Go.join(Nm.getHdbBasePath(),Js.LICENSE_KEY_DIR_NAME,Js.LICENSE_FILE_NAME),n=Go.join(r,Js.LICENSE_FILE_NAME),s=Go.join(r,Js.REG_KEY_FILE_NAME),i="Move license files for version 3.1.0";console.log(i),Mt.info(i);let o="Creating .license directory";console.log(o),Mt.info(o),xo.mkdirpSync(r);try{xo.accessSync(e);try{let c="Moving licence file";console.log(c),Mt.info(c),xo.moveSync(e,n);let l="License file successfully moved.";console.log(l),Mt.info(l)}catch{let l="moving license file failed";console.error(l),Mt.error(l)}}catch{let l=`license file '${e}' does not exist.`;console.warn(l),Mt.warn(l)}try{xo.accessSync(t);try{let c="Moving registration file";console.log(c),Mt.info(c),xo.moveSync(t,s);let l="Registration file successfully moved.";console.log(l),Mt.info(l)}catch{let l="moving registration file failed";console.error(l),Mt.error(l)}}catch{let l=`registration file '${t}' does not exist.`;console.warn(l),Mt.warn(l)}}a(ode,"moveLicenseFiles");DN.sync_functions.push(ide);DN.sync_functions.push(ode);hV.push(DN);pV.exports=hV});var AV=R((vIe,RV)=>{"use strict";var Nn=Ye(),{insertRecords:ade}=Zo(),cde=Nr(),qo=_t(),lde=Y(),Fi=k(),ude=Y(),Xs=require("fs-extra"),ki=require("path"),_de=require("cli-progress"),wd=require("assert"),dde=require("pino"),fde=X();RV.exports=Ede;var ym,SV,Im,LN,Tr,Cd=!1;async function Ede(e=!0){return ym=fde.getHdbBasePath(),SV=ki.join(ym,"schema"),Im=ki.join(ym,"4_0_0_upgrade_tmp"),LN=ki.join(ym,"transactions"),console.info("Reindexing upgrade started for schemas"),Fi.notify("Reindexing upgrade started for schemas"),await TV(SV,!1,e),await Xs.pathExists(LN)&&(console.info(`
107
+ ${Ee.MAX_CUSTOM_FUNCTION_PROCESSES} = ${fl.getDefaultConfig(_l.HTTP_THREADS)}
108
+ `,n=lT.get("settings_path"),s=Ha.dirname(n),i=Ha.join(s,"3_1_0_upgrade_settings.bak");try{cr.info(`Backing up old settings file to: ${i}`),xa.copySync(n,i)}catch(c){throw cr.error(c),console.error("There was a problem writing the backup for the old settings file. Please check the log for details."),c}try{cr.info("New settings file values for 3.1.0 upgrade:",r),cr.info(`Creating new/upgraded settings file at '${n}'`),xa.writeFileSync(n,r),cr.info("Updating env variables with new settings values")}catch(c){throw console.error("There was a problem writing the new settings file. Please check the log for details."),cr.error("Attempting to reset the settings file to its original state. Use the '.bak' file if this fails."),cr.error(c),xa.copySync(i,n),c}lT.initSync();let o="New settings file for 3.1.0 upgrade successfully created.";return console.log(o),cr.info(o),o}a(pEe,"updateSettingsFile_3_1_0");function mEe(){let e=Ha.join(N1.getHomeDir(),qi.HDB_HOME_DIR_NAME,qi.LICENSE_KEY_DIR_NAME,qi.LICENSE_FILE_NAME),t=Ha.join(N1.getHomeDir(),qi.HDB_HOME_DIR_NAME,qi.LICENSE_KEY_DIR_NAME,qi.REG_KEY_FILE_NAME),r=Ha.join(lT.getHdbBasePath(),qi.LICENSE_KEY_DIR_NAME,qi.LICENSE_FILE_NAME),n=Ha.join(r,qi.LICENSE_FILE_NAME),s=Ha.join(r,qi.REG_KEY_FILE_NAME),i="Move license files for version 3.1.0";console.log(i),cr.info(i);let o="Creating .license directory";console.log(o),cr.info(o),xa.mkdirpSync(r);try{xa.accessSync(e);try{let c="Moving licence file";console.log(c),cr.info(c),xa.moveSync(e,n);let l="License file successfully moved.";console.log(l),cr.info(l)}catch{let l="moving license file failed";console.error(l),cr.error(l)}}catch{let l=`license file '${e}' does not exist.`;console.warn(l),cr.warn(l)}try{xa.accessSync(t);try{let c="Moving registration file";console.log(c),cr.info(c),xa.moveSync(t,s);let l="Registration file successfully moved.";console.log(l),cr.info(l)}catch{let l="moving registration file failed";console.error(l),cr.error(l)}}catch{let l=`registration file '${t}' does not exist.`;console.warn(l),cr.warn(l)}}a(mEe,"moveLicenseFiles");CI.sync_functions.push(pEe);CI.sync_functions.push(mEe);I1.push(CI);w1.exports=I1});var U1=y((rMe,M1)=>{"use strict";var zn=_t(),{insertRecords:SEe}=dc(),TEe=an(),Fa=Bt(),gEe=ee(),Bo=V(),REe=ee(),$i=require("fs-extra"),Ho=require("path"),AEe=require("cli-progress"),DE=require("assert"),bEe=require("pino"),yEe=te();M1.exports=OEe;var uT,D1,dT,DI,rn,PE=!1;async function OEe(e=!0){return uT=yEe.getHdbBasePath(),D1=Ho.join(uT,"schema"),dT=Ho.join(uT,"4_0_0_upgrade_tmp"),DI=Ho.join(uT,"transactions"),console.info("Reindexing upgrade started for schemas"),Bo.notify("Reindexing upgrade started for schemas"),await P1(D1,!1,e),await $i.pathExists(DI)&&(console.info(`
103
109
 
104
- Reindexing upgrade started for transaction logs`),Fi.notify("Reindexing upgrade started for transaction logs"),await TV(LN,!0,e)),Fi.notify("Reindexing upgrade complete"),"Reindexing for 4.0.0 upgrade complete"+(Cd?", but errors occurred":"")}a(Ede,"reindexUpgrade");async function TV(e,t,r){let n=await Xs.readdir(e),s=n.length;for(let i=0;i<s;i++){let o=n[i],c=ki.join(e,o.toString());if(o===".DS_Store")continue;let l=await Xs.readdir(c),_=l.length;for(let u=0;u<_;u++){let d=l[u];if(d!==".DS_Store"&&Xs.statSync(ki.join(c,d)).isDirectory())try{await hde(o,d,t),Tr.info(`Reindexing started for ${o}.${d}`),Fi.notify(`${t?"Transaction":"Schema"} reindexing started for ${o}.${d}`),await mde(o,d,c,t,r),Tr.info(`Reindexing completed for ${o}.${d}`),Fi.notify(`Reindexing completed for ${o}.${d}`)}catch(E){Cd=!0,E.schema_path=c,E.table_name=d,Fi.error("There was an error with the reindex upgrade, check the logs in hdb/3_0_0_upgrade_tmp for more details"),Fi.error(E),Tr.error(E),console.error(E)}}}if(!Cd)try{await Xs.rm(Im,{recursive:!0})}catch{}}a(TV,"processTables");async function hde(e,t,r){let s=`${e}_${t}_${r?"transaction_reindex":"schema_reindex"}.log`,i=ki.join(Im,s);await Xs.ensureDir(Im),await Xs.writeFile(i,""),Tr=dde({level:"debug",formatters:{bindings(){}}},i)}a(hde,"initPinoLogger");var pde=20;async function mde(e,t,r,n,s){let i;try{i=await Nn.openEnvironment(r,t,n)}catch(T){if(T.message==="MDB_INVALID: File is not an LMDB file"){Fi.notify(`${e}.${t} file is not from the old environment and has been skipped`),console.info(`${e}.${t} file is not from the old environment and has been skipped`),Tr.error(T);return}throw T}let o=gde(i.dbis),c=Nn.openDBI(i,o),l=Object.keys(i.dbis),_=Nn.statDBI(i,o);Tr.info(`Old environment stats: ${JSON.stringify(_)}`);let u=new _de.SingleBar({format:`${e}.${t} |{bar}| {percentage}% || {value}/{total} records`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,clearOnComplete:!1});u.start(_.entryCount,0,{});let d=await Nn.createEnvironment(r,t,!1);Nn.createDBI(d,o,!1,!0);let E=[];try{for(let T of c.getRange({start:!1}))T.value=Object.assign({},T.value),E.push(T),n||e==="system"&&(t==="hdb_schema"&&(T.key=T.key.toString(),T.value.name=T.value.name.toString()),t==="hdb_table"&&(T.key=T.key.toString(),T.value.schema=T.value.schema.toString(),T.value.name=T.value.name.toString()),t==="hdb_attribute"&&(T.key=T.key.toString(),T.value.schema=T.value.schema.toString(),T.value.table=T.value.table.toString(),T.value.attribute=T.value.attribute.toString())),E.length>pde&&await f();await f()}catch(T){throw Cd=!0,Tr.error(T),T}async function f(){let T,b=E.map(({value:v})=>v);n?T=await Promise.all(b.map(v=>Sde(d,v))):T=await ade(d,o,l.filter(v=>v!=="__blob__"),b,!1);for(let v=0,U=E.length;v<U;v++){let{key:F,value:M}=E[v];Tr.info(`Record hash value: ${F} hash: ${o}`);let W;n?W=T[v]:W=T.written_hashes.indexOf(F)>-1,wd(W,!0),Tde(d,o,M[o],n),Tr.info(`Insert success, written hashes: ${T.written_hashes}`),u.increment()}E=[],u.value/u.total*100%10===0&&Fi.notify(`${e}.${t} ${u.value}/${u.total} records inserted`),Tr.info(`${u.value}/${u.total} records inserted`)}a(f,"finishOutstanding"),u.stop();let h=Nn.statDBI(i,o),m=Nn.statDBI(d,o);if(Tr.info(`Old stats entry count: ${h.entryCount}. New stats entry count: ${m.entryCount}`),wd.deepStrictEqual(h.entryCount,m.entryCount),await Nn.closeEnvironment(i),await Nn.closeEnvironment(d),delete global.lmdb_map[`${e}.${t}`],s){let T=ki.join(r,t),b=ki.join(T,"data.mdb"),N=ki.join(T,"lock.mdb");await Xs.unlink(b),await Xs.unlink(N),await Xs.rmdir(T),Tr.info(`Deleted old environment files from schema folder: ${b}, ${N}`)}let S=await Nn.openEnvironment(r,t),g=Nn.statDBI(S,o);Tr.info(`New stats: ${JSON.stringify(m)}. New stats after move: ${JSON.stringify(g)}`),wd.deepStrictEqual(g.entryCount,m.entryCount),await Nn.closeEnvironment(S),delete global.lmdb_map[`${e}.${t}`]}a(mde,"processTable");async function Sde(e,t){Nn.initializeDBIs(e,qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,qo.TRANSACTIONS_DBIS);let r=t.timestamp;return e.dbis[qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(r,()=>{e.dbis[qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(r,t),ude.isEmpty(t.user_name)||e.dbis[qo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(t.user_name,r);for(let n of t.hash_values)e.dbis[qo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n,r)})}a(Sde,"insertTransaction");function Tde(e,t,r,n){let i=e.dbis[t].get(r);wd.deepStrictEqual(typeof i,"object");let o;if(n){let c={[qo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME]:i.user_name,[qo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE]:i.hash_values};o=Object.entries(c)}else o=Object.entries(i);for(let[c,l]of o)if(c!==t&&e.dbis[c]!==void 0&&!lde.isEmptyOrZeroLength(l))if(n&&c==="hash_value")for(let _=0,u=l.length;_<u;_++){let d=l[_];gV(e,c,d,r)}else gV(e,c,l,r)}a(Tde,"validateIndices");function gV(e,t,r,n){try{let s=!1,i=cde.getIndexedValues(r);if(!i)return;for(let o of i)s=e.dbis[t].doesExist(o,n),s||Tr.info(`Validate indices did not find value in new DBI: ${o}. Hash: ${n}`),wd.deepStrictEqual(s,!0)}catch(s){Cd=!0,Tr.error(s),console.error(s)}}a(gV,"validateIndex");function gde(e){let t;for(let[r,n]of Object.entries(e))if(n.__dbi_defintion__.is_hash_attribute===!0){t=r;break}return t}a(gde,"getHashDBI")});var Cm=R((HIe,bV)=>{"use strict";var Rde=require("mkcert"),wm=require("path"),PN=require("fs-extra"),MN=k(),Ade=X(),UN=D(),Ml=wT(),Ode=to(),bde=Et();bV.exports={generateKeys:Nde,updateConfigCert:OV};async function Nde(){let e=Ade.getHdbBasePath(),t=wm.join(e,UN.LICENSE_KEY_DIR_NAME),r=await Rde.createCert({domains:["127.0.0.1","localhost","::1"],validityDays:3650,caKey:Ml.CERTIFICATE_VALUES.key,caCert:Ml.CERTIFICATE_VALUES.cert}),n=wm.join(t,Ml.CERTIFICATE_PEM_NAME),s=wm.join(t,Ml.PRIVATEKEY_PEM_NAME),i=wm.join(t,Ml.CA_PEM_NAME);try{await PN.writeFile(n,r.cert)}catch(o){throw MN.error(o),console.error("There was a problem creating the certificate file. Please check the install log for details."),o}try{await PN.writeFile(s,r.key)}catch(o){throw MN.error(o),console.error("There was a problem creating the private key file. Please check the install log for details."),o}try{await PN.writeFile(i,Ml.CERTIFICATE_VALUES.cert)}catch(o){throw MN.error(o),console.error("There was a problem creating the certificate authority file. Please check the install log for details."),o}OV(n,s,i)}a(Nde,"generateKeys");function OV(e,t,r){let n=Ode(Object.keys(UN.CONFIG_PARAM_MAP),!0),s=UN.CONFIG_PARAMS,i={[s.CLUSTERING_TLS_CERTIFICATE]:n[s.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]?n[s.CLUSTERING_TLS_CERTIFICATE]:e,[s.CLUSTERING_TLS_PRIVATEKEY]:n[s.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]?n[s.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]:t,[s.CLUSTERING_TLS_CERT_AUTH]:n[s.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]?n[s.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]:r,[s.TLS_CERTIFICATE]:n[s.TLS_CERTIFICATE.toLowerCase()]?n[s.TLS_CERTIFICATE.toLowerCase()]:e,[s.TLS_PRIVATEKEY]:n[s.TLS_PRIVATEKEY.toLowerCase()]?n[s.TLS_PRIVATEKEY.toLowerCase()]:t,[s.TLS_CERTIFICATEAUTHORITY]:n[s.TLS_CERTIFICATEAUTHORITY.toLowerCase()]?n[s.TLS_CERTIFICATEAUTHORITY.toLowerCase()]:r};n[s.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(i[s.OPERATIONSAPI_TLS_CERTIFICATE]=n[s.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),n[s.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(i[s.OPERATIONSAPI_TLS_PRIVATEKEY]=n[s.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),n[s.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(i[s.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=n[s.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),bde.updateConfigValue(void 0,void 0,i,!1,!0)}a(OV,"updateConfigCert")});var CV=R((qIe,wV)=>{"use strict";var Dm=require("path"),Fo=require("fs-extra"),yde=CN(),Za=k(),NV=Et(),vN=X(),As=D(),Lm=Y(),Ide=require("properties-reader"),wde=as(),Cde=GE(),Dde=ur(),xIe=require("util"),Lde=Dde.searchByValue,Pde=Cr(),Mde=ih(),Ude=Ze(),vde=AV(),yV=Cm(),Bde=bm(),Pd=new yde("4.0.0"),IV=[],Dd,Ld;async function Hde(){try{if(await Bde.upgradeCertsPrompt()){if(console.log("Generating new certificates."),Dd){let t=Lm.changeExtension(Dd,".bak");await Fo.move(Dd,t)}if(Ld){let t=Lm.changeExtension(Ld,".bak");await Fo.move(Ld,t)}await yV.generateKeys()}else console.log("Using existing certificates."),yV.updateConfigCert(Dd,Ld,void 0)}catch(e){throw console.error("There was a problem generating new keys. Please check the log for details."),e}}a(Hde,"generateNewKeys");async function Gde(){console.log("Updating HarperDB nodes."),Za.info("Updating HarperDB nodes.");let e=[];try{let t=new wde(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*","name",["*"]),r=Array.from(await Lde(t)),n=[];for(let i=0,o=r.length;i<o;i++){let c=r[i];if(!Ude.NATS_TERM_CONSTRAINTS_RX.test(c.name)){let u=`Node name '${c.name}' is invalid, must not contain ., * or >. Please change name and try again.`;throw console.error(u),u}let l={host:c.host,port:c.port};e.push(l);let _=[];for(let u=0,d=c.subscriptions.length;u<d;u++){let E=c.subscriptions[u],f=E.channel.split(":");_.push({schema:f[0],table:f[1],publish:E.publish,subscribe:E.subscribe})}n.push({name:c.name,subscriptions:_,system_info:{hdb_version:As.PRE_4_0_0_VERSION,node_version:void 0,platform:void 0}})}if(Lm.isEmptyOrZeroLength(n))return;let s=new Cde(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,n);await Pde.update(s)}catch(t){throw console.error("There was a problem updating the hdb_nodes table. Please check the log for details."),t}try{Mde.setRoutes({server:"hub",routes:e})}catch(t){throw console.error("There was a problem setting the clustering routes. Please check the log for details."),t}}a(Gde,"updateNodes");async function xde(){let e=vN.get(As.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);if(!e.includes(Dm.join("config","settings.js"))){Za.info("pre 4.0.0 settings.js file not found, skipping settings file update");return}let t="Updating settings file for version 4.0.0";console.log(t),Za.info(t);let r=Dm.dirname(e),n=vN.get(As.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),s=Dm.join(n,"backup","4_0_0_upgrade_settings.bak"),i=Dm.join(n,As.HDB_CONFIG_FILE);try{Za.info(`Backing up old settings file to: ${s}`),console.log(`Backing up old settings file to: ${s}`),Fo.copySync(e,s)}catch(d){throw console.error("There was a problem writing the backup for the old settings file. Please check the log for details."),d}try{Za.info(`Creating new/upgraded settings file at '${i}'`),console.log(`Creating new/upgraded settings file at '${i}'`),Za.info("Updating env variables with new settings values");let d=NV.initOldConfig(e);Dd=d[As.CONFIG_PARAMS.TLS_CERTIFICATE.toLowerCase()],Ld=d[As.CONFIG_PARAMS.TLS_PRIVATEKEY.toLowerCase()],NV.createConfigFile(d)}catch(d){throw console.log("There was a problem creating the new HarperDB config file. Please check the log for details."),d}let o=Lm.getPropsFilePath();Fo.accessSync(o,Fo.constants.F_OK|Fo.constants.R_OK);let l=Ide(o).get(As.HDB_SETTINGS_NAMES.INSTALL_USER),_=`settings_path = ${i}
105
- install_user = ${l}`;try{Fo.writeFileSync(o,_)}catch(d){throw console.log("There was a problem updating the HarperDB boot properties file. Please check the log for details."),d}try{vN.initSync(!0)}catch(d){throw console.error("Unable to initialize new properties. Please check the log for details."),d}let u="New settings file for 4.0.0 upgrade successfully created.";try{Fo.removeSync(r),console.log(u),Za.info(u)}catch(d){throw console.error("There was a problem deleting the old settings file and directory. Please check the log for details."),d}}a(xde,"updateSettingsFile_4_0_0");Pd.async_functions.push(xde);Pd.async_functions.push(Hde);Pd.async_functions.push(vde);Pd.async_functions.push(Gde);IV.push(Pd);wV.exports=IV});var BN=R((kIe,MV)=>{"use strict";var ec=Y(),qde=D(),DV=k(),{DATA_VERSION:Fde,UPGRADE_VERSION:kde}=qde.UPGRADE_JSON_FIELD_NAMES_ENUM,LV=mV(),Pm=CV(),tc=new Map;LV&&LV.forEach(e=>{tc.set(e.version,e)});Pm&&Pm.forEach(e=>{tc.set(e.version,e)});Pm&&Pm.forEach(e=>{tc.set(e.version,e)});function Vde(){return[...tc.keys()].sort(ec.compareVersions)}a(Vde,"getSortedVersions");function PV(e){let t=e[Fde],r=e[kde];return ec.isEmptyOrZeroLength(t)||ec.isEmptyOrZeroLength(r)?(DV.info(`There is an issue with the version data in your instance of HDB. Current version data: ${e}`),DV.error("There was an error when trying to evaluate the version information for your instance. Trying to start the server anyways but it may fail. If you continue to have this problem, please contact support@harperdb.io."),[]):[...tc.keys()].sort(ec.compareVersions).filter(function(n){return ec.compareVersions(n,t)>0&&ec.compareVersions(n,r)<=0})}a(PV,"getVersionsForUpgrade");function $de(e){return PV(e).length>0}a($de,"hasUpgradesRequired");function Yde(e){return ec.isEmptyOrZeroLength(e)?null:tc.has(e)?tc.get(e):null}a(Yde,"getDirectiveByVersion");MV.exports={getSortedVersions:Vde,getDirectiveByVersion:Yde,getVersionsForUpgrade:PV,hasUpgradesRequired:$de}});var Md=R(($Ie,GV)=>{"use strict";var Kde=require("util"),HN=require("chalk"),Wde=require("os"),vV=Cr(),Qde=ur(),yn=D(),BV=iV(),xN=OT(),{UpgradeObject:UV}=cV(),{forceDowngradePrompt:jde}=bm(),zde=Ri(),Mm=k(),Ul=Y(),qN=Bn(),Jde=(Re(),ae($e)),Xde=BN(),Zde=Kde.promisify(qN.setSchemaDataToGlobal),efe=Qde.searchByValue,tfe="info_id",rfe="2.9.9",nfe="3.0.0";async function sfe(e){let t=new BV.HdbInfoInsertObject(1,e,e),r=new xN.InsertObject(yn.OPERATIONS_ENUM.INSERT,yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,yn.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return qN.setSchemaDataToGlobal(),vV.insert(r)}a(sfe,"insertHdbInstallInfo");async function GN(e){let t,r=await HV(),n=new Map([[0,{}]]);for(let c of r)n.set(c.info_id,c);let i=Math.max.apply(null,[...n.keys()])+1;t=new BV.HdbInfoInsertObject(i,e,e);let o=new xN.InsertObject(yn.OPERATIONS_ENUM.INSERT,yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,yn.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return await Zde(),vV.insert(o)}a(GN,"insertHdbUpgradeInfo");async function HV(){let e=new xN.NoSQLSeachObject(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,tfe,yn.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,["*"],"*"),t=[];try{t=Array.from(await efe(e))}catch(r){console.error(r)}return t}a(HV,"getAllHdbInfoRecords");async function ife(){let e=await HV();if(e.length===0)return;let t,r=new Map;for(let s of e)r.set(s.info_id,s);let n=Math.max.apply(null,[...r.keys()]);return t=r.get(n),t}a(ife,"getLatestHdbInfoRecord");async function ofe(){Mm.info("Checking if HDB software has been updated");try{let e=zde.version(),t=await ife(),r;if(Ul.isEmpty(t))r=rfe;else if(r=t.data_version_num,Ul.compareVersions(r.toString(),e.toString())>0){if(!Ul.isCompatibleDataVersion(r.toString(),e.toString()))throw console.log(HN.yellow(`This instance's data was last run on version ${r}`)),console.error(HN.red(`You have installed a version lower than the version that your data was created on or was upgraded to. This may cause issues and is currently not supported.${Wde.EOL}${yn.SUPPORT_HELP_MSG}`)),new Error("Trying to downgrade major HDB versions is not supported.");Ul.isCompatibleDataVersion(r.toString(),e.toString(),!0)||(console.log(HN.yellow(`This instance's data was last run on version ${r}`)),await jde(new UV(r,e))?await GN(e.toString()):(console.log("Cancelled downgrade, closing HarperDB"),process.exit(0)))}if(qN.setSchemaDataToGlobal(),afe(r),e.toString()===r.toString())return;let n=new UV(r,e);if(Xde.hasUpgradesRequired(n))return n;Ul.compareVersions(n.data_version.toString(),n.upgrade_version.toString())<0&&(await GN(n.upgrade_version),Mm.notify(`HarperDB running on upgraded version: ${n.upgrade_version}`))}catch(e){throw Mm.fatal("Error while trying to evaluate the state of hdb data and the installed hdb version"),Mm.fatal(e),e}}a(ofe,"getVersionUpdateInfo");function afe(e){let t=`You are attempting to upgrade from an old instance of HarperDB that is no longer supported. In order to upgrade to this version, you must do a fresh install. If you need support, please contact ${yn.HDB_SUPPORT_ADDRESS}`;if(!("hdb_info"in Jde.databases.system))throw console.log(t),new Error(t);if(!Ul.isEmpty(e)&&e<nfe)throw console.log(t),new Error(t)}a(afe,"checkIfInstallIsSupported");GV.exports={insertHdbInstallInfo:sfe,insertHdbUpgradeInfo:GN,getVersionUpdateInfo:ofe}});var VV=R((KIe,kV)=>{"use strict";var FN=require("joi"),{boolean:cfe,string:xV,number:lfe}=FN.types(),qV=require("fs-extra"),Ud=D(),FV=require("path"),ufe=nt();kV.exports=_fe;function _fe(e){let t=xV.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),r=FN.object({[Ud.INSTALL_PROMPTS.ROOTPATH]:FN.custom(dfe),[Ud.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT]:lfe.min(0).allow("null",null),[Ud.INSTALL_PROMPTS.TC_AGREEMENT]:xV.valid("yes","YES","Yes"),[Ud.INSTALL_PROMPTS.CLUSTERING_NODENAME]:t,[Ud.INSTALL_PROMPTS.CLUSTERING_ENABLED]:cfe});return ufe.validateBySchema(e,r)}a(_fe,"installValidator");function dfe(e,t){if(qV.existsSync(FV.join(e,"system/hdb_user/data.mdb"))||qV.existsSync(FV.join(e,"system/hdb_user.mdb")))return t.message(`'${e}' is already in use. Please enter a different path.`)}a(dfe,"validateRootAvailable")});var $N=R((QIe,$V)=>{"use strict";var{mkdirpSync:ffe}=require("fs-extra"),Zs=require("path"),vl=D(),VN=k(),Efe=Hn(),kN=_i(),hfe=ze();$V.exports=pfe;async function pfe(e){VN.trace("Mounting HarperDB"),Os(e),Os(Zs.join(e,"backup")),Os(Zs.join(e,"trash")),Os(Zs.join(e,"keys")),Os(Zs.join(e,"keys",vl.LICENSE_FILE_NAME)),Os(Zs.join(e,"log")),Os(Zs.join(e,"doc")),Os(Zs.join(e,"database")),Os(Zs.join(e,vl.TRANSACTIONS_DIR_NAME)),Os(Zs.join(e,"clustering","leaf")),Os(Zs.join(e,"components")),await mfe()}a(pfe,"mountHdb");async function mfe(){let e=Uu(),t=Object.keys(kN);for(let r=0;r<t.length;r++){let n=t[r],s=kN[n].hash_attribute;try{hfe.initSystemSchemaPaths(vl.SYSTEM_SCHEMA_NAME,n);let i=new e(vl.SYSTEM_SCHEMA_NAME,n,s);i.attributes=kN[n].attributes;let o=i.attributes.find(({attribute:c})=>c===s);o.isPrimaryKey=!0,await Efe.createTable(n,i)}catch(i){throw VN.error(`issue creating environment for ${vl.SYSTEM_SCHEMA_NAME}.${n}: ${i}`),i}}}a(mfe,"createLMDBTables");function Os(e){ffe(e,{mode:vl.HDB_FILE_PERMISSIONS}),VN.info(`Directory ${e} created`)}a(Os,"makeDirectory")});var vm=R((zIe,r$)=>{"use strict";var KN=require("os"),QV=require("inquirer"),Jn=require("fs-extra"),Sfe=require("properties-reader"),rc=require("chalk"),ri=require("path"),Tfe=require("human-readable-ids").hri,gfe=require("ora"),Rfe=require("yaml"),Ut=k(),$o=X(),vd=Y(),Um=to(),jV=Md(),zV=Ri(),ne=D(),Afe=VV(),Ofe=$N(),WN=Et(),bfe=Lr(),Nfe=vE(),yfe=ON(),Ife=Bn(),wfe=require("util").promisify,Cfe=wfe(Ife.setSchemaDataToGlobal),Dfe=Cm(),Bl=a(e=>e,"PROMPT_ANSWER_TRANSFORMER"),gr=a(e=>rc.magenta.bold(e),"HDB_PROMPT_MSG"),Lfe="https://harperdb.io/legal/end-user-license-agreement",Yo=KN.EOL,ko="",Pfe="yes",YV="Starting HarperDB install...",KV="HarperDB installation was successful.",WV="Terms & Conditions acceptance is required to proceed with installation. Exiting install...",Mfe="An out of date version of HarperDB is already installed.",YN="It appears that HarperDB is already installed. Exiting install...",Ufe="Aborting install",vfe=new RegExp(/^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/),Bfe=new RegExp(/^[^\s.,*>]+$/),Hfe=KN.homedir(),Gfe=ri.join(Hfe,ne.HDB_ROOT_DIR_NAME),xfe=9925,qfe="HDB_ADMIN",Ffe="CLUSTER_USER",zr={DESTINATION:"Please enter a destination for HarperDB:",HDB_PORT:"Please enter a server listening port for HarperDB:",HDB_USERNAME:"Please enter a username for the HDB_ADMIN:",HDB_PASS:"Please enter a password for the HDB_ADMIN:",NODE_NAME:"Please enter a unique name for this node:",CLUSTER_USERNAME:"Please enter a username for the CLUSTER_USER:",CLUSTER_PASS:"Please enter a password for the CLUSTER_USER:"},Ko=Um([ne.INSTALL_PROMPTS.HDB_CONFIG]),ti,JV=!1,XV=!1;r$.exports={install:ZV,updateConfigEnv:Xfe,setIgnoreExisting:Zfe};ZV.createSuperUser=t$;async function ZV(){console.log(gr(Yo+YV+Yo)),Ut.notify(YV);let e;Ko[ne.INSTALL_PROMPTS.HDB_CONFIG]&&(e=kfe());let t=$fe();Object.assign(t,e);let r=Afe(t);if(r)throw r.message;await Yfe(),await Kfe(t);let n=await Vfe(t);n[ne.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_SECUREPORT]&&(n[ne.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT]=null),ti=n[ne.INSTALL_PROMPTS.ROOTPATH],Ko[ne.INSTALL_PROMPTS.HDB_CONFIG]&&ri.dirname(Ko[ne.INSTALL_PROMPTS.HDB_CONFIG])===ti&&(JV=!0),!Ko[ne.INSTALL_PROMPTS.HDB_CONFIG]&&await Jn.pathExists(ri.join(ti,ne.HDB_CONFIG_FILE))&&(console.error(YN),process.exit());let s=gfe({prefixText:gr("Installing"),color:"magenta",spinner:"simpleDots"});if(s.start(),vd.isEmpty(ti))throw new Error("Installer should have the HDB root param at the stage it is in but it does not.");$o.setHdbBasePath(ti),await Ofe(ti),await Wfe(),await Qfe(n),Ut.initLogSettings(!0),await t$(n),await zfe(n),await Dfe.generateKeys(),await Jfe(),yfe(),s.stop(),console.log(gr(Yo+KV+Yo)),Ut.notify(KV)}a(ZV,"install");function kfe(){let e=Rfe.parseDocument(Jn.readFileSync(Ko[ne.INSTALL_PROMPTS.HDB_CONFIG],"utf8"),{simpleKeys:!0}),t=WN.flattenConfig(e.toJSON());return t[ne.CONFIG_PARAMS.ROOTPATH.toLowerCase()]&&(t.ROOTPATH=t[ne.CONFIG_PARAMS.ROOTPATH.toLowerCase()]),t}a(kfe,"getConfigFromFile");async function Vfe(e){Ut.trace("Getting install prompts and params.");let t,r=[{type:"input",transformer:Bl,when:Vo(e[ne.INSTALL_PROMPTS.ROOTPATH],zr.DESTINATION),name:ne.INSTALL_PROMPTS.ROOTPATH,prefix:ko,default:Gfe,validate:async s=>ei(s)?ei(s):await Jn.pathExists(ri.join(s,"system","hdb_user.mdb"))?`'${s}' is already in use. Please enter a different path.`:!0,message:gr(zr.DESTINATION)},{type:"input",transformer:Bl,when:Vo(e[ne.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT]??e[ne.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_SECUREPORT],zr.HDB_PORT),name:ne.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT,prefix:ko,default:xfe,validate:s=>vfe.test(s)?!0:"Invalid port.",message:gr(zr.HDB_PORT)},{type:"input",transformer:Bl,when:Vo(e[ne.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],zr.HDB_USERNAME),name:ne.INSTALL_PROMPTS.HDB_ADMIN_USERNAME,prefix:ko,default:qfe,validate:s=>ei(s)?ei(s):(t=s,!0),message:gr(zr.HDB_USERNAME)},{type:"password",when:Vo(e[ne.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD],zr.HDB_PASS),name:ne.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD,prefix:ko,validate:s=>ei(s)?ei(s):!0,message:gr(zr.HDB_PASS)}];if(vd.autoCastBoolean(e[ne.INSTALL_PROMPTS.CLUSTERING_ENABLED])===!0){let s=[{type:"input",transformer:Bl,when:Vo(e[ne.INSTALL_PROMPTS.CLUSTERING_NODENAME],zr.NODE_NAME),name:ne.INSTALL_PROMPTS.CLUSTERING_NODENAME,prefix:ko,default:Tfe.random(),validate:i=>Bfe.test(i)?!0:"Invalid node name, must not contain ., * or >",message:gr(zr.NODE_NAME)},{type:"input",transformer:Bl,when:Vo(e[ne.INSTALL_PROMPTS.CLUSTERING_USER],zr.CLUSTER_USERNAME),name:ne.INSTALL_PROMPTS.CLUSTERING_USER,prefix:ko,default:Ffe,validate:i=>ei(i)?ei(i):i.toLowerCase()===t.toLowerCase()?"Username is already in use.":!0,message:gr(zr.CLUSTER_USERNAME)},{type:"password",when:Vo(e[ne.INSTALL_PROMPTS.CLUSTERING_PASSWORD],zr.CLUSTER_PASS),name:ne.INSTALL_PROMPTS.CLUSTERING_PASSWORD,prefix:ko,validate:i=>ei(i)?ei(i):!0,message:gr(zr.CLUSTER_PASS)}];r.push(...s)}let n=await QV.prompt(r);if(Object.keys(n).length===0)return e;for(let s in n)e[s]===void 0&&(e[s]=n[s]);return e}a(Vfe,"installPrompts");function Vo(e,t){return e!==void 0?(t.includes("password")?(console.log(`${gr(t)} ${rc.gray("[hidden]")}`),Ut.trace(`${gr(t)} [hidden]`)):(console.log(`${gr(t)} ${e}`),Ut.trace(`${gr(t)} ${e}`)),!1):!0}a(Vo,"displayCmdEnvVar");function ei(e){let t=e.replace(/ /g,"");if(t===""||t==="''"||t==='""')return"Value cannot be empty."}a(ei,"checkForEmptyValue");function $fe(){let e=Object.keys(ne.INSTALL_PROMPTS),t=Um(e),r=Um(Object.keys(ne.CONFIG_PARAM_MAP),!0),n={};for(let s of e){let i=ne.CONFIG_PARAM_MAP[s.toLowerCase()];t[s]?i===void 0?n[s]=t[s]:n[i.toUpperCase()]=t[s]:i!==void 0&&r[i.toLowerCase()]&&(n[s]=r[i.toLowerCase()])}return n}a($fe,"checkForPromptOverride");async function Yfe(){Ut.trace("Checking for existing install.");let e=vd.getPropsFilePath(),t=await Jn.pathExists(e),r;if(t){Ut.trace(`Install found an existing boot prop file at:${e}`);let n=Sfe(e),s=WN.getConfigValue(ne.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)||n.get(ne.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY);r=await Jn.pathExists(s)}if(!t&&vd.noBootFile()&&(r=!0),r&&!XV){if(Ut.trace(`Install found existing HDB config at:${e}`),await jV.getVersionUpdateInfo()){let s=`Please use \`harperdb upgrade\` to update to ${zV.version()}. Exiting install...`;console.log(Yo+rc.magenta.bold(Mfe)),console.log(rc.magenta.bold(s)),Ut.error(s)}else console.log(Yo+rc.magenta.bold(YN)),Ut.error(YN);process.exit(0)}}a(Yfe,"checkForExistingInstall");async function Kfe(e){Ut.info("Asking for terms agreement.");let t=`Terms & Conditions can be found at ${Lfe}${Yo}and can be viewed by typing or copying and pasting the URL into your web browser.${Yo}I Agree to the HarperDB Terms and Conditions. (yes/no)`,r={prefix:ko,transformer:Bl,when:Vo(e[ne.INSTALL_PROMPTS.TC_AGREEMENT],t),name:ne.INSTALL_PROMPTS.TC_AGREEMENT,message:gr(t),validate:s=>s.toLowerCase()==="yes"||s.toLowerCase()==="no"?!0:rc.yellow("Please enter 'yes' or 'no'")},n=await QV.prompt([r]);n[ne.INSTALL_PROMPTS.TC_AGREEMENT]&&n[ne.INSTALL_PROMPTS.TC_AGREEMENT].toLowerCase()!==Pfe&&(console.log(rc.yellow(WV)),Ut.error(WV),process.exit(0))}a(Kfe,"termsAgreement");async function Wfe(){let e=ri.join(ti,ne.HDB_CONFIG_FILE),t;try{t=KN.userInfo().username}catch{t=process.env.USERNAME||process.env.USER||process.env.LOGNAME||process.env.LNAME||process.env.SUDO_USER}if(t){let r=`settings_path = ${e}
106
- install_user = ${t}`,n=vd.getHomeDir(),s=ri.join(n,ne.HDB_HOME_DIR_NAME),i=ri.join(s,ne.LICENSE_KEY_DIR_NAME);try{Jn.mkdirpSync(s,{mode:ne.HDB_FILE_PERMISSIONS}),Jn.mkdirpSync(i,{mode:ne.HDB_FILE_PERMISSIONS})}catch{console.error(`Could not make settings directory ${ne.HDB_HOME_DIR_NAME} in home directory. Please check your permissions and try again.`)}let o=ri.join(s,ne.BOOT_PROPS_FILE_NAME);try{await Jn.writeFile(o,r)}catch(c){throw Ut.error(`There was an error creating the boot file at path: ${o}`),c}$o.setProperty(ne.HDB_SETTINGS_NAMES.INSTALL_USER,`${t}`),$o.setProperty(ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,e),$o.setProperty($o.BOOT_PROPS_FILE_PATH,o)}}a(Wfe,"createBootPropertiesFile");async function Qfe(e){Ut.trace("Creating HarperDB config file");let t=Um(Object.keys(ne.CONFIG_PARAM_MAP),!0);Object.assign(t,e);try{Ko[ne.INSTALL_PROMPTS.HDB_CONFIG]||WN.createConfigFile(t),$o.initSync()}catch(r){jfe(r)}}a(Qfe,"createConfigFile");function jfe(e){Ut.error(`Error creating HarperDB config file. Rolling back install - ${e}`),console.error(e),console.error(Ufe);let t=ri.resolve($o.get($o.BOOT_PROPS_FILE_PATH),"../");t&&Jn.removeSync(t),ti&&(JV?Jn.readdirSync(ti,{withFileTypes:!0}).forEach(n=>{let s=ri.join(n.path,n.name);s!==Ko[ne.INSTALL_PROMPTS.HDB_CONFIG]&&Jn.removeSync(s)}):Jn.removeSync(ti)),process.exit(1)}a(jfe,"rollbackInstall");async function e$(e,t){Ut.trace("Creating admin user"),await Cfe();let r;try{r=await Nfe.addRole(e)}catch(n){if(n.message.includes("already exists"))t=void 0;else throw n.message+="Error creating role",n}if(t)try{t.role=r.role,await bfe.addUser(t)}catch(n){throw n.message=`Error creating user - ${n}`,n}}a(e$,"createAdminUser");async function t$(e){Ut.trace("Creating Super user.");let t={role:"super_user",permission:{super_user:!0}},r={username:e[ne.INSTALL_PROMPTS.HDB_ADMIN_USERNAME].toString(),password:e[ne.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD].toString(),active:!0};await e$(t,r),delete e[ne.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],delete e[ne.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD]}a(t$,"createSuperUser");async function zfe(e){Ut.trace("Creating Cluster user.");let t;e[ne.INSTALL_PROMPTS.CLUSTERING_USER]&&e[ne.INSTALL_PROMPTS.CLUSTERING_PASSWORD]&&(t={username:e[ne.INSTALL_PROMPTS.CLUSTERING_USER].toString(),password:e[ne.INSTALL_PROMPTS.CLUSTERING_PASSWORD].toString(),active:!0}),await e$({role:"cluster_user",permission:{cluster_user:!0}},t),delete e[ne.INSTALL_PROMPTS.CLUSTERING_USER],delete e[ne.INSTALL_PROMPTS.CLUSTERING_PASSWORD]}a(zfe,"createClusterUser");async function Jfe(){let e=zV.version();if(e)await jV.insertHdbInstallInfo(e);else throw new Error("The version is missing/removed from HarperDB package.json")}a(Jfe,"insertHdbVersionInfo");function Xfe(e){Ko[ne.INSTALL_PROMPTS.HDB_CONFIG]=e}a(Xfe,"updateConfigEnv");function Zfe(e){XV=e}a(Zfe,"setIgnoreExisting")});var i$=R((XIe,s$)=>{"use strict";var QN=Y(),In=k(),n$=BN();s$.exports={processDirectives:eEe};async function eEe(e){console.log("Starting upgrade process...");let t=n$.getVersionsForUpgrade(e),r=nEe(t),n=[],s=r.length;for(let i=0;i<s;i++){let o=r[i],c=`Running upgrade for version ${o.version}`;In.notify(c),console.log(c);let l=[],_=[];try{l=tEe(o.sync_functions)}catch(u){throw In.error(`Error while running an upgrade script for ${o.version}`),u}try{_=await rEe(o.async_functions)}catch(u){throw In.error(`Error while running an upgrade script for ${o.version}`),u}n.push(...l,..._)}return n}a(eEe,"processDirectives");function tEe(e){if(QN.isEmptyOrZeroLength(e))return In.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return In.info("Passed parameter is not an array"),[];let t=[];for(let r of e){if(In.info(`Running function ${r.name}`),!(r instanceof Function)){In.info("Variable being processed is not a function");continue}let n=r();In.info(n),t.push(n)}return t}a(tEe,"runSyncFunctions");async function rEe(e){if(QN.isEmptyOrZeroLength(e))return In.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return In.info("Passed parameter is not an array"),[];let t=[],r=e.length;for(let n=0;n<r;n++){let s=e[n];if(In.info(`Running function ${s.name}`),!(s instanceof Function)){In.info("Variable being processed is not a function");continue}let i=await s();In.info(i),t.push(i)}return t}a(rEe,"runAsyncFunctions");function nEe(e){if(QN.isEmptyOrZeroLength(e))return[];let t=[];for(let r of e){let n=n$.getDirectiveByVersion(r);n&&t.push(n)}return t}a(nEe,"getUpgradeDirectivesToInstall")});var JN=R((ewe,_$)=>{"use strict";var Bm=X();Bm.initSync();var l$=require("chalk"),o$=require("fs-extra"),$i=k(),Vi=D(),a$=Ri(),sEe=i$(),jN=Y(),u$=Md(),iEe=bm(),c$=fS(),oEe=Bn(),aEe=require("util").promisify,cEe=aEe(oEe.setSchemaDataToGlobal),zN,{UPGRADE_VERSION:Hm}=Vi.UPGRADE_JSON_FIELD_NAMES_ENUM;_$.exports={upgrade:lEe};async function lEe(e){await cEe(),zN===void 0&&(zN=Yc()),o$.existsSync(Bm.get(Bm.BOOT_PROPS_FILE_PATH))||(Bd("The hdb_boot_properties file was not found. Please install HDB.",Vi.LOG_LEVELS.ERROR),process.exit(1)),o$.existsSync(Bm.get(Vi.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))||(Bd("The hdb settings file was not found. Please make sure HDB is installed.",Vi.LOG_LEVELS.ERROR),process.exit(1));let t=e;t||(t=await u$.getVersionUpdateInfo(),t||(console.log("HarperDB version is current"),process.exit(0))),Bd(`This version of HarperDB is ${a$.version()}`,Vi.LOG_LEVELS.INFO);let r=t[Hm]?t[Hm]:a$.version();r||(console.log(`Current Version field missing from the package.json file. Cannot continue with upgrade. If you need support, please contact ${Vi.HDB_SUPPORT_ADDRESS}`),$i.notify("Missing new version field from upgrade info object"),process.exit(1)),await uEe();let n,s=0;try{n=await iEe.forceUpdatePrompt(t)}catch(i){$i.error("There was an error when prompting user about upgrade."),$i.error(i),n=!1,s=1}n||(console.log("Cancelled upgrade, closing HarperDB"),process.exit(s)),$i.info(`Starting upgrade to version ${r}`),await _Ee(t),Bd(`HarperDB was successfully upgraded to version ${t[Hm]}`,Vi.LOG_LEVELS.INFO)}a(lEe,"upgrade");async function uEe(){let e=!1,t=await c$.findPs(Vi.HDB_PROC_NAME);if(jN.isEmptyOrZeroLength(t)||(e=!0),!e){let r=await c$.findPs("hdb_express");jN.isEmptyOrZeroLength(r)||(e=!0)}if(!e){let r=await zN.list();jN.isEmptyOrZeroLength(r)||(e=!0)}if(e){let r="HarperDB is running, please stop all HarperDB services with 'harperdb stop' and run the upgrade command again.";console.log(l$.red(r)),$i.error(r),process.exit(1)}}a(uEe,"checkIfRunning");async function _Ee(e){try{await sEe.processDirectives(e)}catch(t){throw Bd("There was an error during the data upgrade. Please check the logs.",Vi.LOG_LEVELS.ERROR),t}try{await u$.insertHdbUpgradeInfo(e[Hm])}catch(t){$i.error("Error updating the 'hdb_info' system table."),$i.error(t)}}a(_Ee,"runUpgrade");function Bd(e,t=void 0){t||(t=$i.info),$i[t](e),console.log(l$.magenta(e))}a(Bd,"printToLogAndConsole")});var p$=R((rwe,h$)=>{"use strict";var{promises:ZN,createReadStream:dEe,createWriteStream:fEe}=require("fs"),{createGzip:EEe}=require("zlib"),{promisify:hEe}=require("util"),{pipeline:pEe}=require("stream"),mEe=hEe(pEe),SEe=require("path"),sc=X();sc.initSync();var nc=k(),{CONFIG_PARAMS:Hd,ITC_EVENT_TYPES:TEe}=D(),{onMessageFromWorkers:gEe}=rt(),REe=6e4,AEe="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",OEe="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",XN,f$;h$.exports=E$;gEe(e=>{e.type===TEe.RESTART&&(sc.initSync(!0),clearInterval(f$),sc.get(Hd.LOGGING_ROTATION_ENABLED)&&E$())});async function E$(){try{let e=nc.getLogFilePath(),t=sc.get(Hd.LOGGING_ROTATION_MAXSIZE),r=sc.get(Hd.LOGGING_ROTATION_INTERVAL);if(!t&&!r){nc.error(AEe);return}let n=sc.get(Hd.LOGGING_ROTATION_PATH);if(!n){nc.error(OEe);return}let s;if(t){let o=t.slice(-1),c=t.slice(0,-1);o==="G"?s=c*1e9:o==="M"?s=c*1e6:s=c*1e3}let i;if(r){let o=r.slice(-1),c=r.slice(0,-1);o==="D"?i=c*1440:o==="H"?i=c*60:i=c}XN=Date.now()/6e4,nc.trace("Log rotate enabled, maxSize:",t,"interval:",r),f$=setInterval(async()=>{if(s){let o;o=await ZN.stat(e),o.size>=s&&await d$(e,n)}i&&Date.now()/6e4-XN>=i&&(await d$(e,n),XN=Date.now()/6e4)},REe).unref()}catch(e){nc.error(e)}}a(E$,"logRotator");async function d$(e,t){let r=sc.get(Hd.LOGGING_ROTATION_COMPRESS),n=SEe.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.${r?"log.gz":"log"}`);r?(await mEe(dEe(e),EEe(),fEe(n)),await ZN.unlink(e)):await ZN.rename(e,n),nc.closeLogFile(),nc.notify(`hdb.log rotated, old log moved to ${n}`)}a(d$,"moveLogFile")});var ic=R((dwe,b$)=>{"use strict";var Jr=X();Jr.initSync();var swe=bo(),bt=D(),si=k(),Yi=require("fs-extra"),Wo=require("path"),bEe=require("systeminformation"),NEe=ON(),{install:yEe}=vm(),ey=require("chalk"),IEe=ma(),Ki=Y(),S$=Et(),T$=to(),m$=dh(),wEe=JN(),CEe=p$(),{compactOnStart:DEe}=(gh(),ae(Th)),LEe=require("minimist"),{PACKAGE_ROOT:PEe}=D(),{startHTTPThreads:MEe,startSocketServer:iwe,mostIdleRouting:owe,remoteAffinityRouting:awe}=(Nb(),ae(jq)),UEe=Md(),{isMainThread:vEe}=require("worker_threads"),cwe=_i(),lwe=Ei(),uwe=Sg(),_we=Uu(),Gm=D(),ni,Hl,g$=!1,BEe="Upgrade complete. Starting HarperDB.",HEe="Got an error while trying to upgrade your HarperDB instance. Exiting HarperDB.",GEe="HarperDB not found, starting install process.",xEe="There was an error during install, check install_log.log for more details. Exiting.",qEe="HarperDB successfully started.";function FEe(){if(!g$){let e=a(()=>{Yi.removeSync(Wo.join(Jr.get(bt.CONFIG_PARAMS.ROOTPATH),bt.HDB_PID_FILE)),process.exit(0)},"remove_hdb_pid");process.on("exit",()=>{e()}),process.on("SIGINT",()=>{e()}),process.on("SIGQUIT",()=>{e()}),process.on("SIGTERM",()=>{e()})}}a(FEe,"addExitListeners");async function R$(e=!1,t=!1){if(console.log(ey.magenta("Starting HarperDB...")),await O$()===!1){console.log(GEe);try{await yEe()}catch(o){console.error(xEe,o),si.error(o),process.exit(1)}}if(!e){let o=T$(Object.keys(bt.CONFIG_PARAM_MAP),!0);!Ki.isEmpty(o)&&!Ki.isEmptyOrZeroLength(Object.keys(o))&&S$.updateConfigValue(void 0,void 0,o,!0,!0)}let r,n=Hl?.service==="clustering";Hl?.service&&!n&&(console.error("Unrecognized service argument"),process.exit(1));try{let o=Number.parseInt(await Yi.readFile(Wo.join(Jr.get(bt.CONFIG_PARAMS.ROOTPATH),bt.HDB_PID_FILE),"utf8")),c=await bEe.processes();for(let l of c.list)if(l.pid===o){n?r=!0:console.log("HarperDB appears to be already running.");break}}catch{}ni===void 0&&(ni=Yc()),n&&(r||(console.error("HarperDB must be running to start clustering."),process.exit()),Jr.get(bt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY)||(console.error("Clustering must be setup and enabled in harperdb-config."),process.exit()),console.log("Starting clustering."),await m$.generateNatsConfig(),await ni.startClusteringProcesses(!0),process.exit()),FEe(),await Yi.writeFile(Wo.join(Jr.get(Gm.CONFIG_PARAMS.ROOTPATH),Gm.HDB_PID_FILE),`${process.pid}`),si.info("HarperDB PID",process.pid);let s;try{let o=await UEe.getVersionUpdateInfo();o!==void 0&&(s=o[bt.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION],await wEe.upgrade(o),console.log(BEe))}catch(o){s?(console.error(`Got an error while trying to upgrade your HarperDB instance to version ${s}. Exiting HarperDB.`,o),si.error(o)):(console.error(HEe,o),si.error(o)),process.exit(1)}NEe(),$Ee(),Ki.autoCastBoolean(Jr.get(bt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&vEe&&await m$.generateNatsConfig(t)}a(R$,"initialize");async function kEe(e=!1){try{Hl=LEe(process.argv),Hl.ROOTPATH&&S$.updateConfigObject("settings_path",Wo.join(Hl.ROOTPATH,bt.HDB_CONFIG_FILE)),await R$(e,!0),Jr.get(bt.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await DEe();let t=process.env.IS_SCRIPTED_SERVICE&&!Hl.service;Ki.autoCastBoolean(Jr.get(bt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&(t||await ni.startClusteringProcesses(),await ni.startClusteringThreads()),await MEe(process.env.DEV_MODE?1:Jr.get(Gm.CONFIG_PARAMS.THREADS_COUNT)??Jr.get(Gm.CONFIG_PARAMS.THREADS)),Jr.get(bt.CONFIG_PARAMS.LOGGING_ROTATION_ENABLED)&&await CEe(),t||A$()}catch(t){console.error(t),si.error(t),process.exit(1)}}a(kEe,"main");function A$(){si.suppressLogging(()=>{console.log(ey.magenta(""+Yi.readFileSync(Wo.join(PEe,"utility/install/ascii_logo.txt")))),console.log(ey.magenta(`|------------- HarperDB ${IEe.version} successfully started ------------|`))}),si.notify(qEe)}a(A$,"started");async function VEe(e=!0){g$=!e;try{ni===void 0&&(ni=Yc()),ni.enterPM2Mode(),await R$(),Ki.autoCastBoolean(Jr.get(bt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&await ni.startClusteringProcesses(),await ni.startService(bt.PROCESS_DESCRIPTORS.HDB),A$(),e&&process.exit(0)}catch(t){console.error(t),si.error(t),process.exit(1)}}a(VEe,"launch");function $Ee(){let e=Wo.join(Jr.get(bt.CONFIG_PARAMS.ROOTPATH),bt.LICENSE_KEY_DIR_NAME,bt.LICENSE_FILE_NAME),t=Wo.join(e,bt.LICENSE_FILE_NAME),r=Wo.join(e,bt.REG_KEY_FILE_NAME);try{let{HARPERDB_FINGERPRINT:n,HARPERDB_LICENSE:s}=T$(["HARPERDB_FINGERPRINT","HARPERDB_LICENSE"]);if(Ki.isEmpty(n)||Ki.isEmpty(s))return;Yi.mkdirpSync(e),Yi.writeFileSync(r,n),Yi.writeFileSync(t,s)}catch(n){let s=`Failed to write license & fingerprint due to: ${n.message}`;console.error(s),si.error(s)}}a($Ee,"writeLicenseFromVars");b$.exports={launch:VEe,main:kEe,isHdbInstalled:O$};async function O$(){try{await Yi.stat(Ki.getPropsFilePath()),await Yi.stat(Jr.get(bt.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}catch(e){if(Ki.noBootFile())return!0;if(e.code==="ENOENT")return!1;throw si.error(`Error checking for HDB install - ${e}`),e}return!0}a(O$,"isHdbInstalled")});var iy=R((Ewe,F$)=>{"use strict";var N$=require("os"),Fm=require("https"),y$=require("http"),$t=require("fs-extra"),I$=require("yaml"),YEe=require("human-readable-ids").hri,{pipeline:w$}=require("stream/promises"),{createWriteStream:km,ensureDir:Vm}=require("fs-extra"),{join:Cn}=require("path"),v$=require("lodash"),KEe=require("minimist"),kd=require("path"),WEe=require("properties-reader"),bs=X(),QEe=gi(),B$=k(),ty=Et(),{restart:jEe}=bo(),$m=Y(),zEe=to(),C$=gt(),JEe=Bn(),{main:H$,launch:XEe}=ic(),{install:ZEe,updateConfigEnv:ehe,setIgnoreExisting:ny}=vm(),G$=$N(),Xr=D(),the=Ri(),rhe=Md(),{SYSTEM_TABLE_NAMES:D$,SYSTEM_SCHEMA_NAME:nhe,CONFIG_PARAMS:Gd,OPERATIONS_ENUM:Dn}=Xr,she=1e4,ihe="clone-node-config.yaml",sy=[D$.ROLE_TABLE_NAME,D$.USER_TABLE_NAME],ohe={clustering_nodename:!0,clustering_leafserver_streams_path:!0,clustering_tls_certificate:!0,clustering_tls_privatekey:!0,clustering_tls_certificateauthority:!0,logging_file:!0,logging_root:!0,logging_rotation_path:!0,operationsapi_network_domainsocket:!0,operationsapi_tls_certificate:!0,operationsapi_tls_privatekey:!0,operationsapi_tls_certificateauthority:!0,rootpath:!0,storage_path:!0,storage_audit_path:!0,databases:!0,mqtt_network_mtls_certificateauthority:!0,componentsroot:!0,tls_certificate:!0,tls_privatekey:!0,tls_certificateauthority:!0},lr={HDB_LEADER_USERNAME:"HDB_LEADER_USERNAME",HDB_LEADER_PASSWORD:"HDB_LEADER_PASSWORD",HDB_LEADER_URL:"HDB_LEADER_URL",HDB_LEADER_CLUSTERING_HOST:"HDB_LEADER_CLUSTERING_HOST",HDB_LEADER_CLUSTERING_PORT:"HDB_LEADER_CLUSTERING_PORT",HDB_CLONE_CLUSTERING_HOST:"HDB_CLONE_CLUSTERING_HOST",HDB_FULLY_CONNECTED:"HDB_FULLY_CONNECTED",HDB_CLONE_OVERTOP:"HDB_CLONE_OVERTOP",CLUSTERING_NODENAME:"CLUSTERING_NODENAME"},ji=KEe(process.argv),xd=ji[lr.HDB_LEADER_USERNAME]??process.env[lr.HDB_LEADER_USERNAME],qd=ji[lr.HDB_LEADER_PASSWORD]??process.env[lr.HDB_LEADER_PASSWORD],Fd=ji[lr.HDB_LEADER_URL]??process.env[lr.HDB_LEADER_URL],qm=ji[lr.HDB_LEADER_CLUSTERING_HOST]??process.env[lr.HDB_LEADER_CLUSTERING_HOST],L$=ji[lr.HDB_CLONE_CLUSTERING_HOST]??process.env[lr.HDB_CLONE_CLUSTERING_HOST],ahe=(ji[lr.HDB_FULLY_CONNECTED]??process.env[lr.HDB_FULLY_CONNECTED])==="true",x$=(ji[lr.HDB_CLONE_OVERTOP]??process.env[lr.HDB_CLONE_OVERTOP])==="true",P$=ji[lr.CLUSTERING_NODENAME]??process.env[lr.CLUSTERING_NODENAME],che=ji[Gd.CLONED.toUpperCase()]??process.env[Gd.CLONED.toUpperCase()],ry,Zr,Qi={},M$,Wi,ii={},ut,Gl,vt,wn,Ns,xl=!1,Km=!1;F$.exports=a(async function(t=!1){if(console.info(`Starting clone node form leader node: ${Fd}`),delete process.env.HDB_LEADER_URL,vt=$m.getEnvCliRootPath(),!vt)try{let s=Cn(N$.homedir(),Xr.HDB_HOME_DIR_NAME,Xr.BOOT_PROPS_FILE_NAME);if(await $t.pathExists(s)){let i=WEe(s);vt=kd.parse(i.get(Xr.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)).dir}}catch{throw new Error("There was an error setting the clone default root path. Please set ROOTPATH using an environment or CLI variable.")}vt?await $t.pathExists(vt)?console.log(`Existing HarperDB install found at ${vt}. Clone node will only clone items that do not already exist on clone.`):(console.log(`No HarperDB install found at ${vt} starting fresh clone`),xl=!0):(console.log("No HarperDB install found, starting fresh clone"),xl=!0),vt||(vt=Cn(N$.homedir(),Xr.HDB_ROOT_DIR_NAME),console.log("Using default root path",vt));let r;try{r=Cn(vt,ihe),Zr=I$.parseDocument(await $t.readFile(r,"utf8"),{simpleKeys:!0}).toJSON(),console.log("Clone config file found")}catch{}let n=Cn(vt,Xr.HDB_CONFIG_FILE);if(await $t.pathExists(n))try{M$=I$.parseDocument(await $t.readFile(n,"utf8"),{simpleKeys:!0}).toJSON(),Qi=ty.flattenConfig(M$)}catch(s){console.error("Error reading existing harperdb-config.yaml on clone",s)}if(Qi?.cloned&&che!=="false")return console.log("Instance marked as cloned, clone will not run"),bs.setCloneVar(!1),bs.initSync(),H$();P$?Gl=P$:Qi[Xr.CONFIG_PARAMS.CLUSTERING_NODENAME.toLowerCase()]?Gl=Qi[Xr.CONFIG_PARAMS.CLUSTERING_NODENAME.toLowerCase()]:Gl=Zr?.clustering?.nodeName??YEe.random(),await lhe(),bs.setCloneVar(!1),bs.setHdbBasePath(vt),$t.ensureDir(bs.get(Xr.CONFIG_PARAMS.LOGGING_ROOT)),B$.initLogSettings(),await uhe(),Km||await _he(),await Ehe(t),ry&&qm&&await hhe(),console.info(`
107
- Successfully cloned node: `+Fd),t&&process.exit()},"cloneNode");async function lhe(){console.info("Cloning configuration"),Wi=await Ym({operation:Dn.GET_CONFIGURATION}),Wi=await JSON.parse(Wi.body),ry=Wi?.clustering?.enabled,ii=ty.flattenConfig(Wi);let e=Wi?.clustering?.hubServer?.cluster?.network?.port,t=Zr?.componentConfig?.exclude,r={cloned:!0,clustering_nodename:Gl,rootpath:vt};for(let s in ii)if(!(ii[s]!==null&&typeof ii[s]=="object"&&!(ii[s]instanceof Array)||ohe[s])){if(s.includes("_package")||s.includes("_port")){if(ii[s]?.includes?.("hdb/components"))continue;if(t){let i=!1;for(let o of t)if(s.includes(o.name)){i=!0;break}if(i)continue}}Qi[s]||(s==="clustering_hubserver_cluster_network_routes"&&qm&&e&&(Array.isArray(ii[s])||(ii[s]=[]),ii[s].push({host:qm,port:e})),r[s]=ii[s])}for(let s in Qi)s!=="databases"&&typeof Qi[s]=="object"&&!(Qi[s]instanceof Array)||(r[s]=Qi[s]);let n=zEe(Object.keys(Xr.CONFIG_PARAM_MAP),!0);if(Object.assign(r,n),ty.createConfigFile(r,!0),bs.initSync(!0),ry&&qm&&L$){let s={host:L$,port:bs.get(Gd.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT)};console.log("Setting clustering route on leader:",s),await Ym({operation:"cluster_set_routes",server:"hub",routes:[s]})}}a(lhe,"cloneConfig");async function uhe(){process.env.HDB_FETCH==="true"?(await fhe(),process.env.NODE_TLS_REJECT_UNAUTHORIZED&&delete process.env.NODE_TLS_REJECT_UNAUTHORIZED):await dhe()}a(uhe,"cloneDatabases");async function _he(){if(console.info("Clone node installing HarperDB."),process.env.TC_AGREEMENT="yes",process.env.ROOTPATH=vt,!xd)throw new Error("HDB_LEADER_USERNAME is undefined.");if(process.env.HDB_ADMIN_USERNAME=xd,!qd)throw new Error("HDB_LEADER_PASSWORD is undefined.");process.env.HDB_ADMIN_PASSWORD=qd,process.env.OPERATIONSAPI_NETWORK_PORT=bs.get(Gd.OPERATIONSAPI_NETWORK_PORT),ehe(kd.join(vt,Xr.HDB_CONFIG_FILE)),ny(!0),await ZEe()}a(_he,"installHDB");function oi(e){return bs.get(Xr.CONFIG_PARAMS.DATABASES)?.[e]?.path||bs.get(Gd.STORAGE_PATH)||kd.join(vt,Xr.DATABASES_DIR_NAME)}a(oi,"getDBPath");async function dhe(){let e=oi("system"),t=Cn(e,"system.mdb");if(xl||!await $t.exists(t)||x$){console.info("Cloning system database"),await Vm(e);let r=km(t,{overwrite:!0}),n={operation:Dn.GET_BACKUP,database:"system",tables:sy},s=await U$(n,r);await $t.utimes(t,Date.now(),new Date(s.date)),xl||(await G$(vt),await q$(),ny(!0))}else Km=!0,console.log("Not cloning system database due to it already existing on clone");ut=await Ym({operation:Dn.DESCRIBE_ALL}),ut=await JSON.parse(ut.body),wn=Zr?.databaseConfig?.excludeDatabases,wn=wn?wn.reduce((r,n)=>({...r,[n.database]:!0}),{}):{};for(let r in ut)await $t.exists(kd.join(oi(r),r+".mdb"))&&(console.log(`Not cloning database ${r} due to it already existing on clone`),wn[r]=!0);Ns=Zr?.databaseConfig?.excludeTables,Ns=Ns?Ns.reduce((r,n)=>({...r,[n.database==null?null:n.database+n.table]:!0}),{}):{};for(let r in ut){if(wn[r]){ut[r]="excluded";continue}if(v$.isEmpty(ut[r]))continue;let n=[],s=!1;for(let u in ut[r])Ns[r+u]?(s=!0,ut[r][u]="excluded"):n.push(u);if(n.length===0)return;let i;s?(console.info(`Cloning database: ${r} tables: ${n}`),i={operation:Dn.GET_BACKUP,database:r,tables:n}):(console.info(`Cloning database: ${r}`),i={operation:Dn.GET_BACKUP,database:r});let o=oi(r);await Vm(o);let c=Cn(o,r+".mdb"),l=km(c,{overwrite:!0}),_=await U$(i,l);await $t.utimes(c,Date.now(),new Date(_.date))}}a(dhe,"cloneTablesHttp");async function fhe(){let e=oi("system"),t=Cn(e,"system.mdb");if(xl||!await $t.exists(t)||x$){console.info("Cloning system database using fetch");let r={operation:Dn.GET_BACKUP,database:"system",tables:sy},n=await xm(r,!0),s=oi("system");await Vm(s);let i=Cn(s,"system.mdb");await w$(n.body,km(i,{overwrite:!0})),await $t.utimes(i,Date.now(),new Date(n.headers.get("date"))),xl||(await G$(vt),await q$(),ny(!0))}else Km=!0,console.log("Not cloning system database due to it already existing on clone");ut=await xm({operation:Dn.DESCRIBE_ALL}),ut=await ut.json(),wn=Zr?.databaseConfig?.excludeDatabases,wn=wn?wn.reduce((r,n)=>({...r,[n.database]:!0}),{}):{};for(let r in ut)await $t.exists(kd.join(oi(r),r+".mdb"))&&(console.log(`Not cloning database ${r} due to it already existing on clone`),wn[r]=!0);Ns=Zr?.databaseConfig?.excludeTables,Ns=Ns?Ns.reduce((r,n)=>({...r,[n.database==null?null:n.database+n.table]:!0}),{}):{};for(let r in ut){if(wn[r]){ut[r]="excluded";continue}if(v$.isEmpty(ut[r]))continue;let n=[],s=!1;for(let u in ut[r])Ns[r+u]?(s=!0,ut[r][u]="excluded"):n.push(u);if(n.length===0)return;let i;s?(console.info(`Cloning database: ${r} tables: ${n}`),i=await xm({operation:Dn.GET_BACKUP,database:r,tables:n},!0)):(console.info(`Cloning database: ${r}`),i=await xm({operation:Dn.GET_BACKUP,database:r},!0));let o=oi(r);await Vm(o);let c=new Date(i.headers.get("date")),l=Cn(o,`${c.getTime()}-${r}.mdb`);await w$(i.body,km(l,{overwrite:!0}));let _=Cn(o,r+".mdb");await $t.rename(l,_),await $t.utimes(_,Date.now(),c)}}a(fhe,"cloneTablesFetch");async function xm(e,t=!1){let r=Zr?.httpsRejectUnauthorized??!1,n=new Fm.Agent({rejectUnauthorized:r});r||(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");let i={Authorization:"Basic "+Buffer.from(xd+":"+qd).toString("base64"),"Content-Type":"application/json"};t&&(i["Accept-Encoding"]="gzip");let o=await fetch(Fd,{method:"POST",headers:i,body:JSON.stringify(e),agent:n,compress:!0});if(o.ok)return o;throw console.error(`HTTP Error Response: ${o.status} ${o.statusText}`),new Error(await o.text())}a(xm,"leaderHttpReqFetch");async function Ehe(e){let t=await QEe.getHDBProcessInfo();t.clustering.length===0||t.core.length===0?e?await XEe(!1):await H$():(console.info(await jEe({operation:Dn.RESTART})),await $m.async_set_timeout(she)),e&&await $m.async_set_timeout(2e3)}a(Ehe,"startHDB");async function hhe(){console.info("Clustering cloned tables");let e=Zr?.clusteringConfig?.subscribeToLeaderNode!==!1,t=Zr?.clusteringConfig?.publishToLeaderNode!==!1;await JEe.setSchemaDataToGlobalAsync();let r=c_(),n=await Ym({operation:Dn.CLUSTER_STATUS});n=await JSON.parse(n.body);let s=[];if(!Km){let l=await $t.stat(Cn(oi("system"),"system.mdb"));for(let _ of sy)s.push({schema:nhe,table:_,subscribe:e,publish:t,start_time:l.mtime.toISOString()})}let i=Zr?.clusteringConfig?.excludeDatabases;i=i?i.reduce((l,_)=>({...l,[_.database]:!0}),{}):{};let o=Zr?.clusteringConfig?.excludeTables;o=o?o.reduce((l,_)=>({...l,[_.database==null?null:_.database+_.table]:!0}),{}):{};for(let l in ut){if(ut[l]==="excluded"||i[l])continue;let _=await $t.stat(Cn(oi(l),l+".mdb"));_.mtime.setSeconds(_.mtime.getSeconds()-10);for(let u in ut[l])ut[l][u]==="excluded"||o[l+u]||s.push({schema:l,table:u,subscribe:e,publish:t,start_time:_.mtime.toISOString()})}await C$.createTableStreams(s),B$.info("Sending add_node request to node:",Wi?.clustering?.nodeName,"with subscriptions:",s);let c;if(ahe&&n.connections.length>0){let l=ZE(),_=[{node_name:Wi?.clustering?.nodeName,subscriptions:s}],u=!1;Gl=bs.get(Xr.CONFIG_PARAMS.CLUSTERING_NODENAME);for(let d of n.connections){if(d.node_name===Gl)continue;let E={node_name:d.node_name,subscriptions:[]};for(let f of d.subscriptions){if(wn[f.schema]||Ns[f.schema+f.table]||i[f.schema]||o[f.schema+f.table])continue;u=!0;let h=await $t.stat(Cn(oi(f.schema),f.schema+".mdb"));h.mtime.setSeconds(h.mtime.getSeconds()-10),f.start_time=h.mtime.toISOString(),E.subscriptions.push(f)}_.push(E)}u&&(c=await l({operation:Dn.CONFIGURE_CLUSTER,connections:_}),console.info(JSON.stringify(c)))}!c&&s.length>0&&await r({operation:Dn.ADD_NODE,node_name:Wi?.clustering?.nodeName,subscriptions:s},!0),await C$.closeConnection()}a(hhe,"clusterTables");async function Ym(e){let t=new Fm.Agent({rejectUnauthorized:Zr?.httpsRejectUnauthorized??!1}),n={Authorization:"Basic "+Buffer.from(xd+":"+qd).toString("base64"),"Content-Type":"application/json"},s=new URL(Fd),i={protocol:s.protocol,host:s.hostname,method:"POST",headers:n};return s.protocol==="https:"&&(i.agent=t),s.port&&(i.port=s.port),await $m.httpRequest(i,e)}a(Ym,"leaderHttpReq");async function U$(e,t){let r=new Fm.Agent({rejectUnauthorized:Zr?.httpsRejectUnauthorized??!1}),s={Authorization:"Basic "+Buffer.from(xd+":"+qd).toString("base64"),"Content-Type":"application/json"},i=new URL(Fd),o={protocol:i.protocol,host:i.hostname,method:"POST",headers:s};return i.protocol==="https:"&&(o.agent=r,y$=Fm),i.port&&(o.port=i.port),new Promise((c,l)=>{let _=y$.request(o,u=>{u.statusCode!==200&&l("Request to leader node failed with code: "+u.statusCode),u.pipe(t),u.on("end",()=>{t.close(),c(u.headers)})});_.on("error",u=>{l(u)}),_.write(JSON.stringify(e)),_.end()})}a(U$,"leaderHttpStream");async function q$(){let e=the.version();if(e)await rhe.insertHdbInstallInfo(e);else throw new Error("The version is missing/removed from HarperDB package.json")}a(q$,"insertHdbVersionInfo")});var V$=R((pwe,k$)=>{var phe=vm(),mhe=k();k$.exports=She;async function She(){try{await phe.install()}catch(e){console.error("There was an error during the install."),console.error(e),mhe.error(e),process.exit(1)}}a(She,"install")});var K$=R((Swe,Y$)=>{"use strict";var The=ah(),ghe=k(),$$="Registration failed.";async function Rhe(){let e;try{e=await The.register()}catch(t){return ghe.error(`Registration error ${t}`),$$}return e||$$}a(Rhe,"register");Y$.exports={register:Rhe}});var z$=R((gwe,j$)=>{"use strict";var Ahe=k(),Ohe=D(),bhe=require("util"),Nhe=require("child_process"),W$=bhe.promisify(Nhe.exec),yhe=gi(),Vd=Yc(),Q$="Stopping HarperDB.";j$.exports=Ihe;async function Ihe(){if(console.log(Q$),Ahe.notify(Q$),await Vd.isServiceRegistered(Ohe.HDB_PROC_DESCRIPTOR)){Vd.enterPM2Mode();let r=await Vd.getUniqueServicesList();for(let n in r)await Vd.stop(n)}await Vd.kill();let t=await yhe.getHDBProcessInfo();t.clustering.forEach(r=>{W$(`kill ${r.pid}`)}),t.core.forEach(r=>{W$(`kill ${r.pid}`)})}a(Ihe,"stop")});var eY=R((Awe,Z$)=>{"use strict";var ay=require("fs-extra"),cy=require("path"),oy=require("yaml"),$d=gt(),Yd=D(),J$=Ze(),ly=k(),whe=Lr(),Che=nh(),Dhe=th(),Lhe=gi(),X$=X(),{isHdbInstalled:Phe}=ic();X$.initSync();var Xn={RUNNING:"running",STOPPED:"stopped",ERRORED:"errored",NOT_INSTALLED:"not installed"},en={LEAF:"leaf server",HUB:"hub server"},Wm;Z$.exports=Mhe;async function Mhe(){let e={harperdb:{status:Xn.STOPPED}};if(!await Phe()){e.harperdb.status=Xn.NOT_INSTALLED,console.log(oy.stringify(e));return}Wm=X$.get(Yd.CONFIG_PARAMS.ROOTPATH);let t;try{t=Number.parseInt(await ay.readFile(cy.join(Wm,Yd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Yd.NODE_ERROR_CODES.ENOENT){ly.info("`harperdb status` did not find a hdb.pid file"),e.harperdb.status=Xn.STOPPED,console.log(oy.stringify(e));return}throw n}let r=await Lhe.getHDBProcessInfo();for(let n of r.core)if(n.pid===t){e.harperdb.status=Xn.RUNNING,e.harperdb.pid=t;break}if(e.clustering=await Uhe(r),e.clustering[en.HUB].status===Xn.RUNNING&&e.clustering[en.LEAF].status===Xn.RUNNING){let n=[],s=await Che({});for(let o of s.nodes){let c={};for(let l in o)c[l.replace("_"," ")]=o[l];n.push(c)}e.clustering.network=n;let i=await Dhe.clusterStatus();e.clustering.replication={"node name":i.node_name,"is enabled":i.is_enabled,connections:[]};for(let o of i.connections){let c={};c["node name"]=o?.node_name,c.status=o?.status,c.ports={clustering:o?.ports?.clustering,"operations api":o?.ports?.operations_api},c["latency ms"]=o?.latency_ms,c.uptime=o?.uptime,c.subscriptions=o?.subscriptions,c["system info"]={"hdb version":o?.system_info?.hdb_version,"node version":o?.system_info?.node_version,platform:o?.system_info?.platform},e.clustering.replication.connections.push(c)}await $d.closeConnection()}console.log(oy.stringify(e)),process.exit()}a(Mhe,"status");async function Uhe(e){let t={[en.HUB]:{},[en.LEAF]:{}};if(e.clustering.length===0)return t[en.HUB].status=Xn.STOPPED,t[en.LEAF].status=Xn.STOPPED,t;let{port:r}=$d.getServerConfig(Yd.PROCESS_DESCRIPTORS.CLUSTERING_HUB),{username:n,decrypt_hash:s}=await whe.getClusterUser();try{(await $d.createConnection(r,n,s,!1)).close(),t[en.HUB].status=Xn.RUNNING}catch{t[en.HUB].status=Xn.ERRORED}let{port:i}=$d.getServerConfig(Yd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);try{(await $d.createConnection(i,n,s,!1)).close(),t[en.LEAF].status=Xn.RUNNING}catch{t[en.LEAF].status=Xn.ERRORED}try{t[en.HUB].pid=Number.parseInt(await ay.readFile(cy.join(Wm,"clustering",J$.PID_FILES.HUB),"utf8"))}catch(o){ly.error(o),t[en.HUB].pid=void 0}try{t[en.LEAF].pid=Number.parseInt(await ay.readFile(cy.join(Wm,"clustering",J$.PID_FILES.LEAF),"utf8"))}catch(o){ly.error(o),t[en.LEAF].pid=void 0}return t}a(Uhe,"getHubLeafStatus")});var Qm=process.env.HDB_LEADER_URL||process.argv.includes("--HDB_LEADER_URL");Qm&&X().setCloneVar(!0);var Kd=require("fs"),tY=require("path"),oc=k(),rY=Zk(),vhe=Ri(),Bhe=rV(),uy=D(),{SERVICE_ACTIONS_ENUM:Rr,PACKAGE_ROOT:Hhe}=uy;Ghe();function Ghe(){let e=Bhe();if(e)if(e.error){console.error(e.error),oc.error(e.error);return}else e.warn&&(console.warn(e.warn),oc.warn(e.warn));let t;Kd.readdir(tY.join(Hhe,"bin"),r=>{if(r)return oc.error(r);process.argv&&process.argv[2]&&!process.argv[2].startsWith("-")&&(t=process.argv[2].toLowerCase());let n;Qm||(n=rY.buildRequest(),n.operation&&(t=Rr.OPERATION));let s;switch(t){case Rr.OPERATION:oc.trace("calling cli operations with:",n),rY.cliOperations(n).then();break;case Rr.DEV:process.env.DEV_MODE=!0;case Rr.RUN:let i=process.argv[3];i&&i[0]!=="-"&&(Kd.existsSync(i)||(console.error(`The folder ${i} does not exist`),process.exit(1)),Kd.statSync(i).isDirectory()||(console.error(`The path ${i} is not a folder`),process.exit(1)),i=Kd.realpathSync(i),Kd.existsSync(tY.join(i,uy.HDB_CONFIG_FILE))?process.env.ROOTPATH=i:process.env.RUN_HDB_APP=i),ic().main();break;case Rr.START:Qm?iy()(!0).catch(S=>{console.log(S)}):s=ic().launch();break;case Rr.INSTALL:V$()().then(()=>ic().main(!0)).catch(m=>{console.error(m)});break;case Rr.REGISTER:K$().register().then(m=>{console.log(m)}).catch(m=>{console.error(m)});break;case Rr.STOP:z$()().then(()=>{process.exit(0)}).catch(m=>{console.error(m)});break;case Rr.RESTART:bo().restart({}).then().catch(m=>{oc.error(m),console.error(`There was an error restarting HarperDB. ${m}`),process.exit(1)});break;case Rr.VERSION:vhe.printVersion();break;case Rr.UPGRADE:oc.setLogLevel(uy.LOG_LEVELS.INFO),JN().upgrade(null).then(()=>{console.log("Your instance of HarperDB is up to date!")}).catch(m=>{oc.error(`Got an error during upgrade ${m}`)});break;case Rr.STATUS:eY()().then().catch(m=>{console.error(m)});break;case Rr.RENEWCERTS:let{generateKeys:E}=Cm();E().then(()=>{console.log("Successfully renewed self-signed certificates")}).catch(()=>{console.error(r)});break;case Rr.COPYDB:let f=process.argv[3],h=process.argv[4];(gh(),ae(Th)).copyDb(f,h);break;case void 0:Qm?iy()().catch(S=>{console.log(S)}):ic().main();break;default:console.warn(`The "${t}" command is not understood.`);case Rr.HELP:console.log(`
110
+ Reindexing upgrade started for transaction logs`),Bo.notify("Reindexing upgrade started for transaction logs"),await P1(DI,!0,e)),Bo.notify("Reindexing upgrade complete"),"Reindexing for 4.0.0 upgrade complete"+(PE?", but errors occurred":"")}a(OEe,"reindexUpgrade");async function P1(e,t,r){let n=await $i.readdir(e),s=n.length;for(let i=0;i<s;i++){let o=n[i],c=Ho.join(e,o.toString());if(o===".DS_Store")continue;let l=await $i.readdir(c),d=l.length;for(let u=0;u<d;u++){let _=l[u];if(_!==".DS_Store"&&$i.statSync(Ho.join(c,_)).isDirectory())try{await NEe(o,_,t),rn.info(`Reindexing started for ${o}.${_}`),Bo.notify(`${t?"Transaction":"Schema"} reindexing started for ${o}.${_}`),await wEe(o,_,c,t,r),rn.info(`Reindexing completed for ${o}.${_}`),Bo.notify(`Reindexing completed for ${o}.${_}`)}catch(E){PE=!0,E.schema_path=c,E.table_name=_,Bo.error("There was an error with the reindex upgrade, check the logs in hdb/3_0_0_upgrade_tmp for more details"),Bo.error(E),rn.error(E),console.error(E)}}}if(!PE)try{await $i.rm(dT,{recursive:!0})}catch{}}a(P1,"processTables");async function NEe(e,t,r){let s=`${e}_${t}_${r?"transaction_reindex":"schema_reindex"}.log`,i=Ho.join(dT,s);await $i.ensureDir(dT),await $i.writeFile(i,""),rn=bEe({level:"debug",formatters:{bindings(){}}},i)}a(NEe,"initPinoLogger");var IEe=20;async function wEe(e,t,r,n,s){let i;try{i=await zn.openEnvironment(r,t,n)}catch(m){if(m.message==="MDB_INVALID: File is not an LMDB file"){Bo.notify(`${e}.${t} file is not from the old environment and has been skipped`),console.info(`${e}.${t} file is not from the old environment and has been skipped`),rn.error(m);return}throw m}let o=PEe(i.dbis),c=zn.openDBI(i,o),l=Object.keys(i.dbis),d=zn.statDBI(i,o);rn.info(`Old environment stats: ${JSON.stringify(d)}`);let u=new AEe.SingleBar({format:`${e}.${t} |{bar}| {percentage}% || {value}/{total} records`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,clearOnComplete:!1});u.start(d.entryCount,0,{});let _=await zn.createEnvironment(r,t,!1);zn.createDBI(_,o,!1,!0);let E=[];try{for(let m of c.getRange({start:!1}))m.value={...m.value},E.push(m),n||e==="system"&&(t==="hdb_schema"&&(m.key=m.key.toString(),m.value.name=m.value.name.toString()),t==="hdb_table"&&(m.key=m.key.toString(),m.value.schema=m.value.schema.toString(),m.value.name=m.value.name.toString()),t==="hdb_attribute"&&(m.key=m.key.toString(),m.value.schema=m.value.schema.toString(),m.value.table=m.value.table.toString(),m.value.attribute=m.value.attribute.toString())),E.length>IEe&&await f();await f()}catch(m){throw PE=!0,rn.error(m),m}async function f(){let m,C=E.map(({value:x})=>x);n?m=await Promise.all(C.map(x=>CEe(_,x))):m=await SEe(_,o,l.filter(x=>x!=="__blob__"),C,!1);for(let x=0,F=E.length;x<F;x++){let{key:Y,value:$}=E[x];rn.info(`Record hash value: ${Y} hash: ${o}`);let Z;n?Z=m[x]:Z=m.written_hashes.indexOf(Y)>-1,DE(Z,!0),DEe(_,o,$[o],n),rn.info(`Insert success, written hashes: ${m.written_hashes}`),u.increment()}E=[],u.value/u.total*100%10===0&&Bo.notify(`${e}.${t} ${u.value}/${u.total} records inserted`),rn.info(`${u.value}/${u.total} records inserted`)}a(f,"finishOutstanding"),u.stop();let h=zn.statDBI(i,o),S=zn.statDBI(_,o);if(rn.info(`Old stats entry count: ${h.entryCount}. New stats entry count: ${S.entryCount}`),DE.deepStrictEqual(h.entryCount,S.entryCount),await zn.closeEnvironment(i),await zn.closeEnvironment(_),delete global.lmdb_map[`${e}.${t}`],s){let m=Ho.join(r,t),C=Ho.join(m,"data.mdb"),O=Ho.join(m,"lock.mdb");await $i.unlink(C),await $i.unlink(O),await $i.rmdir(m),rn.info(`Deleted old environment files from schema folder: ${C}, ${O}`)}let T=await zn.openEnvironment(r,t),g=zn.statDBI(T,o);rn.info(`New stats: ${JSON.stringify(S)}. New stats after move: ${JSON.stringify(g)}`),DE.deepStrictEqual(g.entryCount,S.entryCount),await zn.closeEnvironment(T),delete global.lmdb_map[`${e}.${t}`]}a(wEe,"processTable");async function CEe(e,t){zn.initializeDBIs(e,Fa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Fa.TRANSACTIONS_DBIS);let r=t.timestamp;return e.dbis[Fa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(r,()=>{e.dbis[Fa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(r,t),REe.isEmpty(t.user_name)||e.dbis[Fa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(t.user_name,r);for(let n of t.hash_values)e.dbis[Fa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n,r)})}a(CEe,"insertTransaction");function DEe(e,t,r,n){let i=e.dbis[t].get(r);DE.deepStrictEqual(typeof i,"object");let o;if(n){let c={[Fa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME]:i.user_name,[Fa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE]:i.hash_values};o=Object.entries(c)}else o=Object.entries(i);for(let[c,l]of o)if(c!==t&&e.dbis[c]!==void 0&&!gEe.isEmptyOrZeroLength(l))if(n&&c==="hash_value")for(let d=0,u=l.length;d<u;d++){let _=l[d];L1(e,c,_,r)}else L1(e,c,l,r)}a(DEe,"validateIndices");function L1(e,t,r,n){try{let s=!1,i=TEe.getIndexedValues(r);if(!i)return;for(let o of i)s=e.dbis[t].doesExist(o,n),s||rn.info(`Validate indices did not find value in new DBI: ${o}. Hash: ${n}`),DE.deepStrictEqual(s,!0)}catch(s){PE=!0,rn.error(s),console.error(s)}}a(L1,"validateIndex");function PEe(e){let t;for(let[r,n]of Object.entries(e))if(n.__dbi_defintion__.is_hash_attribute===!0){t=r;break}return t}a(PEe,"getHashDBI")});var F1=y((iMe,x1)=>{"use strict";var _T=require("path"),ka=require("fs-extra"),LEe=wI(),El=V(),v1=yt(),PI=te(),li=M(),fT=ee(),MEe=require("properties-reader"),UEe=zs(),vEe=Im(),BEe=jr(),sMe=require("util"),HEe=BEe.searchByValue,xEe=un(),FEe=Km(),kEe=At(),GEe=U1(),B1=Ss(),qEe=cT(),UE=new LEe("4.0.0"),H1=[],LE,ME;async function $Ee(){try{if(await qEe.upgradeCertsPrompt()){if(console.log("Generating new certificates."),LE){let t=fT.changeExtension(LE,".bak");await ka.move(LE,t)}if(ME){let t=fT.changeExtension(ME,".bak");await ka.move(ME,t)}await B1.generateKeys()}else console.log("Using existing certificates."),B1.updateConfigCert(LE,ME,void 0)}catch(e){throw console.error("There was a problem generating new keys. Please check the log for details."),e}}a($Ee,"generateNewKeys");async function VEe(){console.log("Updating HarperDB nodes."),El.info("Updating HarperDB nodes.");let e=[];try{let t=new UEe(li.SYSTEM_SCHEMA_NAME,li.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*","name",["*"]),r=Array.from(await HEe(t)),n=[];for(let i=0,o=r.length;i<o;i++){let c=r[i];if(!kEe.NATS_TERM_CONSTRAINTS_RX.test(c.name)){let u=`Node name '${c.name}' is invalid, must not contain ., * or >. Please change name and try again.`;throw console.error(u),u}let l={host:c.host,port:c.port};e.push(l);let d=[];for(let u=0,_=c.subscriptions.length;u<_;u++){let E=c.subscriptions[u],f=E.channel.split(":");d.push({schema:f[0],table:f[1],publish:E.publish,subscribe:E.subscribe})}n.push({name:c.name,subscriptions:d,system_info:{hdb_version:li.PRE_4_0_0_VERSION,node_version:void 0,platform:void 0}})}if(fT.isEmptyOrZeroLength(n))return;let s=new vEe(li.SYSTEM_SCHEMA_NAME,li.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,n);await xEe.update(s)}catch(t){throw console.error("There was a problem updating the hdb_nodes table. Please check the log for details."),t}try{FEe.setRoutes({server:"hub",routes:e})}catch(t){throw console.error("There was a problem setting the clustering routes. Please check the log for details."),t}}a(VEe,"updateNodes");async function YEe(){let e=PI.get(li.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);if(!e.includes(_T.join("config","settings.js"))){El.info("pre 4.0.0 settings.js file not found, skipping settings file update");return}let t="Updating settings file for version 4.0.0";console.log(t),El.info(t);let r=_T.dirname(e),n=PI.get(li.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),s=_T.join(n,"backup","4_0_0_upgrade_settings.bak"),i=_T.join(n,li.HDB_CONFIG_FILE);try{El.info(`Backing up old settings file to: ${s}`),console.log(`Backing up old settings file to: ${s}`),ka.copySync(e,s)}catch(_){throw console.error("There was a problem writing the backup for the old settings file. Please check the log for details."),_}try{El.info(`Creating new/upgraded settings file at '${i}'`),console.log(`Creating new/upgraded settings file at '${i}'`),El.info("Updating env variables with new settings values");let _=v1.initOldConfig(e);LE=_[li.CONFIG_PARAMS.TLS_CERTIFICATE.toLowerCase()],ME=_[li.CONFIG_PARAMS.TLS_PRIVATEKEY.toLowerCase()],v1.createConfigFile(_)}catch(_){throw console.log("There was a problem creating the new HarperDB config file. Please check the log for details."),_}let o=fT.getPropsFilePath();ka.accessSync(o,ka.constants.F_OK|ka.constants.R_OK);let l=MEe(o).get(li.HDB_SETTINGS_NAMES.INSTALL_USER),d=`settings_path = ${i}
111
+ install_user = ${l}`;try{ka.writeFileSync(o,d)}catch(_){throw console.log("There was a problem updating the HarperDB boot properties file. Please check the log for details."),_}try{PI.initSync(!0)}catch(_){throw console.error("Unable to initialize new properties. Please check the log for details."),_}let u="New settings file for 4.0.0 upgrade successfully created.";try{ka.removeSync(r),console.log(u),El.info(u)}catch(_){throw console.error("There was a problem deleting the old settings file and directory. Please check the log for details."),_}}a(YEe,"updateSettingsFile_4_0_0");UE.async_functions.push(YEe);UE.async_functions.push($Ee);UE.async_functions.push(GEe);UE.async_functions.push(VEe);H1.push(UE);x1.exports=H1});var LI=y((aMe,$1)=>{"use strict";var hl=ee(),KEe=M(),k1=V(),{DATA_VERSION:WEe,UPGRADE_VERSION:jEe}=KEe.UPGRADE_JSON_FIELD_NAMES_ENUM,G1=C1(),ET=F1(),pl=new Map;G1&&G1.forEach(e=>{pl.set(e.version,e)});ET&&ET.forEach(e=>{pl.set(e.version,e)});ET&&ET.forEach(e=>{pl.set(e.version,e)});function QEe(){return[...pl.keys()].sort(hl.compareVersions)}a(QEe,"getSortedVersions");function q1(e){let t=e[WEe],r=e[jEe];return hl.isEmptyOrZeroLength(t)||hl.isEmptyOrZeroLength(r)?(k1.info(`There is an issue with the version data in your instance of HDB. Current version data: ${e}`),k1.error("There was an error when trying to evaluate the version information for your instance. Trying to start the server anyways but it may fail. If you continue to have this problem, please contact support@harperdb.io."),[]):[...pl.keys()].sort(hl.compareVersions).filter(function(n){return hl.compareVersions(n,t)>0&&hl.compareVersions(n,r)<=0})}a(q1,"getVersionsForUpgrade");function zEe(e){return q1(e).length>0}a(zEe,"hasUpgradesRequired");function JEe(e){return hl.isEmptyOrZeroLength(e)?null:pl.has(e)?pl.get(e):null}a(JEe,"getDirectiveByVersion");$1.exports={getSortedVersions:QEe,getDirectiveByVersion:JEe,getVersionsForUpgrade:q1,hasUpgradesRequired:zEe}});var vE=y((lMe,j1)=>{"use strict";var XEe=require("util"),MI=require("chalk"),ZEe=require("os"),Y1=un(),ehe=jr(),Jn=M(),K1=m1(),vI=iA(),{UpgradeObject:V1}=g1(),{forceDowngradePrompt:the}=cT(),rhe=go(),hT=V(),md=ee(),BI=_s(),nhe=(De(),ne(at)),she=LI(),ihe=XEe.promisify(BI.setSchemaDataToGlobal),ohe=ehe.searchByValue,ahe="info_id",che="2.9.9",lhe="3.0.0";async function uhe(e){let t=new K1.HdbInfoInsertObject(1,e,e),r=new vI.InsertObject(Jn.OPERATIONS_ENUM.INSERT,Jn.SYSTEM_SCHEMA_NAME,Jn.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,Jn.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return BI.setSchemaDataToGlobal(),Y1.insert(r)}a(uhe,"insertHdbInstallInfo");async function UI(e){let t,r=await W1(),n=new Map([[0,{}]]);for(let c of r)n.set(c.info_id,c);let i=Math.max.apply(null,[...n.keys()])+1;t=new K1.HdbInfoInsertObject(i,e,e);let o=new vI.InsertObject(Jn.OPERATIONS_ENUM.INSERT,Jn.SYSTEM_SCHEMA_NAME,Jn.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,Jn.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return await ihe(),Y1.insert(o)}a(UI,"insertHdbUpgradeInfo");async function W1(){let e=new vI.NoSQLSeachObject(Jn.SYSTEM_SCHEMA_NAME,Jn.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,ahe,Jn.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,["*"],"*"),t=[];try{t=Array.from(await ohe(e))}catch(r){console.error(r)}return t}a(W1,"getAllHdbInfoRecords");async function dhe(){let e=await W1();if(e.length===0)return;let t,r=new Map;for(let s of e)r.set(s.info_id,s);let n=Math.max.apply(null,[...r.keys()]);return t=r.get(n),t}a(dhe,"getLatestHdbInfoRecord");async function _he(){hT.info("Checking if HDB software has been updated");try{let e=rhe.version(),t=await dhe(),r;if(md.isEmpty(t))r=che;else if(r=t.data_version_num,md.compareVersions(r.toString(),e.toString())>0){if(!md.isCompatibleDataVersion(r.toString(),e.toString()))throw console.log(MI.yellow(`This instance's data was last run on version ${r}`)),console.error(MI.red(`You have installed a version lower than the version that your data was created on or was upgraded to. This may cause issues and is currently not supported.${ZEe.EOL}${Jn.SUPPORT_HELP_MSG}`)),new Error("Trying to downgrade major HDB versions is not supported.");md.isCompatibleDataVersion(r.toString(),e.toString(),!0)||(console.log(MI.yellow(`This instance's data was last run on version ${r}`)),await the(new V1(r,e))?await UI(e.toString()):(console.log("Cancelled downgrade, closing HarperDB"),process.exit(0)))}if(BI.setSchemaDataToGlobal(),fhe(r),e.toString()===r.toString())return;let n=new V1(r,e);if(she.hasUpgradesRequired(n))return n;md.compareVersions(n.data_version.toString(),n.upgrade_version.toString())<0&&(await UI(n.upgrade_version),hT.notify(`HarperDB running on upgraded version: ${n.upgrade_version}`))}catch(e){throw hT.fatal("Error while trying to evaluate the state of hdb data and the installed hdb version"),hT.fatal(e),e}}a(_he,"getVersionUpdateInfo");function fhe(e){let t=`You are attempting to upgrade from an old instance of HarperDB that is no longer supported. In order to upgrade to this version, you must do a fresh install. If you need support, please contact ${Jn.HDB_SUPPORT_ADDRESS}`;if(!("hdb_info"in nhe.databases.system))throw console.log(t),new Error(t);if(!md.isEmpty(e)&&e<lhe)throw console.log(t),new Error(t)}a(fhe,"checkIfInstallIsSupported");j1.exports={insertHdbInstallInfo:uhe,insertHdbUpgradeInfo:UI,getVersionUpdateInfo:_he}});var X1=y((dMe,J1)=>{"use strict";var pT=require("joi"),{boolean:Ehe,string:HI,number:hhe}=pT.types(),Q1=require("fs-extra"),BE=M(),z1=require("path"),phe=St();J1.exports=mhe;function mhe(e){let t=HI.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),r=pT.object({[BE.INSTALL_PROMPTS.ROOTPATH]:pT.custom(She),[BE.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT]:pT.alternatives([hhe.min(0),HI]).allow("null",null),[BE.INSTALL_PROMPTS.TC_AGREEMENT]:HI.valid("yes","YES","Yes"),[BE.INSTALL_PROMPTS.CLUSTERING_NODENAME]:t,[BE.INSTALL_PROMPTS.CLUSTERING_ENABLED]:Ehe});return phe.validateBySchema(e,r)}a(mhe,"installValidator");function She(e,t){if(Q1.existsSync(z1.join(e,"system/hdb_user/data.mdb"))||Q1.existsSync(z1.join(e,"system/hdb_user.mdb")))return t.message(`'${e}' is already in use. Please enter a different path.`)}a(She,"validateRootAvailable")});var kI=y((fMe,Z1)=>{"use strict";var{mkdirpSync:The}=require("fs-extra"),Vi=require("path"),Sd=M(),FI=V(),ghe=Hn(),xI=ao(),Rhe=mt();Z1.exports=Ahe;async function Ahe(e){FI.trace("Mounting HarperDB"),ui(e),ui(Vi.join(e,"backup")),ui(Vi.join(e,"trash")),ui(Vi.join(e,"keys")),ui(Vi.join(e,"keys",Sd.LICENSE_FILE_NAME)),ui(Vi.join(e,"log")),ui(Vi.join(e,"doc")),ui(Vi.join(e,"database")),ui(Vi.join(e,Sd.TRANSACTIONS_DIR_NAME)),ui(Vi.join(e,"clustering","leaf")),ui(Vi.join(e,"components")),await bhe()}a(Ahe,"mountHdb");async function bhe(){let e=G_(),t=Object.keys(xI);for(let r=0;r<t.length;r++){let n=t[r],s=xI[n].hash_attribute;try{Rhe.initSystemSchemaPaths(Sd.SYSTEM_SCHEMA_NAME,n);let i=new e(Sd.SYSTEM_SCHEMA_NAME,n,s);i.attributes=xI[n].attributes;let o=i.attributes.find(({attribute:c})=>c===s);o.isPrimaryKey=!0,await ghe.createTable(n,i)}catch(i){throw FI.error(`issue creating environment for ${Sd.SYSTEM_SCHEMA_NAME}.${n}: ${i}`),i}}}a(bhe,"createLMDBTables");function ui(e){The(e,{mode:Sd.HDB_FILE_PERMISSIONS}),FI.info(`Directory ${e} created`)}a(ui,"makeDirectory")});var TT=y((mMe,fY)=>{"use strict";var qI=require("os"),sY=require("inquirer"),Us=require("fs-extra"),yhe=require("properties-reader"),Sl=require("chalk"),Ki=require("path"),Ohe=require("human-readable-ids").hri,Nhe=require("ora"),Ihe=require("yaml"),lr=V(),Ga=te(),HE=ee(),ST=Jo(),iY=vE(),oY=go(),ae=M(),{CONFIG_PARAM_MAP:hMe,CONFIG_PARAMS:Mt}=ae,whe=X1(),Che=kI(),$I=yt(),Dhe=_n(),Phe=ym(),Lhe=AI(),Mhe=_s(),Uhe=require("util").promisify,vhe=Uhe(Mhe.setSchemaDataToGlobal),eY=Ss(),ml=a(e=>e,"PROMPT_ANSWER_TRANSFORMER"),Fr=a(e=>Sl.magenta.bold(e),"HDB_PROMPT_MSG"),Bhe="https://harperdb.io/legal/end-user-license-agreement",qa=qI.EOL,xo="",Hhe="yes",tY="Starting HarperDB install...",rY="HarperDB installation was successful.",nY="Terms & Conditions acceptance is required to proceed with installation. Exiting install...",xhe="An out of date version of HarperDB is already installed.",GI="It appears that HarperDB is already installed. Exiting install...",Fhe="Aborting install",pMe=new RegExp(/^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/),khe=new RegExp(/^[^\s.,*>]+$/),Ghe=qI.homedir(),qhe=Ki.join(Ghe,ae.HDB_ROOT_DIR_NAME),$he="HDB_ADMIN",Vhe="CLUSTER_USER",Yhe="dev",Khe="localhost",mT={[Mt.HTTP_CORS]:!0,[Mt.HTTP_CORSACCESSLIST]:["*"],[Mt.HTTP_PORT]:9926,[Mt.AUTHENTICATION_AUTHORIZELOCAL]:!0,[Mt.THREADS_COUNT]:1,[Mt.THREADS_DEBUG]:!0,[Mt.LOGGING_STDSTREAMS]:!0,[Mt.LOGGING_LEVEL]:"info",[Mt.OPERATIONSAPI_NETWORK_PORT]:9925,[Mt.LOCALSTUDIO_ENABLED]:!0},xr={DESTINATION:"Please enter a destination for HarperDB:",HDB_USERNAME:"Please enter a username for the administrative user:",HDB_PASS:"Please enter a password for the administrative user:",NODE_NAME:"Please enter a unique name for this node:",CLUSTER_USERNAME:"Please enter a username for the CLUSTER_USER:",CLUSTER_PASS:"Please enter a password for the CLUSTER_USER:",DEFAULTS_MODE:"Default Config - dev (easy access/debugging) or prod (security/performance): (dev/prod)",REPLICATION_HOSTNAME:"Please enter the hostname for this server:"},$a=ST([ae.INSTALL_PROMPTS.HDB_CONFIG]),Yi,aY=!1,cY=!1,lY=!1;fY.exports={install:uY,updateConfigEnv:npe,setIgnoreExisting:spe};uY.createSuperUser=_Y;async function uY(){console.log(Fr(qa+tY+qa)),lr.notify(tY);let e;$a[ae.INSTALL_PROMPTS.HDB_CONFIG]&&(e=Whe());let t=Qhe();Object.assign(t,e),t[ae.INSTALL_PROMPTS.TC_AGREEMENT]&&t[ae.INSTALL_PROMPTS.ROOTPATH]&&t[ae.INSTALL_PROMPTS.HDB_ADMIN_USERNAME]&&t[ae.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD]&&(lY=!0,t[ae.INSTALL_PROMPTS.DEFAULTS_MODE]="prod");let r=whe(t);if(r)throw r.message;await zhe(),await Jhe(t);let n=await jhe(t);Yi=n[ae.INSTALL_PROMPTS.ROOTPATH],$a[ae.INSTALL_PROMPTS.HDB_CONFIG]&&Ki.dirname($a[ae.INSTALL_PROMPTS.HDB_CONFIG])===Yi&&(aY=!0),!$a[ae.INSTALL_PROMPTS.HDB_CONFIG]&&await Us.pathExists(Ki.join(Yi,ae.HDB_CONFIG_FILE))&&(console.error(GI),process.exit());let s=Nhe({prefixText:Fr("Installing"),color:"magenta",spinner:"simpleDots"});if(s.start(),HE.isEmpty(Yi))throw new Error("Installer should have the HDB root param at the stage it is in but it does not.");Ga.setHdbBasePath(Yi),await Che(Yi),await Xhe(),await Zhe(n),lr.initLogSettings(!0),await _Y(n),await tpe(n),await eY.updateConfigCert(),await eY.generateCertsKeys(),await rpe(),Lhe(),s.stop(),console.log(Fr(qa+rY+qa)),lr.notify(rY)}a(uY,"install");function Whe(){let e=Ihe.parseDocument(Us.readFileSync($a[ae.INSTALL_PROMPTS.HDB_CONFIG],"utf8"),{simpleKeys:!0}),t=$I.flattenConfig(e.toJSON());return t[ae.CONFIG_PARAMS.ROOTPATH.toLowerCase()]&&(t.ROOTPATH=t[ae.CONFIG_PARAMS.ROOTPATH.toLowerCase()]),t}a(Whe,"getConfigFromFile");async function jhe(e){lr.trace("Getting install prompts and params.");let t,r=[{type:"input",transformer:ml,when:Fo(e[ae.INSTALL_PROMPTS.ROOTPATH],xr.DESTINATION),name:ae.INSTALL_PROMPTS.ROOTPATH,prefix:xo,default:qhe,validate:async s=>Ms(s)?Ms(s):await Us.pathExists(Ki.join(s,"system","hdb_user.mdb"))?`'${s}' is already in use. Please enter a different path.`:!0,message:Fr(xr.DESTINATION)},{type:"input",transformer:ml,when:Fo(e[ae.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],xr.HDB_USERNAME),name:ae.INSTALL_PROMPTS.HDB_ADMIN_USERNAME,prefix:xo,default:$he,validate:s=>Ms(s)?Ms(s):(t=s,!0),message:Fr(xr.HDB_USERNAME)},{type:"password",when:Fo(e[ae.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD],xr.HDB_PASS),name:ae.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD,prefix:xo,validate:s=>Ms(s)?Ms(s):!0,message:Fr(xr.HDB_PASS)},{type:"input",transformer:ml,when:Fo(e[ae.INSTALL_PROMPTS.DEFAULTS_MODE],xr.DEFAULTS_MODE),name:ae.INSTALL_PROMPTS.DEFAULTS_MODE,prefix:xo,default:Yhe,validate:s=>Ms(s)?Ms(s):s!=="dev"&&s!=="prod"?`Invalid response '${s}', options are 'dev' or 'prod'.`:!0,message:Fr(xr.DEFAULTS_MODE)}];if(lY||r.push({type:"input",name:ae.INSTALL_PROMPTS.REPLICATION_HOSTNAME,transformer:ml,when:Fo(e[ae.INSTALL_PROMPTS.REPLICATION_HOSTNAME],xr.REPLICATION_HOSTNAME),prefix:xo,default:Khe,message:Fr(xr.REPLICATION_HOSTNAME)}),HE.autoCastBoolean(e[ae.INSTALL_PROMPTS.CLUSTERING_ENABLED])===!0){let s=[{type:"input",transformer:ml,when:Fo(e[ae.INSTALL_PROMPTS.CLUSTERING_NODENAME],xr.NODE_NAME),name:ae.INSTALL_PROMPTS.CLUSTERING_NODENAME,prefix:xo,default:Ohe.random(),validate:i=>khe.test(i)?!0:"Invalid node name, must not contain ., * or >",message:Fr(xr.NODE_NAME)},{type:"input",transformer:ml,when:Fo(e[ae.INSTALL_PROMPTS.CLUSTERING_USER],xr.CLUSTER_USERNAME),name:ae.INSTALL_PROMPTS.CLUSTERING_USER,prefix:xo,default:Vhe,validate:i=>Ms(i)?Ms(i):i.toLowerCase()===t.toLowerCase()?"Username is already in use.":!0,message:Fr(xr.CLUSTER_USERNAME)},{type:"password",when:Fo(e[ae.INSTALL_PROMPTS.CLUSTERING_PASSWORD],xr.CLUSTER_PASS),name:ae.INSTALL_PROMPTS.CLUSTERING_PASSWORD,prefix:xo,validate:i=>Ms(i)?Ms(i):!0,message:Fr(xr.CLUSTER_PASS)}];r.push(...s)}let n=await sY.prompt(r);if(Object.keys(n).length===0)return e;for(let s in n)e[s]===void 0&&(e[s]=n[s]);return e}a(jhe,"installPrompts");function Fo(e,t){return e!==void 0?(t.includes("password")?(console.log(`${Fr(t)} ${Sl.gray("[hidden]")}`),lr.trace(`${Fr(t)} [hidden]`)):(console.log(`${Fr(t)} ${e}`),lr.trace(`${Fr(t)} ${e}`)),!1):!0}a(Fo,"displayCmdEnvVar");function Ms(e){let t=e.replace(/ /g,"");if(t===""||t==="''"||t==='""')return"Value cannot be empty."}a(Ms,"checkForEmptyValue");function Qhe(){let e=Object.keys(ae.INSTALL_PROMPTS),t=ST(e),r=ST(Object.keys(ae.CONFIG_PARAM_MAP),!0),n={};for(let s of e){let i=ae.CONFIG_PARAM_MAP[s.toLowerCase()];t[s]?i===void 0?n[s]=t[s]:n[i.toUpperCase()]=t[s]:i!==void 0&&r[i.toLowerCase()]&&(n[s]=r[i.toLowerCase()])}return n}a(Qhe,"checkForPromptOverride");async function zhe(){lr.trace("Checking for existing install.");let e=HE.getPropsFilePath(),t=await Us.pathExists(e),r;if(t){lr.trace(`Install found an existing boot prop file at:${e}`);let n=yhe(e),s=$I.getConfigValue(ae.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)||n.get(ae.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY);r=await Us.pathExists(s)}if(!t&&HE.noBootFile()&&(r=!0),r&&!cY){if(lr.trace(`Install found existing HDB config at:${e}`),await iY.getVersionUpdateInfo()){let s=`Please use \`harperdb upgrade\` to update to ${oY.version()}. Exiting install...`;console.log(qa+Sl.magenta.bold(xhe)),console.log(Sl.magenta.bold(s)),lr.error(s)}else console.log(qa+Sl.magenta.bold(GI)),lr.error(GI);process.exit(0)}}a(zhe,"checkForExistingInstall");async function Jhe(e){lr.info("Asking for terms agreement.");let t=`Terms & Conditions can be found at ${Bhe}${qa}and can be viewed by typing or copying and pasting the URL into your web browser.${qa}I agree to the HarperDB Terms and Conditions: (yes/no)`,r={prefix:xo,transformer:ml,when:Fo(e[ae.INSTALL_PROMPTS.TC_AGREEMENT],t),name:ae.INSTALL_PROMPTS.TC_AGREEMENT,message:Fr(t),validate:s=>s.toLowerCase()==="yes"||s.toLowerCase()==="no"?!0:Sl.yellow("Please enter 'yes' or 'no'")},n=await sY.prompt([r]);n[ae.INSTALL_PROMPTS.TC_AGREEMENT]&&n[ae.INSTALL_PROMPTS.TC_AGREEMENT].toLowerCase()!==Hhe&&(console.log(Sl.yellow(nY)),lr.error(nY),process.exit(0))}a(Jhe,"termsAgreement");async function Xhe(){let e=Ki.join(Yi,ae.HDB_CONFIG_FILE),t;try{t=qI.userInfo().username}catch{t=process.env.USERNAME||process.env.USER||process.env.LOGNAME||process.env.LNAME||process.env.SUDO_USER}if(t){let r=`settings_path = ${e}
112
+ install_user = ${t}`,n=HE.getHomeDir(),s=Ki.join(n,ae.HDB_HOME_DIR_NAME),i=Ki.join(s,ae.LICENSE_KEY_DIR_NAME);try{Us.mkdirpSync(s,{mode:ae.HDB_FILE_PERMISSIONS}),Us.mkdirpSync(i,{mode:ae.HDB_FILE_PERMISSIONS})}catch{console.error(`Could not make settings directory ${ae.HDB_HOME_DIR_NAME} in home directory. Please check your permissions and try again.`)}let o=Ki.join(s,ae.BOOT_PROPS_FILE_NAME);try{await Us.writeFile(o,r)}catch(c){throw lr.error(`There was an error creating the boot file at path: ${o}`),c}Ga.setProperty(ae.HDB_SETTINGS_NAMES.INSTALL_USER,`${t}`),Ga.setProperty(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,e),Ga.setProperty(Ga.BOOT_PROPS_FILE_PATH,o)}}a(Xhe,"createBootPropertiesFile");async function Zhe(e){lr.trace("Creating HarperDB config file");let t=ST(Object.keys(ae.CONFIG_PARAM_MAP),!0);if(Object.assign(t,e),e[ae.INSTALL_PROMPTS.DEFAULTS_MODE]==="dev"){process.env.DEV_MODE="true";for(let r in mT){if(r===Mt.HTTP_PORT&&t[Mt.HTTP_SECUREPORT.toLowerCase()]===void 0){t[r]=t[r.toLowerCase()]??mT[r],t[Mt.HTTP_SECUREPORT]=null;continue}else if(r===Mt.HTTP_PORT)continue;if(r===Mt.OPERATIONSAPI_NETWORK_PORT&&t[Mt.OPERATIONSAPI_NETWORK_SECUREPORT.toLowerCase()]===void 0){t[r]=t[r.toLowerCase()]??mT[r],t[Mt.OPERATIONSAPI_NETWORK_SECUREPORT]=null;continue}else if(r===Mt.OPERATIONSAPI_NETWORK_PORT)continue;t[r.toLowerCase()]===void 0&&(t[r]=mT[r])}}else t[Mt.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]&&(t[Mt.OPERATIONSAPI_NETWORK_SECUREPORT]=null),t[Mt.HTTP_PORT.toLowerCase()]&&(t[Mt.HTTP_SECUREPORT]=null);try{$a[ae.INSTALL_PROMPTS.HDB_CONFIG]||$I.createConfigFile(t),Ga.initSync()}catch(r){epe(r)}}a(Zhe,"createConfigFile");function epe(e){lr.error(`Error creating HarperDB config file. Rolling back install - ${e}`),console.error(e),console.error(Fhe);let t=Ki.resolve(Ga.get(Ga.BOOT_PROPS_FILE_PATH),"../");t&&Us.removeSync(t),Yi&&(aY?Us.readdirSync(Yi,{withFileTypes:!0}).forEach(n=>{let s=Ki.join(n.path,n.name);s!==$a[ae.INSTALL_PROMPTS.HDB_CONFIG]&&Us.removeSync(s)}):Us.removeSync(Yi)),process.exit(1)}a(epe,"rollbackInstall");async function dY(e,t){lr.trace("Creating admin user"),await vhe();let r;try{r=await Phe.addRole(e)}catch(n){if(n.message.includes("already exists"))t=void 0;else throw n.message+="Error creating role",n}if(t)try{t.role=r.role,await Dhe.addUser(t)}catch(n){throw n.message=`Error creating user - ${n}`,n}}a(dY,"createAdminUser");async function _Y(e){lr.trace("Creating Super user.");let t={role:"super_user",permission:{super_user:!0}},r={username:e[ae.INSTALL_PROMPTS.HDB_ADMIN_USERNAME].toString(),password:e[ae.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD].toString(),active:!0};await dY(t,r),delete e[ae.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],delete e[ae.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD]}a(_Y,"createSuperUser");async function tpe(e){lr.trace("Creating Cluster user.");let t;e[ae.INSTALL_PROMPTS.CLUSTERING_USER]&&e[ae.INSTALL_PROMPTS.CLUSTERING_PASSWORD]&&(t={username:e[ae.INSTALL_PROMPTS.CLUSTERING_USER].toString(),password:e[ae.INSTALL_PROMPTS.CLUSTERING_PASSWORD].toString(),active:!0}),await dY({role:"cluster_user",permission:{cluster_user:!0}},t),delete e[ae.INSTALL_PROMPTS.CLUSTERING_USER],delete e[ae.INSTALL_PROMPTS.CLUSTERING_PASSWORD]}a(tpe,"createClusterUser");async function rpe(){let e=oY.version();if(e)await iY.insertHdbInstallInfo(e);else throw new Error("The version is missing/removed from HarperDB package.json")}a(rpe,"insertHdbVersionInfo");function npe(e){$a[ae.INSTALL_PROMPTS.HDB_CONFIG]=e}a(npe,"updateConfigEnv");function spe(e){cY=e}a(spe,"setIgnoreExisting")});var pY=y((TMe,hY)=>{"use strict";var VI=ee(),Xn=V(),EY=LI();hY.exports={processDirectives:ipe};async function ipe(e){console.log("Starting upgrade process...");let t=EY.getVersionsForUpgrade(e),r=cpe(t),n=[],s=r.length;for(let i=0;i<s;i++){let o=r[i],c=`Running upgrade for version ${o.version}`;Xn.notify(c),console.log(c);let l=[],d=[];try{l=ope(o.sync_functions)}catch(u){throw Xn.error(`Error while running an upgrade script for ${o.version}`),u}try{d=await ape(o.async_functions)}catch(u){throw Xn.error(`Error while running an upgrade script for ${o.version}`),u}n.push(...l,...d)}return n}a(ipe,"processDirectives");function ope(e){if(VI.isEmptyOrZeroLength(e))return Xn.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return Xn.info("Passed parameter is not an array"),[];let t=[];for(let r of e){if(Xn.info(`Running function ${r.name}`),!(r instanceof Function)){Xn.info("Variable being processed is not a function");continue}let n=r();Xn.info(n),t.push(n)}return t}a(ope,"runSyncFunctions");async function ape(e){if(VI.isEmptyOrZeroLength(e))return Xn.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return Xn.info("Passed parameter is not an array"),[];let t=[],r=e.length;for(let n=0;n<r;n++){let s=e[n];if(Xn.info(`Running function ${s.name}`),!(s instanceof Function)){Xn.info("Variable being processed is not a function");continue}let i=await s();Xn.info(i),t.push(i)}return t}a(ape,"runAsyncFunctions");function cpe(e){if(VI.isEmptyOrZeroLength(e))return[];let t=[];for(let r of e){let n=EY.getDirectiveByVersion(r);n&&t.push(n)}return t}a(cpe,"getUpgradeDirectivesToInstall")});var WI=y((RMe,AY)=>{"use strict";var gT=te();gT.initSync();var gY=require("chalk"),mY=require("fs-extra"),Go=V(),ko=M(),SY=go(),lpe=pY(),YI=ee(),RY=vE(),upe=cT(),TY=Qg(),dpe=_s(),_pe=require("util").promisify,fpe=_pe(dpe.setSchemaDataToGlobal),KI,{UPGRADE_VERSION:RT}=ko.UPGRADE_JSON_FIELD_NAMES_ENUM;AY.exports={upgrade:Epe};async function Epe(e){await fpe(),KI===void 0&&(KI=Ku()),mY.existsSync(gT.get(gT.BOOT_PROPS_FILE_PATH))||(xE("The hdb_boot_properties file was not found. Please install HDB.",ko.LOG_LEVELS.ERROR),process.exit(1)),mY.existsSync(gT.get(ko.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))||(xE("The hdb settings file was not found. Please make sure HDB is installed.",ko.LOG_LEVELS.ERROR),process.exit(1));let t=e;t||(t=await RY.getVersionUpdateInfo(),t||(console.log("HarperDB version is current"),process.exit(0))),xE(`This version of HarperDB is ${SY.version()}`,ko.LOG_LEVELS.INFO);let r=t[RT]?t[RT]:SY.version();r||(console.log(`Current Version field missing from the package.json file. Cannot continue with upgrade. If you need support, please contact ${ko.HDB_SUPPORT_ADDRESS}`),Go.notify("Missing new version field from upgrade info object"),process.exit(1)),await hpe();let n,s=0;try{n=await upe.forceUpdatePrompt(t)}catch(i){Go.error("There was an error when prompting user about upgrade."),Go.error(i),n=!1,s=1}n||(console.log("Cancelled upgrade, closing HarperDB"),process.exit(s)),Go.info(`Starting upgrade to version ${r}`),await ppe(t),xE(`HarperDB was successfully upgraded to version ${t[RT]}`,ko.LOG_LEVELS.INFO)}a(Epe,"upgrade");async function hpe(){let e=!1,t=await TY.findPs(ko.HDB_PROC_NAME);if(YI.isEmptyOrZeroLength(t)||(e=!0),!e){let r=await TY.findPs("hdb_express");YI.isEmptyOrZeroLength(r)||(e=!0)}if(!e){let r=await KI.list();YI.isEmptyOrZeroLength(r)||(e=!0)}if(e){let r="HarperDB is running, please stop all HarperDB services with 'harperdb stop' and run the upgrade command again.";console.log(gY.red(r)),Go.error(r),process.exit(1)}}a(hpe,"checkIfRunning");async function ppe(e){try{await lpe.processDirectives(e)}catch(t){throw xE("There was an error during the data upgrade. Please check the logs.",ko.LOG_LEVELS.ERROR),t}try{await RY.insertHdbUpgradeInfo(e[RT])}catch(t){Go.error("Error updating the 'hdb_info' system table."),Go.error(t)}}a(ppe,"runUpgrade");function xE(e,t=void 0){t||(t=Go.info),Go[t](e),console.log(gY.magenta(e))}a(xE,"printToLogAndConsole")});var IY=y((bMe,NY)=>{"use strict";var{promises:QI,createReadStream:mpe,createWriteStream:Spe}=require("fs"),{createGzip:Tpe}=require("zlib"),{promisify:gpe}=require("util"),{pipeline:Rpe}=require("stream"),Ape=gpe(Rpe),bpe=require("path"),gl=te();gl.initSync();var Tl=V(),{CONFIG_PARAMS:FE,ITC_EVENT_TYPES:ype}=M(),{onMessageFromWorkers:Ope}=ut(),Npe=6e4,Ipe="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",wpe="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",jI,yY;NY.exports=OY;Ope(e=>{e.type===ype.RESTART&&(gl.initSync(!0),clearInterval(yY),gl.get(FE.LOGGING_ROTATION_ENABLED)&&OY())});async function OY(){try{let e=Tl.getLogFilePath(),t=gl.get(FE.LOGGING_ROTATION_MAXSIZE),r=gl.get(FE.LOGGING_ROTATION_INTERVAL);if(!t&&!r){Tl.error(Ipe);return}let n=gl.get(FE.LOGGING_ROTATION_PATH);if(!n){Tl.error(wpe);return}let s;if(t){let o=t.slice(-1),c=t.slice(0,-1);o==="G"?s=c*1e9:o==="M"?s=c*1e6:s=c*1e3}let i;if(r){let o=r.slice(-1),c=r.slice(0,-1);o==="D"?i=c*1440:o==="H"?i=c*60:i=c}jI=Date.now()/6e4,Tl.trace("Log rotate enabled, maxSize:",t,"interval:",r),yY=setInterval(async()=>{if(s){let o;o=await QI.stat(e),o.size>=s&&await bY(e,n)}i&&Date.now()/6e4-jI>=i&&(await bY(e,n),jI=Date.now()/6e4)},Npe).unref()}catch(e){Tl.error(e)}}a(OY,"logRotator");async function bY(e,t){let r=gl.get(FE.LOGGING_ROTATION_COMPRESS),n=bpe.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.${r?"log.gz":"log"}`);r?(await Ape(mpe(e),Tpe(),Spe(n)),await QI.unlink(e)):await QI.rename(e,n),Tl.closeLogFile(),Tl.notify(`hdb.log rotated, old log moved to ${n}`)}a(bY,"moveLogFile")});var Rl=y(UY=>{"use strict";var Se=te();Se.initSync();var OMe=Ca(),Xt=M(),di=V(),qo=require("fs-extra"),Va=require("path"),Cpe=require("systeminformation"),Dpe=AI(),{install:Ppe}=TT(),zI=require("chalk"),Lpe=Cc(),$o=ee(),JI=yt(),CY=Jo(),wY=Xm(),Mpe=WI(),Upe=IY(),{compactOnStart:vpe}=(oS(),ne(iS)),Bpe=require("minimist"),Hpe=Ss(),{PACKAGE_ROOT:xpe,CONFIG_PARAMS:Pe}=M(),{startHTTPThreads:Fpe,startSocketServer:NMe,mostIdleRouting:IMe,remoteAffinityRouting:wMe}=(XI(),ne(vY)),kpe=vE(),{isMainThread:Gpe}=require("worker_threads"),CMe=ao(),DMe=uo(),PMe=tb(),LMe=G_(),AT=M(),Wi,Td,DY=!1,qpe="Upgrade complete. Starting HarperDB.",$pe="Got an error while trying to upgrade your HarperDB instance. Exiting HarperDB.",Vpe="HarperDB not found, starting install process.",Ype="There was an error during install, check install_log.log for more details. Exiting.",Kpe="HarperDB successfully started.";function Wpe(){if(!DY){let e=a(()=>{qo.removeSync(Va.join(Se.get(Xt.CONFIG_PARAMS.ROOTPATH),Xt.HDB_PID_FILE)),process.exit(0)},"remove_hdb_pid");process.on("exit",()=>{e()}),process.on("SIGINT",()=>{e()}),process.on("SIGQUIT",()=>{e()}),process.on("SIGTERM",()=>{e()})}}a(Wpe,"addExitListeners");async function PY(e=!1,t=!1){if(console.log(zI.magenta("Starting HarperDB...")),di.suppressLogging?.(()=>{console.log(zI.magenta(""+qo.readFileSync(Va.join(xpe,"utility/install/ascii_logo.txt"))))}),await MY()===!1){console.log(Vpe);try{await Ppe()}catch(o){console.error(Ype,o),di.error(o),process.exit(1)}}if(!e){let o=CY(Object.keys(Xt.CONFIG_PARAM_MAP),!0);!$o.isEmpty(o)&&!$o.isEmptyOrZeroLength(Object.keys(o))&&JI.updateConfigValue(void 0,void 0,o,!0,!0)}let r,n=Td?.service==="clustering";Td?.service&&!n&&(console.error("Unrecognized service argument"),process.exit(1));try{let o=Number.parseInt(await qo.readFile(Va.join(Se.get(Xt.CONFIG_PARAMS.ROOTPATH),Xt.HDB_PID_FILE),"utf8")),c=await Cpe.processes();for(let l of c.list)if(l.pid===o){n?r=!0:console.log("HarperDB appears to be already running.");break}}catch{}Wi===void 0&&(Wi=Ku()),n&&(r||(console.error("HarperDB must be running to start clustering."),process.exit()),Se.get(Xt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY)||(console.error("Clustering must be setup and enabled in harperdb-config."),process.exit()),console.log("Starting clustering."),await wY.generateNatsConfig(),await Wi.startClusteringProcesses(!0),process.exit()),Wpe(),await qo.writeFile(Va.join(Se.get(AT.CONFIG_PARAMS.ROOTPATH),AT.HDB_PID_FILE),`${process.pid}`),di.info("HarperDB PID",process.pid);let s;try{let o=await kpe.getVersionUpdateInfo();o!==void 0&&(s=o[Xt.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION],await Mpe.upgrade(o),console.log(qpe))}catch(o){s?(console.error(`Got an error while trying to upgrade your HarperDB instance to version ${s}. Exiting HarperDB.`,o),di.error(o)):(console.error($pe,o),di.error(o)),process.exit(1)}Dpe(),zpe(),await Hpe.reviewSelfSignedCert(),$o.autoCastBoolean(Se.get(Xt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&Gpe&&await wY.generateNatsConfig(t)}a(PY,"initialize");async function jpe(e=!1){try{Td=Bpe(process.argv),Td.ROOTPATH&&JI.updateConfigObject("settings_path",Va.join(Td.ROOTPATH,Xt.HDB_CONFIG_FILE)),await PY(e,!0),Se.get(Xt.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await vpe();let t=process.env.IS_SCRIPTED_SERVICE&&!Td.service;$o.autoCastBoolean(Se.get(Xt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&(t||await Wi.startClusteringProcesses(),await Wi.startClusteringThreads()),await Fpe(process.env.DEV_MODE?1:Se.get(AT.CONFIG_PARAMS.THREADS_COUNT)??Se.get(AT.CONFIG_PARAMS.THREADS)),Se.get(Xt.CONFIG_PARAMS.LOGGING_ROTATION_ENABLED)&&await Upe(),t||LY()}catch(t){console.error(t),di.error(t),process.exit(1)}}a(jpe,"main");function LY(){di.suppressLogging(()=>{console.log(zI.magenta(`HarperDB ${Lpe.version} successfully started`))}),di.notify(Kpe)}a(LY,"started");async function Qpe(e=!0){DY=!e;try{Wi===void 0&&(Wi=Ku()),Wi.enterPM2Mode(),await PY(),$o.autoCastBoolean(Se.get(Xt.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&await Wi.startClusteringProcesses(),await Wi.startService(Xt.PROCESS_DESCRIPTORS.HDB),LY(),e&&process.exit(0)}catch(t){console.error(t),di.error(t),process.exit(1)}}a(Qpe,"launch");function zpe(){let e=Va.join(Se.get(Xt.CONFIG_PARAMS.ROOTPATH),Xt.LICENSE_KEY_DIR_NAME,Xt.LICENSE_FILE_NAME),t=Va.join(e,Xt.LICENSE_FILE_NAME),r=Va.join(e,Xt.REG_KEY_FILE_NAME);try{let{HARPERDB_FINGERPRINT:n,HARPERDB_LICENSE:s}=CY(["HARPERDB_FINGERPRINT","HARPERDB_LICENSE"]);if($o.isEmpty(n)||$o.isEmpty(s))return;qo.mkdirpSync(e),qo.writeFileSync(r,n),qo.writeFileSync(t,s)}catch(n){let s=`Failed to write license & fingerprint due to: ${n.message}`;console.error(s),di.error(s)}}a(zpe,"writeLicenseFromVars");Object.assign(UY,{launch:Qpe,main:jpe,isHdbInstalled:MY,startupLog:Jpe});async function MY(){try{await qo.stat($o.getPropsFilePath()),await qo.stat(Se.get(Xt.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}catch(e){if($o.noBootFile())return!0;if(e.code==="ENOENT")return!1;throw di.error(`Error checking for HDB install - ${e}`),e}return!0}a(MY,"isHdbInstalled");function Jpe(e){let r=a(E=>E.padEnd(20),"pad"),n=`
113
+ `;Se.get(Pe.REPLICATION_HOSTNAME)&&(n+=`${r("Hostname:")}${Se.get(Pe.REPLICATION_HOSTNAME)}
114
+ `),Se.get(Pe.REPLICATION_URL)&&(n+=`${r("Replication Url:")}${Se.get(Pe.REPLICATION_URL)}
115
+ `),n+=`${r("Worker Threads:")}${Se.get(Pe.THREADS_COUNT)}
116
+ `,n+=`${r("Root Path:")}${Se.get(Pe.ROOTPATH)}
117
+ `,Se.get(Pe.THREADS_DEBUG)!==!1&&(n+=`${r("Debugging:")}enabled: true`,n+=Se.get(Pe.THREADS_DEBUG_PORT)?`, TCP: ${Se.get(Pe.THREADS_DEBUG_PORT)}
118
+ `:`
119
+ `),n+=`${r("Logging:")}level: ${Se.get(Pe.LOGGING_LEVEL)}, location: ${Se.get(Pe.LOGGING_ROOT)}
120
+ `,n+=r("Default:"),n+=Se.get(Pe.HTTP_PORT)?`HTTP (and WS): ${Se.get(Pe.HTTP_PORT)}, `:"",n+=Se.get(Pe.HTTP_SECUREPORT)?`HTTPS (and WS): ${Se.get(Pe.HTTP_SECUREPORT)}, `:"",n+=`CORS: ${Se.get(Pe.HTTP_CORS)?`enabled for ${Se.get(Pe.HTTP_CORSACCESSLIST)}`:"disabled"}
121
+ `,n+=r("Operations API:"),n+=Se.get(Pe.OPERATIONSAPI_NETWORK_PORT)?`HTTP: ${Se.get(Pe.OPERATIONSAPI_NETWORK_PORT)}, `:"",n+=Se.get(Pe.OPERATIONSAPI_NETWORK_SECUREPORT)?`HTTPS: ${Se.get(Pe.OPERATIONSAPI_NETWORK_SECUREPORT)}, `:"",n+=`CORS: ${Se.get(Pe.OPERATIONSAPI_NETWORK_CORS)?`enabled for ${Se.get(Pe.OPERATIONSAPI_NETWORK_CORSACCESSLIST)}`:"disabled"}`,n+=`, unix socket: ${Se.get(Pe.OPERATIONSAPI_NETWORK_DOMAINSOCKET)}
122
+ `,n+=r("MQTT:"),n+=Se.get(Pe.MQTT_NETWORK_PORT)?`TCP: ${Se.get(Pe.MQTT_NETWORK_PORT)}, `:"",n+=Se.get(Pe.MQTT_NETWORK_SECUREPORT)?`TLS: ${Se.get(Pe.MQTT_NETWORK_SECUREPORT)}`:"",n+=Se.get(Pe.MQTT_WEBSOCKET)&&Se.get(Pe.HTTP_PORT)?`, WS: ${Se.get(Pe.HTTP_PORT)}`:"",n+=Se.get(Pe.MQTT_WEBSOCKET)&&Se.get(Pe.HTTP_SECUREPORT)?`, WSS: ${Se.get(Pe.HTTP_SECUREPORT)}
123
+ `:`
124
+ `;let s=Se.get(Pe.REPLICATION_PORT)??Se.get(Pe.OPERATIONSAPI_NETWORK_PORT),i=Se.get(Pe.REPLICATION_SECUREPORT)??Se.get(Pe.OPERATIONSAPI_NETWORK_SECUREPORT),o=r("Replication:");o+=s?`WS: ${s}, `:"",o+=i?`WSS: ${i} `:"",n+=`${o.slice(0,-2)}
125
+ `;let c=[],l=JI.getConfigObj();for(let E in l)l[E].package&&c.push(E);let d={},u=`${r("REST:")}`;for(let[E,f]of e)for(let h of f){let S=h.name;S==="rest"&&(u+=`${h.protocol_name}: ${E}, `),c.includes(S)&&(d[S]?d[S]+=`${h.protocol_name}: ${E}, `:d[S]=`${h.protocol_name}: ${E}, `)}u.length>21&&(u=u.slice(0,-2),n+=`${u}
126
+ `);let _=Se.get(Pe.HTTP_PORT)?`HTTP: ${Se.get(Pe.HTTP_PORT)}, `:"";_+=Se.get(Pe.HTTP_SECUREPORT)?`HTTPS: ${Se.get(Pe.HTTP_SECUREPORT)}, `:"",_.length>21&&(_=_.slice(0,-2));for(let E of c)d[E]?n+=`${r(E)}${d[E].slice(0,-2)}
127
+ `:n+=`${r(E)}${_}
128
+ `;console.log(n)}a(Jpe,"startupLog")});var cw=y(Ya=>{"use strict";var{isMainThread:ew,parentPort:$E,threadId:yT,workerData:Xpe}=require("worker_threads"),{Socket:Zpe,createServer:eme}=require("net"),{createServer:tme,IncomingMessage:rme}=require("http"),{createServer:nme}=require("https"),{unlinkSync:xY,existsSync:sme}=require("fs"),nn=V(),gt=te(),Zt=M(),{server:wT}=(Wr(),ne(ic)),{WebSocketServer:ime}=require("ws"),{createServer:ome}=require("node:tls"),{getTicketKeys:ame,restartNumber:cme,getWorkerIndex:gd}=ut(),{Headers:tw,appendHeader:lme}=(zf(),ne(bG)),{recordAction:kE,recordActionBinary:ume}=(Ci(),ne(Z_)),{Request:FY,createReuseportFd:qE}=(aT(),ne(gI)),{checkMemoryLimit:dme}=Rc(),{createTLSSelector:kY}=Ss(),{resolvePath:GY}=yt(),{startupLog:_me}=Rl(),qY=gt.get(Zt.CONFIG_PARAMS.THREADS_DEBUG);if(qY){let e;if(ew)e=gt.get(Zt.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){nn.info("Could not close debugger",t)}});else{let t=gt.get(Zt.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&gd()>=0&&(e=t+gd())}if(e){let t=gt.get(Zt.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=gt.get(Zt.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){nn.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&ew)try{require("inspector").open(9229)}catch(e){cme<=1&&nn.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.isHandled||e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:vMe,CONFIG_PARAMS:fme}=Zt;gt.initSync();var Eme=gt.get(fme.HTTP_SESSIONAFFINITY),ji={},rw=new Map;Ya.registerServer=ow;Ya.httpServer=aw;Ya.deliverSocket=iw;Ya.startServers=$Y;Ya.listenOnPorts=VY;Ya.when_components_loaded=null;wT.http=aw;wT.request=Sme;wT.socket=Tme;wT.ws=gme;var ZI={},GE={},hme,bT={},OT={},pme=[],nw=[];function $Y(){return Ya.when_components_loaded=CT().loadRootComponents(!0).then(()=>{$E?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)iw(n,r,s);else if(t.requestId)mme(t);else if(t.type===Zt.ITC_EVENT_TYPES.SHUTDOWN){nn.trace("received shutdown request",yT);for(let i in ji){let o=ji[i],c;if(o.closeIdleConnections){let d=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),u=0,_=setInterval(()=>{u++;let E=u>=100,f=o[d][E?"all":"idle"]();if(f.length===0){E&&clearInterval(_);return}u===1?nn.info(`Closing ${f.length} idle connections`):E&&nn.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,S=f.length;h<S;h++){let T=f[h].socket;T._httpMessage&&!T._httpMessage.finished&&!E||(E?T.destroySoon():T.end(`HTTP/1.1 408 Request Timeout\r
129
+ Connection: close\r
130
+ \r
131
+ `))}},25).unref()}o.close?.(()=>{if(gt.get(Zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&gd()==0)try{xY(GY(gt.get(Zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,yT),o.cantCleanupProperly||nn.warn("Had to forcefully exit the thread",yT),process.exit(0)},5e3).unref()})}if(qY||process.env.DEV_MODE)try{require("inspector").close()}catch(i){nn.info("Could not close debugger",i)}}}).ref();let e;qE&&!Eme&&(e=VY()),Promise.resolve(e).then(()=>{if(gd()===0)try{_me(rw)}catch(t){console.error("Error displaying start-up log",t)}$E?.postMessage({type:Zt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a($Y,"startServers");function VY(){let e=[];for(let t in ji){let r=ji[t];if(t.includes?.("/")&&gd()==0){sme(t)&&xY(t),e.push(new Promise((o,c)=>{r.listen({path:t},()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),nn.info("Domain socket listening on "+t)}).on("error",c)}));continue}let n,s=gt.get(Zt.CONFIG_PARAMS.HTTP_THREADRANGE);if(s){let o=typeof s=="string"?s.split("-"):s,c=gd();if(c<o[0]||c>o[1])continue}let i;try{let o=t.lastIndexOf(":");o>0?qE?n={fd:qE(+t.slice(o+1).replace(/[\[\]]/g,""),t.slice(0,o))}:n={host:+t.slice(o+1).replace(/[\[\]]/g,""),port:t.slice(0,o)}:qE?n={fd:qE(+t,"::")}:n={port:t}}catch(o){console.error(`Unable to bind to port ${t}`,o);continue}e.push(new Promise((o,c)=>{r.listen(n,()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),nn.trace("Listening on port "+t,yT)}).on("error",c)}))}return Promise.all(e)}a(VY,"listenOnPorts");!ew&&!Xpe.noServerStart&&$Y();function iw(e,t,r){let n=e?.read?e:new Zpe({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ji[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=ji[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(nn.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(iw,"deliverSocket");var BY=new Map;function mme(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=BY.get(s),r){case"connection":i=iw(void 0,t),BY.set(s,i),i.write=(c,l,d)=>($E.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),d&&d(),!0),i.end=(c,l,d)=>($E.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),d&&d(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),$E.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(mme,"proxyRequest");var{getComponentName:NT}=(rE(),ne(tE));function ow(e,t,r=!0){t||(t=gt.get(Zt.CONFIG_PARAMS.HTTP_PORT));let n=ji[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",HY),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ji[t]=e;e.on("unhandled",HY)}a(ow,"registerServer");function YY(e){let t=[],r=e?.securePort;return r&&t.push({port:r,secure:!0}),r=e?.port,r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],gt.get(Zt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:gt.get(Zt.CONFIG_PARAMS.HTTP_PORT),secure:gt.get(Zt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),gt.get(Zt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:gt.get(Zt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&gt.get(Zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:GY(gt.get(Zt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}a(YY,"getPorts");function aw(e,t){let r=[];for(let{port:n,secure:s}of YY(t))r.push(KY(n,s,t?.isOperationsServer)),typeof e=="function"?nw[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,ow(e,n,!1)),OT[n]=sw(nw,n),hme=sw(pme,n);return r}a(aw,"httpServer");function IT(e,t){let r=rw.get(e)??[];rw.set(e,[...r,t])}a(IT,"setPortServerMap");function KY(e,t,r){if(IT(e,{protocol_name:t?"HTTPS":"HTTP",name:NT()}),!bT[e]){let n=r?"operationsApi_network":"http",s={noDelay:!0,keepAliveTimeout:gt.get(n+"_keepAliveTimeout"),headersTimeout:gt.get(n+"_headersTimeout"),requestTimeout:gt.get(n+"_timeout"),highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600},i=gt.get(n+"_mtls"),o=gt.get(n+"_mtls_required");t&&Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!(i||r),ticketKeys:ame(),maxHeaderSize:gt.get(Zt.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:kY(r?"operations-api":"server",i),ALPNCallback:function(d){return d.protocols.includes("harperdb-replication")&&(this.isReplicationConnection=!0),"http/1.1"},ALPNProtocols:null});let c=dme(),l=bT[e]=(t?nme:tme)(s,async(d,u)=>{try{let E=performance.now(),f=new FY(d,u);r&&(f.isOperationsServer=!0);let h=await OT[e](f);if(!h){if(f._nodeResponse.statusCode)return;h=WY(f)}if(h.headers?.set||(h.headers=new tw(h.headers)),c?h.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):h.headers?.set?.("Server","HarperDB"),h.status===-1){for(let F of h.headers||[])u.setHeader(F[0],F[1]);return d.baseRequest=f,u.baseResponse=h,bT[e].emit("unhandled",d,u)}let S=h.status||200,T=performance.now(),g=T-E,m=h.body,C;if(!h.handlesHeaders){let F=h.headers||new tw;m?m.length>=0&&(typeof m=="string"?F.set("Content-Length",Buffer.byteLength(m)):F.set("Content-Length",m.length),C=!0):(F.set("Content-Length","0"),C=!0);let Y=`hdb;dur=${g.toFixed(2)}`;h.wasCacheMiss&&(Y+=", miss"),lme(F,"Server-Timing",Y,!0),u.writeHead(S,F&&(F[Symbol.iterator]?Array.from(F):F)),C&&u.end(m)}let O=f.handlerPath,x=f.method;if(kE(g,"duration",O,x,h.wasCacheMiss==null?void 0:h.wasCacheMiss?"cache-miss":"cache-hit"),ume(S<400,"success",O,x),!C)if(m?.pipe){m.pipe(u),m.destroy&&u.on("close",()=>{m.destroy()});let F=0;m.on("data",Y=>{F+=Y.length}),m.on("end",()=>{kE(performance.now()-T,"transfer",O,x),kE(F,"bytes-sent",O,x)})}else m?.then?m.then(F=>{u.end(F)},_):u.end(m)}catch(E){_(E)}function _(E){let f=E.headers;u.writeHead(E.statusCode||500,f&&(f[Symbol.iterator]?Array.from(f):f)),u.end(E.toString()),E.statusCode?E.statusCode===500?nn.warn(E):nn.info(E):nn.error(E)}a(_,"onError")});t&&(l.ports||(l.ports=[]),l.ports.push(e),s.SNICallback.initialize(l),i&&(l.mtlsConfig=i),l.on("secureConnection",d=>{d._parent.startTime&&kE(performance.now()-d._parent.startTime,"tls-handshake",e),kE(d.isSessionReused(),"tls-reused",e)}),l.isSecure=!0),ow(l,e)}return bT[e]}a(KY,"getHTTPServer");function sw(e,t){let r=WY;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(sw,"makeCallbackChain");function WY(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new tw}}a(WY,"unhandled");function Sme(e,t){aw(e,{requestOnly:!0,...t})}a(Sme,"onRequest");function Tme(e,t){let r;if(t.securePort){IT(t.securePort,{protocol_name:"TLS",name:NT()});let n=kY("server",t.mtls);r=ome({rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,SNICallback:n},e),n.initialize(r),ji[t.securePort]=r}return t.port&&(IT(t.port,{protocol_name:"TCP",name:NT()}),r=eme(e,{noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600}),ji[t.port]=r),r}a(Tme,"onSocket");Object.defineProperty(rme.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 gme(e,t){let r=[];for(let{port:n,secure:s}of YY(t)){if(IT(n,{protocol_name:s?"WSS":"WS",name:NT()}),!GE[n]){let c;GE[n]=new ime({server:c=KY(n,s,t?.isOperationsServer)}),c._ws=GE[n],r.push(c),GE[n].on("connection",async(l,d)=>{try{let u=new FY(d);u.isWebSocket=!0;let _=OT[n](u),E=d.headers["sec-websocket-protocol"],f=ZI[n],h;if(E){for(let S=0;S<f.length;S++){let T=f[S];T.protocol===E&&(h=!0,T.listener(l,u,_))}if(h)return}for(let S=0;S<f.length;S++){let T=f[S];T.protocol||(T.listener(l,u,_),h=!0)}h||l.close(1008,"No handler for protocol")}catch(u){nn.warn("Error handling WebSocket connection",u)}}),GE[n].on("error",l=>{console.log("Error in setting up WebSocket server",l)})}let i=t?.subProtocol||"",o=ZI[n];o||(o=ZI[n]=[]),o.push({listener:e,protocol:i}),OT[n]=sw(nw,n)}return r}a(gme,"onWebSocket");function HY(e,t){t.writeHead(404),t.end(`Not found
132
+ `)}a(HY,"defaultNotFound")});var vY={};tt(vY,{startHTTPThreads:()=>Ame,startSocketServer:()=>fw,updateWorkerIdleness:()=>tK});async function Ame(e=2,t){try{if(t)dw(0,1,!0);else{let{loadRootComponents:r}=CT();if(e===0)return(0,vs.setMainIsWorker)(!0),await cw().startServers(),Promise.resolve([]);await r()}eK();for(let r=0;r<e;r++)dw(r,e);return Promise.all(ZY)}finally{(0,vs.threadsHaveStarted)()}}function eK(){let e=(0,JY.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),uw=setInterval(()=>{LT.notify(e)},Rme).unref())}function dw(e,t=1,r){if(lw++,(0,vs.startWorker)("server/threads/threadServer.js",{name:Od.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(d){d.type===Od.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});ZY.push(s),await s,Rd.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=PT.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Rd.indexOf(n);o>-1&&Rd.splice(o,1)}if(a(i,"removeWorker"),Ad){let o=Ad;Ad=[];for(let c of o)XY[c.localPort](null,c)}}}),r){let n=setInterval(()=>{_w?_w=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,vs.shutdownWorkers)(),lw=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function fw(e=0,t){if(typeof e=="string")try{(0,MT.existsSync)(e)&&(0,MT.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=bme:r=yme(t):r=Ew;let n=(0,bd.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=XY[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),_w=!0,r(o,(c,l)=>{if(!c){if(jY){let u=o._socket||new bd.Socket({handle:o,writable:!0,readable:!0});jY.deliverSocket(u,e,l),u.resume()}else lw>0?(Ad.length===0&&setTimeout(()=>{Ad.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,Ad.push(o)):(console.log("start up a dynamic thread to handle request"),dw(0));Rr(!1,"socket-routed");return}c.requests++;let d=o.fd;if(d>=0)c.postMessage({port:e,fd:d,data:l});else{let u=o._socket||new bd.Socket({handle:o,writable:!0,readable:!0});Ime(u,c,e)}Rr(!0,"socket-routed")})};let s=Cc();LT.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 Ew(e,t){let r,n=0;for(let s of Rd){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=DT)return DT=i,t(r);n=i}DT=0,t(r)}function bme(e,t){let r={};e.getpeername(r);let n=r.address,s=yd.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);Ew(e,o=>{yd.set(n,{worker:o,lastUsed:i}),t(o)})}function yme(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new bd.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let l=o.toString("latin1").match(t)?.[1],d=yd.get(l),u=Date.now();if(d&&d.worker.threadId!==-1)return d.lastUsed=u,s(d.worker);Ew(n,_=>{yd.set(l,{worker:_,lastUsed:u}),s(_,o)})})}a(r,"findByHeaderAffinity")}function tK(){DT=0;for(let e of Rd)e.expectedIdle=e.recentELU.idle+Ome,e.requests=1;Rd.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Ime(e,t,r){let n=Nme++;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(),PT.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")),PT.delete(n)),s.event=="destroy"&&(e.destroy(),PT.delete(n))})}var vs,bd,Od,LT,MT,zY,JY,Rd,Ad,XY,jY,lw,ZY,uw,Rme,_w,DT,QY,yd,Ome,PT,Nme,XI=Ce(()=>{vs=B(ut()),bd=require("net"),Od=B(M()),LT=B(V()),MT=require("fs");Ci();zY=require("worker_threads"),JY=B(Rc()),Rd=[],Ad=[],XY=[],lw=0,ZY=[];zY.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,vs.onMessageFromWorkers)(e=>{e.type===Od.ITC_EVENT_TYPES.RESTART&&uw&&(clearInterval(uw),eK())}));Rme=6e5;a(Ame,"startHTTPThreads");a(eK,"licenseWarning");a(dw,"startHTTPWorker");a(fw,"startSocketServer");DT=0;a(Ew,"findMostIdleWorker");QY=36e5,yd=new Map;a(bme,"findByRemoteAddressAffinity");a(yme,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of yd)r.lastUsed+QY<e&&yd.delete(t)},QY).unref();Ome=1e3;a(tK,"updateWorkerIdleness");(0,vs.setMonitorListener)(tK);PT=new Map,Nme=1;a(Ime,"proxySocket")});var iK=y((YMe,sK)=>{"use strict";var wme=require("cluster"),Al=te();Al.initSync();var nK=M(),kMe=require("util"),Vo=V(),GMe=require("fs"),Cme=require("fastify"),qMe=Cc(),Dme=require("@fastify/cors"),Pme=require("@fastify/compress"),Lme=require("@fastify/static"),Mme=vN(),Ume=require("path"),{PACKAGE_ROOT:vme}=M(),Bme=_s(),Hme=ee(),xme=_n(),Fme=Rc(),{server:kme}=(Wr(),ne(ic)),{node_request_key:$Me}=(aT(),ne(gI)),{authHandler:Gme,handlePostRequest:qme,serverErrorHandler:$me,reqBodyValidationHandler:Vme}=iT(),VMe=require("net"),{registerContentHandlers:Yme}=(Ju(),ne(t$)),Kme=6e4,Wme=1024*1024*1024,jme="TRUE",{CONFIG_PARAMS:VE}=nK,Nd;sK.exports={hdbServer:rK,start:rK};async function rK(e){try{Vo.debug("In Fastify server"+process.cwd()),Vo.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vo.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=wme.isMaster,await Qme();let t=e.securePort>0;Nd=zme(t),await Nd.ready(),e||(e={}),e.isOperationsServer=!0;try{kme.http(Nd.server,e),Nd.server.closeIdleConnections||await Nd.listen({port:0,host:"::"})}catch(r){throw Nd.close(),Vo.error(r),Vo.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vo.fatal(t),process.exit(1)}}a(rK,"operationsServer");async function Qme(){Vo.trace("Configuring HarperDB process."),Bme.setSchemaDataToGlobal(),await xme.setUsersToGlobal(),await Fme.getLicense()}a(Qme,"setUp");function zme(e){Vo.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Jme(e),r=Cme(t);r.server.headersTimeout=Zme(),r.setErrorHandler($me);let n=Xme();n&&r.register(Dme,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,d){r.server.emit("unhandled",l.raw,d.raw)}),c()}),r.register(Mme),r.register(Pme),r.register(Lme,{root:Ume.join(vme,"studio/build-local")}),Yme(r);let s=Al.get(nK.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Hme.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Vme,Gme],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),qme(i,o)}),r.get("/health",()=>"HarperDB is running."),Vo.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(zme,"buildServer");function Jme(e){let t=Al.get(VE.OPERATIONSAPI_NETWORK_TIMEOUT),r=Al.get(VE.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Wme,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Jme,"getServerOptions");function Xme(){let e=Al.get(VE.OPERATIONSAPI_NETWORK_CORS),t=Al.get(VE.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===jme)&&(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(Xme,"getCORSOpts");function Zme(){return Al.get(VE.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Kme}a(Zme,"getHeaderTimeoutConfig")});var gw={};tt(gw,{disableNATS:()=>tSe,publishToStream:()=>BT,setNATSReplicator:()=>hw,setPublishToStream:()=>rSe,setSubscription:()=>Tw,start:()=>eSe});function eSe(){YE.default.get(KE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&sSe()}function tSe(e=!0){uK=e}function rSe(e,t){BT=e,Tw=t}function sSe(){if(uK||process.env._DISABLE_NATS)return;let e=ft(),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];hw(s,r,i)}}Gc((r,n)=>{hw(r.tableName,r.databaseName,r),n&&_K(r)}),!oK&&(oK=!0)}function hw(e,t,r){if(t==="system"&&iSe.includes(e))return;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 wr{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[ze],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[ze]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[ze],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[ze],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[ze]})}static defineSchema(i){_K(i)}static subscribe(){let i=new Mn;return Tw(t,e,i),i}static subscribeOnThisThread(i){return i<(YE.default.get(KE.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??nSe)}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 UT(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=dK;return i}a(n,"getNATSTransaction")}function _K(e){let t=YE.default.get(KE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);BT(`${mw.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,Sw.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 aK,mw,Sw,cK,lK,YE,KE,vT,uK,BT,Tw,nSe,dK,oK,iSe,UT,pw,fK=Ce(()=>{De();ls();aK=B(nr()),mw=B(At()),Sw=B(lo());kl();cK=B(xb()),lK=B(an()),YE=B(te()),KE=B(M()),vT=B(V());a(eSe,"start");a(tSe,"disableNATS");BT=aK.publishToStream,Tw=cK.setSubscription;a(rSe,"setPublishToStream");nSe=2;a(sSe,"assignReplicationSource");iSe=["hdb_job","hdb_analytics","hdb_raw_analytics","hdb_info","hdb_license"];a(hw,"setNATSReplicator");a(_K,"publishSchema");UT=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=YE.default.get(KE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],l,d;for(let u of i){let _=u.table,E=u.operation=="put"?"upsert":u.operation;l||(vT.trace(`Sending transaction event ${E}`),d=l={operation:E,schema:s,table:_,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,E!=="delete"&&E!=="invalidate"&&(l.records=o)),l.table===_&&l.operation===E?(o.push(u.record),c.push(u.id)):d=d.next={operation:E,table:_,id:u.id,record:u.record},u.expiresAt&&(d.expiresAt=u.expiresAt)}l&&n.push(BT(`${mw.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,Sw.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(u=>{throw vT.error("An error has occurred trying to replicate transaction",l,u),u.statusCode=504,u}))}return Promise.all(n)}},pw=class extends UT{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,lK.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};dK=new pw});async function SK({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await Rw.get(e,{returnNonexistent:!0});i=new yw(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await Rw.get(e);o&&o.delete()}i=new xT(e,t)}return n&&(n.id=e,n.user={username:t?.username},WE.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function Aw(){return HT++,HT>65500&&(HT=1),HT}function bw(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=da.getMatch(n,"mqtt");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 wt(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var hK,Ka,pK,mK,EK,Rw,WE,HT,xT,yw,TK=Ce(()=>{De();lf();hK=B(an()),Ka=B(V());Ic();pK=B(ut()),mK=B(cw());Wr();EK=100,Rw=dt({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"}]}}]}),WE=dt({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,pK.getWorkerIndex)()===0&&(async()=>{await mK.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of WE.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await nt.getUser(r.user.username));try{await bw(r,t,r)}catch{(0,Ka.warn)("Failed to publish will",t)}WE.delete(e.id)}})();a(SK,"getSession");HT=1;a(Aw,"getNextMessageId");xT=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;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("?"),l,d;if(c>-1?(l=s.slice(c),d=s.slice(0,c)):d=s,!d)throw new Error("No topic provided");if(d.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let u=this.subscriptions.find(g=>g.topic===s),_;u?(_=i>0,u.end(),this.subscriptions.splice(this.subscriptions.indexOf(u),1)):_=i===2;let E={search:l,async:!0,user:this.user,startTime:o,omitCurrent:_,url:""};o&&(0,Ka.trace)("Resuming subscription from",s,"from",o);let f=da.getMatch(d,"mqtt");if(!f){let g=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw g.statusCode=404,g}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let g=E.url.slice(1);if(g.indexOf("#")>-1&&g.indexOf("#")!==g.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,g.indexOf("+")===g.length-1)E.onlyChildren=!0,E.url="/"+g.slice(0,g.length-1);else{let m=g.split("/"),C;for(let F=0;F<m.length;F++)if(m[F].indexOf("+")>-1)if(m[F]==="+")C=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&C)throw new Error("Filters can not be combined");let O=!0;m[m.length-1]==="#"&&(m.length--,O=!1),C&&(n=a(F=>{let Y=F.id;if(!Array.isArray(Y)||O&&Y.length!==m.length)return!1;for(let $=0;$<m.length;$++)if(m[$]!=="+"&&m[$]!==Y[$])return!1;return!0},"filter"));let x=m.indexOf("+");E.url="/"+(x>-1?m.slice(0,x):m).concat("").join("/")}}let h=f.path,S=f.Resource,T=await wt(E,async()=>{let g=this.createContext();g.topic=s,g.retainHandling=i;let m=await S.subscribe(E,g);if(!m)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!m[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let C=(async()=>{for await(let O of m)try{let x;if(O.type&&O.type!=="put"&&O.type!=="delete"&&O.type!=="message"&&O.type!=="patch"||n&&!n(O))continue;r?(O.topic=s,x=this.needsAcknowledge(O)):(O.acknowledge?.(),x=Aw());let F=O.id;if(Array.isArray(F)&&(F=fu(F)),F==null&&(F=""),await this.listener(h+"/"+F,O.value,x,t)===!1)break;this.awaitingAcks?.size>EK?await new Promise($=>setTimeout($,this.awaitingAcks.size-EK)):await new Promise(setImmediate)}catch(x){(0,Ka.warn)(x)}})();return m});return T.topic=s,T.qos=t.qos,this.subscriptions.push(T),T}resume(){}needsAcknowledge(t){let r=Aw();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 bw(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){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();wt(r,async()=>{try{if(!t){let n=await WE.get(this.sessionId);n?.doesExist()&&await bw(n,n.data,r)}}finally{await WE.delete(this.sessionId)}}).catch(n=>{(0,Ka.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(bw,"publish");yw=class extends xT{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=Aw(),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);if(!r)return;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,Ka.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,hK.getNextMonotonicTime)()),(0,Ka.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),Rw.put(this.sessionRecord)}}});var Nw={};tt(Nw,{bypassAuth:()=>oSe,start:()=>aSe});function oSe(){yK=!0}function aSe({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new bK.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((d,u,_)=>{if(d.protocol==="mqtt"){o.events.emit("connection",d),kr.debug?.("Received WebSocket connection for MQTT from",d._socket.remoteAddress);let{onMessage:E,onClose:f}=RK(d,h=>{d.send(h)},u,Promise.resolve(_).then(()=>u?.user),o);d.on("message",E),d.on("close",f),d.on("error",h=>{kr.info?.("WebSocket error",h)})}},{subProtocol:"mqtt",...n})),(t||s)&&c.push(e.socket(async d=>{let u;if(o.events.emit("connection",d),kr.debug?.(`Received ${d.getCertificate?"SSL":"TCP"} connection for MQTT from ${d.remoteAddress}`),l){if(d.authorized)try{let f=l.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=d.getPeerCertificate().subject.CN);try{u=await e.getUser(f,null,null),(0,Id.get)(Gr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&kT.notify?.({username:u?.username,status:Gr.AUTH_AUDIT_STATUS.SUCCESS,type:Gr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:d.remoteAddress})}catch(h){throw(0,Id.get)(Gr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&kT.error?.({username:f,status:Gr.AUTH_AUDIT_STATUS.FAILURE,type:Gr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:d.remoteAddress}),h}}else kr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",d.remoteAddress)}catch(f){o.events.emit("error",f,d),kr.error?.(f)}else if(l.required)return kr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${d.authorizationError}`),d.end()}!u&&yK&&d.remoteAddress.includes("127.0.0.1")&&(u=await(0,AK.getSuperUser)(),kr.debug?.("Auto-authorizing local connection",u?.username));let{onMessage:_,onClose:E}=RK(d,f=>d.write(f),null,u,o);d.on("data",_),d.on("close",E),d.on("error",f=>{kr.info?.("Socket error",f)})},{port:t,securePort:s,mtls:l})),c}function RK(e,t,r,n,s){gK||(gK=!0,X_(_=>{FT>0&&_.push({metric:"mqtt-connections",connections:FT,byThread:!0})}));let i;FT++;let o,c={protocolVersion:4},l=(0,GT.parser)({protocolVersion:5});function d(_){l.parse(_)}a(d,"onMessage");function u(){FT--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Vn(!1,"connection","mqtt","disconnect"),kr.debug?.("MQTT connection was closed",e.remoteAddress))}return a(u,"onClose"),l.on("packet",async _=>{n?.then&&(n=await n),o?.then&&await o;let E=_.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;Rr(_.length,"bytes-received",h,T(_),"mqtt");try{switch(o?.receivedPacket?.(),_.cmd){case"connect":if(c.protocolVersion=_.protocolVersion,_.username)try{n=await nt.getUser(_.username,_.password.toString(),r),(0,Id.get)(Gr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&kT.notify?.({username:n?.username,status:Gr.AUTH_AUDIT_STATUS.SUCCESS,type:Gr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch($){return(0,Id.get)(Gr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&kT.error?.({username:_.username,status:Gr.AUTH_AUDIT_STATUS.FAILURE,type:Gr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",_,e,$),Vn(!1,"connection","mqtt","connect"),S({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",_,e),Vn(!1,"connection","mqtt","connect"),S({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(_,n),_.will){let $=e.deserialize||(e.deserialize=il(r?.headers.get?.("content-type")));_.will.data=_.will.payload?.length>0?$(_.will.payload):void 0,delete _.will.payload}o=SK({user:n,..._}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch($){return kr.error?.($),s.events.emit("auth-failed",_,e,$),Vn(!1,"connection","mqtt","connect"),S({cmd:"connack",reasonCode:$.code||5,returnCode:$.code||128})}s.events.emit("connected",o,e),Vn(!0,"connection","mqtt","connect"),S({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener(($,Z,Q,_e)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",$);let K=$.indexOf("/",1),ie=K>0?$.slice(0,K):$;S({cmd:"publish",topic:$,payload:g(Z),messageId:Q||Math.floor(Math.random()*1e8),qos:_e.qos},ie);let le=e._socket??e;return le.writableNeedDrain?new Promise(we=>le.once("drain",we)):!le.closed}catch(K){return kr.error?.(K),o?.disconnect(),s.sessions.delete(o),!1}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let m=[];for(let $ of _.subscriptions){let Z;try{Z=(await o.addSubscription($,$.qos>=1)).qos||0}catch(Q){s.events.emit("error",Q,e,$,o),kr.error?.(Q),Z=c.protocolVersion<5?128:Q.statusCode===403?135:Q.statusCode===404?143:128}m.push(Z)}await o.committed,S({cmd:"suback",granted:m,messageId:_.messageId});break;case"unsubscribe":{let $=[];for(let Z of _.unsubscriptions)$.push(o.removeSubscription(Z)?0:17);S({cmd:"unsuback",granted:$,messageId:_.messageId});break}case"pubrel":S({cmd:"pubcomp",messageId:_.messageId,reasonCode:0});return;case"publish":let C=_.qos===2?"pubrec":"puback",O=e.deserialize||(e.deserialize=il(r?.headers.get?.("content-type"))),F=(_.payload?.length||0)>0?O(_.payload):void 0,Y;try{Y=await o.publish(_,F)}catch($){s.events.emit("error",$,e,_,o),kr.warn?.($),_.qos>0&&S({cmd:C,messageId:_.messageId,reasonCode:128},_.topic);break}_.qos>0&&S({cmd:C,messageId:_.messageId,reasonCode:Y===!1?144:0},_.topic);break;case"pubrec":S({cmd:"pubrel",messageId:_.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(_.messageId);break;case"pingreq":S({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Vn(!0,"connection","mqtt","disconnect"),kr.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(m){s.events.emit("error",m,e,_,o),kr.error?.(m),S({cmd:"disconnect"})}function S(m,C){let O=(0,GT.generate)(m,c);t(O),Rr(O.length,"bytes-sent",C,T(m),"mqtt")}a(S,"sendPacket");function T(m){return m.qos>0?m.cmd+",qos="+m.qos:m.cmd}a(T,"packetMethodName");function g(m){return el(m,r)}a(g,"serialize")}),l.on("error",_=>{kr.warn("MQTT parsing error, closing connection:",_.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:d,onClose:u}}var GT,AK,Id,Gr,Ow,bK,kT,kr,yK,gK,FT,OK=Ce(()=>{GT=require("mqtt-packet");TK();AK=B(_n());Ju();Ci();Wr();Id=B(te()),Gr=B(M()),Ow=B(du()),bK=require("events"),kT=(0,Ow.loggerWithTag)("auth-event"),kr=(0,Ow.loggerWithTag)("mqtt"),yK=(0,Id.get)(Gr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(oSe,"bypassAuth");a(aSe,"start");FT=0;a(RK,"onSocket")});var tE={};tt(tE,{component_errors:()=>Cd,getComponentName:()=>_Se,loadComponent:()=>$T,loadComponentDirectories:()=>MK,setErrorReporter:()=>dSe});function MK(e,t){t&&(ww=t),e&&(Cw=e);let r=[];if((0,Nt.existsSync)(Iw)){let s=(0,Nt.readdirSync)(Iw,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ut.join)(Iw,o);r.push($T(c,ww,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push($T(n,ww,n,!1,null,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{LK=!0})}function dSe(e){jE=e}async function $T(e,t,r,n,s,i){let o=(0,Nt.realpathSync)(e);if(!IK.has(o)){IK.set(o,!0),s&&(Cw=s);try{let c;n&&(Cd=new Map);let l=(0,Ut.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Nt.existsSync)(l)?c=n?(0,VT.getConfigObj)():(0,wK.parseDocument)((0,Nt.readFileSync)(l,"utf8")).toJSON():c=Dw;let d=(0,Ut.join)(e,"node_modules","harperdb");try{bl.isMainThread&&(n||(0,Nt.existsSync)(d)&&(0,Nt.realpathSync)(Pd.PACKAGE_ROOT)!==(0,Nt.realpathSync)(d))&&((0,Nt.rmSync)(d,{recursive:!0,force:!0}),(0,Nt.existsSync)((0,Ut.join)(e,"node_modules"))||(0,Nt.mkdirSync)((0,Ut.join)(e,"node_modules")),(0,Nt.symlinkSync)(Pd.PACKAGE_ROOT,d,"dir"))}catch(E){wd.default.error("Error symlinking harperdb module",E)}let u=qT,_=n;for(let E in c){qT=E;let f=c[E];if(Cd.set(n?E:(0,Ut.basename)(e),!1),!f)continue;let h,S=f.package;try{if(S){let O=e,x;for(;!(0,Nt.existsSync)(x=(0,Ut.join)(O,"node_modules",E));)if(O=(0,Ut.dirname)(O),O.length<(0,PK.getHdbBasePath)().length){x=null;break}if(x)h=await $T(x,t,r,!1),_=!0;else throw new Error(`Unable to find package ${E}:${S}`)}else h=uSe[E];if(!h)continue;let T=a(O=>(O.origin=r,dt(O)),"ensureTable"),g=f.network||(f.port||f.securePort)&&f,m=g?.securePort||g?.https&&g.port,C=!g?.https&&g?.port;if(bl.isMainThread&&(h=await h.startOnMainThread?.({server:nt,ensureTable:T,port:C,securePort:m,resources:t,...f})||h,n&&g))for(let O of[C,m])try{if(+O&&!NK.includes(O)){let x=Pw.get(Pd.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);x&&wd.default.warn("Session affinity is not recommended and may cause memory leaks"),(x||!oT)&&(NK.push(O),fw(O,x))}}catch(x){console.error("Error listening on socket",O,x,E)}if(t.isWorker&&(h=await h.start?.({server:nt,ensureTable:T,port:C,securePort:m,resources:t,...f})||h),Cw.set(h,!0),(h.handleFile||h.handleDirectory||h.setupFile||h.setupDirectory)&&f.files!=null){if(f.files.includes(".."))throw(0,DK.handleHDBError)("Can not reference parent directories");let O=(0,Ut.join)(e,f.files).replace(/\\/g,"/"),x=O.indexOf("/*");if(x>-1&&f.files!==Dw[E]?.files&&!(0,Nt.existsSync)(O.slice(0,x)))throw new Error(`The path '${O.slice(0,x)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let F=(0,Ut.basename)(e),Y=f.path||"/";Y=Y.startsWith("/")?Y:Y.startsWith("./")?"/"+F+Y.slice(2):Y==="."?"/"+F:"/"+F+"/"+Y;let $,Z,Q;if(f.root){let K=f.root;K.startsWith("/")&&(K=K.slice(1)),K.endsWith("/")&&(K=K.slice(0,-1)),K+="/",Z=(0,Ut.join)(e,K)}else(Q=O.indexOf("/*"))>-1&&(Z=O.slice(0,Q+1),$=(0,Ut.relative)(e,Z));let _e=!1;if(bl.isMainThread&&h.setupDirectory&&(_e=await h.setupDirectory?.(Y,Z,t)),t.isWorker&&h.handleDirectory&&(_e=await h.handleDirectory?.(Y,Z,t)),_e)continue;for(let K of await(0,CK.default)(O,{onlyFiles:!1,objectMode:!0})){let{path:ie,dirent:le}=K;_=!0;let we=(0,Ut.relative)(e,ie).replace(/\\/g,"/");if($)if(we.startsWith($))we=we.slice($.length+1);else throw new Error(`The root path '${f.root}' does not reference a valid part of the file path '${we}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let ve=Y+(Y.endsWith("/")?"":"/")+we;try{if(le.isFile()){let et=await lSe(ie);bl.isMainThread&&await h.setupFile?.(et,ve,ie,t),t.isWorker&&await h.handleFile?.(et,ve,ie,t)}else bl.isMainThread&&await h.setupDirectory?.(ve,ie,t),t.isWorker&&await h.handleDirectory?.(ve,ie,t)}catch(et){et.message=`Could not load ${le.isFile()?"file":"directory"} '${ie}'${f.module?" using '"+f.module+"'":""} for application '${e}' due to: ${et.message}`,jE?.(et),((0,Dd.getWorkerIndex)()===0?console:wd.default).error(et),t.set(f.path||"/",new ua(et)),Cd.set(n?E:(0,Ut.basename)(e),et.message)}}}}catch(T){T.message=`Could not load component '${E}' for application '${(0,Ut.basename)(e)}' due to: ${T.message}`,jE?.(T),((0,Dd.getWorkerIndex)()===0?console:wd.default).error(T),t.set(f.path||"/",new ua(T),null,!0),Cd.set(n?E:(0,Ut.basename)(e),T.message)}}if(qT=u,bl.isMainThread&&!LK&&i&&(0,Dd.watchDir)(e,async()=>MK()),c.extensionModule)return await Uh((0,Ut.join)(e,c.extensionModule));if(!_&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;jE?.(new Error(E)),((0,Dd.getWorkerIndex)()===0?console:wd.default).error(E),Cd.set((0,Ut.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,jE?.(c),t.set("",new ua(c))}}}var Nt,Ut,bl,wK,Pw,Pd,CK,Dd,wd,DK,PK,cSe,VT,lSe,Iw,Cw,LK,ww,Cd,uSe,Dw,NK,IK,jE,qT,_Se,rE=Ce(()=>{Nt=require("fs"),Ut=require("path"),bl=require("worker_threads"),wK=require("yaml"),Pw=B(te()),Pd=B(M());UD();xD();FD();h$();a1();f1();CK=B(require("fast-glob")),Dd=B(ut()),wd=B(V());rR();Wr();DK=B(ce());De();XI();PK=B(te()),cSe=B(iK());fS();fK();hs();OK();VT=B(yt());aT();Jb();({readFile:lSe}=Nt.promises),Iw=(0,VT.resolvePath)(Pw.get(Pd.CONFIG_PARAMS.COMPONENTSROOT)),Cw=new Map,Cd=new Map;a(MK,"loadComponentDirectories");uSe={REST:FS,rest:FS,graphqlSchema:tR,jsResource:sR,fastifyRoutes:hI,login:oR,static:pI,operationsApi:cSe,customFunctions:{},http:{},clustering:gw,replication:ma,authentication:Jf,mqtt:Nw},Dw={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(Dw,"static",{value:{files:"web/**"}});NK=[],IK=new Map;a(dSe,"setErrorReporter");_Se=a(()=>qT,"getComponentName");a($T,"loadComponent")});var CT=y((TUe,vK)=>{var{isMainThread:UK}=require("worker_threads"),{getTables:fSe,getDatabases:mUe,table:SUe}=(De(),ne(at)),{loadComponentDirectories:ESe,loadComponent:hSe}=(rE(),ne(tE)),{resetResources:pSe}=(lf(),ne(xB)),mSe=JO(),SSe=yt(),{dirname:TSe}=require("path"),{getConnection:gSe}=nr(),RSe=te(),{CONFIG_PARAMS:ASe}=M(),{loadCertificates:bSe}=Ss(),Lw=new Map;async function ySe(e=!1){!UK&&RSe.get(ASe.CLUSTERING_ENABLED)&&gSe();try{UK&&await mSe()}catch(n){console.error(n)}let t=pSe();fSe(),t.isWorker=e,await bSe(),await hSe(TSe(SSe.getConfigFilePath()),t,"hdb",!0,Lw),await ESe(Lw,t);let r=[];for(let[n]of Lw)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(ySe,"loadRootComponents");vK.exports.loadRootComponents=ySe});var ut=y((RUe,_i)=>{"use strict";var{Worker:OSe,MessageChannel:NSe,parentPort:Qi,isMainThread:Hw,threadId:ISe,workerData:zi}=require("worker_threads"),{PACKAGE_ROOT:wSe}=M(),{join:FK,isAbsolute:CSe,extname:DSe}=require("path"),{server:kK}=(Wr(),ne(ic)),{watch:PSe,readdir:LSe}=require("fs/promises"),{totalmem:BK}=require("os"),QE=M(),GK=te(),Ji=V(),{randomBytes:MSe}=require("crypto"),{_assignPackageExport:USe}=no(),vSe=M(),HK=1024*1024,Wa=[],Bs=[],BSe=50,xw=1e4,HSe="restart",qK="request_thread_info",$K="resource_report",VK="thread_info",YK="added-port",xSe="ack",Mw;USe("threads",Bs);_i.exports={startWorker:Uw,restartWorkers:kw,shutdownWorkers:$Se,workers:Wa,setMonitorListener:JSe,onMessageFromWorkers:VSe,onMessageByType:XK,broadcast:KSe,broadcastWithAcknowledgement:jSe,setChildListenerByType:qSe,getWorkerIndex:KK,getWorkerCount:WK,getTicketKeys:QK,setMainIsWorker:kSe,setTerminateTimeout:FSe,restartNumber:zi?.restartNumber||1};Bs.onMessageByType=XK;Bs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Bs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};_i.exports.whenThreadsStarted=new Promise(e=>{_i.exports.threadsHaveStarted=e});var Fw;function FSe(e){xw=e}a(FSe,"setTerminateTimeout");function KK(){return zi?zi.workerIndex:Fw?0:void 0}a(KK,"getWorkerIndex");function WK(){return zi?zi.workerCount:Fw?1:void 0}a(WK,"getWorkerCount");function kSe(e){Fw=e,_i.exports.threadsHaveStarted()}a(kSe,"setMainIsWorker");var jK=1,YT;function QK(){return YT||(YT=Hw?MSe(48):zi.ticketKeys,YT)}a(QK,"getTicketKeys");Object.defineProperty(kK,"workerIndex",{get(){return KK()}});Object.defineProperty(kK,"workerCount",{get(){return WK()}});var zK={[qK](e,t){QSe(t)},[$K](e,t){zSe(t,e)}};function Uw(e,t={}){let r=process.constrainedMemory?.()||BK();r=Math.min(r,BK(),2e4*HK);let n=GK.get(QE.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/HK/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Bs){let d=new NSe;d.existingPort=l,i.push(d),o.push(d.port2)}DSe(e)||(e+=".js");let c=new OSe(CSe(e)?e:FK(wSe,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:jK=t.threadCount,name:t.name,restartNumber:_i.exports.restartNumber,ticketKeys:QK()},transferList:o,...t});for(let{port1:l,existingPort:d}of i)d.postMessage({type:YK,port:l,threadId:c.threadId},[l]);return WT(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>Uw(e,t),c.on("error",l=>{Ji.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Wa.splice(Wa.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<BSe?(t.unexpectedRestarts=c.unexpectedRestarts+1,Uw(e,t)):Ji.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{zK[l.type]?.(l,c)}),Wa.push(c),ZSe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(Uw,"startWorker");var GSe=[QE.THREAD_TYPES.HTTP];async function kw(e=null,t=Math.max(jK>3,1),r=!0){if(Hw){if(r){let{loadRootComponents:o}=CT();await o()}_i.exports.restartNumber++,t<1&&(t=t*Wa.length);let n=[],s=[];for(let o of Wa.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ji.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:_i.exports.restartNumber,type:QE.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=GSe.indexOf(o.name)>-1,l=new Promise(d=>{let u=setTimeout(()=>{Ji.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},xw*2).unref();o.on("exit",()=>{clearTimeout(u),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),d()})});if(n.push(l),c&&r){let d=o.startCopy(),u=new Promise(_=>{let E=a(f=>{f.type===vSe.ITC_EVENT_TYPES.CHILD_STARTED&&(Ji.trace("Worker has started",d.threadId),_(),s.splice(s.indexOf(u)),d.off("message",E))},"startListener");Ji.trace("Waiting for worker to start",d.threadId),d.on("message",E)});s.push(u),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}=Ca();r&&(e==="http"||!e)&&GK.get(QE.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Qi.postMessage({type:HSe,workerType:e})}a(kw,"restartWorkers");function qSe(e,t){zK[e]=t}a(qSe,"setChildListenerByType");function $Se(e){return kw(e,1/0,!1)}a($Se,"shutdownWorkers");var JK=[];function VSe(e){JK.push(e)}a(VSe,"onMessageFromWorkers");var vw=new Map;function XK(e,t){let r=vw.get(e);r||vw.set(e,r=[]),r.push(t)}a(XK,"onMessageByType");var YSe=10;async function KSe(e,t){let r=0;for(let n of Bs)try{n.postMessage(e),r++>YSe&&(r=0,await new Promise(setImmediate))}catch(s){Ji.error("Unable to send message to worker",s)}t&&eW(e,null)}a(KSe,"broadcast");var KT=new Map,WSe=1;function jSe(e){return new Promise(t=>{let r=0;for(let n of Bs)try{let s=WSe++,i=a(()=>{KT.delete(s),--r===0&&t(),n!==Qi&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,KT.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of KT)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ji.error("Unable to send message to worker",s)}r===0&&t()})}a(jSe,"broadcastWithAcknowledgement");function QSe(e){e.postMessage({type:VK,workers:ZK()})}a(QSe,"sendThreadInfo");function ZK(){let e=Date.now();return Wa.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(ZK,"getChildWorkerInfo");function zSe(e,t){e.resources=t,e.resources.updated=Date.now()}a(zSe,"recordResourceReport");var Bw;function JSe(e){Bw=e}a(JSe,"setMonitorListener");var XSe=1e3,xK=!1;function ZSe(){xK||(xK=!0,setInterval(()=>{for(let e of Wa){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}Bw&&Bw()},XSe).unref())}a(ZSe,"startMonitoring");var eTe=1e3;if(Qi&&zi?.addPorts){WT(Qi);for(let e=0,t=zi.addPorts.length;e<t;e++){let r=zi.addPorts[e];r.threadId=zi.addThreadIds[e],WT(r)}setInterval(()=>{let e=process.memoryUsage();Qi.postMessage({type:$K,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},eTe).unref(),Mw=a(()=>new Promise((e,t)=>{Qi.on("message",r),Qi.postMessage({type:qK});function r(n){n.type===VK&&(Qi.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else Mw=ZK;_i.exports.getThreadInfo=Mw;function WT(e,t){Bs.push(e),e.on("message",r=>{if(r.type===YK)r.port.threadId=r.threadId,WT(r.port);else if(r.type===xSe){let n=KT.get(r.id);n&&n()}else eW(r,e)}).on("close",()=>{Bs.splice(Bs.indexOf(e),1)}).on("exit",()=>{Bs.splice(Bs.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(WT,"addPort");function eW(e,t){for(let n of JK)n(e,t);let r=vw.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){Ji.error(s)}}a(eW,"notifyMessageListeners");if(Hw){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await LSe(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(FK(s,o.name));try{for await(let{filename:o}of PSe(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await kw(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");_i.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else Qi.on("message",async e=>{let{type:t}=e;t===QE.ITC_EVENT_TYPES.SHUTDOWN&&(_i.exports.restartNumber=e.restartNumber,Qi.unref(),setTimeout(()=>{Ji.warn("Thread did not voluntarily terminate",ISe),process.exit(0)},xw).unref())})});var $v={};tt($v,{AUDIT_STORE_OPTIONS:()=>Yf,Decoder:()=>Ou,HAS_CURRENT_RESIDENCY_ID:()=>cc,HAS_EXPIRATION_EXTENDED_TYPE:()=>h_,HAS_ORIGINATING_OPERATION:()=>E_,HAS_PREVIOUS_RESIDENCY_ID:()=>lc,REMOTE_SEQUENCE_UPDATE:()=>dm,createAuditEntry:()=>ql,getLastRemoved:()=>Ty,openAuditStore:()=>XT,readAuditEntry:()=>Ht,setAuditRetention:()=>rTe,transactionKeyEncoder:()=>dW});function XT(e){let t=e.auditStore=e.openDB(Gw.AUDIT_STORE_NAME,{create:!1,...Yf});t||(t=e.auditStore=e.openDB(Gw.AUDIT_STORE_NAME,Yf),rW(t,1)),t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=jT){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c,l;try{for(let{key:d,value:u}of t.getRange({start:1,snapshot:!1,end:Date.now()-qw})){if((u[0]&15)===$w){let _=Ht(u),E=_.tableId;r[E]?.(_.recordId)}if(c=t.remove(d),l=d,await new Promise(setImmediate),++o>=tTe){i=10;break}}await c}finally{o===0?i=Math.min(i<<1,qw/10):rW(t,l),s(i)}},i).unref()}if(a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,JE.getWorkerIndex)()===(0,JE.getWorkerCount)()-1&&s(jT),(0,JE.getWorkerIndex)()===0&&!tW)for(let i of t.getKeys({reverse:!0,limit:1}))i>Date.now()&&(tW=!0,JT.error("The current time is before the last recorded entry in the audit log. Time reversal can undermine the integrity of data tracking and certificate validation and the time must be corrected."));return t}function rW(e,t){Vw[0]=t,e.put(Symbol.for("last-removed"),_W)}function Ty(e){let t=e.get(Symbol.for("last-removed"));if(t)return _W.set(t),Vw[0]}function rTe(e,t=jT){qw=e,jT=t}function ql(e,t,r,n,s,i,o,c,l,d,u,_,E){let f=fW[o];if(!f)throw new Error(`Invalid audit entry type ${o}`);let h=1;if(n&&(n>1?ja.setFloat64(0,n):Hs.set(bR),h=9),l){if(l&16761087)throw new Error("Illegal extended type");h++}g(s),g(t),T(r),ja.setFloat64(h,e),h+=8,l&cc&&g(d),l&lc&&g(u),l&h_&&(ja.setFloat64(h,_),h+=8),l&E_&&g(EW[E]),i?T(i):Hs[h++]=0,l?ja.setUint16(n?8:0,f|l|32768):Hs[n?8:0]=f;let S=Hs.subarray(0,h);if(c)return Buffer.concat([S,c]);return S;function T(m){let C=h;h+=1,h=(0,Ld.writeKey)(m,Hs,h);let O=h-C-1;O>127?O>16383?(JT.error("Key or username was too large for audit entry",m),h=C+1,Hs[C]=0):(Hs.copyWithin(C+2,C+1,h),ja.setUint16(C,O|32768),h++):Hs[C]=O}function g(m){m<128?Hs[h++]=m:m<16384?(ja.setUint16(h,m|32768),h+=2):m<1056964608?(ja.setUint32(h,m|3221225472),h+=4):(Hs[h]=255,ja.setUint32(h+1,m),h+=5)}}function Ht(e){try{let t=e.dataView||(e.dataView=new Ou(e.buffer,e.byteOffset,e.byteLength)),r;e[t.position]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,l=t.position+=o,d=t.readFloat64(),u,_,E,f;if(n&cc&&(u=t.readInt()),n&lc&&(_=t.readInt()),n&h_&&(E=t.readFloat64()),n&E_){let T=t.readInt();f=EW[T]}o=t.readInt();let h=t.position,S=t.position+=o;return{type:fW[n&7],tableId:i,nodeId:s,get recordId(){return cW(e,c,l)},getBinaryRecordId(){return e.subarray(c,l)},version:d,previousLocalTime:r,get user(){return S>h?cW(e,h,S):void 0},encoded:e,getValue(T,g,m){if(n&QT||n&zE&&!g)return T.decoder.decode(e.subarray(t.position));if(n&zE&&m)return Yw(T.getEntry(this.recordId),m,T)},getBinaryValue(){return n&(QT|zE)?e.subarray(t.position):void 0},extendedType:n,residencyId:u,previousResidencyId:_,expiresAt:E,originatingOperation:f}}catch(t){return JT.error("Reading audit entry error",t,e),{}}}function cW(e,t,r){let n=e.subarray(t,r);return(0,Ld.readKey)(n,0,r-t)}var Ld,zT,Gw,lW,JE,uW,JT,Hs,ja,dW,Yf,qw,tTe,Vw,_W,jT,tW,QT,zE,nW,$w,sW,iW,oW,aW,dm,cc,lc,E_,h_,fW,EW,Ou,io=Ce(()=>{Ld=require("ordered-binary"),zT=B(te()),Gw=B(Bt()),lW=B(M()),JE=B(ut()),uW=B(ee());$l();JT=B(V());ZT();(0,zT.initSync)();Hs=Buffer.alloc(1024),ja=new DataView(Hs.buffer,Hs.byteOffset,1024),dW={writeKey(e,t,r){return e===f_?(t.set(f_,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Ld.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,Ld.readKey)(e,t,r)}},Yf={encoding:"binary",keyEncoder:dW},qw=(0,uW.convertToMS)((0,zT.get)(lW.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,tTe=1e3,Vw=new Float64Array(1),_W=new Uint8Array(Vw.buffer),jT=1e4,tW=!1;a(XT,"openAuditStore");a(rW,"updateLastRemoved");a(Ty,"getLastRemoved");a(rTe,"setAuditRetention");QT=16,zE=32,nW=1,$w=2,sW=3,iW=4,oW=5,aW=6,dm=11,cc=512,lc=1024,E_=2048,h_=4096,fW={put:nW|QT,[nW]:"put",delete:$w,[$w]:"delete",message:sW|QT,[sW]:"message",invalidate:iW|zE,[iW]:"invalidate",patch:oW|zE,[oW]:"patch",relocate:aW,[aW]:"relocate"},EW={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(ql,"createAuditEntry");a(Ht,"readAuditEntry");Ou=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t;try{t=this.getUint8(this.position++)}catch(r){throw r}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(cW,"readKeySafely")});var Kw={};tt(Kw,{add:()=>eg,applyReverse:()=>hW,getRecordAtTime:()=>Yw,rebuildUpdateBefore:()=>tg});function eg(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function tg(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,eg(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function hW(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=nTe[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=pW}}function Yw(e,t,r){let n=r.rootStore.auditStore,s={...e.value},i=e.localTime;for(;i>t;){let l=n.get(i),d=Ht(l);switch(d.type){case"put":s=d.getValue(r);break;case"patch":hW(s,d.getValue(r));break;case"delete":s=null}i=d.previousLocalTime}let o={},c=0;for(let l in s)s[l]===pW&&(o[l]=!0,c++);for(;c>0&&i>0;){let l=n.get(i),d=Ht(l),u;switch(d.type){case"put":u=d.getValue(r);break;case"patch":u=d.getValue(r);break}for(let _ in u)o[_]&&(s[_]=u[_],o[_]=!1,c--);i=d.previousLocalTime}if(c>0)for(let l in o)s[l]=null;return s}var nTe,pW,ZT=Ce(()=>{io();a(eg,"add");eg.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};nTe={add:eg};a(tg,"rebuildUpdateBefore");a(hW,"applyReverse");pW={};a(Yw,"getRecordAtTime")});function Zn(e){return e[ur]||(e[ur]=Object.create(null))}function og(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,l,d;if(o.resolve)d={get(){return o.resolve(this,this[xe])},set(u){return o.set(this,u)},configurable:!0};else{switch(o.type){case"String":l=a(function(u){if(!(typeof u=="string"||u==null&&o.nullable!==!1))throw new xs.ClientError(`${c} must be a string, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"ID":l=a(function(u){if(!(typeof u=="string"||u?.length>0&&u.every?.(_=>typeof _=="string")||u==null&&o.nullable!==!1))throw new xs.ClientError(`${c} must be a string, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"Float":case"Number":l=a(function(u){let _=u?.__op__?u.value:u;if(!(typeof _=="number"||u==null&&o.nullable!==!1))throw new xs.ClientError(`${c} must be a number, attempt to assign ${_}`);Zn(this)[c]=u},"set");break;case"Int":l=a(function(u){let _=u?.__op__?u.value:u;if(!(_>>0===_||u==null&&o.nullable!==!1))if(typeof _=="number"&&Math.abs((_>>0)-_)<=1)_=Math.round(_),u?.__op__?u.value=_:u=_;else throw new xs.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"Long":l=a(function(u){let _=u?.__op__?u.value:u;if(!(Math.round(_)===u&&Math.abs(_)<=9007199254740992||u==null&&o.nullable!==!1))if(typeof _=="number"&&Math.abs(_)<=9007199254740992)_=Math.round(_),u?.__op__?u.value=_:u=_;else throw new xs.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"BigInt":l=a(function(u){let _=u?.__op__?u.value:u;if(!(typeof _=="bigint"||u==null&&o.nullable!==!1))if(typeof _=="string"||typeof _=="number")_=BigInt(_),u?.__op__?u.value=_:u=_;else throw new xs.ClientError(`${c} must be a number, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"Boolean":l=a(function(u){if(!(typeof u=="boolean"||u==null&&o.nullable!==!1))throw new xs.ClientError(`${c} must be a boolean, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"Date":l=a(function(u){if(!(u instanceof Date||u==null&&o.nullable!==!1))if(typeof u=="string"||typeof u=="number")u=new Date(u);else throw new xs.ClientError(`${c} must be a Date, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"Bytes":l=a(function(u){if(!(u instanceof Uint8Array||u==null&&o.nullable!==!1))throw new xs.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${u}`);Zn(this)[c]=u},"set");break;case"Any":case void 0:l=a(function(u){Zn(this)[c]=u},"set");break;default:l=a(function(u){if(!(typeof u=="object"||u==null&&o.nullable!==!1))throw new xs.ClientError(`${c} must be an object, attempt to assign ${u}`);Zn(this)[c]=u},"set")}d={get(){let u=this[ur];if(u&&c in u){let E=u[c];if(E?.__op__){let f=this[Ue]?.[c];return E.update(f)}return E}let _=this[Ue]?.[c];if(_&&typeof _=="object"){let E=SW(_,o);if(E)return u||(u=this[ur]=Object.create(null)),u[c]=E}return _},set:l,enumerable:!0,configurable:!0}}d.get.isAttribute=!0,n[c]=d,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,d)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let l=this[ur];return l?.[o]!==void 0?l[o]:this[Ue]?.[o]}),i("set",function(o,c){let l=n[o];if(l)return l.set.call(this,c);if(t.sealed)throw new xs.ClientError("Can not add a property to a sealed table schema");Zn(this)[o]=c}),i("deleteProperty",function(o){Zn(this)[o]=void 0}),i("toJSON",function(){let o=this[ur],c;for(let d in o){c||(c={...this[Ue]});let u=o[d];if(u?.__op__){let _=c[d];u=u.update(_)}c[d]=u}return Object.keys(this).length>0&&(c||(c={...this[Ue]}),Object.assign(c,this)),c||this[Ue]}),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 SW(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?.[Ue])throw new Error("Can not track an already tracked object, check for circular references");this[Ue]=s}},og(r,t)),new r(e)):new rg(e);case Array:let n=new sg(e.length);n[Ue]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=SW(o,t?.elements)),n[s]=o}return n;default:return e}}function Mp(e){let t=e[ur],r;for(let s in t){r||(r={...e[Ue]});let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=Mp(i);r[s]=i}return Object.keys(e).length>0&&(r||(r={...e[Ue]}),Object.assign(r,e)),r||e[Ue]}function Ol(e,t=e[ur]){let r;if(mW.call(e,Ue)&&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=Ol(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={...e[Ue]});let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=Kw[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Ol(s);r[n]=s}return r?Object.freeze(r):mW.call(e,Ue)?e[Ue]:e}function ng(e){let t=e[Ue];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[yl]||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?.[Ue]===s){if(ng(i))return!0}else return!0}}else{let r=e[ur];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[Ue]===i){if(ng(s))return!0}else return!0}else return!0}}return!1}var xs,ur,rg,mW,yl,sg,ig,Up=Ce(()=>{ls();xs=B(ce());ZT();ur=Symbol("own-data");a(Zn,"getChanges");a(og,"assignTrackedAccessors");a(SW,"trackObject");rg=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[Ue])throw new Error("Can not track an already tracked object, check for circular references");this[Ue]=t}};og(rg,{});a(Mp,"collapseData");mW=Object.prototype.hasOwnProperty;a(Ol,"deepFreeze");a(ng,"hasChanges");yl=Symbol.for("has-array-changes"),sg=class extends Array{static{a(this,"TrackedArray")}[yl];constructor(t){super(t)}splice(...t){return this[yl]=!0,super.splice(...t)}push(...t){return this[yl]=!0,super.push(...t)}pop(){return this[yl]=!0,super.pop()}unshift(...t){return this[yl]=!0,super.unshift(...t)}shift(){return this[yl]=!0,super.shift()}};sg.prototype.constructor=Array;ig=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var zA={};tt(zA,{CONTEXT:()=>xe,ID_PROPERTY:()=>ze,IS_COLLECTION:()=>fi,MultiPartId:()=>ad,RECORD_PROPERTY:()=>Ue,Resource:()=>wr,snake_case:()=>iTe,transformForSelect:()=>cg});function iTe(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function TW(e,t){if(XE=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(XE=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new ad;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){XE=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function es(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,d,u;if(r?(o?(u=i,o=o[xe]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(u=s,c=u[this.primaryKey]??null,o=i[xe]||i):u=i:(u=s,s=void 0,c=u[ze]??u[this.primaryKey]),c===null&&(d=!0)):i?o=i[xe]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let S=this.parseQuery(c.slice(f+1));l?l=Object.assign(S,l):l=S,c=c.slice(0,f)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=h.query),d=h.isCollection,c=h.id):c=h}else if(s[Symbol.iterator]){c=[],d=!0;for(let f of s){if(typeof f=="object"&&f)break;c.push(f)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,d=!1)))}c===void 0&&(c=s.id??null,c==null&&(d=!0))}else c=s,l=new ol(c),c===null&&(d=!0);o||(o={});let _;if(l?.ensureLoaded!=null||l?.async||d?(_={...t},l?.ensureLoaded!=null&&(_.ensureLoaded=l.ensureLoaded),l?.async&&(_.async=l.async),d&&(_.isCollection=!0)):_=t,o.transaction){let f=this.getResource(c,o,_);return f.then?f.then(E):E(f)}else return wt(o,()=>{let f=this.getResource(c,o,_);return f.then?f.then(E):E(f)},_);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,l,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,u,o):f.allowUpdate(o.user,u,o):t.type==="create"?f.allowCreate(o.user,u,o):f.allowDelete(o.user,l,o);if(h?.then)return h.then(S=>{if(!S)throw new ag(o.user);return typeof u?.then=="function"?u.then(T=>e(f,l,o,T)):e(f,l,o,u)});if(!h)throw new ag(o.user)}return typeof u?.then=="function"?u.then(h=>e(f,l,o,h)):e(f,l,o,u)}a(E,"authorizeActionOnResource")}}function ts(e,t){let r=new AW.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 Ww(e,t,r){let n=e[Ue];if(n){let s=e[ur];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 cg(e,t){let r=t?.propertyResolvers,n=t[xe],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):Ww(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(c);let d=[],u=i(Ww(l,r,n));for(let _ of e)d.push(u(_));return d},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(E=>E&&typeof E=="object"?c(E):E);let d={},u=i(Ww(l,r,n)),_;for(let E of e){let f=u(E);f===void 0&&o&&(f=null),f?.then?(_||(_=[]),_.push(f.then(h=>d[E.name||E]=h))):d[E.name||E]=f}return _?Promise.all(_).then(()=>d):d},"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 l=s[c.name];if(!l){let u=r[c.name]?.definition?.tableClass;l=s[c.name]=cg(c.select||c,u)}let d=o(c.name);return l(d)}else return o(c);else return c}}a(i,"handleProperty")}var gW,RW,AW,xe,ze,fi,Ue,sTe,wr,ag,XE,ad,ls=Ce(()=>{gW=require("crypto");kl();RW=B(no()),AW=B(ce());Up();Ic();SE();xe=Symbol.for("context"),ze=Symbol.for("primary-key"),fi=Symbol("is-collection"),Ue=Symbol("stored-record"),sTe={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},wr=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[ze]=t;let n=r?.[xe];this[xe]=n!==void 0?n:r||null}static get=es(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let d=cg(l,t.constructor);return typeof c?.map=="function"?c.map(d):d(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=es(function(t,r,n,s){if(Array.isArray(s)&&t[fi]){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,d=l.getResource(c[l.primaryKey],n,{async:!0});d.then?i.push(d.then(u=>u.put(c,n))):i.push(d.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):ts(t,"put")},{hasContent:!0,type:"update"});static patch=es(function(t,r,n,s){return t.patch?t.patch(s,r):ts(t,"patch")},{hasContent:!0,type:"update"});static delete=es(function(t,r,n,s){return t.delete?t.delete(r):ts(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,gW.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),wt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):ts(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=es(function(t,r,n,s){return t.invalidate?t.invalidate(r):ts(t,"delete")},{hasContent:!1,type:"update"});static post=es(function(t,r,n,s){return t[ze]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=es(function(t,r,n,s){return t.connect?t.connect(s,r):ts(t,"connect")},{hasContent:!0,type:"read"});static subscribe=es(function(t,r,n,s){return t.subscribe?t.subscribe(r):ts(t,"subscribe")},{type:"read"});static publish=es(function(t,r,n,s){return t[ze]!=null&&t.update?.(),t.publish?t.publish(s,r):ts(t,"publish")},{hasContent:!0,type:"create"});static search=es(function(t,r,n,s){let i=t.search?t.search(r):ts(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=cg(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=es(function(t,r,n,s){return t.search?t.search(s,r):ts(t,"search")},{hasContent:!0,type:"read"});static copy=es(function(t,r,n,s){return t.copy?t.copy(s,r):ts(t,"copy")},{hasContent:!0,type:"create"});static move=es(function(t,r,n,s){return t.move?t.move(s,r):ts(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this[fi])return(await this.constructor.create(this[ze],t,this[xe]))[ze];ts(this,"post")}static isCollection(t){return t?.[fi]}static coerceId(t){return t}static parseQuery(t){return HS(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&&sTe[o];if(c)r.requestedContentType=c;else if(n)n.property=o;else return{query:{property:o},id:TW(t,this),isCollection:XE}}let i=TW(t,this);return XE?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[xe],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 l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let d=l.asMap.get(t);if(s=d?.find(u=>u.constructor===c),s)return s;d||l.asMap.set(t,d=[]),d.push(s=new c(t,i))}else{if(s=l.find(d=>d[ze]===t&&d.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let d=new Map;for(let u of l){let _=u[ze],E=d.get(_);E?E.push(u):d.set(_,[u])}i.resourceCache.length=0,i.resourceCache.asMap=d}}}else s=new c(t,i);return o&&(s[fi]=!0),s}subscribe(t){return new Mn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Mn}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[ze]}getContext(){return this[xe]}};wr.prototype[xe]=null;(0,RW._assignPackageExport)("Resource",wr);a(iTe,"snake_case");ag=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(TW,"pathToId");ad=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(es,"transactional");a(ts,"missingMethod");a(Ww,"selectFromObject");a(cg,"transformForSelect")});var XN={};tt(XN,{EVICTED:()=>va,INVALIDATED:()=>ki,coerceType:()=>ug,makeTable:()=>fg,setServerUtilities:()=>ETe,updateResource:()=>dg});function fg(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:d,dbisDB:u,sealed:_,replicate:E}=e,{expirationMS:f,evictionMS:h,audit:S,trackDeletes:T}=e,{attributes:g}=e;g||(g=[]);let m=NR(i,n,l),C,O,x={},F=Promise.resolve(),Y,$,Z;for(let G of g)(G.assignCreatedTime||G.name==="__createdtime__")&&(Y=G),(G.assignUpdatedTime||G.name==="__updatedtime__")&&($=G),G.expiresAt&&(Z=G),G.isPrimaryKey&&(x=G);let Q,_e=[],K=[],ie=1,le=2,we={},ve={},et=864e5,Ja,Xa,Dn,Yd=!1,Kd,mh=new Map,Lg=new Map,Rt,Za,os=Md.get(Fs.CONFIG_PARAMS.REPLICATION_DATABASES);if(Array.isArray(os)){for(let G of os)if(G.name===c&&G.replicateTo>=0){Za=G.replicateTo;break}}let $s=i.getRange({start:!1,end:!1}).constructor,Sh=10,mC=6;S&&ge();class Oe extends wr{static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=S;static databasePath=o;static databaseName=c;static attributes=g;static replicate=E;static sealed=_;static createdTimeProperty=Y;static updatedTimeProperty=$;static propertyResolvers;static userResolvers={};static sources=[];static get expirationMS(){return f}static dbisDB=u;static schemaDefined=d;static sourcedFrom(p,R){if(R&&(this.sourceOptions=R,(R.expiration||R.eviction||R.scanInterval)&&this.setTTLExpiration(R)),R?.intermediateSource)p.intermediateSource=!0,this.sources.unshift(p);else{if(this.sources.some(w=>!w.intermediateSource))throw new Error("Can not have multiple canonical (non-intermediate) sources");this.sources.push(p)}O=O||p.get&&(!p.get.reliesOnPrototype||p.prototype.get),C=C||p.load;let b=a(w=>{let N=this.sources;if(N=N.filter(v=>v.intermediateSource&&v[w]&&(!v[w].reliesOnPrototype||v.prototype[w])),N.length>0)if(N.length===1){let v=N[0];return(U,L,P)=>{if(U?.source!==v)return v[w](L,P,U)}}else return(v,U,L)=>{let P=[];for(let H of N){if(v?.source===H)break;P.push(H[w](U,L,v))}return Promise.all(P)}},"getApplyToIntermediateSource"),A=this.sources[this.sources.length-1];A.intermediateSource&&(A={});let I=a(w=>{if(A[w]&&(!A[w].reliesOnPrototype||A.prototype[w]))return(N,v,U)=>{if(!N?.source)return A[w](v,U,N)}},"getApplyToCanonicalSource");return we={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish")},ve={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish"),invalidate:b("invalidate")},(async()=>{let w=!1,N,v=a(async(U,L)=>{let P=U.value,H=U.table?Ve[c][U.table]:Oe;if(c===Fs.SYSTEM_SCHEMA_NAME&&(U.table===Fs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===Fs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(w=!0),U.id===void 0&&(U.id=P[H.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=p;let k={residencyId:Te(U.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:U.nodeId},ue=await H.getResource(U.id,L,k);switch(U.type){case"put":return ue._writeUpdate(P,!0,k);case"patch":return ue._writeUpdate(P,!1,k);case"delete":return ue._writeDelete(k);case"publish":return ue._writePublish(P,k);case"invalidate":return ue._writeInvalidate(k);case"relocate":return ue._writeRelocate(k);default:Ye.default.error?.("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=p.subscribe;U&&T==null&&(T=!0);let L=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Il.getWorkerIndex)()):(0,Il.getWorkerIndex)()===0,P=U&&L&&await p.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(P){let H;for await(let k of P)try{if(!(k.type==="transaction"?k.writes[0]:k)){Ye.default.error?.("Bad subscription event",k);continue}if(k.source=p,k.type==="end_txn"){if(H?.resolve(),k.localTime&&N!==k.localTime){if(k.remoteNodeIds?.length>0){let Ne=[Symbol.for("seq"),k.remoteNodeIds[0]],fe=u.get(Ne),he=fe?.nodes;he||(he=[]);for(let z of k.remoteNodeIds.slice(1)){let Re=he.find(ke=>ke.name===z);Re||(Re={id:z,seqId:0},he.push(Re)),Re.seqId=Math.max(fe?.seqId??1,k.localTime),z===k.nodeId&&(Re.lastTxnTime=k.timestamp)}let se=Math.max(fe?.seqId??1,k.localTime);Ye.default.trace?.("Received txn",c,se,k.localTime,k.remoteNodeIds),u.put(Ne,{seqId:se,nodes:he})}N=k.localTime}k.onCommit&&H?.committed.then(k.onCommit);continue}if(H)if(k.beginTxn)H.resolve();else{H.write_promises.push(v(k,H));continue}let X=wt(k,()=>{if(k.type==="transaction"){let Ne=[];for(let fe of k.writes)try{Ne.push(v(fe,k))}catch(he){throw he.message+=" writing "+JSON.stringify(fe)+" of event "+JSON.stringify(k),he}return Promise.all(Ne)}else if(k.type==="define_schema"){let Ne=this.attributes.slice(0),fe;for(let he of k.attributes)Ne.find(se=>se.name===he.name)||(Ne.push(he),fe=!0);fe&&(dt({table:s,database:c,attributes:Ne,origin:"cluster"}),nh.signalSchemaChange(new sh.SchemaEventMsg(process.pid,Fs.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return k.beginTxn?(H=k,H.write_promises=[v(k,k)],new Promise(Ne=>{H.resolve=()=>Ne(Promise.all(H.write_promises))})):v(k,k)});H&&(H.committed=X),w&&X&&!X?.waitingForUserChange&&(X.then(()=>nh.signalUserChange(new sh.UserEventMsg(process.pid))),X.waitingForUserChange=!0),k.onCommit&&(X?X.then(k.onCommit):k.onCommit())}catch(ue){Ye.default.error?.("error in subscription handler",ue)}}}catch(U){Ye.default.error?.(U)}})(),this}static getResource(p,R,b){let A=super.getResource(p,R,b);if(p!=null){hi(p);try{if(A.hasOwnProperty(Ue))return A;if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let I=!b?.async||i.cache?.get(p),w=Vr(R),N=w.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Bl(p,R,{transaction:N,ensureLoaded:b?.ensureLoaded},I,v=>{if(v?dg(A,v):A[Ue]=null,R.onlyIfCached&&R.noCacheStore){if(!A.doesExist())throw new $r.ServerError("Entry is not cached",504)}else if(b?.ensureLoaded){let U=tc(p,v,R,A);if(U)return w?.disregardReadTxn(),A[jw]=!0,zw(U,L=>(dg(A,L),A))}return A})}catch(I){throw I.message.includes("Unable to serialize object")&&(I.message+=": "+JSON.stringify(p)),I}}return A}ensureLoaded(){let p=tc(this[ze],this[qr],this[xe]);if(p)return this[jw]=!0,zw(p,R=>{this[qr]=R,this[Ue]=R.value,this[th]=R.version})}static getNewId(){let p=x?.type;if(p==="String"||p==="ID")return super.getNewId();if(!Rt){let I=i.getEntry(Symbol.for("id_allocation")),w=I?.value,N;if(w&&w.nodeName===server.hostname&&(!pTe(i)||w.pid===process.pid)){let v=w.start,U=w.end;N=v;for(let L of i.getKeys({start:U,end:v,limit:1,reverse:!0}))N=L}else w=A(I?.version??null),N=w.start;Rt=new BigInt64Array([BigInt(N)+1n]),Rt=new BigInt64Array(i.getUserSharedBuffer("id",Rt.buffer)),Rt.maxSafeId=w.end}let R=Number(Atomics.add(Rt,0,1n)),b=p==="Int"?512:1048576;if(R+b>=Rt.maxSafeId){let I=a(w=>{Rt.maxSafeId=R+(p==="Int"?1023:4194303);let N=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,v=w?void 0:i.useReadTransaction(),U=Number(Rt[0]);for(let H of i.getKeys({start:U+1,end:N,limit:1,transaction:v}))N=H;v?.done();let{value:L,version:P}=i.getEntry(Symbol.for("id_allocation"));if(Rt.maxSafeId<N){if(L.end>Rt.maxSafeId-100)return;Ye.default.info?.("New id allocation",R,Rt.maxSafeId,P),i.put(Symbol.for("id_allocation"),{start:L.start,end:Rt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),P)}else{Ye.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Rt.maxSafeId}, but id of ${N} detected`);let H=A(P);H.alreadyUpdated||Atomics.store(Rt,0,BigInt(H.start+1)),Rt.maxSafeId=H.end}},"updateEnd");R+b===Rt.maxSafeId?setImmediate(I):R+100>=Rt.maxSafeId&&(Ye.default.warn?.(`Synchronous id allocation required on table ${s}${p=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>I(!0)))}return R;function A(I){let w=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,N=w/4,v,U,L=!1,P,H;do{P=Math.floor(Math.random()*w),H={start:P,end:P+(p==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},v=0;for(let k of i.getKeys({start:P,limit:1,reverse:!0}))v=k;U=w;for(let k of i.getKeys({start:P+1,end:w,limit:1}))U=k;N*=.875,N<1e3&&!L&&(L=!0,Ye.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${p==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,P,v,U,N))}while(!(N<U-P&&(N<P-v||v===0)));return i.transactionSync(()=>{let k=i.getEntry(Symbol.for("id_allocation"));return(k?.version??null)==I?(Ye.default.info?.("Allocated new id range",H),i.put(Symbol.for("id_allocation"),H,Date.now()),H):(Ye.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...k.value})})}}static setTTLExpiration(p){if(typeof p=="number")f=p*1e3,h||(h=0);else if(p&&typeof p=="object")f=p.expiration*1e3,h=(p.eviction||0)*1e3,et=p.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");et=et||(f+h)/4,re()}static getResidencyRecord(p){return u.get([Symbol.for("residency_by_id"),p])}static setResidency(p){Oe.getResidency=p}static setResidencyById(p){Oe.getResidencyById=p}static getResidency(p,R,b){if(Oe.getResidencyById)return Oe.getResidencyById(p[t]);let A=Za;if(R.replicateTo!=null){if(Array.isArray(R.replicateTo))return R.replicateTo.includes(server.hostname)?R.replicateTo:[server.hostname,...R.replicateTo];R.replicateTo>=0&&(A=R.replicateTo)}if(A>=0&&server.nodes){let I=[server.hostname];if(b)I.push(...b.slice(0,A));else{let w=server.nodes.map(U=>U.name),N=Math.floor(w.length*Math.random());I.push(...w.slice(N,N+A));let v=N+A-w.length;v>0&&I.push(...w.slice(0,v))}return I}}static enableAuditing(p=!0){S=p,p&&ge(),Oe.audit=p}static coerceId(p){return p===""?null:ug(p,x)}static async dropTable(){if(delete Ve[c][s],c===o){for(let p of g)u.remove(Oe.tableName+"/"+p.name),r[p.name]?.drop();u.remove(Oe.tableName+"/"),i.drop(),await u.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));nh.signalSchemaChange(new sh.SchemaEventMsg(process.pid,Fs.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(p){if(typeof p=="string")return this.getProperty(p);if(this[fi])return this.search(p);if(this[ze]===null){if(p?.conditions)return this.search(p);let R=Oe.getRecordCount();return{recordCount:R.recordCount,estimatedRecordRange:R.estimatedRange,records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:g}}if(p?.property)return this.getProperty(p.property);if(this.doesExist()||p?.ensureLoaded===!1||this[xe]?.returnNonexistent)return this}allowRead(p,R){let b=Hl(p);if(b?.read){if(b.isSuperUser)return!0;let A=b.attribute_permissions,I=R?.select;if(A?.length>0||Yd&&I){if(R||(R={}),I){let w=A?.length>0&&Qw(A,"read");R.select=I.map(N=>{let v=N.name||N;if(!w||w[v]){let U=Dn[v]?.definition?.tableClass;if(U){if(N.name||(N={name:N}),!U.prototype.allowRead.call(null,p,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else R.select=A.filter(w=>w.read&&!Dn[w.attribute_name]).map(w=>w.attribute_name);return R}else return!0}}allowUpdate(p,R){let b=Hl(p);if(b?.update){let A=b.attribute_permissions;if(A?.length>0){let I=Qw(A,"update");for(let w in R)if(!I[w])return!1;for(let w of A){let N=w.attribute_name;!w.update&&!(N in R)&&(R[N]=this.getProperty(N))}}return Wo(this[xe])}}allowCreate(p,R){if(this[fi]){let b=Hl(p);if(b?.insert){let A=b.attribute_permissions;if(A?.length>0){let I=Qw(A,"insert");for(let w in R)if(!I[w])return!1;return Wo(this[xe])}else return Wo(this[xe])}}else return this.allowUpdate(p,{})}allowDelete(p){return Hl(p)?.delete&&Wo(this[xe])}update(p,R){if(!Vr(this[xe]))throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let A;return typeof p=="object"&&p&&(R?(Object.isFrozen(p)&&(p={...p}),this[Ue]={},this[ur]=p):(A=this[ur],A&&(p=Object.assign(A,p)),this[ur]=A=p)),this._writeUpdate(this[ur],R),this}addTo(p,R){if(typeof R=="number"||typeof R=="bigint")this[ZE]===yW?this.set(p,(+this.getProperty(p)||0)+R):(this[ZE]||this.update(),this.set(p,new ig(R)));else throw new Error("Can not add a non-numeric value")}subtractFrom(p,R){if(typeof R=="number")return this.addTo(p,-R);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[qr]}invalidate(){this._writeInvalidate()}_writeInvalidate(p){let R=this[xe],b=this[ze];hi(b),Vr(this[xe]).addWrite({key:b,store:i,invalidated:!0,entry:this[qr],before:we.invalidate?.bind(this,R,b),beforeIntermediate:ve.invalidate?.bind(this,R,b),commit:(I,w)=>{if(nc(I,w,p?.nodeId))return;let N=null;for(let v in r)N||(N={}),N[v]=this.getProperty(v);Ye.default.trace?.(`Invalidating entry id: ${b}, timestamp: ${new Date(I).toISOString()}`),m(b,N,this[qr],I,ki,S,{user:R?.user,residencyId:p?.residencyId,nodeId:p?.nodeId},"invalidate")}})}_writeRelocate(p){let R=this[xe],b=this[ze];hi(b),Vr(this[xe]).addWrite({key:b,store:i,invalidated:!0,entry:this[qr],before:we.relocate?.bind(this,R,b),beforeIntermediate:ve.relocate?.bind(this,R,b),commit:(I,w)=>{if(nc(I,w,p?.nodeId))return;let N=Oe.getResidencyRecord(p.residencyId),v=0,U=null,L=w?.value;if(N&&!N.includes(server.hostname)){for(let P in r)U||(U={}),U[P]=L(P);v=ki}else U=L;Ye.default.trace?.(`Relocating entry id: ${b}, timestamp: ${new Date(I).toISOString()}`),m(b,U,this[qr],I,v,S,{user:R.user,residencyId:p.residencyId,nodeId:p.nodeId,expiresAt:p.expiresAt},"relocate",!1,null)}})}static _recordRelocate(p,R){let b={previousResidency:this.getResidencyRecord(p.residencyId),isRelocation:!0},A=this.getResidency(R.value,b),I;if(A){if(!Array.isArray(A))throw new Error("Residency must be an array, but was: "+A);if(!A.includes(server.hostname))return;I=Te(A)}let N=m(p.key,R.value,p,p.version,0,!0,{residencyId:I,expiresAt:R.expiresAt},"relocate",!1,null)}static evict(p,R,b){let A=this.Source,I;if(!((O||S)&&(!R||(I=i.getEntry(p),!I||!R)||I.version!==b))){if(O){if(i.hasLock(p,I.version))return;let w;for(let N in r)w||(w={}),w[N]=R[N];if(w)return m(p,w,I,b,va,null,null,null,!0)}return i.ifVersion(p,b,()=>{ec(p,R,null)}),S?m(p,null,I,b,va,null,null,null,!0):i.remove(p,b)}}lock(){throw new Error("Not yet implemented")}static operation(p,R){return p.table||=s,p.schema||=c,PW.operation(p,R)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,R,b){let A=this[xe],I=Vr(A),w=this[ze];hi(w);let N=this[qr];this[ZE]=R?yW:dTe;let v={key:w,store:i,entry:N,nodeName:A?.nodeName,validate:U=>{p||(p=this[ur]),R||p&&ng(this[ur]===p?this:p)?A?.source||(I.checkOverloaded(),this.validate(p,!R),$&&(p[$.name]=$.type==="Date"?new Date(U):$.type==="String"?new Date(U).toISOString():U),R&&(t&&p[t]!==w&&(p[t]=w),Y&&(N?.value?p[Y.name]=N?.value[Y.name]:p[Y.name]=Y.type==="Date"?new Date(U):Y.type==="String"?new Date(U).toISOString():U),p=Ol(p))):I.removeWrite(v)},before:R?we.put?()=>we.put(A,w,p):null:we.patch?()=>we.patch(A,w,p):we.put?()=>we.put(A,w,Ol(this)):null,beforeIntermediate:R?ve.put?()=>ve.put(A,w,p):null:ve.patch?()=>ve.patch(A,w,p):ve.put?()=>ve.put(A,w,Ol(this)):null,commit:(U,L,P)=>{if(P){if(A&&L?.version>(A.lastModified||0)&&(A.lastModified=L.version),this[qr]=L,L?.value?.[Ue])throw new Error("Can not assign a record to a record, check for circular references");R||(this[Ue]=L?.value??null)}this[ur]=void 0,this[th]=U;let H=L?.value,k=p;if(this[ZE]=0,nc(U,L,b?.nodeId))if(S){let z=L.localTime,Re=L.version;for(;k&&(z>U||Re>=U&&z>0);){let ke=l.get(z);if(!ke)break;let Yt=Ht(ke);if(Re=Yt.version,Re>U){if(Yt.type==="patch"){let pe=Yt.getValue(i);k=tg(k,pe)}else if(Yt.type==="put"||Yt.type==="delete")return}else if(Re===U)return;z=Yt.previousLocalTime}}else{if(R)return;k=tg(k,H)}let X;if(R?X=k:(this[Ue]=H,X=R?k:Ol(this,k)),this[Ue]=X,X?.[Ue])throw new Error("Can not assign a record to a record, check for circular references");let Ne,fe;if(b?.residencyId!=null)fe=b.residencyId;else{N?.residencyId&&(A.previousResidency=Oe.getResidencyRecord(N.residencyId));let z=Oe.getResidency(X,A);if(z){if(!Array.isArray(z))throw new Error("Residency must be an array, got: "+z);z.includes(server.hostname)||z.push(server.hostname)}fe=Te(z)}R||(Ne=p);let he=A?.expiresAt??(f?f+Date.now():-1);Ye.default.trace?.(`Saving record with id: ${w}, timestamp: ${new Date(U).toISOString()}${he?", expires at: "+new Date(he).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`),ec(w,H,X);let se=R?"put":"patch";m(w,X,L,U,0,S,{user:A?.user,residencyId:fe,expiresAt:he,nodeId:b?.nodeId,originatingOperation:A?.originatingOperation},se,!1,Ne),A.expiresAt&&re()}};I.addWrite(v)}async delete(p){if(typeof p=="string")return this.deleteProperty(p);if(this[fi]){for await(let R of this.search(p))(await Oe.getResource(R[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(p);return}return this[Ue]?this._writeDelete(p):!1}_writeDelete(p){let R=Vr(this[xe]),b=this[ze];hi(b);let A=this[xe];return R.addWrite({key:b,store:i,resource:this,nodeName:A?.nodeName,before:we.delete?.bind(this,A,b),beforeIntermediate:ve.delete?.bind(this,A,b),commit:(I,w,N)=>{let v=w?.value;N&&(A&&w?.version>(A.lastModified||0)&&(A.lastModified=w.version),dg(this,w)),!nc(I,w,p?.nodeId)&&(ec(this[ze],v),Ye.default.trace?.(`Deleting record with id: ${b}, txn timestamp: ${new Date(I).toISOString()}`),S||T?(m(b,null,this[qr],I,0,S,{user:A?.user,nodeId:p?.nodeId},"delete"),S||re()):i.remove(this[ze]))}}),!0}search(p){let R=this[xe],b=Vr(R);if(!p)throw new Error("No query provided");let A=p.conditions;A?A.length===void 0&&(A=A[Symbol.iterator]?Array.from(A):[A]):A=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this[ze]&&(A=[{attribute:null,comparator:"prefix",value:this[ze]}].concat(A));let I,w={};function N(z,Re){let ke;switch(Re){case"and":case void 0:if(z.length<1)throw new Error('An "and" operator requires at least one condition');ke=!0;break;case"or":if(z.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Re)}let Yt=ke&&{},pe;for(let be of z){if(be.conditions){be.conditions=N(be.conditions,be.operator);continue}let Ke=be[0]??be.attribute,Xe=Ke==null?x:Fi(g,Ke);if(Xe){if(ke){let We=si(Ke),ot=Yt[We];ot?(ot.push(be),pe=!0):Yt[We]=[be]}(Xe.type||ON[be.comparator])&&(be[1]===void 0?be.value=U(be.value,Xe):be[1]=U(be[1],Xe))}else if(Ke!=null)throw(0,$r.handleHDBError)(new Error,`${Ke} is not a defined attribute`,404)}if(p.enforceExecutionOrder)return z;if(pe)for(let be in Yt){let Ke=Yt[be],Xe=Ke.length;if(Xe>1)for(let We=0;We<Xe;We++){let ot=Ke[We];if(ot.comparator==="ge"||ot.comparator==="greater_than_equal")for(let gr=0;gr<Xe;gr++){let Yr=Ke[gr];(Yr.comparator==="le"||Yr.comparator==="less_than_equal")&&(ot.comparator="between",ot.value=[ot.value,Yr.value],z.splice(z.indexOf(Yr),1))}if(ot.comparator==="equals"||!ot.comparator){for(let gr=0;gr<Xe;gr++)if(gr!==We){let Yr=Ke[gr];z.splice(z.indexOf(Yr),1)}break}}}return z}a(N,"prepareConditions");function v(z,Re){if(p.enforceExecutionOrder)return z;for(let ke of z)ke.conditions&&(ke.conditions=v(ke.conditions,ke.operator));return z.length>1&&Re!=="or"?(0,DW.sortBy)(z,BS(Oe)):z}a(v,"orderConditions");function U(z,Re){return Array.isArray(z)?z.map(ke=>ug(ke,Re)):ug(z,Re)}a(U,"coerceTypedValues");let L=p.operator;(A.length>0||L)&&(A=N(A,L));let P=typeof p.sort=="object"&&p.sort,H;if(P&&L!=="or"){let z=P.attribute;if(I=A.find(Re=>si(Re.attribute)===si(z)),!I){let Re=Fi(g,z);if(!Re)throw(0,$r.handleHDBError)(new Error,`${Array.isArray(z)?z.join("."):z} is not a defined attribute`,404);if(Re.indexed)I={attribute:z,comparator:"sort"},A.push(I);else if(A.length===0&&!p.allowFullScan)throw(0,$r.handleHDBError)(new Error,`${Array.isArray(z)?z.join("."):z} is not indexed and not combined with any other conditions`,404)}I&&(I.descending=!!P.descending)}A=v(A,L),P&&(I&&A[0]===I?P.next&&(H={dbOrderedAttribute:P.attribute,attribute:P.next.attribute,descending:P.next.descending,next:P.next.next}):(I&&A.splice(A.indexOf(I),1),H=P));let k=p.select;if(A.length===0&&(A=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:A,operator:L,postOrdering:H,selectApplied:!!k};let ue=b.useReadTxn(),X=NN(A,L,Oe,ue,p,R,(z,Re)=>rc(z,k,R,ue,Re),w),Ne=p.ensureLoaded!==!1;H||(X=se(X));let fe=Oe.transformEntryForSelect(k,R,ue,w,Ne,!0),he=Oe.transformToOrderedSelect(X,k,H,ue,R,fe);function se(z){return p.offset||p.limit!==void 0?z.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0):z}return a(se,"applyOffset"),H&&(he=se(he)),he.onDone=()=>{he.onDone=null,b.doneReadTxn()},he.selectApplied=!0,he.getColumns=()=>{if(k){let z=[];for(let Re of k)Re==="*"?z.push(...g.map(ke=>ke.name)):z.push(Re.name||Re);return z}return g.filter(z=>!z.computed&&!z.relationship).map(z=>z.name)},he}static transformToOrderedSelect(p,R,b,A,I,w){let N=new $s;if(b){p=rc(p,R,A,I,null);let v;N.iterate=function(){let L,P=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),H,k=b.dbOrderedAttribute,ue,X,Ne=!0;function fe(se){let z=se.next&&fe(se.next),Re=se.descending;return(ke,Yt)=>{let pe=xl(ke,se.attribute,A),be=xl(Yt,se.attribute,A),Ke=Re?(0,wl.compareKeys)(be,pe):(0,wl.compareKeys)(pe,be);return Ke===0?z?.(ke,Yt)||0:Ke}}a(fe,"createComparator");let he=fe(b);return{async next(){let se;if(L)if(se=L.next(),se.done){if(H)return N.onDone&&N.onDone(),se}else return{value:await w.call(this,se.value)};v=[],ue&&v.push(ue);do if(se=await P.next(),se.done){if(H=!0,v.length)break;return N.onDone&&N.onDone(),se}else{let z=se.value;if(z?.then&&(z=await z),k){let Re=xl(z,k,A);if(Ne)Ne=!1,X=Re;else if(Re!==X){X=Re,ue=z;break}}v.push(z)}while(!0);return b.isGrouped,v.sort(he),L=v[Symbol.iterator](),se=L.next(),se.done?(N.onDone&&N.onDone(),se):{value:await w.call(this,se.value)}},return(){N.onDone&&N.onDone(),P.return()},throw(){N.onDone&&N.onDone(),P.throw()}}};let U=a(L=>{if(typeof R=="object"&&Array.isArray(L.attribute))for(let P=0;P<R.length;P++){let H=R[P],k;if(H.name===L.attribute[0]){for(k=H.sort||(H.sort={});k.next;)k=k.next;k.attribute=L.attribute.slice(1),k.descending=L.descending}else H===L.attribute[0]&&(R[P]=k={name:H,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&U(L.next)},"applySortingOnSelect");U(b)}else N.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),N=N.map(function(v){try{let U=w.call(this,v);return typeof U?.catch=="function"?U.catch(L=>{throw L.partialObject={[t]:v.key},L}):U}catch(U){throw U.partialObject={[t]:v.key},U}});return N}static transformEntryForSelect(p,R,b,A,I,w){if(p&&(p===t||p?.length===1&&p[0]===t&&Array.isArray(p))){let L=a(P=>(R?.transaction?.stale&&(R.transaction.stale=!1),P?.key??P),"transform");return p===t?L:p.asArray?P=>[L(P)]:P=>({[t]:L(P)})}let N;I&&O&&!(typeof p=="string"?[p]:p)?.every(L=>{let P;return typeof L=="object"?P=L.name:P=L,r[P]||P===t})&&(N=!0);let v,U=a(function(L){let P;if(R?.transaction?.stale&&(R.transaction.stale=!1),L!=null){if(P=L.value||L.deref?.(),!P&&(L.key===void 0||L.deref)){if(L=Bl(L.key??L,R,{transaction:b,lazy:p?.length<4},this?.isSync,H=>H),L?.then)return L.then(U.bind(this));P=L?.value}if(N&&L?.metadataFlags&(ki|va)||L?.expiresAt!=null&&L?.expiresAt<Date.now()){let H=tc(L.key??L,L,R);if(H?.then)return H.then(U)}}if(P==null)return w?Nl.SKIP:P;if(p&&!(p[0]==="*"&&p.length===1)){let H,k=a((X,Ne)=>{let fe;typeof X=="object"?fe=X.name:fe=X;let he=Dn?.[fe],se;if(he){let z=A?.[fe];if(z)if(z.hasMappings){let ke=he.from?P[he.from]:si(L.key);se=z.get(ke),se||(se=[])}else se=z.fromRecord?.(P);else se=he(P,R,L);let Re=a(ke=>{if(ke&&typeof ke=="object"){let Yt=he.definition?.tableClass||Oe;v||(v={});let pe=v[fe]||(v[fe]=Yt.transformEntryForSelect(fe===X?null:X.select||(Array.isArray(X)?X:null),R,b,z,I));if(Array.isArray(ke)){let be=[],Ke=Yt.transformToOrderedSelect(ke,X.select,typeof X.sort=="object"&&X.sort,R,b,pe)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Xe=a(ot=>{for(;!ot.done;){if(ot?.then)return ot.then(Xe);be.push(ot.value),ot=Ke.next()}Ne(be,fe)},"nextValue"),We=Xe(Ke.next());We&&(H||(H=[]),H.push(We));return}else if(ke=pe.call(this,ke),ke?.then){H||(H=[]),H.push(ke.then(be=>Ne(be,fe)));return}}Ne(ke,fe)},"handleResolvedValue");se?.then?(H||(H=[]),H.push(se.then(Re))):Re(se);return}else se=P[fe],se&&typeof se=="object"&&fe!==X&&(se=Oe.transformEntryForSelect(X.select||X,R,b,null)({value:se}));Ne(se,fe)},"selectAttribute"),ue;if(typeof p=="string")k(p,X=>{ue=X});else if(Array.isArray(p))if(p.asArray)ue=[],p.forEach((X,Ne)=>{X==="*"?p[Ne]=P:k(X,fe=>ue[Ne]=fe)});else{ue={};let X=p.forceNulls;for(let Ne of p)if(Ne==="*")for(let fe in P)ue[fe]=P[fe];else k(Ne,(fe,he)=>{fe===void 0&&X&&(fe=null),ue[he]=fe})}else throw new $r.ClientError("Invalid select"+p);return H?Promise.all(H).then(()=>ue):ue}return P},"transform");return U}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");S||dt({table:s,database:c,schemaDefined:d,attributes:g,audit:!0}),p||(p={});let R=!p.rawEvents,b=[],A=ey(Oe,this[ze]??null,function(w,N,v,U){try{let L=N.getValue?.(i,R),P=N.type;if(!L&&N.type==="patch"&&R){let k=i.getEntry(w);k?.version===N.version?L=k.value:L=N.getValue?.(i,!0,v),P="put"}let H={id:w,timestamp:v,value:L,version:N.version,type:P,beginTxn:U};b?b.push(H):this.send(H)}catch(L){Ye.default.error?.(L)}},p.startTime||0,p),I=(async()=>{this[fi]&&(A.includeDescendants=!0,p.onlyChildren&&(A.onlyChildren=!0)),p.supportsTransactions&&(A.supportsTransactions=!0);let w=this[ze],N=p.previousCount;N>1e3&&(N=1e3);let v=p.startTime;if(this[fi]){if(v){if(N)throw new $r.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:U,value:L}of l.getRange({start:v,exclusiveStart:!0,snapshot:!1})){let P=Ht(L);if(P.tableId!==n)continue;let H=P.recordId;if(w==null||wW(w,H)){let k=P.getValue(i,R,U);if(A.send({id:H,timestamp:U,value:k,version:P.version,type:P.type}),A.queue?.length>NW&&await A.waitForDrain()===!1)return}A.startTime=U}}else if(N){let U=[];for(let{key:L,value:P}of l.getRange({start:"z",end:!1,reverse:!0}))try{let H=Ht(P);if(H.tableId!==n)continue;let k=H.recordId;if(w==null||wW(w,k)){let ue=H.getValue(i,R,L);if(U.push({id:k,timestamp:L,value:ue,version:H.version,type:H.type}),--N<=0)break}}catch(H){Ye.default.error("Error getting history entry",L,H)}for(let L=U.length;L>0;)A.send(U[--L]);U[0]&&(A.startTime=U[0].timestamp)}else if(!p.omitCurrent){for(let{key:U,value:L,version:P,localTime:H}of i.getRange({start:w??!1,end:w==null?void 0:[w,wl.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(L&&(A.send({id:U,timestamp:H,value:L,version:P,type:"put"}),A.queue?.length>NW&&await A.waitForDrain()===!1))return}}else{N&&!v&&(v=0);let U=this[qr]?.localTime;if(U===OR&&(i.cache?.delete(w),this[qr]=i.getEntry(w),Ye.default.trace?.("re-retrieved record",U,this[qr]?.localTime),U=this[qr]?.localTime),Ye.default.trace?.("Subscription from",v,"from",w,U),v<U){let L=[],P=U;do{let H=l.get(P);if(H){p.omitCurrent=!0;let k=Ht(H),ue=k.getValue(i,R,P);R&&(k.type="put"),L.push({id:w,value:ue,timestamp:P,...k}),P=k.previousLocalTime}else break;N&&N--}while(P>v&&N!==0);for(let H=L.length;H>0;)A.send(L[--H]);A.startTime=U}!p.omitCurrent&&this.doesExist()&&A.send({id:w,timestamp:U,value:this[Ue],version:this[th],type:"put"})}for(let U of b)A.send(U);b=null})();return p.listener&&A.on("data",p.listener),A}doesExist(){return!!(this[Ue]||this[ZE])}publish(p,R){this._writePublish(p,R)}_writePublish(p,R){let b=Vr(this[xe]),A=this[ze]||null;A!=null&&hi(A);let I=this[xe];b.addWrite({key:A,store:i,entry:this[qr],nodeName:I?.nodeName,validate:()=>{I?.source||(b.checkOverloaded(),this.validate(p))},before:we.publish?.bind(this,I,A,p),beforeIntermediate:ve.publish?.bind(this,I,A,p),commit:(w,N,v)=>{N===void 0&&T&&!S&&re(),Ye.default.trace?.(`Publishing message to id: ${A}, timestamp: ${new Date(w).toISOString()}`),m(A,N?.value??null,N,N?.version||w,0,!0,{user:I?.user,residencyId:R?.residencyId,expiresAt:I?.expiresAt,nodeId:R?.nodeId},"message",!1,p)}})}validate(p,R){let b,A=a((I,w,N)=>{if(w.type&&I!=null)if(R&&I.__op__&&(I=I.value),w.properties){typeof I!="object"&&(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be an object${w.type?" ("+w.type+")":""}`);let v=w.properties;for(let U=0,L=v.length;U<L;U++){let P=v[U],H=A(I[P.name],P,N+"."+P.name);H&&(I[P.name]=H)}if(w.sealed&&I!=null&&typeof I=="object")for(let U in I)v.find(L=>L.name===U)||(b||(b=[])).push(`Property ${U} is not allowed within object in property ${N}`)}else switch(w.type){case"Int":(typeof I!="number"||I>>0!==I)&&(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof I!="number"||!(Math.floor(I)===I&&Math.abs(I)<=9007199254740992))&&(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof I!="number"&&(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a number`);break;case"ID":typeof I=="string"||I?.length>0&&I.every?.(v=>typeof v=="string")||(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof I!="string"&&(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a string`);break;case"Boolean":typeof I!="boolean"&&(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a boolean`);break;case"Date":if(!(I instanceof Date)){if(typeof I=="string"||typeof I=="number")return new Date(I);(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof I!="bigint"){if(typeof I=="string"||typeof I=="number")return BigInt(I);(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a bigint`)}break;case"Bytes":I instanceof Uint8Array||(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(I)){if(w.elements)for(let v=0,U=I.length;v<U;v++){let L=I[v],P=A(L,w.elements,N+"[*]");P&&(I[v]=P)}}else(b||(b=[])).push(`Value ${Ei(I)} in property ${N} must be a Buffer or Uint8Array`);break}w.nullable===!1&&I==null&&(b||(b=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let I=0,w=g.length;I<w;I++){let N=g[I];if(!(N.relationship||N.computed)&&(!R||N.name in p)){let v=A(p[N.name],N,N.name);v&&(p[N.name]=v)}}if(_)for(let I in p)g.find(w=>w.name===I)||(b||(b=[])).push(`Property ${I} is not allowed`);if(b)throw new $r.ClientError(b.join(". "))}getUpdatedTime(){return this[th]}wasLoadedFromSource(){return O?!!this[jw]:void 0}static async addAttributes(p){let R=g.slice(0);for(let b of p){if(!b.name)throw new $r.ClientError("Attribute name is required");if(b.name.match(/[`/]/))throw new $r.ClientError("Attribute names cannot include backticks or forward slashes");R.push(b)}return dt({table:s,database:c,schemaDefined:d,attributes:R}),Oe.indexingOperation}static async removeAttributes(p){let R=g.filter(b=>!p.includes(b.name));return dt({table:s,database:c,schemaDefined:d,attributes:R}),Oe.indexingOperation}static getRecordCount(p){let R=i.getStats().entryCount,b=1e3/2,A=performance.now(),I=Math.floor(R/2),w=p?.exactCount,N=0,v=0,U;for(let{value:L}of i.getRange({start:!0,lazy:!0}))if(L!=null&&N++,v++,!w&&v<I&&performance.now()-A>b){U=v;break}if(U){let L=N;N=0;for(let{value:se}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:U}))se!=null&&N++;let P=U*2,H=(N+L)/P,k=Math.pow((N-L+1)/U/2,2)+H*(1-H)/P,ue=Math.max(Math.sqrt(k)*R,1),X=Math.round(H*R),Ne=Math.max(X-1.96*ue,N+L),fe=Math.min(X+1.96*ue,R),he=Math.pow(10,Math.round(Math.log10(ue)));return he>X&&(he=he/10),N=Math.round(X/he)*he,{recordCount:N,estimatedRange:[Math.round(Ne),Math.round(fe)]}}return{recordCount:N}}static updatedAttributes(){Dn=this.propertyResolvers={$id:(p,R,b)=>({value:b.key}),$updatedtime:(p,R,b)=>b.version,$record:(p,R,b)=>b?{value:p}:p};for(let p of this.attributes){p.resolve=null;let R=p.relationship,b=p.computed;if(R)if(p.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),b&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Yd=!0,R.to)p.elements?.definition?(Dn[p.name]=p.resolve=(A,I,w)=>{let N=A[R.from?R.from:t],v=p.elements.definition.tableClass;return w?od({attribute:R.to,value:N},Vr(I).getReadTxn(),!1,v,!1).asArray:v.search([{attribute:R.to,value:N}],I).asArray},p.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},p.resolve.definition=p.elements.definition,R.from&&(p.resolve.from=R.from)):console.error(`The one-to-many/many-to-many relationship property "${p.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(R.from){let A=p.definition||p.elements?.definition;A?(Dn[p.name]=p.resolve=(I,w,N)=>{let v=I[R.from];if(v!==void 0){if(p.elements){let U,L=v.map(P=>{let H=N?A.tableClass.primaryStore.getEntry(P,{transaction:Vr(w).getReadTxn()}):A.tableClass.get(P,w);return H?.then&&(U=!0),H});return R.filterMissing?U?Promise.all(L).then(P=>P.filter(CW)):L.filter(CW):U?Promise.all(L):L}return N?A.tableClass.primaryStore.getEntry(v,{transaction:Vr(w).getReadTxn()}):A.tableClass.get(v,w)}},p.set=(I,w)=>{if(Array.isArray(w)){let N=w.map(v=>v[ze]||v[A.tableClass.primaryKey]);I[R.from]=N}else{let N=w[ze]||w[A.tableClass.primaryKey];I[R.from]=N}},p.resolve.definition=p.definition||p.elements?.definition,p.resolve.from=R.from):console.error(`The relationship property "${p.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${p.name}" in table "${s}" must use either "from" or "to" arguments`);else b&&(typeof b.from=="function"&&this.setComputedAttribute(p.name,b.from),Dn[p.name]=p.resolve=(A,I,w)=>{let N=typeof b.from=="string"?A[b.from]:A,v=this.userResolvers[p.name];if(v)return v(N,I,w);Ye.default.warn(`Computed attribute "${p.name}" does not have a function assigned to it. Please use setComputedAttribute('${p.name}', resolver) to assign a resolver function.`),this.userResolvers[p.name]=()=>{}})}og(this,this)}static setComputedAttribute(p,R){let b=Fi(g,p);if(!b){console.error(`The attribute "${p}" does not exist in the table "${s}"`);return}if(!b.computed){console.error(`The attribute "${p}" is not defined as computed in the table "${s}"`);return}this.userResolvers[p]=R}static async deleteHistory(p=0){let R;for(let{key:b,value:A}of l.getRange({start:0,end:p}))await eh(),Ht(A).tableId===n&&(R=l.remove(b));await R}static async*getHistory(p=0,R=1/0){for(let{key:b,value:A}of l.getRange({start:p,end:R})){await eh();let I=Ht(A);I.tableId===n&&(yield{id:I.recordId,localTime:b,version:I.version,type:I.type,value:I.getValue(i,!0,b),user:I.user,operation:I.originatingOperation})}}static async getHistoryOfRecord(p){let R=[];if(p==null)throw new Error("An id is required");let b=i.getEntry(p);if(!b)return R;let A=b.localTime;if(!A)throw new Error("The entry does not have a local audit time");let I=0;do{await eh();let w=l.get(A);if(w){let N=Ht(w);R.push({id:N.recordId,localTime:A,version:N.version,type:N.type,value:N.getValue(i,!0,A),user:N.user}),A=N.previousLocalTime}else break}while(I<1e3&&A);return R.reverse()}static cleanup(){Q?.remove()}}Oe.updatedAttributes();let Th=Oe.prototype;return Th[uTe]=!0,f&&Oe.setTTLExpiration(f/1e3),Z&&it(),Oe;function ec(G,p,R){let b;for(let A in r){let I=r[A],w=I.isIndexing,N=Dn[A],v=R&&(N?N(R):R[A]),U=p&&(N?N(p):p[A]);if(v===U&&!w)continue;b=!0;let L=I.indexNulls,P=(0,rh.getIndexedValues)(v,L),H=(0,rh.getIndexedValues)(U,L);if(H?.length>0){let k=new Set(H);if(P=P?P.filter(ue=>{if(k.has(ue))k.delete(ue);else return!0}):[],H=Array.from(k),(H.length>0||P.length>0)&&bW){let ue=H.concat(P).map(X=>({key:X,value:G}));I.prefetch(ue,IW)}for(let ue=0,X=H.length;ue<X;ue++)I.remove(H[ue],G)}else P?.length>0&&bW&&I.prefetch(P.map(k=>({key:k,value:G})),IW);if(P)for(let k=0,ue=P.length;k<ue;k++)I.put(P[k],G)}return b}a(ec,"updateIndices");function hi(G){switch(typeof G){case"number":return!0;case"string":if(G.length<659)return!0;if(G.length>OW)throw new Error("Primary key size is too large: "+G.length);break;case"object":if(G===null)throw new Error("Invalid primary key of null");break;case"bigint":if(G<2n**64n&&G>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof G)}if((0,wl.writeKey)(G,_Te,0)>OW)throw new Error("Primary key size is too large: "+G.length);return!0}a(hi,"checkValidId");function Bl(G,p,R,b,A){if(Oe.getResidencyById&&R.ensureLoaded){let w=Oe.getResidencyById(G);if(w&&!w.includes(server.hostname))return C({key:G,residency:w}).then(A)}let I=a(()=>{if(p?.transaction?.stale&&(p.transaction.stale=!1),R.transaction?.isDone)return A(null,G);let w=i.getEntry(G,R);return w?.residencyId&&w.metadataFlags&ki&&C&&R.ensureLoaded?C(w).then(N=>A(N,G)):(w&&p&&(w?.version>(p.lastModified||0)&&(p.lastModified=w.version),w?.localTime&&!p.lastRefreshed&&(p.lastRefreshed=w.localTime)),A(w,G))},"whenPrefetched");return b?I():ie>0?(ie--,I()):new Promise((w,N)=>{ie===0?(ie--,i.prefetch([G],()=>{v(),U()})):(_e.push(G),K.push(U),_e.length>mC&&(ie--,v()));function v(){if(_e.length>0){let L=K;i.prefetch(_e,()=>{ie===-1?v():ie++;for(let P of L)P()}),_e=[],K=[],le>2&&le--}else ie=le,le<Sh&&le++}a(v,"prefetch");function U(){try{w(I())}catch(L){N(L)}}a(U,"load")})}a(Bl,"loadLocalRecord");function Hl(G){if(!G?.role)return;let p=G.role.permission;if(p.super_user)return fTe;let R=p[c],b,A=R?.tables;if(A)return A[s];if(c==="data"&&(b=p[s])&&!b.tables)return b}a(Hl,"getTablePermissions");function tc(G,p,R,b){if(O){let A=!1;if(R.noCache?A=!0:(p?(!p.value||p.metadataFlags&(ki|va)||p.expiresAt!=null&&p.expiresAt<Date.now())&&(A=!0):A=!0,Vn(!A,"cache-hit",s)),A){let I=Wd(G,p,R).then(w=>(w?.value?.[Ue]&&Ye.default.error?.("Can not assign a record with a record property"),R&&(w?.version>(R.lastModified||0)&&(R.lastModified=w.version),R.lastRefreshed=Date.now()),w));if(R?.onlyIfCached||p?.value&&b?.allowStaleWhileRevalidate?.(p,G)){if(I.catch(w=>Ye.default.warn?.(w)),R?.onlyIfCached&&!b.doesExist())throw new $r.ServerError("Entry is not cached",504);return}else return I}}else if(p?.value&&p.expiresAt!=null&&p.expiresAt<Date.now())return Oe.evict(p.key,p.value,p.version),p.value=null,{then(A){return A(p)}}}a(tc,"ensureLoadedFromSource");function Vr(G){let p=G?.transaction;if(p){if(!p.lmdbDb)return p.lmdbDb=i,p;do{if(p.lmdbDb?.path===i.path)return p;let R=p.next;if(!R)return p=p.next=new Nc,p.lmdbDb=i,p;p=R}while(!0)}else return new Dp}a(Vr,"txnForContext");function xl(G,p,R){if(!G)return;let b=G.value||G.deref?.()||i.getEntry(G.key)?.value;if(typeof p=="object"){let I=Dn,w=b;for(let N=0,v=p.length;N<v;N++){let U=p[N],L=I?.[U];w=L&&w?L(w,R,!0)?.value:w?.[U],I=L?.definition?.tableClass?.propertyResolvers}return w}let A=Dn[p];return A?A(b,R):b[p]}a(xl,"getAttributeValue");function rc(G,p,R,b,A){let I=A?.length,w={transaction:b,lazy:I>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},N;function v(U,L){let P=U?.value;if(!P)return Nl.SKIP;for(let H=0;H<I;H++)if(!N?.includes(H)&&!A[H](P,U))return Nl.SKIP;return L!==void 0&&(U.key=L),U}if(a(v,"processEntry"),I>0||!G.hasEntries){let U=G.map(L=>{if(N=null,typeof L=="object"&&L?.key!==void 0)return I>0?v(L):L;if(L==null)return Nl.SKIP;for(let P=0;P<I;P++){let k=A[P].idFilter;if(k){if(!k(L))return Nl.SKIP;N||(N=[]),N.push(P)}}return Bl(L,R,w,!1,v)});return Array.isArray(G)&&(U=U.filter(L=>L!==Nl.SKIP)),U.hasEntries=!0,U}return G}a(rc,"transformToEntries");function nc(G,p,R=server.replication?.getThisNodeId(l)){if(G<=p?.version){if(p?.version===G&&R!==void 0){let b=server.replication?.exportIdMapping(l),A=p.localTime,I=l.get(A);if(I){let w,N,v=Ht(I);for(let U in b)b[U]===R&&(w=U),b[U]===v.nodeId&&(N=U);if(w>N)return!1}}return!0}return!1}a(nc,"precedesExistingVersion");async function Wd(G,p,R){let b=p?.metadataFlags,A=p?.version,I,w;if(!i.attemptLock(G,A,()=>{clearTimeout(w);let L=i.getEntry(G);!L||!L.value||L.metadataFlags&(ki|va)?I(Wd(G,i.getEntry(G),R)):I(L)}))return new Promise(L=>{I=L,w=setTimeout(()=>{i.unlock(G,A)},lTe)});let N=p?.value,v={requestContext:R,replacingRecord:N,replacingEntry:p,replacingVersion:A,noCacheStore:!1,source:null,resourceCache:R?.resourceCache},U=R?.responseHeaders;return new Promise((L,P)=>{let H;zw(wt(v,async k=>{let ue=performance.now(),X,Ne,fe;try{for(let Re of Oe.sources)if(Re.get&&(!Re.get.reliesOnPrototype||Re.prototype.get)){if(Re.available?.(p)===!1)continue;if(v.source=Re,X=await Re.get(G,v),X)break}fe=b&ki;let se=v.lastModified||fe&&A;Ne=fe||se>A||!N,se||(se=(0,rh.getNextMonotonicTime)());let z=performance.now()-ue;if(Rr(z,"cache-resolution",s),U&&KO(U,"Server-Timing",`cache-resolve;dur=${z.toFixed(2)}`,!0),k.timestamp=se,f&&v.expiresAt==null&&(v.expiresAt=Date.now()+f),X){if(typeof X!="object")throw new Error("Only objects can be cached and stored in tables");if(X.status>0&&X.headers)if(X.status>=300)if(X.status===304)X=N,se=A;else throw new $r.ServerError(X.body||"Error from source",X.status);else X=X.body;typeof X.toJSON=="function"&&(X=X.toJSON()),t&&X[t]!==G&&(X[t]=G)}H=!0,L({key:G,version:se,value:X})}catch(se){se.message+=` while resolving record ${G} for ${s}`,N&&((se.code==="ECONNRESET"||se.code==="ECONNREFUSED"||se.code==="EAI_AGAIN")&&!R?.mustRevalidate||R?.staleIfError&&(se.statusCode===500||se.statusCode===502||se.statusCode===503||se.statusCode===504))?(L({key:G,version:A,value:N}),Ye.default.trace?.(se.message,"(returned stale record)")):P(se),v.transaction.abort();return}if(R?.noCacheStore||v.noCacheStore){v.transaction.abort();return}Vr(v).addWrite({key:G,store:i,entry:p,nodeName:"source",commit:(se,z)=>{if(z?.version!==A)return;let Re=ec(G,N,X);X?(ve.put?.(v,G,X),Ye.default.trace?.(`Writing resolved record from source with id: ${G}, timestamp: ${new Date(se).toISOString()}`),m(G,X,z,se,0,S&&Ne||null,{user:v?.user,expiresAt:v.expiresAt},"put",!!fe)):z&&(ve.delete?.(v,G),Ye.default.trace?.(`Deleting resolved record from source with id: ${G}, timestamp: ${new Date(se).toISOString()}`),S||T?m(G,null,z,se,0,S&&Ne||null,{user:v?.user},"delete",!!fe):i.remove(G,A))}})}),()=>{i.unlock(G,A)},k=>{i.unlock(G,A),H&&Ye.default.error?.("Error committing cache update",k)})})}a(Wd,"getFromSource");function Wo(G){if(!G||G.user?.role?.permission?.super_user)return!0;if(G.replicateTo)throw new $r.ClientError("Can not specify replication parameters without super user permissions",403);if(G.replicatedConfirmation)throw new $r.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Wo,"checkContextPermissions");function re(){if(et!==Ja&&(Ja=et,(0,Il.getWorkerIndex)()===(0,Il.getWorkerCount)()-1)){if(Xa&&clearTimeout(Xa),!et)return;let G=new Date;G.setMonth(0),G.setDate(1),G.setHours(0),G.setMinutes(0),G.setSeconds(0);let p=Math.ceil((Date.now()-G.getTime())/et)*et+G.getTime(),R=a(b=>{Ye.default.trace?.(`Scheduled next cleanup scan at ${new Date(b)}ms`),Xa=setTimeout(()=>F=F.then(async()=>{if(R(Math.max(b+et,Date.now())),i.rootStore.status!=="open"){clearTimeout(Xa);return}let A=50,I=new Array(A),w=0;Ye.default.info?.(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:v,value:U,version:L,expiresAt:P}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let H;U===null&&!S&&L+cTe<Date.now()?H=i.remove(v,L):P!=null&&P+h<Date.now()&&(H=Oe.evict(v,U,L),N++),H&&(await I[w],I[w]=H.catch(k=>{Ye.default.error?.("Cleanup error",k)}),++w>=A&&(w=0)),await eh()}Ye.default.info?.(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){Ye.default.warn?.(`Error in cleanup scan for ${s}:`,N)}}),Math.min(b-Date.now(),2147483647)).unref()},"startNextTimer");R(p)}}a(re,"scheduleCleanup");function ge(){Q=l?.addDeleteRemovalCallback(n,G=>{let p=i.getEntry(G);p?.value===null&&i.remove(G,p.version)})}a(ge,"addDeleteRemoval");function it(){(0,Il.getWorkerIndex)()===0&&setInterval(async()=>{if(!Kd){Kd=!0;try{let G=Z.name,p=r[G];if(!p)throw new Error(`expiresAt attribute ${Z} must be indexed`);for(let R of p.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let b of p.getValues(R)){let A=i.getEntry(b);A?.value?A.value[G]<Date.now()&&Oe.evict(b,A.value,A.version):i.ifVersion(b,A?.version,()=>p.remove(R,b))}await eh()}}catch(G){Ye.default.error?.("Error in evicting old records",G)}finally{Kd=!1}}},aTe).unref()}a(it,"runRecordExpirationEviction");function Te(G){if(G){let p=G.join(","),R=u.get([Symbol.for("residency_by_set"),p]);return R||(u.put([Symbol.for("residency_by_set"),p],R=Math.floor(Math.random()*2147483647)),u.put([Symbol.for("residency_by_id"),R],G),R)}}a(Te,"getResidencyId")}function Qw(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 IW(){}function ETe(e){PW=e}function ug(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return lg(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return lg(+e);case"Float":return e==="null"?null:lg(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;hTe.test(e)||(e+="Z");let n=new Date(e);return lg(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,_g.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function lg(e){if(isNaN(e))throw new SyntaxError;return e}function wW(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 zw(e,t,r){return e?.then?e.then(t,r):t(e)}function dg(e,t){e[qr]=t,e[Ue]=t?.value??null,e[th]=t?.version}function CW(e){return e!=null}function Ei(e){try{return JSON.stringify(e)}catch{return e}}function pTe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Fs,Nl,rh,DW,Md,$r,nh,sh,Ye,wl,Il,_g,oTe,PW,aTe,cTe,bW,lTe,th,uTe,qr,ZE,yW,dTe,jw,ki,va,_Te,OW,NW,fTe,JUe,hTe,eh,TE=Ce(()=>{Fs=B(M()),Nl=require("lmdb"),rh=B(an()),DW=require("lodash");ls();Pp();Md=B(te());ty();$r=B(ce()),nh=B(_o()),sh=B(Qs());De();SE();Ye=B(du());Up();Ic();wl=require("ordered-binary"),Il=B(ut());io();_g=B(ee());$l();Ci();ZT();zf();oTe=new Uint8Array(9);oTe[8]=192;aTe=6e4,cTe=864e5;Md.initSync();bW=Md.get(Fs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),lTe=1e4,th=Symbol.for("version"),uTe=Symbol.for("incremental-update"),qr=Symbol("entry"),ZE=Symbol("is-saving"),yW=1,dTe=2,jw=Symbol("loaded-from-source"),ki=1,va=8,_Te=Buffer.allocUnsafeSlow(8192),OW=1978,NW=100,fTe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},JUe=(0,_g.convertToMS)(Md.get(Fs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(fg,"makeTable");a(Qw,"attributesAsObject");a(IW,"noop");a(ETe,"setServerUtilities");hTe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(ug,"coerceType");a(lg,"rejectNaN");a(wW,"isDescendantId");eh=a(()=>new Promise(setImmediate),"rest");a(zw,"when");a(dg,"updateResource");a(CW,"exists");a(Ei,"stringify");a(pTe,"hasOtherProcesses")});var at={};tt(at,{database:()=>ou,databases:()=>Ve,dropDatabase:()=>Ab,dropTableMeta:()=>RTe,getDatabases:()=>ft,getDefaultCompression:()=>aS,getTables:()=>mTe,onRemovedDB:()=>mf,onUpdatedTable:()=>Gc,readMetaDb:()=>ih,resetDatabases:()=>Wu,table:()=>dt,tables:()=>Un});function mTe(){return mg||ft(),Un||{}}function ft(){if(mg)return Ve;mg=!0,Bd=new Map;let e=(0,er.getHdbBasePath)()&&(0,vt.join)((0,er.getHdbBasePath)(),Tr.DATABASES_DIR_NAME),t=(0,er.get)(Tr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,er.get)(Tr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,rs.existsSync)(e)?e:(0,vt.join)((0,er.getHdbBasePath)(),Tr.LEGACY_DATABASES_DIR_NAME)),!e)return;if((0,rs.existsSync)(e))for(let n of(0,rs.readdirSync)(e,{withFileTypes:!0})){let s=(0,vt.basename)(n.name,".mdb");n.isFile()&&(0,vt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&ih((0,vt.join)(e,n.name),null,s)}if((0,rs.existsSync)((0,vd.getBaseSchemaPath)())){for(let n of(0,rs.readdirSync)((0,vd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,vt.join)((0,vd.getBaseSchemaPath)(),n.name),i=(0,vt.join)((0,vd.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,rs.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,vt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,vt.join)(i,o.name);ih((0,vt.join)(s,o.name),(0,vt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,rs.existsSync)(i))for(let c of(0,rs.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,vt.extname)(c.name).toLowerCase()===".mdb"&&ih((0,vt.join)(i,c.name),(0,vt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],d=(0,vt.join)(l.path,(0,vt.basename)(c+".mdb"));(0,rs.existsSync)(d)&&ih(d,c,n,null,!0)}}for(let n in Ve){let s=Bd.get(n);if(s){let i=Ve[n];n.includes("delete")&&$t.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||($t.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Un)delete Un[i];delete Un[Sg]}}let r=["hdb_temp","hdb_certificate","hdb_analytics","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if(Ve.system)for(let n of r)Ve.system[n]&&(Ve.system[n].replicate=!1);return Bd=null,Ve}function Wu(){mg=!1;for(let[,e]of Qa)e.needsDeletion=!0;ft();for(let[e,t]of Qa)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Qa.delete(e),delete Ve[t.databaseName],ah.forEach(r=>r(t.databaseName)));return Ve}function ih(e,t,r=Zw,n,s){let i=new Jw.default(e,!1);try{let o=Qa.get(e);o?o.needsDeletion=!1:(o=(0,Hd.open)(i),Qa.set(e,o));let c=new Cl.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(Eg.INTERNAL_DBIS_NAME,c)),d=o.auditStore;d||(n?(0,rs.existsSync)(n)&&(i.path=n,d=(0,Hd.open)(i),d.isLegacy=!0):d=XT(o));let u=vW(r),_=u[Sg],E=new Map;for(let{key:f,value:h}of l.getRange({start:!1})){let[S,T]=f.toString().split("/");T===""?T=h.name:T||(T=S,S=t,h.name||(h.name=T,h.indexed=!h.is_hash_attribute)),_?.add(S);let g=E.get(S);g||E.set(S,g={attributes:[]}),(T==null||h.is_hash_attribute)&&(g.primary=h),T!=null&&g.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:S,primary:T}=h;if(!T){for(let K of S)if(K.is_hash_attribute||K.isPrimaryKey){T=K;break}if(!T){$t.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(S)}`);continue}}let g=u[f],m={},C=[],O,x,F=typeof T.audit=="boolean"?T.audit:(0,er.get)(Tr.CONFIG_PARAMS.LOGGING_AUDITLOG),Y=T.trackDeletes,$=T.expiration,Z=T.eviction,Q=T.sealed,_e=T.replicate;if(g)m=g.indices,C=g.attributes,g.schemaVersion++;else{O=T.tableId,O?O>=(l.get(Ud)||0)&&(l.putSync(Ud,O+1),$t.info(`Updating next table id (it was out of sync) to ${O+1} for ${f}`)):(T.tableId=O=l.get(Ud),O||(O=1),$t.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(Ud,O+1),l.putSync(T.key,T));let K=new Cl.default(!T.is_hash_attribute,T.is_hash_attribute);if(K.compression=T.compression,K.compression){let ie=(0,er.get)(Tr.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||UW;K.compression.threshold=ie}x=kh(o.openDB(T.key,K)),o.databaseName=r,x.rootStore=o,x.tableId=O}for(let K of S){K.attribute=K.name;try{if(!K.is_hash_attribute&&(K.indexed||K.attribute&&!K.name)){if(!m[K.name]){let le=new Cl.default(!K.is_hash_attribute,K.is_hash_attribute);m[K.name]=o.openDB(K.key,le),m[K.name].indexNulls=K.indexNulls}let ie=C.find(le=>le.name===K.name);ie?C.splice(C.indexOf(ie),1,K):C.push(K)}}catch(ie){$t.error("Error trying to update attribute",K,C,m,ie)}}if(!g){g=BW(u,f,fg({primaryStore:x,auditStore:d,audit:F,sealed:Q,replicate:_e,expirationMS:$&&$*1e3,evictionMS:Z&&Z*1e3,trackDeletes:Y,tableName:f,tableId:O,primaryKey:T.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:m,attributes:S,schemaDefined:T.schemaDefined,dbisDB:l})),g.schemaVersion=1;for(let K of oh)K(g)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function vW(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Un:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),Bd&&!Bd.has(e)){let r=new Set;t[Sg]=r,Bd.set(e,r)}return t}function BW(e,t,r){return e[t]=r,r}function ou({database:e,table:t}){e||(e=Zw),ft();let r=vW(e),n=(0,vt.join)((0,er.getHdbBasePath)(),Tr.DATABASES_DIR_NAME),s=(0,er.get)(Tr.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,er.get)(Tr.CONFIG_PARAMS.STORAGE_PATH)||((0,rs.existsSync)(n)?n:(0,vt.join)((0,er.getHdbBasePath)(),Tr.LEGACY_DATABASES_DIR_NAME));let o=(0,vt.join)(n,(i?t:e)+".mdb"),c=Qa.get(o);if(!c||c.status==="closed"){let l=new Jw.default(o,!1);c=(0,Hd.open)(l),Qa.set(o,c)}return c.auditStore||(c.auditStore=XT(c)),c}async function Ab(e){if(!Ve[e])throw new Error("Schema does not exist");let t=Ve[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Qa.delete(r.path),r.status==="open"&&(await r.close(),await ch.remove(r.path));if(r||(r=ou({database:e,table:null}),r.status==="open"&&(await r.close(),await ch.remove(r.path))),e==="data"){for(let n in Un)delete Un[n];delete Un[Sg]}delete Ve[e],ah.forEach(n=>n(e))}function dt(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,replicate:d,trackDeletes:u,schemaDefined:_,origin:E}=e;r||(r=Zw);let f=ou({database:r,table:t}),h=Ve[r];$t.trace(`Defining ${t} in ${r}`);let S=h?.[t];if(f.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let T,g,m;_==null&&(_=!0);let C=new Cl.default(!1);for(let Q of o)Q.attribute&&!Q.name?(Q.name=Q.attribute,Q.indexed=!0):Q.attribute=Q.name,Q.expiresAt&&(Q.indexed=!0);let O,x;if(S){if(T=S.primaryKey,S.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);S.attributes.splice(0,S.attributes.length,...o)}else{let Q=f.auditStore;g=o.find(le=>le.isPrimaryKey)||{},T=g.name,g.is_hash_attribute=!0,g.schemaDefined=_,g.compression=aS(),u&&(g.trackDeletes=!0),c=g.audit=typeof c=="boolean"?c:(0,er.get)(Tr.CONFIG_PARAMS.LOGGING_AUDITLOG),n&&(g.expiration=n),s&&(g.eviction=s),typeof l=="boolean"&&(g.sealed=l),typeof d=="boolean"&&(g.replicate=d),E&&(g.origins?g.origins.includes(E)||g.origins.push(E):g.origins=[E]),$t.trace(`${t} table loading, opening primary store`);let _e=new Cl.default(!1,!0);_e.compression=g.compression;let K=t+"/";if(m=f.dbisDb=f.openDB(Eg.INTERNAL_DBIS_NAME,C),Z(),m.get(K))return x&&x(),Wu(),dt(e);let ie=kh(f.openDB(K,_e));f.databaseName=r,ie.rootStore=f,ie.tableId=m.get(Ud),$t.trace(`Assigning new table id ${ie.tableId} for ${t}`),ie.tableId||(ie.tableId=1),m.put(Ud,ie.tableId+1),g.tableId=ie.tableId,S=BW(h,t,fg({primaryStore:ie,auditStore:Q,audit:c,sealed:l,replicate:d,trackDeletes:u,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:T,tableName:t,tableId:ie.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:m})),S.schemaVersion=1,O=!0,m.put(K,g)}let F=S.indices;m=m||(f.dbisDb=f.openDB(Eg.INTERNAL_DBIS_NAME,C)),S.dbisDB=m;let Y=[];for(let{key:Q,value:_e}of m.getRange({start:!0})){let[K,ie]=Q.toString().split("/");if(ie===""&&(ie=_e.name),ie){if(K!==t)continue}else ie=K;if(!o.find(we=>we.name===ie)?.indexed&&_e.indexed&&!_e.isPrimaryKey){Z(),O=!0,m.remove(Q);let we=S.indices[K];we&&Y.push(we)}}let $=[];try{for(let Q of o||[]){if((Q.relationship||Q.computed)&&(O=!0,Q.relationship))continue;let _e=t+"/"+(Q.name||"");Object.defineProperty(Q,"key",{value:_e,configurable:!0});let K=m.get(_e);if(Q.isPrimaryKey){if(K=K||m.get(_e=t+"/")||{},c!==void 0&&c!==S.audit||l!==void 0&&l!==S.sealed||d!==void 0&&d!==S.replicate||(+n||void 0)!==(+K.expiration||void 0)||(+s||void 0)!==(+K.eviction||void 0)){let le={...K};typeof c=="boolean"&&(c&&S.enableAuditing(c),le.audit=c),n&&(le.expiration=+n),s&&(le.eviction=+s),l!==void 0&&(le.sealed=l),d!==void 0&&(le.replicate=d),O=!0,Z(),m.put(_e,le)}continue}K?.attribute&&!K.name&&(K.indexed=!0);let ie=!K||K.type!==Q.type||K.indexed!==Q.indexed||K.nullable!==Q.nullable||K.version!==Q.version||JSON.stringify(K.attributes)!==JSON.stringify(Q.attributes)||JSON.stringify(K.elements)!==JSON.stringify(Q.elements);if(Q.indexed){let le=new Cl.default(!0,!1),we=f.openDB(_e,le);(ie||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<lh.workerData?.restartNumber)&&(O=!0,Z(),K=m.get(_e),(ie||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<lh.workerData?.restartNumber)&&(O=!0,Q.indexNulls===void 0&&(Q.indexNulls=!0),S.primaryStore.getStats().entryCount>0&&(Q.lastIndexedKey=K?.lastIndexedKey??void 0,Q.indexingPID=process.pid,we.isIndexing=!0,Object.defineProperty(Q,"dbi",{value:we}),$.push(Q))),m.put(_e,Q)),K?.indexNulls&&Q.indexNulls===void 0&&(Q.indexNulls=!0),we.indexNulls=Q.indexNulls,F[Q.name]=we}else ie&&(O=!0,Z(),m.put(_e,Q))}}finally{x&&x()}if(O&&(S.schemaVersion++,S.updatedAttributes()),$t.trace(`${t} table loading, running index`),$.length>0||Y.length>0?S.indexingOperation=gTe(S,$,Y):O&&hg.signalSchemaChange(new pg.SchemaEventMsg(process.pid,"schema-change",S.databaseName,S.tableName)),S.origin=E,O)for(let Q of oh)Q(S,E!=="cluster");return(n||s||i)&&S.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),$t.trace(`${t} table loaded`),S;function Z(){x||f.transactionSync(()=>({then(Q){x=Q}}))}a(Z,"startTxn")}async function gTe(e,t,r){try{$t.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await hg.signalSchemaChange(new pg.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let d of r)s=d.drop();let i,o={},c=0,l=t.length;if(await new Promise(d=>setImmediate(d)),l>0){let d;for(let _ of t)(0,Hd.compareKeys)(_.lastIndexedKey,d)<0&&(d=_.lastIndexedKey),_.lastIndexedKey==null&&_.dbi.clearAsync();let u=0;for(let{key:_,value:E,version:f}of e.primaryStore.getRange({start:d,lazy:l<4,versions:!0,snapshot:!1}))if(E){if(u++,s=e.primaryStore.ifVersion(_,f,()=>{for(let h=0;h<l;h++){let S=t[h],T=S.name;try{let g=S.resolve,m=E&&(g?g(E):E[T]),C=(0,LW.getIndexedValues)(m);if(C)for(let O=0,x=C.length;O<x;O++)S.dbi.put(C[O],_)}catch(g){o[T]||(o[T]=!0,$t.error(`Error indexing attribute ${T}`,g))}}}),s.then(()=>u--,h=>{u--,$t.error(h)}),lh.workerData&&lh.workerData.restartNumber!==MW.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=_,e.dbisDB.put(h.key,h);if(i)return}u>STe?await s:u>TTe&&await new Promise(h=>setImmediate(h))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await hg.signalSchemaChange(new pg.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),$t.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){$t.error("Error in indexing",n)}}function RTe({table:e,database:t}){let r=ou({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 Gc(e){return oh.push(e),{remove(){let t=oh.indexOf(e);t>-1&&oh.splice(t,1)}}}function mf(e){return ah.push(e),{remove(){let t=ah.indexOf(e);t>-1&&ah.splice(t,1)}}}function aS(){let e=(0,er.get)(Tr.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,er.get)(Tr.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,er.get)(Tr.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||UW,n={startingOffset:32};return t&&(n.dictionary=ch.readFileSync(t)),r&&(n.threshold=r),e&&n}var er,Eg,Hd,vt,rs,vd,Cl,Jw,Tr,ch,Xw,LW,hg,pg,lh,$t,MW,Zw,Sg,UW,Un,Ve,Ud,oh,ah,mg,Qa,Bd,STe,TTe,De=Ce(()=>{er=B(te()),Eg=B(Bt()),Hd=require("lmdb"),vt=require("path"),rs=require("fs"),vd=B(mt());TE();Cl=B(p_()),Jw=B(m_()),Tr=B(M()),ch=B(require("fs-extra")),Xw=B(no()),LW=B(an()),hg=B(_o()),pg=B(Qs()),lh=require("worker_threads"),$t=B(V()),MW=B(ut());io();$l();Zw="data",Sg=Symbol("defined-tables"),UW=((0,er.get)(Tr.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,er.initSync)();Un=Object.create(null),Ve=Object.create(null);(0,Xw._assignPackageExport)("databases",Ve);(0,Xw._assignPackageExport)("tables",Un);Ud=Symbol.for("next-table-id"),oh=[],ah=[],Qa=new Map;a(mTe,"getTables");a(ft,"getDatabases");a(Wu,"resetDatabases");a(ih,"readMetaDb");a(vW,"ensureDB");a(BW,"setTable");a(ou,"database");a(Ab,"dropDatabase");a(dt,"table");STe=1e3,TTe=10;a(gTe,"runIndexing");a(RTe,"dropTableMeta");a(Gc,"onUpdatedTable");a(mf,"onRemovedDB");a(aS,"getDefaultCompression")});var ee=y((ove,zW)=>{"use strict";var za=require("path"),GW=require("fs-extra"),wn=V(),HW=require("fs-extra"),Tg=require("os"),ATe=require("net"),bTe=require("recursive-iterator"),Vt=M(),yTe=Qg(),xW=require("papaparse"),gg=require("moment"),{inspect:OTe}=require("util"),FW=require("is-number"),ive=require("lodash"),NTe=require("minimist"),ITe=require("https"),wTe=require("http"),{hdb_errors:Rg}=ce(),CTe=/^((\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)))$/,qW=require("util").promisify(setTimeout),DTe=100,PTe=5,LTe="",MTe=4,kW={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};zW.exports={isEmpty:ns,isEmptyOrZeroLength:Xi,arrayHasEmptyValues:BTe,arrayHasEmptyOrZeroLengthValues:HTe,buildFolderPath:xTe,isBoolean:$W,errorizeMessage:UTe,stripFileExtension:kTe,autoCast:GTe,autoCastJSON:VW,autoCastJSONDeep:tC,removeDir:qTe,compareVersions:$Te,isCompatibleDataVersion:VTe,escapeRawValue:YTe,unescapeValue:KTe,stringifyProps:WTe,timeoutPromise:QTe,isClusterOperation:JTe,getClusterUser:ZTe,checkGlobalSchemaTable:XTe,getHomeDir:KW,getPropsFilePath:jTe,promisifyPapaParse:ege,removeBOM:WW,createEventPromise:tge,checkProcessRunning:rge,checkSchemaTableExist:nge,checkSchemaExists:jW,checkTableExists:QW,getStartOfTomorrowInSeconds:sge,getLimitKey:ige,isObject:FTe,isNotEmptyAndHasValue:vTe,autoCasterIsNumberCheck:YW,backtickASTSchemaItems:oge,isPortTaken:zTe,createForkArgs:age,autoCastBoolean:cge,async_set_timeout:qW,getTableHashAttribute:lge,doesSchemaExist:uge,doesTableExist:dge,stringifyObj:_ge,ms_to_time:fge,changeExtension:Ege,getEnvCliRootPath:rC,noBootFile:hge,httpRequest:pge,transformReq:mge,convertToMS:Sge,PACKAGE_ROOT:Vt.PACKAGE_ROOT};function UTe(e){return e instanceof Error?e:new Error(e)}a(UTe,"errorizeMessage");function ns(e){return e==null}a(ns,"isEmpty");function vTe(e){return!ns(e)&&(e||e===0||e===""||$W(e))}a(vTe,"isNotEmptyAndHasValue");function Xi(e){return ns(e)||e.length===0||e.size===0}a(Xi,"isEmptyOrZeroLength");function BTe(e){if(ns(e))return!0;for(let t=0;t<e.length;t++)if(ns(e[t]))return!0;return!1}a(BTe,"arrayHasEmptyValues");function HTe(e){if(Xi(e))return!0;for(let t=0;t<e.length;t++)if(Xi(e[t]))return!0;return!1}a(HTe,"arrayHasEmptyOrZeroLengthValues");function xTe(...e){try{return e.join(za.sep)}catch{console.error(e)}}a(xTe,"buildFolderPath");function $W(e){return ns(e)?!1:e===!0||e===!1}a($W,"isBoolean");function FTe(e){return ns(e)?!1:typeof e=="object"}a(FTe,"isObject");function kTe(e){return Xi(e)?LTe:e.slice(0,-MTe)}a(kTe,"stripFileExtension");function GTe(e){return ns(e)||e===""||typeof e!="string"?e:kW[e]!==void 0?kW[e]:YW(e)===!0?Number(e):CTe.test(e)?new Date(e):e}a(GTe,"autoCast");function VW(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(VW,"autoCastJSON");function tC(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=tC(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=tC(r);n!==r&&(e[t]=n)}return e}else return VW(e)}a(tC,"autoCastJSONDeep");function YW(e){if(e.startsWith("0.")&&FW(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&FW(e))}a(YW,"autoCasterIsNumberCheck");async function qTe(e){if(Xi(e))throw new Error(`Directory path: ${e} does not exist`);try{await HW.emptyDir(e),await HW.remove(e)}catch(t){throw wn.error(`Error removing files in ${e} -- ${t}`),t}}a(qTe,"removeDir");function $Te(e,t){if(Xi(e)){wn.info("Invalid current version sent as parameter.");return}if(Xi(t)){wn.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("."),l=Math.min(o.length,c.length);for(let d=0;d<l;d++)if(r=parseInt(o[d],10)-parseInt(c[d],10),r)return r;return o.length-c.length}a($Te,"compareVersions");function VTe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(VTe,"isCompatibleDataVersion");function YTe(e){if(ns(e))return e;let t=String(e);return t==="."?Vt.UNICODE_PERIOD:t===".."?Vt.UNICODE_PERIOD+Vt.UNICODE_PERIOD:t.replace(Vt.FORWARD_SLASH_REGEX,Vt.UNICODE_FORWARD_SLASH)}a(YTe,"escapeRawValue");function KTe(e){if(ns(e))return e;let t=String(e);return t===Vt.UNICODE_PERIOD?".":t===Vt.UNICODE_PERIOD+Vt.UNICODE_PERIOD?"..":String(e).replace(Vt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(KTe,"unescapeValue");function WTe(e,t){if(ns(e))return wn.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+Tg.EOL}!Xi(n)&&n[0]===";"?r+=" "+n+s+Tg.EOL:Xi(n)||(r+=n+"="+s+Tg.EOL)}catch{wn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(WTe,"stringifyProps");function KW(){let e;try{e=Tg.homedir()}catch{e=process.env.HOME}return e}a(KW,"getHomeDir");function jTe(){let e=za.join(KW(),Vt.HDB_HOME_DIR_NAME,Vt.BOOT_PROPS_FILE_NAME);return GW.existsSync(e)||(e=za.join(__dirname,"../","hdb_boot_properties.file")),e}a(jTe,"getPropsFilePath");function QTe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(QTe,"timeoutPromise");async function zTe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=ATe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(zTe,"isPortTaken");function JTe(e){try{return Vt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){wn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(JTe,"isClusterOperation");function XTe(e,t){let r=(De(),ne(at)).getDatabases();if(!r[e])return Rg.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return Rg.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(XTe,"checkGlobalSchemaTable");function ZTe(e,t){if(ns(t)){wn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ns(e)||Xi(e)){wn.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){wn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){wn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(ZTe,"getClusterUser");function ege(){xW.parsePromise=function(e,t,r){return new Promise(function(n,s){xW.parse(e,{header:!0,transformHeader:WW,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(ege,"promisifyPapaParse");function WW(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(WW,"removeBOM");function tge(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;wn.info(`Got cluster status event response: ${OTe(s)}`);try{i.cancel()}catch{wn.error("Error trying to cancel timeout.")}n(s)})})}a(tge,"createEventPromise");async function rge(e){let t=!0,r=0;do await qW(DTe*r++),(await yTe.findPs(e)).length>0&&(t=!1);while(t&&r<PTe);if(t)throw new Error(`process ${e} was not started`)}a(rge,"checkProcessRunning");function nge(e,t){let r=jW(e);if(r)return r;let n=QW(e,t);if(n)return n}a(nge,"checkSchemaTableExist");function jW(e){let{getDatabases:t}=(De(),ne(at));if(!t()[e])return Rg.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(jW,"checkSchemaExists");function QW(e,t){let{getDatabases:r}=(De(),ne(at));if(!r()[e][t])return Rg.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(QW,"checkTableExists");function sge(){let e=gg().utc().add(1,Vt.MOMENT_DAYS_TAG).startOf(Vt.MOMENT_DAYS_TAG).unix(),t=gg().utc().unix();return e-t}a(sge,"getStartOfTomorrowInSeconds");function ige(){return gg().utc().format("DD-MM-YYYY")}a(ige,"getLimitKey");function oge(e){try{let t=new bTe(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){wn.error("Got an error back ticking items."),wn.error(t)}}a(oge,"backtickASTSchemaItems");function age(e){return[e]}a(age,"createForkArgs");function cge(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(cge,"autoCastBoolean");function lge(e,t){let{getDatabases:r}=(De(),ne(at)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(lge,"getTableHashAttribute");function uge(e){let{getDatabases:t}=(De(),ne(at));return t()[e]!==void 0}a(uge,"doesSchemaExist");function dge(e,t){let{getDatabases:r}=(De(),ne(at));return r()[e]?.[t]!==void 0}a(dge,"doesTableExist");function _ge(e){try{return JSON.stringify(e)}catch{return e}}a(_ge,"stringifyObj");function fge(e){let t=gg.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(fge,"ms_to_time");function Ege(e,t){let r=za.basename(e,za.extname(e));return za.join(za.dirname(e),r+t)}a(Ege,"changeExtension");function rC(){if(process.env[Vt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Vt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=NTe(process.argv);if(e[Vt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Vt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(rC,"getEnvCliRootPath");var eC;function hge(){if(eC)return eC;let e=rC();if(rC()&&GW.pathExistsSync(za.join(e,Vt.HDB_CONFIG_FILE)))return eC=!0,!0}a(hge,"noBootFile");function pge(e,t){let r;return e.protocol==="http:"?r=wTe:r=ITe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",l=>{c.body+=l}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(pge,"httpRequest");function mge(e){if(!e.schema&&!e.database){e.schema=Vt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(mge,"transformReq");function Sge(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(Sge,"convertToMS")});var te=y((tj,rj)=>{"use strict";var nC=require("fs-extra"),Dl=require("path"),JW=require("os"),Tge=require("properties-reader"),dh=V(),uh=ee(),Le=M(),Ag=yt(),gge="Error initializing environment manager",bg="BOOT_PROPS_FILE_PATH",XW=!1,Rge={[Le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Yo={};Object.assign(tj,rj.exports={BOOT_PROPS_FILE_PATH:bg,getHdbBasePath:Age,setHdbBasePath:bge,get:ZW,initSync:Oge,setProperty:Je,initTestEnvironment:Ige,setCloneVar:Nge});function Age(){return Yo[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Age,"getHdbBasePath");function bge(e){Yo[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(bge,"setHdbBasePath");function ZW(e){let t=Ag.getConfigValue(e);return t===void 0?Yo[e]:t}a(ZW,"get");function Je(e,t){Rge[e]&&(Yo[e]=t),Ag.updateConfigObject(e,t)}a(Je,"setProperty");function yge(){let e;try{e=uh.getPropsFilePath(),nC.accessSync(e,nC.constants.F_OK|nC.constants.R_OK),XW=!0;let t=Tge(e);return Yo[Le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Le.HDB_SETTINGS_NAMES.INSTALL_USER),Yo[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Yo[bg]=e,!0}catch{return dh.trace(`Environment manager found no properties file at ${e}`),!1}}a(yge,"doesPropFileExist");function Oge(e=!1){try{(XW||yge()||uh.noBootFile())&&!ej&&(Ag.initConfig(e),Yo[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Ag.getConfigValue(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){dh.error(gge),dh.error(t),console.error(t),process.exit(1)}}a(Oge,"initSync");var ej=!1;function Nge(e){ej=e}a(Nge,"setCloneVar");function Ige(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,l=Dl.join(__dirname,"../../","unitTests");Yo[bg]=Dl.join(l,"hdb_boot_properties.file"),Je(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Dl.join(l,"settings.test")),Je(Le.HDB_SETTINGS_NAMES.INSTALL_USER,JW.userInfo()?JW.userInfo().username:void 0),Je(Le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Je(Le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Dl.join(l,"envDir","log")),Je(Le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Je(Le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Je(Le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Je(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Dl.join(l,"envDir")),Je(Le.CONFIG_PARAMS.STORAGE_PATH,Dl.join(l,"envDir")),s&&(Je(Le.CONFIG_PARAMS.HTTP_SECUREPORT,ZW(Le.CONFIG_PARAMS.HTTP_PORT)),Je(Le.CONFIG_PARAMS.HTTP_PORT,null)),Je(Le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Je(Le.CONFIG_PARAMS.HTTP_PORT,9926),Je(Le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Je(Le.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Je(Le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,uh.isEmpty(i)?!1:i),Je(Le.CONFIG_PARAMS.HTTP_CORS,uh.isEmpty(i)?!1:i),Je(Le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Je(Le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Je(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Je(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Je(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Dl.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Je(Le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,uh.isEmpty(c)?!1:c),o&&(Je("CORS_ACCESSLIST",o),Je(Le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Je(Le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Je(Le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Je(Le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Je(Le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Je(Le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Je(Le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${bg}. Please check your boot props and settings files`;dh.fatal(r),dh.error(t)}}a(Ige,"initTestEnvironment")});var ij=y((lve,sj)=>{"use strict";var Og=te();Og.initSync();var yg=M(),{httpRequest:wge}=ee(),Cge=require("path"),nj=require("fs-extra"),Dge=require("yaml"),Pge={describe_table:!0,describe_all:!0,describe_database:!0,list_users:!0,list_roles:!0,drop_role:!0,add_user:!0,alter_user:!0,drop_user:!0,restart_service:!0,restart:!0,create_database:!0,drop_database:!0,create_table:!0,drop_table:!0,create_attribute:!0,drop_attribute:!0,search_by_id:!0,delete:!0,search_by_value:!0,csv_file_load:!0,csv_url_load:!0,cluster_get_routes:!0,cluster_network:!0,cluster_status:!0,remove_node:!0,add_component:!0,deploy_component:!0,package_component:!0,drop_component:!0,get_components:!0,get_component_file:!0,set_component_file:!0,registration_info:!0,get_fingerprint:!0,set_license:!0,get_job:!0,search_jobs_by_start_date:!0,read_log:!0,read_transaction_log:!0,read_audit_log:!0,delete_transaction_logs_before:!0,purge_stream:!0,delete_records_before:!0,install_node_modules:!0,set_configuration:!0,get_configuration:!0,create_authentication_tokens:!0,refresh_operation_token:!0,system_information:!0,sql:!0,create_csr:!0,sign_certificate:!0,list_certificates:!0,add_certificate:!0,remove_certificate:!0,add_ssh_key:!0,update_ssh_key:!0,delete_ssh_key:!0,list_ssh_keys:!0,set_ssh_known_hosts:!0,get_ssh_known_hosts:!0};sj.exports={cliOperations:Mge,buildRequest:Lge};function Lge(){let e={};for(let t of process.argv){if(Pge[t]){e.operation=t;continue}if(t.includes("=")){let[r,...n]=t.split("=");n=n.join("=");try{n=JSON.parse(n)}catch{}e[r]=n}}return e}a(Lge,"buildRequest");async function Mge(e){nj.existsSync(Cge.join(Og.get(yg.CONFIG_PARAMS.ROOTPATH),yg.HDB_PID_FILE))||(console.error("HarperDB must be running to perform this operation"),process.exit()),nj.existsSync(Og.get(yg.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))||(console.error("No domain socket found, unable to perform this operation"),process.exit());try{let t=await wge({method:"POST",protocol:"http:",socketPath:Og.get(yg.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),headers:{"Content-Type":"application/json"}},e);t=JSON.parse(t.body),e.json?console.log(JSON.stringify(t,null,2)):console.log(Dge.stringify(t).trim())}catch(t){let r="Error: ";t?.response?.data?.error?r+=t.response.data.error:t?.response?.data?r+=t?.response?.data:r+=t.message,console.error(r)}}a(Mge,"cliOperations")});var cj=y((dve,aj)=>{"use strict";var oj=require("semver/functions/major"),Uge=Cc(),sC=process.versions&&process.versions.node?process.versions.node:void 0;aj.exports=vge;function vge(){let e=Uge.engines["minimum-node"];if(sC&&oj(sC)<oj(e))return{error:`The minimum version of Node.js HarperDB supports is: ${e}, the currently installed Node.js version is: ${sC}. Please install a version of Node.js that is withing the defined range.`}}a(vge,"checkNodeVersion")});var dC=y((Eve,Aj)=>{"use strict";var lj=require("os"),Ng=require("https"),uj=require("http"),_r=require("fs-extra"),dj=require("yaml"),{pipeline:_j}=require("stream/promises"),{createWriteStream:Ig,ensureDir:_h}=require("fs-extra"),{join:eo}=require("path"),hj=require("lodash"),Bge=require("minimist"),$d=require("path"),Hge=require("properties-reader"),Ko=te(),xge=To(),cC=V(),aC=yt(),{restart:Fge}=Ca(),wg=ee(),kge=Jo(),Gge=_s(),{main:pj,launch:qge}=Rl(),{install:$ge,updateConfigEnv:Vge,setIgnoreExisting:lC}=TT(),mj=kI(),ks=M(),Yge=go(),Kge=vE(),{SYSTEM_TABLE_NAMES:iC,SYSTEM_SCHEMA_NAME:fve,CONFIG_PARAMS:Cg,OPERATIONS_ENUM:to}=ks,Wge=1e4,jge="clone-node-config.yaml",Sj=[iC.ROLE_TABLE_NAME,iC.USER_TABLE_NAME,iC.NODE_TABLE_NAME],Qge={clustering_nodename:!0,clustering_leafserver_streams_path:!0,clustering_tls_certificate:!0,clustering_tls_privatekey:!0,clustering_tls_certificateauthority:!0,logging_file:!0,logging_root:!0,logging_rotation_path:!0,operationsapi_network_domainsocket:!0,operationsapi_tls_certificate:!0,operationsapi_tls_privatekey:!0,operationsapi_tls_certificateauthority:!0,rootpath:!0,storage_path:!0,storage_audit_path:!0,databases:!0,mqtt_network_mtls_certificateauthority:!0,componentsroot:!0,tls_certificate:!0,tls_privatekey:!0,tls_certificateauthority:!0,replication_hostname:!0,replication_url:!0},ro={HDB_LEADER_USERNAME:"HDB_LEADER_USERNAME",HDB_LEADER_PASSWORD:"HDB_LEADER_PASSWORD",HDB_LEADER_URL:"HDB_LEADER_URL",REPLICATION_HOSTNAME:"REPLICATION_HOSTNAME",HDB_CLONE_OVERTOP:"HDB_CLONE_OVERTOP"},Vd=Bge(process.argv),Fd=Vd[ro.HDB_LEADER_USERNAME]??process.env[ro.HDB_LEADER_USERNAME],kd=Vd[ro.HDB_LEADER_PASSWORD]??process.env[ro.HDB_LEADER_PASSWORD],Gd=Vd[ro.HDB_LEADER_URL]??process.env[ro.HDB_LEADER_URL],Ul=Vd[ro.REPLICATION_HOSTNAME]??process.env[ro.REPLICATION_HOSTNAME],Tj=(Vd[ro.HDB_CLONE_OVERTOP]??process.env[ro.HDB_CLONE_OVERTOP])==="true",zge=Vd[Cg.CLONED.toUpperCase()]??process.env[Cg.CLONED.toUpperCase()],Jge,is,Ll={},fj,xd,Pl={},Nr,dr,Gs,Zi,qd=!1,uC=!1,ss;Aj.exports=a(async function(t=!1,r=!1){if(console.info(`Starting clone node from leader node: ${Gd}`),delete process.env.HDB_LEADER_URL,dr=wg.getEnvCliRootPath(),!dr)try{let i=eo(lj.homedir(),ks.HDB_HOME_DIR_NAME,ks.BOOT_PROPS_FILE_NAME);if(await _r.pathExists(i)){let o=Hge(i);dr=$d.parse(o.get(ks.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)).dir}}catch{throw new Error("There was an error setting the clone default root path. Please set ROOTPATH using an environment or CLI variable.")}dr?await _r.pathExists(dr)?console.log(`Existing HarperDB install found at ${dr}. Clone node will only clone items that do not already exist on clone.`):(console.log(`No HarperDB install found at ${dr} starting fresh clone`),qd=!0):(console.log("No HarperDB install found, starting fresh clone"),qd=!0),dr||(dr=eo(lj.homedir(),ks.HDB_ROOT_DIR_NAME),console.log("Using default root path",dr));let n;try{n=eo(dr,jge),is=dj.parseDocument(await _r.readFile(n,"utf8"),{simpleKeys:!0}).toJSON(),console.log("Clone config file found")}catch{}let s=eo(dr,ks.HDB_CONFIG_FILE);if(await _r.pathExists(s))try{fj=dj.parseDocument(await _r.readFile(s,"utf8"),{simpleKeys:!0}).toJSON(),Ll=aC.flattenConfig(fj)}catch(i){console.error("Error reading existing harperdb-config.yaml on clone",i)}if(Ll?.cloned&&zge!=="false")return console.log("Instance marked as cloned, clone will not run"),Ko.setCloneVar(!1),Ko.initSync(),pj();Nr=await gj({operation:to.DESCRIBE_ALL}),Nr=await JSON.parse(Nr.body),await Xge(),Ko.setCloneVar(!1),Ko.setHdbBasePath(dr),_r.ensureDir(Ko.get(ks.CONFIG_PARAMS.LOGGING_ROOT)),cC.initLogSettings(),await Zge(),uC||await eRe(),await nRe(t,r),Ul&&await iRe(),console.info(`
133
+ Successfully cloned node: `+Gd),t&&process.exit()},"cloneNode");async function Xge(){console.info("Cloning configuration"),xd=await gj({operation:to.GET_CONFIGURATION}),xd=await JSON.parse(xd.body),Jge=xd?.clustering?.enabled,Pl=aC.flattenConfig(xd);let e=is?.componentConfig?.exclude,t={cloned:!0,rootpath:dr};Ul&&(t.replication_hostname=Ul);for(let s in Pl)if(!(Pl[s]!==null&&typeof Pl[s]=="object"&&!(Pl[s]instanceof Array)||Qge[s])){if(s.includes("_package")||s.includes("_port")){if(Pl[s]?.includes?.("hdb/components"))continue;if(e){let i=!1;for(let o of e)if(s.includes(o.name)){i=!0;break}if(i)continue}}Ll[s]||(t[s]=Pl[s])}for(let s in Ll)s!=="databases"&&typeof Ll[s]=="object"&&!(Ll[s]instanceof Array)||(t[s]=Ll[s]);let r={};if(is?.databaseConfig?.excludeDatabases&&is.databaseConfig.excludeDatabases.forEach(s=>{r[s.database]=!0}),is?.clusteringConfig?.excludeDatabases&&is.clusteringConfig.excludeDatabases.forEach(s=>{r[s.database]=!0}),Object.keys(r).length>0){t.replication_databases=[],r.system||t.replication_databases.push("system");for(let s in Nr)r[s]||t.replication_databases.push(s)}let n=kge(Object.keys(ks.CONFIG_PARAM_MAP),!0);Object.assign(t,n),aC.createConfigFile(t,!0),Ko.initSync(!0)}a(Xge,"cloneConfig");async function Zge(){process.env.HDB_FETCH==="true"?(await rRe(),process.env.NODE_TLS_REJECT_UNAUTHORIZED&&delete process.env.NODE_TLS_REJECT_UNAUTHORIZED):await tRe()}a(Zge,"cloneDatabases");async function eRe(){if(console.info("Clone node installing HarperDB."),process.env.TC_AGREEMENT="yes",process.env.ROOTPATH=dr,!Fd)throw new Error("HDB_LEADER_USERNAME is undefined.");if(process.env.HDB_ADMIN_USERNAME=Fd,!kd)throw new Error("HDB_LEADER_PASSWORD is undefined.");process.env.HDB_ADMIN_PASSWORD=kd,process.env.OPERATIONSAPI_NETWORK_PORT=Ko.get(Cg.OPERATIONSAPI_NETWORK_PORT),Vge($d.join(dr,ks.HDB_CONFIG_FILE)),lC(!0),await $ge()}a(eRe,"installHDB");function Ml(e){return Ko.get(ks.CONFIG_PARAMS.DATABASES)?.[e]?.path||Ko.get(Cg.STORAGE_PATH)||$d.join(dr,ks.DATABASES_DIR_NAME)}a(Ml,"getDBPath");async function tRe(){let e=Ml("system"),t=eo(e,"system.mdb");if(await _h(e),qd||!await _r.exists(t)||Tj){if(!Ul){console.info("Cloning system database"),await _h(e);let r=Ig(t,{overwrite:!0}),n={operation:to.GET_BACKUP,database:"system",tables:Sj},s=await Ej(n,r),i=new Date(s.date);(!ss||i<ss)&&(ss=i),await _r.utimes(t,Date.now(),i)}qd||(await mj(dr),await Rj(),lC(!0))}else uC=!0,console.log("Not cloning system database due to it already existing on clone");Gs=is?.databaseConfig?.excludeDatabases,Gs=Gs?Gs.reduce((r,n)=>({...r,[n.database]:!0}),{}):{};for(let r in Nr)await _r.exists($d.join(Ml(r),r+".mdb"))&&(console.log(`Not cloning database ${r} due to it already existing on clone`),Gs[r]=!0);Zi=is?.databaseConfig?.excludeTables,Zi=Zi?Zi.reduce((r,n)=>({...r,[n.database==null?null:n.database+n.table]:!0}),{}):{};for(let r in Nr){if(Gs[r]){Nr[r]="excluded";continue}if(hj.isEmpty(Nr[r]))continue;let n=[],s=!1;for(let _ in Nr[r])Zi[r+_]?(s=!0,Nr[r][_]="excluded"):n.push(Nr[r][_]);if(n.length===0)continue;if(Ul){cC.debug("Setting up tables for #{db}");let _=(De(),ne(at)).table;for(let E of n){for(let f of E.attributes)(f.is_hash_attribute||f.is_primary_key)&&(f.isPrimaryKey=!0);_({database:r,table:E.name,attributes:E.attributes})}continue}n=n.map(_=>_.name);let i;s?(console.info(`Cloning database: ${r} tables: ${n}`),i={operation:to.GET_BACKUP,database:r,tables:n}):(console.info(`Cloning database: ${r}`),i={operation:to.GET_BACKUP,database:r});let o=Ml(r);await _h(o);let c=eo(o,r+".mdb"),l=Ig(c,{overwrite:!0}),d=await Ej(i,l),u=new Date(d.date);(!ss||u<ss)&&(ss=u),await _r.utimes(c,Date.now(),u)}}a(tRe,"cloneTablesHttp");async function rRe(){let e=Ml("system"),t=eo(e,"system.mdb");if(qd||!await _r.exists(t)||Tj){if(!Ul){console.info("Cloning system database using fetch");let r={operation:to.GET_BACKUP,database:"system",tables:Sj},n=await oC(r,!0),s=Ml("system");await _h(s);let i=eo(s,"system.mdb");await _j(n.body,Ig(i,{overwrite:!0}));let o=new Date(n.headers.get("date"));(!ss||o<ss)&&(ss=o),await _r.utimes(i,Date.now(),new Date(n.headers.get("date")))}qd||(await mj(dr),await Rj(),lC(!0))}else uC=!0,console.log("Not cloning system database due to it already existing on clone");if(Ul){cC.info("Replication hostname set, not using backup to clone databases, replication will clone");return}Gs=is?.databaseConfig?.excludeDatabases,Gs=Gs?Gs.reduce((r,n)=>({...r,[n.database]:!0}),{}):{};for(let r in Nr)await _r.exists($d.join(Ml(r),r+".mdb"))&&(console.log(`Not cloning database ${r} due to it already existing on clone`),Gs[r]=!0);Zi=is?.databaseConfig?.excludeTables,Zi=Zi?Zi.reduce((r,n)=>({...r,[n.database==null?null:n.database+n.table]:!0}),{}):{};for(let r in Nr){if(Gs[r]){Nr[r]="excluded";continue}if(hj.isEmpty(Nr[r]))continue;let n=[],s=!1;for(let u in Nr[r])Zi[r+u]?(s=!0,Nr[r][u]="excluded"):n.push(u);if(n.length===0)return;let i;s?(console.info(`Cloning database: ${r} tables: ${n}`),i=await oC({operation:to.GET_BACKUP,database:r,tables:n},!0)):(console.info(`Cloning database: ${r}`),i=await oC({operation:to.GET_BACKUP,database:r},!0));let o=Ml(r);await _h(o);let c=new Date(i.headers.get("date")),l=eo(o,`${c.getTime()}-${r}.mdb`);await _j(i.body,Ig(l,{overwrite:!0}));let d=eo(o,r+".mdb");await _r.rename(l,d),(!ss||c<ss)&&(ss=c),await _r.utimes(d,Date.now(),c)}}a(rRe,"cloneTablesFetch");async function oC(e,t=!1){let r=is?.httpsRejectUnauthorized??!1,n=new Ng.Agent({rejectUnauthorized:r});r||(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");let i={Authorization:"Basic "+Buffer.from(Fd+":"+kd).toString("base64"),"Content-Type":"application/json"};t&&(i["Accept-Encoding"]="gzip");let o=await fetch(Gd,{method:"POST",headers:i,body:JSON.stringify(e),agent:n,compress:!0});if(o.ok)return o;throw console.error(`HTTP Error Response: ${o.status} ${o.statusText}`),new Error(await o.text())}a(oC,"leaderHttpReqFetch");async function nRe(e,t=!1){let r=await xge.getHDBProcessInfo();r.clustering.length===0||r.core.length===0?e?await qge(!1):(t&&await sRe(),await pj()):(console.info(await Fge({operation:to.RESTART})),await wg.async_set_timeout(Wge)),e&&await wg.async_set_timeout(2e3)}a(nRe,"startHDB");async function sRe(){let e=process.argv[3];e&&e[0]!=="-"&&(await _r.exists(e)||console.error(`The folder ${e} does not exist`),_r.statSync(e).isDirectory()||console.error(`The path ${e} is not a folder`),e=await _r.realpath(e),await _r.exists($d.join(e,ks.HDB_CONFIG_FILE))?process.env.ROOTPATH=e:process.env.RUN_HDB_APP=e)}a(sRe,"setAppPath");async function iRe(){console.info("Setting up replication"),await Gge.setSchemaDataToGlobalAsync();let t=await Pf()({operation:to.ADD_NODE,verify_tls:!1,url:`${xd.operationsApi.network.port?"ws":"wss"}://${new URL(Gd).host}`,start_time:ss,authorization:{username:Fd,password:kd}},!0);console.log("Add node response: ",t)}a(iRe,"setupReplication");async function gj(e){let t=new Ng.Agent({rejectUnauthorized:is?.httpsRejectUnauthorized??!1}),n={Authorization:"Basic "+Buffer.from(Fd+":"+kd).toString("base64"),"Content-Type":"application/json"},s=new URL(Gd),i={protocol:s.protocol,host:s.hostname,method:"POST",headers:n};return s.protocol==="https:"&&(i.agent=t),s.port&&(i.port=s.port),await wg.httpRequest(i,e)}a(gj,"leaderHttpReq");async function Ej(e,t){let r=new Ng.Agent({rejectUnauthorized:is?.httpsRejectUnauthorized??!1}),s={Authorization:"Basic "+Buffer.from(Fd+":"+kd).toString("base64"),"Content-Type":"application/json"},i=new URL(Gd),o={protocol:i.protocol,host:i.hostname,method:"POST",headers:s};return i.protocol==="https:"&&(o.agent=r,uj=Ng),i.port&&(o.port=i.port),new Promise((c,l)=>{let d=uj.request(o,u=>{u.statusCode!==200&&l("Request to leader node failed with code: "+u.statusCode),u.pipe(t),u.on("end",()=>{t.close(),c(u.headers)})});d.on("error",u=>{l(u)}),d.write(JSON.stringify(e)),d.end()})}a(Ej,"leaderHttpStream");async function Rj(){let e=Yge.version();if(e)await Kge.insertHdbInstallInfo(e);else throw new Error("The version is missing/removed from HarperDB package.json")}a(Rj,"insertHdbVersionInfo")});var yj=y((pve,bj)=>{var oRe=TT(),aRe=V();bj.exports=cRe;async function cRe(){try{await oRe.install()}catch(e){console.error("There was an error during the install."),console.error(e),aRe.error(e),process.exit(1)}}a(cRe,"install")});var Ij=y((Sve,Nj)=>{"use strict";var lRe=jm(),uRe=V(),Oj="Registration failed.";async function dRe(){let e;try{e=await lRe.register()}catch(t){return uRe.error(`Registration error ${t}`),Oj}return e||Oj}a(dRe,"register");Nj.exports={register:dRe}});var Pj=y((gve,Dj)=>{"use strict";var _Re=V(),fRe=M(),ERe=require("util"),hRe=require("child_process"),wj=ERe.promisify(hRe.exec),pRe=To(),fh=Ku(),Cj="Stopping HarperDB.";Dj.exports=mRe;async function mRe(){if(console.log(Cj),_Re.notify(Cj),await fh.isServiceRegistered(fRe.HDB_PROC_DESCRIPTOR)){fh.enterPM2Mode();let r=await fh.getUniqueServicesList();for(let n in r)await fh.stop(n)}await fh.kill();let t=await pRe.getHDBProcessInfo();t.clustering.forEach(r=>{wj(`kill ${r.pid}`)}),t.core.forEach(r=>{wj(`kill ${r.pid}`)})}a(mRe,"stop")});var vj=y((Ave,Uj)=>{"use strict";var fC=require("fs-extra"),EC=require("path"),_C=require("yaml"),Eh=nr(),hh=M(),Lj=At(),hC=V(),SRe=_n(),TRe=Ym(),gRe=$m(),RRe=To(),Mj=te(),ARe=Rl();Mj.initSync();var qs={RUNNING:"running",STOPPED:"stopped",ERRORED:"errored",NOT_INSTALLED:"not installed"},Cn={LEAF:"leaf server",HUB:"hub server"},Dg;Uj.exports=bRe;async function bRe(){let e={harperdb:{status:qs.STOPPED}};if(!await ARe.isHdbInstalled()){e.harperdb.status=qs.NOT_INSTALLED,console.log(_C.stringify(e));return}Dg=Mj.get(hh.CONFIG_PARAMS.ROOTPATH);let t;try{t=Number.parseInt(await fC.readFile(EC.join(Dg,hh.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===hh.NODE_ERROR_CODES.ENOENT){hC.info("`harperdb status` did not find a hdb.pid file"),e.harperdb.status=qs.STOPPED,console.log(_C.stringify(e));return}throw n}let r=await RRe.getHDBProcessInfo();for(let n of r.core)if(n.pid===t){e.harperdb.status=qs.RUNNING,e.harperdb.pid=t;break}if(e.clustering=await yRe(r),e.clustering[Cn.HUB].status===qs.RUNNING&&e.clustering[Cn.LEAF].status===qs.RUNNING){let n=[],s=await TRe({});for(let o of s.nodes){let c={};for(let l in o)c[l.replace("_"," ")]=o[l];n.push(c)}e.clustering.network=n;let i=await gRe.clusterStatus();e.clustering.replication={"node name":i.node_name,"is enabled":i.is_enabled,connections:[]};for(let o of i.connections){let c={};c["node name"]=o?.node_name,c.status=o?.status,c.ports={clustering:o?.ports?.clustering,"operations api":o?.ports?.operations_api},c["latency ms"]=o?.latency_ms,c.uptime=o?.uptime,c.subscriptions=o?.subscriptions,c["system info"]={"hdb version":o?.system_info?.hdb_version,"node version":o?.system_info?.node_version,platform:o?.system_info?.platform},e.clustering.replication.connections.push(c)}await Eh.closeConnection()}console.log(_C.stringify(e)),process.exit()}a(bRe,"status");async function yRe(e){let t={[Cn.HUB]:{},[Cn.LEAF]:{}};if(e.clustering.length===0)return t[Cn.HUB].status=qs.STOPPED,t[Cn.LEAF].status=qs.STOPPED,t;let{port:r}=Eh.getServerConfig(hh.PROCESS_DESCRIPTORS.CLUSTERING_HUB),{username:n,decrypt_hash:s}=await SRe.getClusterUser();try{(await Eh.createConnection(r,n,s,!1)).close(),t[Cn.HUB].status=qs.RUNNING}catch{t[Cn.HUB].status=qs.ERRORED}let{port:i}=Eh.getServerConfig(hh.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);try{(await Eh.createConnection(i,n,s,!1)).close(),t[Cn.LEAF].status=qs.RUNNING}catch{t[Cn.LEAF].status=qs.ERRORED}try{t[Cn.HUB].pid=Number.parseInt(await fC.readFile(EC.join(Dg,"clustering",Lj.PID_FILES.HUB),"utf8"))}catch(o){hC.error(o),t[Cn.HUB].pid=void 0}try{t[Cn.LEAF].pid=Number.parseInt(await fC.readFile(EC.join(Dg,"clustering",Lj.PID_FILES.LEAF),"utf8"))}catch(o){hC.error(o),t[Cn.LEAF].pid=void 0}return t}a(yRe,"getHubLeafStatus")});var Pg=process.env.HDB_LEADER_URL||process.argv.includes("--HDB_LEADER_URL");Pg&&te().setCloneVar(!0);var ph=require("node:fs"),Bj=require("node:path"),vl=V(),Hj=ij(),ORe=go(),NRe=cj(),pC=M(),{SERVICE_ACTIONS_ENUM:sn,PACKAGE_ROOT:xj}=pC,IRe=`
108
134
  Usage: harperdb [command]
109
135
 
110
- With no command, harperdb will simply run HarperDB (in the foreground)
136
+ With no command, harperdb will simply run HarperDB (in the foreground)
111
137
 
112
138
  Commands:
113
- run <path> - Run the application in the specified path
114
- dev <path> - Run the application in dev mode with debugging, foreground logging, no auth
115
- version - Print the version
116
- start - Starts a separate background process for harperdb and CLI will exit
117
- stop - Stop the harperdb background process
118
- restart - Restart the harperdb background process
119
- install - Install harperdb
120
- register - Register harperdb
121
- upgrade - Upgrade harperdb
122
- renew-certs - Generate a new set of self-signed certificates
123
- status - Print the status of HarperDB and clustering
124
- <api-operation> <parameter>=<value> - Run an API operation and return result to the CLI, not all operations are supported`)}})}a(Ghe,"harperDBService");
139
+ copy-db <source> <target> - Copies a database from source path to target path
140
+ dev <path> - Run the application in dev mode with debugging, foreground logging, no auth
141
+ install - Install harperdb
142
+ operation <op> <param>=<value> - Run an API operation and return result to the CLI, not all operations are supported
143
+ register - Register harperdb
144
+ renew-certs - Generate a new set of self-signed certificates
145
+ restart - Restart the harperdb background process
146
+ run <path> - Run the application in the specified path
147
+ start - Starts a separate background process for harperdb and CLI will exit
148
+ status - Print the status of HarperDB and clustering
149
+ stop - Stop the harperdb background process
150
+ help - Display this output
151
+ upgrade - Upgrade harperdb
152
+ version - Print the version
153
+ `;async function wRe(){let e=NRe();if(e)if(e.error){console.error(e.error),vl.error(e.error);return}else e.warn&&(console.warn(e.warn),vl.warn(e.warn));let t;switch(ph.existsSync(Bj.join(xj,"bin"))||(vl.error(`Missing \`bin\` directory at ${xj}`),process.exit(0)),process.argv&&process.argv[2]&&!process.argv[2].startsWith("-")&&(t=process.argv[2].toLowerCase()),t){case sn.OPERATION:let r;return Pg||(r=Hj.buildRequest(),r.operation&&(t=sn.OPERATION)),vl.trace("calling cli operations with:",r),Hj.cliOperations(r);case sn.START:return Pg?dC()(!0):Rl().launch();case sn.INSTALL:return yj()().then(()=>Rl().main(!0));case sn.REGISTER:return Ij().register();case sn.STOP:return Pj()().then(()=>{process.exit(0)});case sn.RESTART:return Ca().restart({});case sn.VERSION:return ORe.version();case sn.UPGRADE:return vl.setLogLevel(pC.LOG_LEVELS.INFO),WI().upgrade(null).then(()=>"Your instance of HarperDB is up to date!");case sn.STATUS:return vj()();case sn.RENEWCERTS:return Ss().renewSelfSigned().then(()=>"Successfully renewed self-signed certificates");case sn.COPYDB:let n=process.argv[3],s=process.argv[4];return(oS(),ne(iS)).copyDb(n,s);case sn.DEV:process.env.DEV_MODE=!0;case sn.RUN:let i=process.argv[3];if(i&&i[0]!=="-"){if(!ph.existsSync(i))throw new Error(`The folder ${i} does not exist`);if(!ph.statSync(i).isDirectory())throw new Error(`The path ${i} is not a folder`);i=ph.realpathSync(i),ph.existsSync(Bj.join(i,pC.HDB_CONFIG_FILE))?process.env.ROOTPATH=i:process.env.RUN_HDB_APP=i}case void 0:return Pg?dC()():Rl().main();default:console.warn(`The "${t}" command is not understood.`);case sn.HELP:return IRe}}a(wRe,"harperdb");wRe().then(e=>{e&&(console.log(e),vl.notify(e))}).catch(e=>{e&&(console.error(e),vl.error(e)),process.exit(1)});