harperdb 4.5.15 → 4.5.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +1 -1
- package/bin/lite.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +1 -1
- package/launchServiceScripts/launchNatsReplyService.js +1 -1
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +1 -1
- package/npm-shrinkwrap.json +77 -63
- package/package.json +2 -2
- package/server/jobs/jobProcess.js +1 -1
- package/server/threads/threadServer.js +1 -1
- package/utility/scripts/restartHdb.js +1 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`+JSON.stringify(u)),u.cause&&(t[c--]=u.cause,u&&(n+=`
|
|
5
5
|
Caused by:`));else if(typeof u=="object")try{n+=JSON.stringify(u)}catch{n+="Object ["+Object.keys(u)+"]"}else n+=u;c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
6
6
|
`}a(Bs,"createLogRecord");function tf(e){if(ui){if(kP(e),is){zo=!1;try{process.stdout.write(e)}finally{zo=!0}}}else is&&process.stdout.write(e)}a(tf,"logStdOut");function Hm(e){if(ui){if(kP(e),is){zo=!1;try{process.stderr.write(e)}finally{zo=!0}}}else is&&process.stderr.write(e)}a(Hm,"logStdErr");function kP(e){TA(),Wo?ji.appendFileSync(Wo,e):SA||console.log(e)}a(kP,"logToFile");function RA(){try{ji.closeSync(Wo)}catch{}Wo=null}a(RA,"closeLogFile");function TA(){if(!Wo){try{Wo=ji.openSync(xm,"a")}catch(e){SA||(SA=!0,console.error(e))}setTimeout(()=>{RA()},k2).unref()}}a(TA,"openLogFile");function FP(...e){_r[Cr]<=_r.info&&tf(Bs("info",e))}a(FP,"info");function qP(...e){_r[Cr]<=_r.trace&&tf(Bs("trace",e))}a(qP,"trace");function Bm(...e){_r[Cr]<=_r.error&&Hm(Bs("error",e))}a(Bm,"error");function GP(...e){_r[Cr]<=_r.debug&&tf(Bs("debug",e))}a(GP,"debug");function $P(...e){_r[Cr]<=_r.notify&&tf(Bs("notify",e))}a($P,"notify");function VP(...e){_r[Cr]<=_r.fatal&&Hm(Bs("fatal",e))}a(VP,"fatal");function KP(...e){_r[Cr]<=_r.warn&&Hm(Bs("warn",e))}a(KP,"warn");function K2(e,t,...r){t===BP.STDERR?Hm(Bs(e,r)):tf(Bs(e,r))}a(K2,"logCustomLevel");function Y2(){let e;try{e=U2.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=di.join(e,$t.HDB_HOME_DIR_NAME,$t.BOOT_PROPS_FILE_NAME);return ji.existsSync(t)||(t=di.join(AA,"utility/hdb_boot_properties.file")),t}a(Y2,"getPropsFilePath");function W2(e){Cr=e}a(W2,"setLogLevel");function vP(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(vP,"autoCastBoolean");function z2(e){try{if(e.includes("config/settings.js")){let o=xP(e);return{level:o.get($t.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:di.dirname(o.get($t.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get($t.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get($t.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=UP.parseDocument(ji.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===$t.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(z2,"getLogConfig");function j2(){try{let e=UP.parseDocument(ji.readFileSync(H2,"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(j2,"getDefaultConfig");function Q2(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(Q2,"AuthAuditLog")});var yA=P((wRe,zP)=>{"use strict";var J2=require("util"),X2=require("path"),Z2=require("child_process"),eJ=J2.promisify(Z2.execFile),tJ=1e3*1e3*10;zP.exports={findPs:rJ};async function rJ(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await eJ("ps",["wwxo",`pid,${r}`],{maxBuffer:tJ});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:X2.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(rJ,"findPs")});var Ut=P((CRe,QP)=>{"use strict";var nJ="__dbis__",sJ="__txns__",iJ="__environment_name__",oJ="__dbi_defintion__",aJ={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"},cJ=["__createdtime__","__updatedtime__"],lJ="\uFFFF",jP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},uJ=Object.values(jP);QP.exports={AUDIT_STORE_NAME:sJ,INTERNAL_DBIS_NAME:nJ,DBI_DEFINITION_NAME:oJ,SEARCH_TYPES:aJ,TIMESTAMP_NAMES:cJ,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:iJ,TRANSACTIONS_DBI_NAMES_ENUM:jP,TRANSACTIONS_DBIS:uJ,OVERFLOW_MARKER:lJ}});var Pn=P((PRe,iD)=>{"use strict";var JP=(H(),D(G)),XP=Ut(),ZP={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},eD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),tD={500:eD("There was an error processing your request."),400:"Invalid request"},dJ=tD[ZP.INTERNAL_SERVER_ERROR],fJ={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},_J={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},hJ={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),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:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},mJ={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 ${XP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${XP.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"},pJ={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${JP.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),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 ${JP.INSERT_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"},rD={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"},EJ={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:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_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:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},gJ={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_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:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),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:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},SJ={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},TJ={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},AJ={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},nD={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},sD={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:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},RJ={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"},yJ={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},bJ={...rD,...hJ,...fJ,...EJ,...gJ,...SJ,...TJ,...AJ,...pJ,...nD,...sD,...RJ,...yJ,..._J};iD.exports={CHECK_LOGS_WRAPPER:eD,HDB_ERROR_MSGS:bJ,DEFAULT_ERROR_MSGS:tD,DEFAULT_ERROR_RESP:dJ,HTTP_STATUS_CODES:ZP,LMDB_ERRORS_ENUM:mJ,AUTHENTICATION_ERROR_MSGS:rD,VALIDATION_ERROR_MSGS:nD,ITC_ERRORS:sD}});var me=P((LRe,cD)=>{"use strict";var $l=Pn(),OJ=z(),NJ=(H(),D(G)),km=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,oD),this.statusCode=n||$l.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||($l.DEFAULT_ERROR_MSGS[n]?$l.DEFAULT_ERROR_MSGS[n]:$l.DEFAULT_ERROR_MSGS[$l.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&&OJ[s](i)}},bA=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}},OA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function oD(e,t,r,n=NJ.LOG_LEVELS.ERROR,s=null,i=!1){if(aD(e))return e;let o=new km(e,t,r,n,s);return i&&delete o.stack,o}a(oD,"handleHDBError");function aD(e){return e.__proto__.constructor.name===km.name}a(aD,"isHDBError");cD.exports={isHDBError:aD,handleHDBError:oD,ClientError:bA,ServerError:OA,hdb_errors:$l}});var Et=P((vRe,mD)=>{"use strict";var af=(H(),D(G)),wJ=oe(),an=le(),cf=require("path"),IJ=require("minimist"),lD=require("fs-extra"),uD=require("lodash");an.initSync();var{CONFIG_PARAMS:jo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Fm}=af,nf,sf,of;function dD(){if(nf!==void 0)return nf;if(an.getHdbBasePath()!==void 0)return nf=an.get(jo.STORAGE_PATH)||cf.join(an.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(dD,"getBaseSchemaPath");function fD(){if(sf!==void 0)return sf;if(an.getHdbBasePath()!==void 0)return sf=hD(Fm),sf}a(fD,"getSystemSchemaPath");function _D(){if(of!==void 0)return of;if(an.getHdbBasePath()!==void 0)return of=an.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(an.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(_D,"getTransactionAuditStoreBasePath");function CJ(e,t){let r=an.get(jo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(_D(),e.toString())}a(CJ,"getTransactionAuditStorePath");function hD(e,t){e=e.toString(),t=t&&t.toString();let r=an.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(dD(),e)}a(hD,"getSchemaPath");function PJ(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,IJ(process.argv));let n=r[jo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!wJ.isObject(n))throw o;i=n}for(let o of i){let c=o[Fm];if(!c)continue;let l=an.get(jo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return uD.set(l,[Fm,rf.TABLES,t,rf.PATH],u),an.setProperty(jo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return uD.set(l,[Fm,rf.PATH],f),an.setProperty(jo.DATABASES,l),f}}let s=r[jo.STORAGE_PATH.toUpperCase()];if(s){if(!lD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return lD.mkdirsSync(i),an.setProperty(jo.STORAGE_PATH,s),i}return fD()}a(PJ,"initSystemSchemaPaths");function DJ(){nf=void 0,sf=void 0,of=void 0}a(DJ,"resetPaths");mD.exports={getBaseSchemaPath:dD,getSystemSchemaPath:fD,getTransactionAuditStorePath:CJ,getTransactionAuditStoreBasePath:_D,getSchemaPath:hD,initSystemSchemaPaths:PJ,resetPaths:DJ}});var cn=P((HRe,TD)=>{"use strict";var LJ=Pn().LMDB_ERRORS_ENUM,xRe=require("lmdb"),MJ=Ut(),BRe=require("buffer").Buffer,{OVERFLOW_MARKER:pD,MAX_SEARCH_KEY_LENGTH:qm}=MJ,ED=["number","string","symbol","boolean","bigint"];function vJ(e){if(e=e?.primaryStore||e,!e)throw new Error(LJ.ENV_REQUIRED)}a(vJ,"validateEnv");function UJ(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(UJ,"stringifyData");function xJ(e){return e instanceof Date?e.valueOf():e}a(xJ,"convertKeyValueToWrite");function BJ(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(ED.includes(typeof e))return e.length>qm?[e.slice(0,qm)+pD]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(ED.includes(typeof i))i.length>qm?r.push(i.slice(0,qm)+pD):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(BJ,"getIndexedValues");var Gm=0,gD=0;function SD(){gD=Date.now()-performance.now()}a(SD,"adjustStartTime");SD();var HJ=6e4;setInterval(SD,HJ).unref();function kJ(){let e=performance.now()+gD;return e>Gm?(Gm=e,e):(Gm+=488e-6,Gm)}a(kJ,"getNextMonotonicTime");TD.exports={validateEnv:vJ,stringifyData:UJ,convertKeyValueToWrite:xJ,getNextMonotonicTime:kJ,getIndexedValues:BJ}});var lf=P((FRe,AD)=>{"use strict";var FJ=(H(),D(G)).OPERATIONS_ENUM,NA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=FJ.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};AD.exports=NA});var uf=P(($Re,OD)=>{"use strict";var GRe=lf(),$m=(H(),D(G)),wA=oe(),RD=z(),qJ=require("uuid"),{handleHDBError:Vm,hdb_errors:GJ}=me(),{HDB_ERROR_MSGS:Km,HTTP_STATUS_CODES:Ym}=GJ;OD.exports=yD;function yD(e,t,r){for(let s=0;s<t.length;s++)bD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];$J(i,r,e.operation)}}a(yD,"processRows");yD.validateAttribute=bD;function bD(e){if(Buffer.byteLength(String(e))>$m.INSERT_MAX_CHARACTER_SIZE)throw Vm(new Error,Km.ATTR_NAME_LENGTH_ERR(e),Ym.BAD_REQUEST,void 0,void 0,!0);if(wA.isEmptyOrZeroLength(e)||wA.isEmpty(e.trim()))throw Vm(new Error,Km.ATTR_NAME_NULLISH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(bD,"validateAttribute");function $J(e,t,r){if(!e.hasOwnProperty(t)||wA.isEmptyOrZeroLength(e[t])){if(r===$m.OPERATIONS_ENUM.INSERT||r===$m.OPERATIONS_ENUM.UPSERT){e[t]=qJ.v4();return}throw RD.error("Update transaction aborted due to record with no hash value:",e),Vm(new Error,Km.RECORD_MISSING_HASH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>$m.INSERT_MAX_CHARACTER_SIZE)throw RD.error(e),Vm(new Error,Km.HASH_VAL_LENGTH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a($J,"validateHash")});var ND,Dn,IA,Vl=be(()=>{ND=require("events"),Dn=class extends ND.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new IA;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)}},IA=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}}}});function MD(e){PA=e}function WJ(){YJ=setInterval(function(){for(let e of CA)if(e.stale){let t=e.getContext()?.url;PD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},KJ).unref()}var DA,CD,PD,DD,LD,wD,CA,VJ,df,ID,PA,oc,Wm,KJ,YJ,zm=be(()=>{DA=M(cn()),CD=M(me()),PD=M(z()),DD=M(le());H();LD=M(oe()),wD=100,CA=new Set,VJ=(0,LD.convertToMS)(DD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(MD,"replicationConfirmation");oc=class e{static{a(this,"DatabaseTransaction")}#e;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),CA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(CA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-ID>VJ)throw new CD.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||(0,DA.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let h=d;h<this.validated;h++)this.writes[h]?.validate?.(this.timestamp);let _;for(let h=d;h<this.validated;h++){let m=this.writes[h];m&&(m.before||m.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let h=0;h<2;h++){let m;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let A=g[h===0?"before":"beforeIntermediate"];if(A){let E=A();m?m.push?m.push(E):m=[m,E]:m=E}}m&&await(m.push?Promise.all(m):m)}}catch(h){throw this.abort(),h}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;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 _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<wD>>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 df||(df=s,ID=performance.now(),df.then(()=>{df=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];PA&&h&&i.push(PA(_,h.store.getEntry(h.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+wD/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Wm=class extends oc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,DA.getNextMonotonicTime)())}getReadTxn(){}},KJ=3e4;a(WJ,"startMonitoringTxns");WJ()});function Nt(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 oc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(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({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var vD,ac=be(()=>{vD=M(li());zm();a(Nt,"transaction");(0,vD._assignPackageExport)("transaction",Nt);Nt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Nt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function MA(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let h=1;h<e.length;h++){let m=e[h],S=u(m);d=d.concat(S)}let _=new Set;return d.filter(h=>{let m=h.key??h;return _.has(m)?!1:(_.add(m),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?MA(d.conditions,d.operator,r,n,s,i,o,c):Wl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(k=>k(w,v)):(w,v)=>T.every(k=>k(w,v))}let g=(m.attribute||m[0])===r.primaryKey,A=hf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=r4(r.primaryStore,m.estimated_count,h)),A}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Wl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new un.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=_i(n.attributes,E);if(T.relationship){if(o.length<2)throw new un.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let w=T.definition?.tableClass||T.elements?.definition?.tableClass,v=new Map,k=Wl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let $=!!_i(w.attributes,T.relationship.to)?.elements;k=XJ(k,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Wl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,k=ZJ(k,T,w.primaryStore,v,$)):k=k.flatMap($)}return k}else if(o.length===1)o=o[0];else throw new un.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(vA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=fi.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new un.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>os.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>os.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,d=!0,m=m??hf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new un.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new un.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(g?.isIndexing)throw new un.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new un.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??hf(e,n,null,i,S),!m)throw new un.ClientError(`Unknown search operator ${e.comparator}`)}let A={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(A).map(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:Qo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(w&&m(w)?T:Qo.SKIP)}catch($){k($)}}))}:T=>T.value==null&&!(T.metadataFlags&(dn|Xo))?Qo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(A).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>os.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Qo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(m(w)?T:Qo.SKIP)}catch($){k($)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:Qo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Qo.SKIP)}catch(k){v(k)}}))})}function _i(e,t){if(Array.isArray(t))if(t.length>1){let r=_i(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?_i(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 XJ(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=a((u,f)=>{let d=s.get(u);d?d.push(f):s.set(u,d=[f])},"add_entry");for(let u of e){let f=u.value??r.get(u.key??u),d=f?.[c];if(d!=null&&!s.filters?.some(_=>!_(f)))if(n)for(let _=0;_<d.length;_++)l(d[_],u);else l(d,u)}return i=s.keys()[Symbol.iterator](),this.next()}let o=i.next();return o.done?o:{value:o.value}},return(){if(i?.return)return i.return()}}}})}function ZJ(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 u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hf(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 f=c[0],d=_i(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=hf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,A=a((E,T)=>{let w,v;if(S){if(S.from&&m.idFilter){if(!g)if(m.idFilter.idSet?.size===1){for(let $ of m.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,m.idFilter,!0,!0)}else g=u(S.from,m.idFilter,!1,!0);let k=g(E);return g.idFilter&&(A.idFilter=g.idFilter),k}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(m):m(w,v):!1},"recordFilter");return A}}switch(l instanceof Date&&(l=l.getTime()),vA[o]||o){case os.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[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()),u(c,f=>(0,fi.compareKeys)(f,l[0])>=0&&(0,fi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,fi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,fi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,fi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,fi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,fi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new un.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Qm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function A(E){let T=E[f],w;if(typeof T!="object"||!T||h?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!A.idFilter&&++S/g*(i-g)>m)){let v=Wl(e,r.transaction.getReadTxn(),!1,t).map(zl),k=new Set(v);A.idFilter=$=>k.has(zl($)),A.idFilter.idSet=k}return w}return a(A,"recordFilter"),s&&(A.idFilter=d),A}a(u,"attributeComparator")}function Qm(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/Qi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=vA[n]||n,n===os.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=_i(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qm(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*Qi(e.indices[i.relationship.from])/(Qi(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=Qi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=QJ*Qi(e.primaryStore)+1:n==="between"?r.estimated_count=jJ*Qi(e.primaryStore)+1:n==="sort"?r.estimated_count=Qi(e.primaryStore)+1:r.estimated_count=zJ*Qi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jm(e){if(e)if(Jo=e,Kl.lastIndex=0,e4.test(e))try{let t=ff(new Yl,"");if(ln!==Jo.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 ${ln} in '${Jo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Kl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Jo);){ln=r.lastIndex;let[,f,d]=n;if(o){if(f)throw new SyntaxError(`expected operator, but encountered '${f}'`);o=!1,c=!1}else c=!0;let _;switch(d){case"=":if(s!=null){if(f.length<=2)i=f;else throw new SyntaxError(`invalid FIQL operator ${f}`);l=UD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=_f(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=JJ[d],l=LA[i]?UD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_f(f);break;case"&=":case"|=":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 m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&xD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else jm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Kl.lastIndex=ln;let h=ff(f?[]:new Yl,")");switch(f){case"":jm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=BD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Jo[ln]===","?r.lastIndex=++ln:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");Kl.lastIndex=ln,_=ff([],"}"),_.name=f,e.push(_),Jo[ln]===","?r.lastIndex=++ln:o=!0;break;case"[":Kl.lastIndex=ln,f?(_=ff(new Yl,"]"),_.name=f):_=ff(e.conditions?new Yl:[],"]"),e.conditions?(jm(e,u),e.conditions.push(_),s=null):e.push(_),Jo[ln]===","?r.lastIndex=++ln:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let m={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&xD(m,f),jm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));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?t4:Kl,r.lastIndex=ln),ln===Jo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jm(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 _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function UD(e){if(e==="null")return null;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 un.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function xD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new un.ClientError("wildcard can only be used at the end of a string")}function BD(e){let t=HD(e[0]);return e.length>1&&(t.next=BD(e.slice(1))),t}function HD(e){if(Array.isArray(e)){let t=HD(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 zl(e){return Array.isArray(e)?e.join("\0"):e}function Qi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function r4(e,t,r){return t*r/Qi(e)}var un,os,fi,Qo,zJ,jJ,QJ,JJ,LA,vA,e4,Kl,t4,ln,Jo,Yl,cc,mf=be(()=>{un=M(me()),os=M(Ut()),fi=require("ordered-binary"),Qo=require("lmdb");pf();zJ=.3,jJ=.1,QJ=.05,JJ={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},LA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(MA,"executeConditions");a(Wl,"searchByIndex");a(_i,"findAttribute");a(XJ,"joinTo");a(ZJ,"joinFrom");vA={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(hf,"filterByType");a(Qm,"estimateCondition");e4=/[()[\]|!<>.]|(=\w*=)/,Kl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,t4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jm,"parseQuery");a(ff,"parseBlock");a(jm,"assignOperator");a(_f,"decodeProperty");a(UD,"typedDecoding");a(xD,"wildcardDecoding");a(BD,"toSortObject");a(HD,"toSortEntry");Yl=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(zl,"flattenKey");a(Qi,"estimatedEntryCount");a(r4,"intersectionEstimate");cc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var xA={};Ue(xA,{MultiPartId:()=>Zm,Resource:()=>Gr,snake_case:()=>s4,transformForSelect:()=>ep});function s4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function kD(e,t){if(lc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(lc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Zm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){lc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return lc=!0,null;e[e.length-1]==="/"&&(lc=!0)}return t.coerceId(decodeURIComponent(e))}function Ln(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||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")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}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,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new cc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return Nt(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new Xm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Xm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Mn(e,t){let r=new GD.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 UA(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();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 ep(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):UA(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=[],f=i(UA(l,r,n));for(let d of e)u.push(f(d));return u},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(_=>_&&typeof _=="object"?c(_):_);let u={},f=i(UA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"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 f=r[c.name]?.definition?.tableClass;l=s[c.name]=ep(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var FD,qD,GD,n4,Gr,Xm,lc,Zm,Zo=be(()=>{FD=require("crypto");Vl();qD=M(li()),GD=M(me());ac();mf();n4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Gr=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Ln(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 u=ep(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Ln(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Mn(t,"put")},{hasContent:!0,type:"update"});static patch=Ln(function(t,r,n,s){return t.patch?t.patch(s,r):Mn(t,"patch")},{hasContent:!0,type:"update"});static delete=Ln(function(t,r,n,s){return t.delete?t.delete(r):Mn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,FD.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={}),Nt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Mn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Ln(function(t,r,n,s){return t.invalidate?t.invalidate(r):Mn(t,"delete")},{hasContent:!1,type:"update"});static post=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Ln(function(t,r,n,s){return t.connect?t.connect(s,r):Mn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Ln(function(t,r,n,s){return t.subscribe?t.subscribe(r):Mn(t,"subscribe")},{type:"read"});static publish=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Mn(t,"publish")},{hasContent:!0,type:"create"});static search=Ln(function(t,r,n,s){let i=t.search?t.search(r):Mn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ep(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Ln(function(t,r,n,s){return t.search?t.search(s,r):Mn(t,"search")},{hasContent:!0,type:"read"});static copy=Ln(function(t,r,n,s){return t.copy?t.copy(s,r):Mn(t,"copy")},{hasContent:!0,type:"create"});static move=Ln(function(t,r,n,s){return t.move?t.move(s,r):Mn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Mn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Jm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&n4[o];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===o))if(t=t.slice(0,s),n)n.property=o;else return{query:{property:o},id:kD(t,this),isCollection:lc}}let i=kD(t,this);return lc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),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 u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Dn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Dn}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.#e}getContext(){return this.#t}};(0,qD._assignPackageExport)("Resource",Gr);a(s4,"snake_case");Xm=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(kD,"pathToId");Zm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Ln,"transactional");a(Mn,"missingMethod");a(UA,"selectFromObject");a(ep,"transformForSelect")});var ea,BA=be(()=>{ea=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 jl={};Ue(jl,{server:()=>Ke});var $D,Ke,Pr=be(()=>{$D=M(li()),Ke={};(0,$D._assignPackageExport)("server",Ke)});var YD={};Ue(YD,{Resources:()=>tp,keyArrayToString:()=>Ql,resetResources:()=>i4,resources:()=>as});function i4(){return as=new tp,Ke.resources=as,as}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var VD,KD,tp,as,Jl=be(()=>{ac();BA();VD=M(z()),KD=M(me());Pr();tp=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 KD.ServerError(`Conflicting paths for ${t}`);VD.default.error(c),i.Resource=new ea(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}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 Nt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(i4,"resetResources");a(Ql,"keyArrayToString")});var HA=P((hye,WD)=>{if(__filename.endsWith("dev.js")){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n}=require("node:path"),{existsSync:s,statSync:i,readFileSync:o,writeFileSync:c,unlinkSync:l}=require("node:fs"),{isMainThread:u}=require("node:worker_threads"),{spawnSync:f,spawn:d}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:_}=pt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],m="ts-build";if(u){let A=!1,E=!1;if(E=s(n(_,m))){let T=new Set;e.sync(h.map(w=>`${w}/**/*.ts`),{cwd:_}).forEach(w=>{let v=0,k=0;try{T.add(w),v=i(n(_,w)).mtimeMs-5e3,k=i(n(_,m,w.replace(/.ts$/,".js"))).mtimeMs}catch{}v>k&&(A=!0)}),e.sync(h.map(w=>`${w}/**/*.js`),{cwd:n(_,m)}).forEach(w=>{if(!T.has(w.replace(/.js$/,".ts")))try{l(n(_,m,w))}catch{}})}else A=!0;if(A){console.log("Compiling TypeScript...");let T=f("npx",["tsc"],{cwd:_});if(T.stdout?.length&&console.log(T.stdout.toString()),T.stderr?.length&&console.log(T.stderr.toString()),E){let w=n(t(),"harperdb-tsc.pid"),v=!1;if(s(w))try{process.kill(+o(w,"utf8"),0),v=!0}catch{}if(!v){console.log("Starting background TypeScript compilation...");let k=d("npx",["tsc","--watch"],{detached:!0,cwd:_,stdio:"ignore"});k.on("error",$=>{console.error("Error trying to compile TypeScript",$)}),k.pid&&c(w,String(k.pid),"utf-8"),k.unref()}}}}let S=WD.constructor,g=S._findPath;S._findPath=function(A,E,T){if(A.startsWith(".")&&!T&&E.length===1&&E[0].startsWith(_)&&!E[0].includes("node_modules")){let w=r(_,E[0]),v;w.startsWith(m)?v=n(_,r(m,w)):v=n(_,m,w);let k=n(v,A),$=k+".js";if(s($))return $;if(k.includes(".")&&s(k))return k}return g(A,E,T)}}});var qA={};Ue(qA,{loadGQLSchema:()=>c4,start:()=>FA,startOnMainThread:()=>a4});function FA({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,h=[],m;for(let A of d.definitions)switch(A.kind){case l.OBJECT_TYPE_DEFINITION:let k=function(W){if(W.kind==="NonNullType"){let Y=k(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:k(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(k,"getProperty");let E=A.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of A.directives){if(W.name.value==="table"){for(let se of W.arguments)w[se.name.value]=se.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=E),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,h.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,$={};for(let W of A.fields){let te=k(W.type);te.name=W.name.value,T.push(te),$[te.name]=void 0;for(let se of W.directives){let Y=se.name.value;if(Y==="primaryKey")v?console.warn("Can not define two attributes as a primary key at",se.loc):(te.isPrimaryKey=!0,v=!0);else if(Y==="indexed")te.indexed=!0;else if(Y==="computed"){for(let ne of se.arguments||[])if(ne.name.value==="from"){let ue=ne.value.value;te.computed={from:g(ue,ne,$)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(m=w)}function S(A){let E=_.get(A.type);E?(Object.defineProperty(A,"properties",{value:E.properties}),Object.defineProperty(A,"definition",{value:E})):A.type==="array"?S(A.elements):o4.includes(A.type)||(0,jD.getWorkerIndex)()===0&&console.error(`The type ${A.type} is unknown at line ${A.location.line}, column ${A.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let A of _.values())for(let E of A.properties)S(E);for(let A of h)A.tableClass=e(A),A.export&&(A.export.name===""?i.set((0,kA.dirname)(n),A.tableClass):i.set((0,kA.dirname)(n)+"/"+(A.export.name||A.type),A.tableClass,A.export));function g(A,E,T){return new zD.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${A}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var kA,zD,jD,o4,a4,c4,QD=be(()=>{kA=require("path"),zD=require("node:vm");ve();jD=M(Ze()),o4=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(FA,"start");a4=FA,c4=FA({ensureTable:dt}).handleFile});var nL={};Ue(nL,{parse:()=>$A,streamAsJSON:()=>Ef,stringify:()=>uc});function Ef(e){return new GA({value:e})}function JD(e){return console.error(e),JSON.stringify(e.toString())}function XD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function uc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===tL)return rL(e);if(t.resolution)return t.resolution.then(()=>uc(e));throw t}}function rL(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+=rL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+uc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function $A(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),d4.test(e)?l4.parse(e):JSON.parse(e)):null}var ZD,eL,l4,u4,tL,GA,d4,VA=be(()=>{ZD=require("stream"),eL=M(require("json-bigint-fixes")),l4=(0,eL.default)({useNativeBigInt:!0}),u4=1e4,tL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw tL};a(Ef,"streamAsJSON");GA=class extends ZD.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:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")}}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),JD)}catch(s){yield JD(s)}else yield uc(t)}else yield uc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);XD(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>u4?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 XD(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(JD,"handleError");a(XD,"when");a(uc,"stringify");a(rL,"jsStringify");d4=/[[,:]\s*-?\d{16,}/;a($A,"parse")});var hi=P(np=>{var rp=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])rp.logsAtLevel(e)&&(np[e]=rp[e]);np.loggerWithTag=e=>rp.loggerWithTag(e,!0);np.setLogLevel=rp.setLogLevel});var hp={};Ue(hp,{Blob:()=>mi,blobsWereEncoded:()=>fc,databasePaths:()=>YA,decodeBlobsWithWrites:()=>fp,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>_p,deleteBlob:()=>lp,deleteBlobsInObject:()=>ta,deleteRootBlobPathsForDB:()=>zA,encodeBlobsAsBuffers:()=>A4,encodeBlobsWithFilePath:()=>dp,findBlobsInObject:()=>Zl,getFileId:()=>up,getFilePathForBlob:()=>_L,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>m4});function uL(){}function lp(e){let t=_L(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&Ji.default.debug?.("Error trying to remove blob file",r)})},dL)}function m4(e){dL=e}function fL(e){let t=fn.get(e);if(!t)t={storageIndex:0,fileId:null,store:_n},fn.set(e,t);else{if(t.saving)return t;t.store=_n}return E4(t),t.source?KA(e,t.source,t):t.contentBuffer?p4(e,t):KA(e,Sf.Readable.from(e.stream()),t),t}function KA(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,je.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(_4),h=(0,ap.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(f4),t.pipe(d)),t.on("error",S);function m(g){let A=BigInt(g),E=new Uint8Array(hr),T=new DataView(E.buffer);return A|=BigInt(o?WA:lL)<<48n,T.setBigInt64(0,A),E}a(m,"createHeader");function S(g){i.unlock(f,0);let A=d.fd;g?(A&&(0,je.close)(A),u(g)):c?(0,je.fdatasync)(A,E=>{E&&u(E),l(),(0,je.close)(A)}):(l(),(0,je.close)(A))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-hr;e.size=g,(0,je.write)(d.fd,m(g),0,hr,0,S)}})}),e}function up(e){return fn.get(e)?.fileId}function _L(e){let t=fn.get(e);return t?.fileId&&Tf(t)}function Af(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=YA.get(e);if(!t){if(!e.databaseName)return Ji.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,cp.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Zi.join)(n,e.databaseName)):t=[(0,Zi.join)((0,cp.getHdbBasePath)(),"blobs",e.databaseName)],YA.set(e,t)}return t}async function zA(e){let t=Af(e);t&&await Promise.all(t.map(r=>hL(r)))}async function hL(e){if((0,je.existsSync)(e)){for(let t of await(0,Hs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await hL((0,Zi.join)(e,t.name));else try{await(0,Hs.unlink)((0,Zi.join)(e,t.name))}catch(r){Ji.default.warn?.("Error deleting file",r)}try{await(0,Hs.rmdir)(e)}catch(t){Ji.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Zi.join)(n[e],t.slice(-9,-6)||"0",t.slice(-6,-3)||"0",t.length<=9?t.slice(-3):t.slice(0,-9)+t.slice(-3))}function p4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<cL))return e.size=n,KA(e,Sf.Readable.from([r]),t)}function E4(e){let t=Af(e.store),r=g4(),n=t?.length>1?S4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Zi.dirname)(i);(0,je.existsSync)(o)||(0,aL.ensureDirSync)(o),e.filePath=i}function g4(){let e=oL.get(_n);if(!e){let t=0,r=Af(_n);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,Zi.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(_n.getUserSharedBuffer("blob-file-id",e.buffer)),oL.set(_n,e)}return Number(Atomics.add(e,0,1n))}function S4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(op);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,T4(e)),e.frequencyTable[t%op]}async function T4(e){if(!Hs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Hs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(op),n=t.map(s=>1/s);for(let s=0;s<op;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function dp(e,t,r){Xl=t,_n=r,fc=!1;try{return e()}finally{Xl=void 0,_n=void 0}}function A4(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function fp(e,t){try{Dr=[],dc=t,e()}catch(n){throw dc=void 0,Dr=void 0,n}dc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function _p(e,t,r){_n=r;try{return dc=t,e()}finally{dc=void 0}}function _c(e,t){return _n=t,e()}function ta(e){Zl(e,t=>{lp(t)})}function Zl(e,t){if(e instanceof mi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Zl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&Zl(e[r],t)}}function R4(){return class{static{a(this,"Blob")}content;constructor(t){this.content=t[0]}stream(){return new ReadableStream({start(t){t.enqueue(this.content),t.close()}})}text(){return Promise.resolve(this.content.toString())}arrayBuffer(){return Promise.resolve(this.content.buffer)}get size(){return this.content.length}slice(){throw new Error("Not implemented")}bytes(){return Promise.resolve(this.content)}get type(){return""}}}var Xi,Hs,je,ap,Sf,aL,cp,Zi,Ji,cL,hr,lL,WA,sL,f4,_4,iL,fn,dc,mi,Xl,Dr,_n,fc,gf,sp,h4,ip,dL,YA,oL,op,cs=be(()=>{Xi=require("msgpackr"),Hs=require("node:fs/promises"),je=require("node:fs"),ap=require("node:zlib"),Sf=require("node:stream"),aL=require("fs-extra"),cp=M(le());H();Zi=require("path"),Ji=M(hi());eo();cL=8192,hr=8,lL=0,WA=1,sL=255,f4=new Uint8Array([0,lL,255,255,255,255,255,255]),_4=new Uint8Array([0,WA,255,255,255,255,255,255]),iL=0xffffffffffff,fn=new WeakMap,mi=global.Blob||R4(),fc=!1,gf=new Uint8Array(8),sp=new DataView(gf.buffer),h4=6e4;a(uL,"InstanceOfBlobWithNoConstructor");uL.prototype=mi.prototype;ip=class e extends uL{static{a(this,"FileBackedBlob")}type="";size;#e;#t;constructor(t){super(),t?.type&&(this.type=t.type),t?.size!=null&&(this.size=t.size)}on(t,r){if(t==="error")this.#e??=[],this.#e.push(r);else if(t==="size")this.#t??=[],this.#t.push(r);else throw new Error("Only 'error' and 'size' events are supported")}toJSON(){if(this.type?.startsWith("text")){let t=fn.get(this),{start:r,end:n,contentBuffer:s,asString:i}=t;return i||(s&&(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),s?(t.asString=s.toString(),t.asString):(QA()&&jA(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=fn.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Tf(t),o,c=a(async()=>{let l,u=hr;try{if(l=await(0,Hs.readFile)(i),l.length>=hr){l.copy(gf,0,0,hr);let d=sp.getBigUint64(0);if(Number(d>>48n)===sL)throw new Error("Error in blob: "+buffer.subarray(hr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<iL&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,h=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((m,S)=>{if(_.attemptLock(h,0,()=>(o=!0,_.unlock(h,0),m(c()))))return o=!0,_.unlock(h,0),m(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===WA?new Promise((d,_)=>{(0,ap.deflate)(l.subarray(hr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(hr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=fn.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Tf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((A,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(Ji.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(A,E)},20).unref();E(T),h.#e?.forEach(v=>v(T))}else o=w,A(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,A=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),h.#e?.forEach(W=>W($))}a(v,"onError");let k=Buffer.allocUnsafe(262144);(0,je.read)(o,k,0,k.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<hr){A-- >0&&d!==!1?(m(),Ji.default.debug?.("File was empty, waiting for data to be written",i,A),setTimeout(()=>E(T,w),20).unref()):(Ji.default.debug?.("File was empty, throwing error",i,A),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,hr);let se=sp.getBigUint64(0);if(Number(se>>48n)===sL)return v(new Error("Error in blob: "+te.subarray(hr)));if(g=Number(se&0xffffffffffffn),g<iL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(hr,W),l-=hr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,hr,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(sp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},h4).unref():(u=(0,je.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,je.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return Ji.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1,S.unlock(g,0)}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=fn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};fn.set(i,o),this.size!=null&&(i.size=(r==null?this.size:Math.min(r,this.size))-(t??0))}else if(s?.contentBuffer&&!s.storageBuffer){let o={...s,contentBuffer:s.contentBuffer.subarray(t,r)};fn.set(i,o),i.size=(r??this.size)-t}else throw new Error("Can not slice a streaming blob that is not backed by a file");return i}save(t){if(_n=t?.primaryStore?.rootStore,!_n)throw new Error("No target table specified");return fL(this).saving??Promise.resolve()}},dL=500;a(lp,"deleteBlob");a(m4,"setDeletionDelay");global.createBlob=function(e,t){let r=new ip(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(fn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Sf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Sf.Readable.from(e);else throw new Error("Invalid source type");return r};a(fL,"saveBlob");a(KA,"writeBlobWithStream");a(up,"getFileId");a(_L,"getFilePathForBlob");YA=new Map;a(Af,"getRootBlobPathsForDB");a(zA,"deleteRootBlobPathsForDB");a(hL,"rimrafSteadily");a(Tf,"getFilePath");a(p4,"writeBlobWithBuffer");a(E4,"generateFilePath");oL=new Map;a(g4,"getNextFileId");op=128;a(S4,"getNextStorageIndex");a(T4,"createFrequencyTableForStoragePaths");a(dp,"encodeBlobsWithFilePath");a(A4,"encodeBlobsAsBuffers");a(fp,"decodeBlobsWithWrites");a(_p,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ta,"deleteBlobsInObject");a(Zl,"findBlobsInObject");(0,Xi.addExtension)({Class:mi,type:11,unpack:a(function(e){let t=(0,Xi.unpack)(e),r=new ip;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(fn.set(r,{storageIndex:t[1],fileId:t[2],store:_n}),dc)return dc(r)??r;if(!_n)throw new Error("No store specified, cannot load blob from storage")}else fn.set(r,{storageIndex:0,fileId:null,storageBuffer:e,contentBuffer:t[1]}),r.size=t[1]?.length;return r},"unpack"),pack:a(function(e){let t=fn.get(e);if(Xl!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Xl))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<cL)return r.size=t.contentBuffer.length,(0,Xi.pack)([r,t.contentBuffer])}if(Xl!==void 0){if(t=fL(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Xl,(0,Xi.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Tf(t));if(n.length>=hr&&(n.copy(gf,0,0,hr),Number(sp.getBigUint64(0)&0xffffffffffffn)===n.length-hr))return Buffer.concat([(0,Xi.pack)([r]),n]);if(Dr)Dr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Dr)return Dr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,Xi.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(R4,"polyfillBlob")});var RL={};Ue(RL,{asyncSerialization:()=>jA,contentTypes:()=>eR,findBestSerializer:()=>pp,getDeserializer:()=>no,hasAsyncSerialization:()=>QA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>ra,toCsvStream:()=>mp});function b4(e){try{return e?.[0]===123?ZA(e):e}catch{return e}}function bf(e){e.register(N4,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new hc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?mc.Readable.from((0,pi.encodeIter)(t,yf)):(0,pi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),mp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,pi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,hc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function pp(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,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=$r.get(u);if(h){let m=(h.q||1)*d;m>s&&(n=h,i=h.type||u,s=m,o=_)}}if(!n){if(r)throw new EL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from($r.keys()).join(", "),406);n=$r.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=pL&&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||e instanceof mi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=pp(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}),XA.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,ro.createBrotliCompress)({params:{[ro.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?ro.constants.BROTLI_MODE_TEXT:ro.constants.BROTLI_MODE_GENERIC,[ro.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>pL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,ro.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ra(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;to=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=pp(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return to?.length>0?(to.length===1?to[0]:Promise.all(to)).then(()=>ra(e,t,!0)):n}finally{to=void 0}}function jA(e){if(to)to.push(e);else throw new Error("Unable to serialize asynchronously")}function QA(){return!!to}function w4(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 C4(e){return I4.includes(e)}function P4(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function no(e="",t=!1){let r=P4(e),n=r.type&&$r.get(r.type)?.deserialize||D4(r);return t?s=>w4(s).then(n):n}function D4(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!C4(e.parameters.charset)&&XA.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return ZA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function L4(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)}}}}}function mp(e,t){let r=mc.default.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 y4(n,s);return r.pipe(i)}var pi,hc,ro,EL,mc,gL,JA,SL,XA,y4,TL,Rf,ZA,yf,$r,eR,mL,AL,O4,N4,pL,to,I4,eo=be(()=>{VA();pi=require("msgpackr"),hc=require("cbor-x"),ro=require("zlib"),EL=M(me()),mc=M(require("stream"));Pr();gL=M(li()),JA=M(le());H();SL=M(require("yaml")),XA=M(hi());cs();({Transform:y4}=require("json2csv")),TL=JA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=TL?uc:JSON.stringify,ZA=TL?$A:JSON.parse,yf={useRecords:!1,useToJSON:!0},$r=new Map,eR=$r;Ke.contentTypes=eR;(0,gL._assignPackageExport)("contentTypes",eR);$r.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return ZA(e)},q:.8});mL=new hc.Encoder(yf);$r.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new hc.EncoderStream(yf).end(e)},serialize:mL.encode,deserialize:mL.decode,q:1});$r.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?mc.Readable.from((0,pi.encodeIter)(e,yf)):(0,pi.pack)(e)},serialize:pi.pack,deserialize:pi.unpack,q:.9});$r.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),mp(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]),mp(e,e?.getColumns?.())},q:.1});$r.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return mc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});$r.set("text/yaml",{serialize(e){return SL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});$r.set("text/event-stream",{serializeStream:a(function(e){return mc.Readable.from(L4(e,this.serialize))},"serializeStream"),serialize:a(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+`
|
|
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:X2.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(rJ,"findPs")});var Ut=P((CRe,QP)=>{"use strict";var nJ="__dbis__",sJ="__txns__",iJ="__environment_name__",oJ="__dbi_defintion__",aJ={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"},cJ=["__createdtime__","__updatedtime__"],lJ="\uFFFF",jP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},uJ=Object.values(jP);QP.exports={AUDIT_STORE_NAME:sJ,INTERNAL_DBIS_NAME:nJ,DBI_DEFINITION_NAME:oJ,SEARCH_TYPES:aJ,TIMESTAMP_NAMES:cJ,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:iJ,TRANSACTIONS_DBI_NAMES_ENUM:jP,TRANSACTIONS_DBIS:uJ,OVERFLOW_MARKER:lJ}});var Pn=P((PRe,iD)=>{"use strict";var JP=(H(),D(G)),XP=Ut(),ZP={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},eD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),tD={500:eD("There was an error processing your request."),400:"Invalid request"},dJ=tD[ZP.INTERNAL_SERVER_ERROR],fJ={OP_NOT_SUPPORTED_FOR_FS:a(e=>`${e} is not available for this instance because it uses the File System data store.`,"OP_NOT_SUPPORTED_FOR_FS"),MISSING_VALUE:a(e=>`${e} is missing.`,"MISSING_VALUE"),INVALID_VALUE:a(e=>`${e} is invalid.`,"INVALID_VALUE"),NOT_FOUND:a(e=>`${e} not found.`,"NOT_FOUND")},_J={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},hJ={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:a(e=>`There was an error downloading '${e}'.`,"DOWNLOAD_FILE_ERR"),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:a(e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,"INVALID_ACTION_PARAM_ERR"),INVALID_FILE_EXT_ERR:a(e=>`Error selecting correct parser - valid file type not found in json - ${e}`,"INVALID_FILE_EXT_ERR"),MAX_FILE_SIZE_ERR:a((e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,"MAX_FILE_SIZE_ERR"),PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:a(e=>`There was an error downloading '${e}' from AWS.`,"S3_DOWNLOAD_ERR"),WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},mJ={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 ${XP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${XP.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"},pJ={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${JP.INSERT_MAX_CHARACTER_SIZE} bytes.`,"ATTR_NAME_LENGTH_ERR"),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 ${JP.INSERT_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"},rD={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"},EJ={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:a(e=>`Operation '${e}' is restricted to 'super_user' roles`,"OP_IS_SU_ONLY"),OP_NOT_FOUND:a(e=>`Operation '${e}' not found`,"OP_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:a((e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,"UNKNOWN_OP_AUTH_ERROR"),USER_HAS_NO_PERMS:a(e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,"USER_HAS_NO_PERMS"),DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},gJ={ATTR_PERM_MISSING:a((e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,"ATTR_PERM_MISSING"),ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:a((e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,"ATTR_PERM_NOT_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:a(e=>`Invalid attribute '${e}' in 'attribute_permissions'`,"INVALID_ATTRIBUTE_IN_PERMS"),INVALID_PERM_KEY:a(e=>`Invalid table permission key value '${e}'`,"INVALID_PERM_KEY"),INVALID_ATTR_PERM_KEY:a(e=>`Invalid attribute permission key value '${e}'`,"INVALID_ATTR_PERM_KEY"),INVALID_ROLE_JSON_KEYS:a(e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,"INVALID_ROLE_JSON_KEYS"),MISMATCHED_TABLE_ATTR_PERMS:a(e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,"MISMATCHED_TABLE_ATTR_PERMS"),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:a(e=>`A role with name '${e}' already exists`,"ROLE_ALREADY_EXISTS"),ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:a(e=>`Your role does not have permission to view database metadata for '${e}'`,"SCHEMA_PERM_ERROR"),SCHEMA_TABLE_PERM_ERROR:a((e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,"SCHEMA_TABLE_PERM_ERROR"),SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:a(e=>`Value for '${e}' permission must be a boolean`,"SU_CU_ROLE_BOOLEAN_ERROR"),STRUCTURE_USER_ROLE_TYPE_ERROR:a(e=>`Value for '${e}' permission must be a boolean or Array`,"STRUCTURE_USER_ROLE_TYPE_ERROR"),SU_CU_ROLE_NO_PERMS_ALLOWED:a(e=>`Roles with '${e}' set to true cannot have other permissions set.`,"SU_CU_ROLE_NO_PERMS_ALLOWED"),SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:a(e=>`Missing table ${e.toUpperCase()} permission`,"TABLE_PERM_MISSING"),TABLE_PERM_NOT_BOOLEAN:a(e=>`Table ${e.toUpperCase()} permission must be a boolean`,"TABLE_PERM_NOT_BOOLEAN")},SJ={ATTR_NOT_FOUND:a((e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,"ATTR_NOT_FOUND"),ATTR_EXISTS_ERR:a((e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,"ATTR_EXISTS_ERR"),DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:a(e=>`Invalid table ${JSON.stringify(e)}`,"INVALID_TABLE_ERR"),SCHEMA_NOT_FOUND:a(e=>`database '${e}' does not exist`,"SCHEMA_NOT_FOUND"),SCHEMA_EXISTS_ERR:a(e=>`database '${e}' already exists`,"SCHEMA_EXISTS_ERR"),TABLE_EXISTS_ERR:a((e,t)=>`Table '${t}' already exists in '${e}'`,"TABLE_EXISTS_ERR"),SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:a((e,t)=>`Table '${e}.${t}' does not exist`,"TABLE_NOT_FOUND"),TABLE_REQUIRED_ERR:"table is required"},TJ={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},AJ={ALTER_USER_DUP_ROLES:a(e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,"ALTER_USER_DUP_ROLES"),ALTER_USER_ROLE_NOT_FOUND:a(e=>`Update failed. Requested '${e}' role not found.`,"ALTER_USER_ROLE_NOT_FOUND"),DUP_ROLES_FOUND:a(e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,"DUP_ROLES_FOUND"),ROLE_NAME_NOT_FOUND:a(e=>`${e} role not found`,"ROLE_NAME_NOT_FOUND"),USER_ALREADY_EXISTS:a(e=>`User ${e} already exists`,"USER_ALREADY_EXISTS"),USER_NOT_EXIST:a(e=>`User ${e} does not exist`,"USER_NOT_EXIST")},nD={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:a(e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`,"SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE")},sD={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:a(e=>`ITC server received invalid event type: ${e}`,"INVALID_EVENT")},RJ={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"},yJ={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},bJ={...rD,...hJ,...fJ,...EJ,...gJ,...SJ,...TJ,...AJ,...pJ,...nD,...sD,...RJ,...yJ,..._J};iD.exports={CHECK_LOGS_WRAPPER:eD,HDB_ERROR_MSGS:bJ,DEFAULT_ERROR_MSGS:tD,DEFAULT_ERROR_RESP:dJ,HTTP_STATUS_CODES:ZP,LMDB_ERRORS_ENUM:mJ,AUTHENTICATION_ERROR_MSGS:rD,VALIDATION_ERROR_MSGS:nD,ITC_ERRORS:sD}});var me=P((LRe,cD)=>{"use strict";var $l=Pn(),OJ=z(),NJ=(H(),D(G)),km=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,oD),this.statusCode=n||$l.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||($l.DEFAULT_ERROR_MSGS[n]?$l.DEFAULT_ERROR_MSGS[n]:$l.DEFAULT_ERROR_MSGS[$l.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&&OJ[s](i)}},bA=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}},OA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function oD(e,t,r,n=NJ.LOG_LEVELS.ERROR,s=null,i=!1){if(aD(e))return e;let o=new km(e,t,r,n,s);return i&&delete o.stack,o}a(oD,"handleHDBError");function aD(e){return e.__proto__.constructor.name===km.name}a(aD,"isHDBError");cD.exports={isHDBError:aD,handleHDBError:oD,ClientError:bA,ServerError:OA,hdb_errors:$l}});var Et=P((vRe,mD)=>{"use strict";var af=(H(),D(G)),wJ=oe(),an=le(),cf=require("path"),IJ=require("minimist"),lD=require("fs-extra"),uD=require("lodash");an.initSync();var{CONFIG_PARAMS:jo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Fm}=af,nf,sf,of;function dD(){if(nf!==void 0)return nf;if(an.getHdbBasePath()!==void 0)return nf=an.get(jo.STORAGE_PATH)||cf.join(an.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(dD,"getBaseSchemaPath");function fD(){if(sf!==void 0)return sf;if(an.getHdbBasePath()!==void 0)return sf=hD(Fm),sf}a(fD,"getSystemSchemaPath");function _D(){if(of!==void 0)return of;if(an.getHdbBasePath()!==void 0)return of=an.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(an.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(_D,"getTransactionAuditStoreBasePath");function CJ(e,t){let r=an.get(jo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(_D(),e.toString())}a(CJ,"getTransactionAuditStorePath");function hD(e,t){e=e.toString(),t=t&&t.toString();let r=an.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(dD(),e)}a(hD,"getSchemaPath");function PJ(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,IJ(process.argv));let n=r[jo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!wJ.isObject(n))throw o;i=n}for(let o of i){let c=o[Fm];if(!c)continue;let l=an.get(jo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return uD.set(l,[Fm,rf.TABLES,t,rf.PATH],u),an.setProperty(jo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return uD.set(l,[Fm,rf.PATH],f),an.setProperty(jo.DATABASES,l),f}}let s=r[jo.STORAGE_PATH.toUpperCase()];if(s){if(!lD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return lD.mkdirsSync(i),an.setProperty(jo.STORAGE_PATH,s),i}return fD()}a(PJ,"initSystemSchemaPaths");function DJ(){nf=void 0,sf=void 0,of=void 0}a(DJ,"resetPaths");mD.exports={getBaseSchemaPath:dD,getSystemSchemaPath:fD,getTransactionAuditStorePath:CJ,getTransactionAuditStoreBasePath:_D,getSchemaPath:hD,initSystemSchemaPaths:PJ,resetPaths:DJ}});var cn=P((HRe,TD)=>{"use strict";var LJ=Pn().LMDB_ERRORS_ENUM,xRe=require("lmdb"),MJ=Ut(),BRe=require("buffer").Buffer,{OVERFLOW_MARKER:pD,MAX_SEARCH_KEY_LENGTH:qm}=MJ,ED=["number","string","symbol","boolean","bigint"];function vJ(e){if(e=e?.primaryStore||e,!e)throw new Error(LJ.ENV_REQUIRED)}a(vJ,"validateEnv");function UJ(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(UJ,"stringifyData");function xJ(e){return e instanceof Date?e.valueOf():e}a(xJ,"convertKeyValueToWrite");function BJ(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(ED.includes(typeof e))return e.length>qm?[e.slice(0,qm)+pD]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(ED.includes(typeof i))i.length>qm?r.push(i.slice(0,qm)+pD):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(BJ,"getIndexedValues");var Gm=0,gD=0;function SD(){gD=Date.now()-performance.now()}a(SD,"adjustStartTime");SD();var HJ=6e4;setInterval(SD,HJ).unref();function kJ(){let e=performance.now()+gD;return e>Gm?(Gm=e,e):(Gm+=488e-6,Gm)}a(kJ,"getNextMonotonicTime");TD.exports={validateEnv:vJ,stringifyData:UJ,convertKeyValueToWrite:xJ,getNextMonotonicTime:kJ,getIndexedValues:BJ}});var lf=P((FRe,AD)=>{"use strict";var FJ=(H(),D(G)).OPERATIONS_ENUM,NA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=FJ.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};AD.exports=NA});var uf=P(($Re,OD)=>{"use strict";var GRe=lf(),$m=(H(),D(G)),wA=oe(),RD=z(),qJ=require("uuid"),{handleHDBError:Vm,hdb_errors:GJ}=me(),{HDB_ERROR_MSGS:Km,HTTP_STATUS_CODES:Ym}=GJ;OD.exports=yD;function yD(e,t,r){for(let s=0;s<t.length;s++)bD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];$J(i,r,e.operation)}}a(yD,"processRows");yD.validateAttribute=bD;function bD(e){if(Buffer.byteLength(String(e))>$m.INSERT_MAX_CHARACTER_SIZE)throw Vm(new Error,Km.ATTR_NAME_LENGTH_ERR(e),Ym.BAD_REQUEST,void 0,void 0,!0);if(wA.isEmptyOrZeroLength(e)||wA.isEmpty(e.trim()))throw Vm(new Error,Km.ATTR_NAME_NULLISH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(bD,"validateAttribute");function $J(e,t,r){if(!e.hasOwnProperty(t)||wA.isEmptyOrZeroLength(e[t])){if(r===$m.OPERATIONS_ENUM.INSERT||r===$m.OPERATIONS_ENUM.UPSERT){e[t]=qJ.v4();return}throw RD.error("Update transaction aborted due to record with no hash value:",e),Vm(new Error,Km.RECORD_MISSING_HASH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>$m.INSERT_MAX_CHARACTER_SIZE)throw RD.error(e),Vm(new Error,Km.HASH_VAL_LENGTH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a($J,"validateHash")});var ND,Dn,IA,Vl=be(()=>{ND=require("events"),Dn=class extends ND.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new IA;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)}},IA=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}}}});function MD(e){PA=e}function WJ(){YJ=setInterval(function(){for(let e of CA)if(e.stale){let t=e.getContext()?.url;PD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},KJ).unref()}var DA,CD,PD,DD,LD,wD,CA,VJ,df,ID,PA,oc,Wm,KJ,YJ,zm=be(()=>{DA=M(cn()),CD=M(me()),PD=M(z()),DD=M(le());H();LD=M(oe()),wD=100,CA=new Set,VJ=(0,LD.convertToMS)(DD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(MD,"replicationConfirmation");oc=class e{static{a(this,"DatabaseTransaction")}#e;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),CA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(CA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-ID>VJ)throw new CD.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||(0,DA.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let h=d;h<this.validated;h++)this.writes[h]?.validate?.(this.timestamp);let _;for(let h=d;h<this.validated;h++){let m=this.writes[h];m&&(m.before||m.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let h=0;h<2;h++){let m;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let A=g[h===0?"before":"beforeIntermediate"];if(A){let E=A();m?m.push?m.push(E):m=[m,E]:m=E}}m&&await(m.push?Promise.all(m):m)}}catch(h){throw this.abort(),h}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;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 _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<wD>>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 df||(df=s,ID=performance.now(),df.then(()=>{df=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];PA&&h&&i.push(PA(_,h.store.getEntry(h.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+wD/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Wm=class extends oc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,DA.getNextMonotonicTime)())}getReadTxn(){}},KJ=3e4;a(WJ,"startMonitoringTxns");WJ()});function Nt(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 oc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(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({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var vD,ac=be(()=>{vD=M(li());zm();a(Nt,"transaction");(0,vD._assignPackageExport)("transaction",Nt);Nt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Nt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function MA(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let h=1;h<e.length;h++){let m=e[h],S=u(m);d=d.concat(S)}let _=new Set;return d.filter(h=>{let m=h.key??h;return _.has(m)?!1:(_.add(m),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?MA(d.conditions,d.operator,r,n,s,i,o,c):Wl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(k=>k(w,v)):(w,v)=>T.every(k=>k(w,v))}let g=(m.attribute||m[0])===r.primaryKey,A=hf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=r4(r.primaryStore,m.estimated_count,h)),A}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Wl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new un.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=_i(n.attributes,E);if(T.relationship){if(o.length<2)throw new un.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let w=T.definition?.tableClass||T.elements?.definition?.tableClass,v=new Map,k=Wl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let $=!!_i(w.attributes,T.relationship.to)?.elements;k=XJ(k,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Wl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,k=ZJ(k,T,w.primaryStore,v,$)):k=k.flatMap($)}return k}else if(o.length===1)o=o[0];else throw new un.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(vA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=fi.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new un.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>os.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>os.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,d=!0,m=m??hf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new un.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new un.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(g?.isIndexing)throw new un.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new un.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??hf(e,n,null,i,S),!m)throw new un.ClientError(`Unknown search operator ${e.comparator}`)}let A={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(A).map(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:Qo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(w&&m(w)?T:Qo.SKIP)}catch($){k($)}}))}:T=>T.value==null&&!(T.metadataFlags&(dn|Xo))?Qo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(A).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>os.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Qo.SKIP:new Promise((v,k)=>setImmediate(()=>{try{v(m(w)?T:Qo.SKIP)}catch($){k($)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:Qo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Qo.SKIP)}catch(k){v(k)}}))})}function _i(e,t){if(Array.isArray(t))if(t.length>1){let r=_i(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?_i(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 XJ(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;return s.hasMappings=!0,{next(){if(!i){let c=t.relationship.to,l=a((u,f)=>{let d=s.get(u);d?d.push(f):s.set(u,d=[f])},"add_entry");for(let u of e){let f=u.value??r.get(u.key??u),d=f?.[c];if(d!=null&&!s.filters?.some(_=>!_(f)))if(n)for(let _=0;_<d.length;_++)l(d[_],u);else l(d,u)}return i=s.keys()[Symbol.iterator](),this.next()}let o=i.next();return o.done?o:{value:o.value}},return(){if(i?.return)return i.return()}}}})}function ZJ(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 u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hf(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 f=c[0],d=_i(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=hf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,A=a((E,T)=>{let w,v;if(S){if(S.from&&m.idFilter){if(!g)if(m.idFilter.idSet?.size===1){for(let $ of m.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,m.idFilter,!0,!0)}else g=u(S.from,m.idFilter,!1,!0);let k=g(E);return g.idFilter&&(A.idFilter=g.idFilter),k}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(m):m(w,v):!1},"recordFilter");return A}}switch(l instanceof Date&&(l=l.getTime()),vA[o]||o){case os.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[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()),u(c,f=>(0,fi.compareKeys)(f,l[0])>=0&&(0,fi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,fi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,fi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,fi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,fi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,fi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new un.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Qm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function A(E){let T=E[f],w;if(typeof T!="object"||!T||h?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!A.idFilter&&++S/g*(i-g)>m)){let v=Wl(e,r.transaction.getReadTxn(),!1,t).map(zl),k=new Set(v);A.idFilter=$=>k.has(zl($)),A.idFilter.idSet=k}return w}return a(A,"recordFilter"),s&&(A.idFilter=d),A}a(u,"attributeComparator")}function Qm(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/Qi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=vA[n]||n,n===os.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=_i(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qm(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*Qi(e.indices[i.relationship.from])/(Qi(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=Qi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=QJ*Qi(e.primaryStore)+1:n==="between"?r.estimated_count=jJ*Qi(e.primaryStore)+1:n==="sort"?r.estimated_count=Qi(e.primaryStore)+1:r.estimated_count=zJ*Qi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jm(e){if(e)if(Jo=e,Kl.lastIndex=0,e4.test(e))try{let t=ff(new Yl,"");if(ln!==Jo.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 ${ln} in '${Jo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Kl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Jo);){ln=r.lastIndex;let[,f,d]=n;if(o){if(f)throw new SyntaxError(`expected operator, but encountered '${f}'`);o=!1,c=!1}else c=!0;let _;switch(d){case"=":if(s!=null){if(f.length<=2)i=f;else throw new SyntaxError(`invalid FIQL operator ${f}`);l=UD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=_f(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=JJ[d],l=LA[i]?UD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_f(f);break;case"&=":case"|=":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 m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&xD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else jm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Kl.lastIndex=ln;let h=ff(f?[]:new Yl,")");switch(f){case"":jm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=BD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Jo[ln]===","?r.lastIndex=++ln:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");Kl.lastIndex=ln,_=ff([],"}"),_.name=f,e.push(_),Jo[ln]===","?r.lastIndex=++ln:o=!0;break;case"[":Kl.lastIndex=ln,f?(_=ff(new Yl,"]"),_.name=f):_=ff(e.conditions?new Yl:[],"]"),e.conditions?(jm(e,u),e.conditions.push(_),s=null):e.push(_),Jo[ln]===","?r.lastIndex=++ln:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let m={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&xD(m,f),jm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));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?t4:Kl,r.lastIndex=ln),ln===Jo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jm(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 _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function UD(e){if(e==="null")return null;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 un.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function xD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new un.ClientError("wildcard can only be used at the end of a string")}function BD(e){let t=HD(e[0]);return e.length>1&&(t.next=BD(e.slice(1))),t}function HD(e){if(Array.isArray(e)){let t=HD(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 zl(e){return Array.isArray(e)?e.join("\0"):e}function Qi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function r4(e,t,r){return t*r/Qi(e)}var un,os,fi,Qo,zJ,jJ,QJ,JJ,LA,vA,e4,Kl,t4,ln,Jo,Yl,cc,mf=be(()=>{un=M(me()),os=M(Ut()),fi=require("ordered-binary"),Qo=require("lmdb");pf();zJ=.3,jJ=.1,QJ=.05,JJ={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},LA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(MA,"executeConditions");a(Wl,"searchByIndex");a(_i,"findAttribute");a(XJ,"joinTo");a(ZJ,"joinFrom");vA={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(hf,"filterByType");a(Qm,"estimateCondition");e4=/[()[\]|!<>.]|(=\w*=)/,Kl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,t4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jm,"parseQuery");a(ff,"parseBlock");a(jm,"assignOperator");a(_f,"decodeProperty");a(UD,"typedDecoding");a(xD,"wildcardDecoding");a(BD,"toSortObject");a(HD,"toSortEntry");Yl=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(zl,"flattenKey");a(Qi,"estimatedEntryCount");a(r4,"intersectionEstimate");cc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var xA={};Ue(xA,{MultiPartId:()=>Zm,Resource:()=>Gr,snake_case:()=>s4,transformForSelect:()=>ep});function s4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function kD(e,t){if(lc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(lc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Zm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){lc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return lc=!0,null;e[e.length-1]==="/"&&(lc=!0)}return t.coerceId(decodeURIComponent(e))}function Ln(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||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")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}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,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new cc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return Nt(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new Xm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Xm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Mn(e,t){let r=new GD.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 UA(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();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 ep(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):UA(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=[],f=i(UA(l,r,n));for(let d of e)u.push(f(d));return u},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(_=>_&&typeof _=="object"?c(_):_);let u={},f=i(UA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"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 f=r[c.name]?.definition?.tableClass;l=s[c.name]=ep(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var FD,qD,GD,n4,Gr,Xm,lc,Zm,Zo=be(()=>{FD=require("crypto");Vl();qD=M(li()),GD=M(me());ac();mf();n4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Gr=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Ln(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 u=ep(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Ln(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Mn(t,"put")},{hasContent:!0,type:"update"});static patch=Ln(function(t,r,n,s){return t.patch?t.patch(s,r):Mn(t,"patch")},{hasContent:!0,type:"update"});static delete=Ln(function(t,r,n,s){return t.delete?t.delete(r):Mn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,FD.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={}),Nt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Mn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Ln(function(t,r,n,s){return t.invalidate?t.invalidate(r):Mn(t,"delete")},{hasContent:!1,type:"update"});static post=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Ln(function(t,r,n,s){return t.connect?t.connect(s,r):Mn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Ln(function(t,r,n,s){return t.subscribe?t.subscribe(r):Mn(t,"subscribe")},{type:"read"});static publish=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Mn(t,"publish")},{hasContent:!0,type:"create"});static search=Ln(function(t,r,n,s){let i=t.search?t.search(r):Mn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ep(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Ln(function(t,r,n,s){return t.search?t.search(s,r):Mn(t,"search")},{hasContent:!0,type:"read"});static copy=Ln(function(t,r,n,s){return t.copy?t.copy(s,r):Mn(t,"copy")},{hasContent:!0,type:"create"});static move=Ln(function(t,r,n,s){return t.move?t.move(s,r):Mn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Mn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Jm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&n4[o];if(c)r.requestedContentType=c,t=t.slice(0,s);else if(this.attributes?.find(l=>l.name===o))if(t=t.slice(0,s),n)n.property=o;else return{query:{property:o},id:kD(t,this),isCollection:lc}}let i=kD(t,this);return lc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),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 u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Dn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Dn}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.#e}getContext(){return this.#t}};(0,qD._assignPackageExport)("Resource",Gr);a(s4,"snake_case");Xm=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(kD,"pathToId");Zm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Ln,"transactional");a(Mn,"missingMethod");a(UA,"selectFromObject");a(ep,"transformForSelect")});var ea,BA=be(()=>{ea=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 jl={};Ue(jl,{server:()=>Ke});var $D,Ke,Pr=be(()=>{$D=M(li()),Ke={};(0,$D._assignPackageExport)("server",Ke)});var YD={};Ue(YD,{Resources:()=>tp,keyArrayToString:()=>Ql,resetResources:()=>i4,resources:()=>as});function i4(){return as=new tp,Ke.resources=as,as}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var VD,KD,tp,as,Jl=be(()=>{ac();BA();VD=M(z()),KD=M(me());Pr();tp=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 KD.ServerError(`Conflicting paths for ${t}`);VD.default.error(c),i.Resource=new ea(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}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 Nt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(i4,"resetResources");a(Ql,"keyArrayToString")});var HA=P((hye,WD)=>{if(__filename.endsWith("dev.js")){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n}=require("node:path"),{existsSync:s,statSync:i,readFileSync:o,writeFileSync:c,unlinkSync:l}=require("node:fs"),{isMainThread:u}=require("node:worker_threads"),{spawnSync:f,spawn:d}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:_}=pt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],m="ts-build";if(u){let A=!1,E=!1;if(E=s(n(_,m))){let T=new Set;e.sync(h.map(w=>`${w}/**/*.ts`),{cwd:_}).forEach(w=>{let v=0,k=0;try{T.add(w),v=i(n(_,w)).mtimeMs-5e3,k=i(n(_,m,w.replace(/.ts$/,".js"))).mtimeMs}catch{}v>k&&(A=!0)}),e.sync(h.map(w=>`${w}/**/*.js`),{cwd:n(_,m)}).forEach(w=>{if(!T.has(w.replace(/.js$/,".ts")))try{l(n(_,m,w))}catch{}})}else A=!0;if(A){console.log("Compiling TypeScript...");let T=f("npx",["tsc"],{cwd:_});if(T.stdout?.length&&console.log(T.stdout.toString()),T.stderr?.length&&console.log(T.stderr.toString()),E){let w=n(t(),"harperdb-tsc.pid"),v=!1;if(s(w))try{process.kill(+o(w,"utf8"),0),v=!0}catch{}if(!v){console.log("Starting background TypeScript compilation...");let k=d("npx",["tsc","--watch"],{detached:!0,cwd:_,stdio:"ignore"});k.on("error",$=>{console.error("Error trying to compile TypeScript",$)}),k.pid&&c(w,String(k.pid),"utf-8"),k.unref()}}}}let S=WD.constructor,g=S._findPath;S._findPath=function(A,E,T){if(A.startsWith(".")&&!T&&E.length===1&&E[0].startsWith(_)&&!E[0].includes("node_modules")){let w=r(_,E[0]),v;w.startsWith(m)?v=n(_,r(m,w)):v=n(_,m,w);let k=n(v,A),$=k+".js";if(s($))return $;if(k.includes(".")&&s(k))return k}return g(A,E,T)}}});var qA={};Ue(qA,{loadGQLSchema:()=>c4,start:()=>FA,startOnMainThread:()=>a4});function FA({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,h=[],m;for(let A of d.definitions)switch(A.kind){case l.OBJECT_TYPE_DEFINITION:let k=function(W){if(W.kind==="NonNullType"){let Y=k(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:k(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(k,"getProperty");let E=A.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of A.directives){if(W.name.value==="table"){for(let se of W.arguments)w[se.name.value]=se.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=E),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,h.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,$={};for(let W of A.fields){let te=k(W.type);te.name=W.name.value,T.push(te),$[te.name]=void 0;for(let se of W.directives){let Y=se.name.value;if(Y==="primaryKey")v?console.warn("Can not define two attributes as a primary key at",se.loc):(te.isPrimaryKey=!0,v=!0);else if(Y==="indexed")te.indexed=!0;else if(Y==="computed"){for(let ne of se.arguments||[])if(ne.name.value==="from"){let ue=ne.value.value;te.computed={from:g(ue,ne,$)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(m=w)}function S(A){let E=_.get(A.type);E?(Object.defineProperty(A,"properties",{value:E.properties}),Object.defineProperty(A,"definition",{value:E})):A.type==="array"?S(A.elements):o4.includes(A.type)||(0,jD.getWorkerIndex)()===0&&console.error(`The type ${A.type} is unknown at line ${A.location.line}, column ${A.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let A of _.values())for(let E of A.properties)S(E);for(let A of h)A.tableClass=e(A),A.export&&(A.export.name===""?i.set((0,kA.dirname)(n),A.tableClass):i.set((0,kA.dirname)(n)+"/"+(A.export.name||A.type),A.tableClass,A.export));function g(A,E,T){return new zD.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${A}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var kA,zD,jD,o4,a4,c4,QD=be(()=>{kA=require("path"),zD=require("node:vm");ve();jD=M(Ze()),o4=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(FA,"start");a4=FA,c4=FA({ensureTable:dt}).handleFile});var nL={};Ue(nL,{parse:()=>$A,streamAsJSON:()=>Ef,stringify:()=>uc});function Ef(e){return new GA({value:e})}function JD(e){return console.error(e),JSON.stringify(e.toString())}function XD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function uc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===tL)return rL(e);if(t.resolution)return t.resolution.then(()=>uc(e));throw t}}function rL(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+=rL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+uc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function $A(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),d4.test(e)?l4.parse(e):JSON.parse(e)):null}var ZD,eL,l4,u4,tL,GA,d4,VA=be(()=>{ZD=require("stream"),eL=M(require("json-bigint-fixes")),l4=(0,eL.default)({useNativeBigInt:!0}),u4=1e4,tL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw tL};a(Ef,"streamAsJSON");GA=class extends ZD.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:a(()=>({done:!0}),"next")},"")))}catch(c){o={done:!1,value:{error:c.toString()}},i={next:a(()=>({done:!0}),"next")}}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),JD)}catch(s){yield JD(s)}else yield uc(t)}else yield uc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);XD(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>u4?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 XD(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(JD,"handleError");a(XD,"when");a(uc,"stringify");a(rL,"jsStringify");d4=/[[,:]\s*-?\d{16,}/;a($A,"parse")});var hi=P(np=>{var rp=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])rp.logsAtLevel(e)&&(np[e]=rp[e]);np.loggerWithTag=e=>rp.loggerWithTag(e,!0);np.setLogLevel=rp.setLogLevel});var hp={};Ue(hp,{Blob:()=>mi,blobsWereEncoded:()=>fc,databasePaths:()=>YA,decodeBlobsWithWrites:()=>fp,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>_p,deleteBlob:()=>lp,deleteBlobsInObject:()=>ta,deleteRootBlobPathsForDB:()=>zA,encodeBlobsAsBuffers:()=>A4,encodeBlobsWithFilePath:()=>dp,findBlobsInObject:()=>Zl,getFileId:()=>up,getFilePathForBlob:()=>_L,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>m4});function uL(){}function lp(e){let t=_L(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&Ji.default.debug?.("Error trying to remove blob file",r)})},dL)}function m4(e){dL=e}function fL(e){let t=fn.get(e);if(!t)t={storageIndex:0,fileId:null,store:_n},fn.set(e,t);else{if(t.saving)return t;t.store=_n}return E4(t),t.source?KA(e,t.source,t):t.contentBuffer?p4(e,t):KA(e,Sf.Readable.from(e.stream()),t),t}function KA(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,je.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(_4),h=(0,ap.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(f4),t.pipe(d)),t.on("error",S);function m(g){let A=BigInt(g),E=new Uint8Array(hr),T=new DataView(E.buffer);return A|=BigInt(o?WA:lL)<<48n,T.setBigInt64(0,A),E}a(m,"createHeader");function S(g){i.unlock(f,0);let A=d.fd;g?(A&&(0,je.close)(A),u(g)):c?(0,je.fdatasync)(A,E=>{E&&u(E),l(),(0,je.close)(A)}):(l(),(0,je.close)(A))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-hr;e.size=g,(0,je.write)(d.fd,m(g),0,hr,0,S)}})}),e}function up(e){return fn.get(e)?.fileId}function _L(e){let t=fn.get(e);return t?.fileId&&Tf(t)}function Af(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=YA.get(e);if(!t){if(!e.databaseName)return Ji.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,cp.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Zi.join)(n,e.databaseName)):t=[(0,Zi.join)((0,cp.getHdbBasePath)(),"blobs",e.databaseName)],YA.set(e,t)}return t}async function zA(e){let t=Af(e);t&&await Promise.all(t.map(r=>hL(r)))}async function hL(e){if((0,je.existsSync)(e)){for(let t of await(0,Hs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await hL((0,Zi.join)(e,t.name));else try{await(0,Hs.unlink)((0,Zi.join)(e,t.name))}catch(r){Ji.default.warn?.("Error deleting file",r)}try{await(0,Hs.rmdir)(e)}catch(t){Ji.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Zi.join)(n[e],t.slice(-9,-6)||"0",t.slice(-6,-3)||"0",t.length<=9?t.slice(-3):t.slice(0,-9)+t.slice(-3))}function p4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<cL))return e.size=n,KA(e,Sf.Readable.from([r]),t)}function E4(e){let t=Af(e.store),r=g4(),n=t?.length>1?S4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Zi.dirname)(i);(0,je.existsSync)(o)||(0,aL.ensureDirSync)(o),e.filePath=i}function g4(){let e=oL.get(_n);if(!e){let t=0,r=Af(_n);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,Zi.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(_n.getUserSharedBuffer("blob-file-id",e.buffer)),oL.set(_n,e)}return Number(Atomics.add(e,0,1n))}function S4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(op);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,T4(e)),e.frequencyTable[t%op]}async function T4(e){if(!Hs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Hs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(op),n=t.map(s=>1/s);for(let s=0;s<op;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function dp(e,t,r){Xl=t,_n=r,fc=!1;try{return e()}finally{Xl=void 0,_n=void 0}}function A4(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function fp(e,t){try{Dr=[],dc=t,e()}catch(n){throw dc=void 0,Dr=void 0,n}dc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function _p(e,t,r){_n=r;try{return dc=t,e()}finally{dc=void 0}}function _c(e,t){return _n=t,e()}function ta(e){Zl(e,t=>{lp(t)})}function Zl(e,t){if(e instanceof mi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Zl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&Zl(e[r],t)}}function R4(){return class{static{a(this,"Blob")}content;constructor(t){this.content=t[0]}stream(){return new ReadableStream({start(t){t.enqueue(this.content),t.close()}})}text(){return Promise.resolve(this.content.toString())}arrayBuffer(){return Promise.resolve(this.content.buffer)}get size(){return this.content.length}slice(){throw new Error("Not implemented")}bytes(){return Promise.resolve(this.content)}get type(){return""}}}var Xi,Hs,je,ap,Sf,aL,cp,Zi,Ji,cL,hr,lL,WA,sL,f4,_4,iL,fn,dc,mi,Xl,Dr,_n,fc,gf,sp,h4,ip,dL,YA,oL,op,cs=be(()=>{Xi=require("msgpackr"),Hs=require("node:fs/promises"),je=require("node:fs"),ap=require("node:zlib"),Sf=require("node:stream"),aL=require("fs-extra"),cp=M(le());H();Zi=require("path"),Ji=M(hi());eo();cL=8192,hr=8,lL=0,WA=1,sL=255,f4=new Uint8Array([0,lL,255,255,255,255,255,255]),_4=new Uint8Array([0,WA,255,255,255,255,255,255]),iL=0xffffffffffff,fn=new WeakMap,mi=global.Blob||R4(),fc=!1,gf=new Uint8Array(8),sp=new DataView(gf.buffer),h4=6e4;a(uL,"InstanceOfBlobWithNoConstructor");uL.prototype=mi.prototype;ip=class e extends uL{static{a(this,"FileBackedBlob")}type="";size;#e;#t;constructor(t){super(),t?.type&&(this.type=t.type),t?.size!=null&&(this.size=t.size)}on(t,r){if(t==="error")this.#e??=[],this.#e.push(r);else if(t==="size")this.#t??=[],this.#t.push(r);else throw new Error("Only 'error' and 'size' events are supported")}toJSON(){if(this.type?.startsWith("text")){let t=fn.get(this),{start:r,end:n,contentBuffer:s,asString:i}=t;return i||(s&&(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),s?(t.asString=s.toString(),t.asString):(QA()&&jA(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=fn.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Tf(t),o,c=a(async()=>{let l,u=hr;try{if(l=await(0,Hs.readFile)(i),l.length>=hr){l.copy(gf,0,0,hr);let d=sp.getBigUint64(0);if(Number(d>>48n)===sL)throw new Error("Error in blob: "+buffer.subarray(hr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<iL&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,h=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((m,S)=>{if(_.attemptLock(h,0,()=>(o=!0,m(c()))))return o=!0,_.unlock(h,0),m(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===WA?new Promise((d,_)=>{(0,ap.deflate)(l.subarray(hr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(hr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=fn.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Tf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((A,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(Ji.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(A,E)},20).unref();E(T),h.#e?.forEach(v=>v(T))}else o=w,A(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,A=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),h.#e?.forEach(W=>W($))}a(v,"onError");let k=Buffer.allocUnsafe(262144);(0,je.read)(o,k,0,k.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<hr){A-- >0&&d!==!1?(m(),Ji.default.debug?.("File was empty, waiting for data to be written",i,A),setTimeout(()=>E(T,w),20).unref()):(Ji.default.debug?.("File was empty, throwing error",i,A),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,hr);let se=sp.getBigUint64(0);if(Number(se>>48n)===sL)return v(new Error("Error in blob: "+te.subarray(hr)));if(g=Number(se&0xffffffffffffn),g<iL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(hr,W),l-=hr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,hr,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(sp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},h4).unref():(u=(0,je.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,je.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return Ji.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=fn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};fn.set(i,o),this.size!=null&&(i.size=(r==null?this.size:Math.min(r,this.size))-(t??0))}else if(s?.contentBuffer&&!s.storageBuffer){let o={...s,contentBuffer:s.contentBuffer.subarray(t,r)};fn.set(i,o),i.size=(r??this.size)-t}else throw new Error("Can not slice a streaming blob that is not backed by a file");return i}save(t){if(_n=t?.primaryStore?.rootStore,!_n)throw new Error("No target table specified");return fL(this).saving??Promise.resolve()}},dL=500;a(lp,"deleteBlob");a(m4,"setDeletionDelay");global.createBlob=function(e,t){let r=new ip(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(fn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Sf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Sf.Readable.from(e);else throw new Error("Invalid source type");return r};a(fL,"saveBlob");a(KA,"writeBlobWithStream");a(up,"getFileId");a(_L,"getFilePathForBlob");YA=new Map;a(Af,"getRootBlobPathsForDB");a(zA,"deleteRootBlobPathsForDB");a(hL,"rimrafSteadily");a(Tf,"getFilePath");a(p4,"writeBlobWithBuffer");a(E4,"generateFilePath");oL=new Map;a(g4,"getNextFileId");op=128;a(S4,"getNextStorageIndex");a(T4,"createFrequencyTableForStoragePaths");a(dp,"encodeBlobsWithFilePath");a(A4,"encodeBlobsAsBuffers");a(fp,"decodeBlobsWithWrites");a(_p,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ta,"deleteBlobsInObject");a(Zl,"findBlobsInObject");(0,Xi.addExtension)({Class:mi,type:11,unpack:a(function(e){let t=(0,Xi.unpack)(e),r=new ip;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(fn.set(r,{storageIndex:t[1],fileId:t[2],store:_n}),dc)return dc(r)??r;if(!_n)throw new Error("No store specified, cannot load blob from storage")}else fn.set(r,{storageIndex:0,fileId:null,storageBuffer:e,contentBuffer:t[1]}),r.size=t[1]?.length;return r},"unpack"),pack:a(function(e){let t=fn.get(e);if(Xl!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Xl))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<cL)return r.size=t.contentBuffer.length,(0,Xi.pack)([r,t.contentBuffer])}if(Xl!==void 0){if(t=fL(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Xl,(0,Xi.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Tf(t));if(n.length>=hr&&(n.copy(gf,0,0,hr),Number(sp.getBigUint64(0)&0xffffffffffffn)===n.length-hr))return Buffer.concat([(0,Xi.pack)([r]),n]);if(Dr)Dr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Dr)return Dr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,Xi.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(R4,"polyfillBlob")});var RL={};Ue(RL,{asyncSerialization:()=>jA,contentTypes:()=>eR,findBestSerializer:()=>pp,getDeserializer:()=>no,hasAsyncSerialization:()=>QA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>ra,toCsvStream:()=>mp});function b4(e){try{return e?.[0]===123?ZA(e):e}catch{return e}}function bf(e){e.register(N4,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new hc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?mc.Readable.from((0,pi.encodeIter)(t,yf)):(0,pi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),mp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,pi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,hc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function pp(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,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=$r.get(u);if(h){let m=(h.q||1)*d;m>s&&(n=h,i=h.type||u,s=m,o=_)}}if(!n){if(r)throw new EL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from($r.keys()).join(", "),406);n=$r.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=pL&&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||e instanceof mi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=pp(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}),XA.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,ro.createBrotliCompress)({params:{[ro.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?ro.constants.BROTLI_MODE_TEXT:ro.constants.BROTLI_MODE_GENERIC,[ro.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>pL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,ro.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ra(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;to=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=pp(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return to?.length>0?(to.length===1?to[0]:Promise.all(to)).then(()=>ra(e,t,!0)):n}finally{to=void 0}}function jA(e){if(to)to.push(e);else throw new Error("Unable to serialize asynchronously")}function QA(){return!!to}function w4(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 C4(e){return I4.includes(e)}function P4(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function no(e="",t=!1){let r=P4(e),n=r.type&&$r.get(r.type)?.deserialize||D4(r);return t?s=>w4(s).then(n):n}function D4(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!C4(e.parameters.charset)&&XA.default.info(`Unknown Buffer encoding ${e.parameters.charset} in content-type. Proceeding anyways.`),t=>({contentType:e.type,data:t.toString(e.parameters?.charset||"utf-8")})):e.type==="application/octet-stream"?t=>t:t=>{if(e.type==="")try{if(t?.[0]===123)return ZA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function L4(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)}}}}}function mp(e,t){let r=mc.default.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 y4(n,s);return r.pipe(i)}var pi,hc,ro,EL,mc,gL,JA,SL,XA,y4,TL,Rf,ZA,yf,$r,eR,mL,AL,O4,N4,pL,to,I4,eo=be(()=>{VA();pi=require("msgpackr"),hc=require("cbor-x"),ro=require("zlib"),EL=M(me()),mc=M(require("stream"));Pr();gL=M(li()),JA=M(le());H();SL=M(require("yaml")),XA=M(hi());cs();({Transform:y4}=require("json2csv")),TL=JA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=TL?uc:JSON.stringify,ZA=TL?$A:JSON.parse,yf={useRecords:!1,useToJSON:!0},$r=new Map,eR=$r;Ke.contentTypes=eR;(0,gL._assignPackageExport)("contentTypes",eR);$r.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return ZA(e)},q:.8});mL=new hc.Encoder(yf);$r.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new hc.EncoderStream(yf).end(e)},serialize:mL.encode,deserialize:mL.decode,q:1});$r.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?mc.Readable.from((0,pi.encodeIter)(e,yf)):(0,pi.pack)(e)},serialize:pi.pack,deserialize:pi.unpack,q:.9});$r.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),mp(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]),mp(e,e?.getColumns?.())},q:.1});$r.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return mc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});$r.set("text/yaml",{serialize(e){return SL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});$r.set("text/event-stream",{serializeStream:a(function(e){return mc.Readable.from(L4(e,this.serialize))},"serializeStream"),serialize:a(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+`
|
|
8
8
|
`),e.data){let r=e.data;typeof r=="object"&&(r=Rf(r)),t+="data: "+r+`
|
|
9
9
|
`}return e.id&&(t+="id: "+e.id+`
|
|
10
10
|
`),e.retry&&(t+="retry: "+e.retry+`
|