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
package/README.md
CHANGED
package/bin/harperdb.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
`+JSON.stringify(u)),u.cause&&(t[c--]=u.cause,u&&(n+=`
|
|
6
6
|
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}
|
|
7
7
|
`}a(Qs,"createLogRecord");function If(e){if(yi){if(PD(e),Es){pa=!1;try{process.stdout.write(e)}finally{pa=!0}}}else Es&&process.stdout.write(e)}a(If,"logStdOut");function _m(e){if(yi){if(PD(e),Es){pa=!1;try{process.stderr.write(e)}finally{pa=!0}}}else Es&&process.stderr.write(e)}a(_m,"logStdErr");function PD(e){aR(),_a?co.appendFileSync(_a,e):oR||console.log(e)}a(PD,"logToFile");function lR(){try{co.closeSync(_a)}catch{}_a=null}a(lR,"closeLogFile");function aR(){if(!_a){try{_a=co.openSync(dm,"a")}catch(e){oR||(oR=!0,console.error(e))}setTimeout(()=>{lR()},qQ).unref()}}a(aR,"openLogFile");function DD(...e){hr[Dr]<=hr.info&&If(Qs("info",e))}a(DD,"info");function LD(...e){hr[Dr]<=hr.trace&&If(Qs("trace",e))}a(LD,"trace");function fm(...e){hr[Dr]<=hr.error&&_m(Qs("error",e))}a(fm,"error");function MD(...e){hr[Dr]<=hr.debug&&If(Qs("debug",e))}a(MD,"debug");function vD(...e){hr[Dr]<=hr.notify&&If(Qs("notify",e))}a(vD,"notify");function UD(...e){hr[Dr]<=hr.fatal&&_m(Qs("fatal",e))}a(UD,"fatal");function xD(...e){hr[Dr]<=hr.warn&&_m(Qs("warn",e))}a(xD,"warn");function zQ(e,t,...r){t===ID.STDERR?_m(Qs(e,r)):If(Qs(e,r))}a(zQ,"logCustomLevel");function jQ(){let e;try{e=HQ.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=bi.join(e,Vt.HDB_HOME_DIR_NAME,Vt.BOOT_PROPS_FILE_NAME);return co.existsSync(t)||(t=bi.join(cR,"utility/hdb_boot_properties.file")),t}a(jQ,"getPropsFilePath");function JQ(e){Dr=e}a(JQ,"setLogLevel");function OD(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(OD,"autoCastBoolean");function QQ(e){try{if(e.includes("config/settings.js")){let o=wD(e);return{level:o.get(Vt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:bi.dirname(o.get(Vt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Vt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Vt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=ND.parseDocument(co.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===Vt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(QQ,"getLogConfig");function XQ(){try{let e=ND.parseDocument(co.readFileSync(GQ,"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(XQ,"getDefaultConfig");function ZQ(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(ZQ,"AuthAuditLog")});var uR=P((Wye,kD)=>{"use strict";var e4=require("util"),t4=require("path"),r4=require("child_process"),n4=e4.promisify(r4.execFile),s4=1e3*1e3*10;kD.exports={findPs:i4};async function i4(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await n4("ps",["wwxo",`pid,${r}`],{maxBuffer:s4});for(let s of n.trim().split(`
|
|
8
|
-
`).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:t4.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(i4,"findPs")});var xt=P((jye,GD)=>{"use strict";var o4="__dbis__",a4="__txns__",c4="__environment_name__",l4="__dbi_defintion__",u4={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"},d4=["__createdtime__","__updatedtime__"],f4="\uFFFF",FD={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},_4=Object.values(FD);GD.exports={AUDIT_STORE_NAME:a4,INTERNAL_DBIS_NAME:o4,DBI_DEFINITION_NAME:l4,SEARCH_TYPES:u4,TIMESTAMP_NAMES:d4,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:c4,TRANSACTIONS_DBI_NAMES_ENUM:FD,TRANSACTIONS_DBIS:_4,OVERFLOW_MARKER:f4}});var Hn=P((Jye,JD)=>{"use strict";var qD=(k(),D(q)),$D=xt(),VD={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},KD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),YD={500:KD("There was an error processing your request."),400:"Invalid request"},p4=YD[VD.INTERNAL_SERVER_ERROR],h4={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")},m4={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},E4={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"},g4={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 ${$D.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${$D.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"},S4={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${qD.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 ${qD.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"},WD={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"},T4={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."},A4={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")},R4={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"},y4={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},b4={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")},zD={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")},jD={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")},O4={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"},N4={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},w4={...WD,...E4,...h4,...T4,...A4,...R4,...y4,...b4,...S4,...zD,...jD,...O4,...N4,...m4};JD.exports={CHECK_LOGS_WRAPPER:KD,HDB_ERROR_MSGS:w4,DEFAULT_ERROR_MSGS:YD,DEFAULT_ERROR_RESP:p4,HTTP_STATUS_CODES:VD,LMDB_ERRORS_ENUM:g4,AUTHENTICATION_ERROR_MSGS:WD,VALIDATION_ERROR_MSGS:zD,ITC_ERRORS:jD}});var he=P((Xye,ZD)=>{"use strict";var _u=Hn(),I4=z(),C4=(k(),D(q)),pm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,QD),this.statusCode=n||_u.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(_u.DEFAULT_ERROR_MSGS[n]?_u.DEFAULT_ERROR_MSGS[n]:_u.DEFAULT_ERROR_MSGS[_u.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&&I4[s](i)}},dR=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}},fR=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function QD(e,t,r,n=C4.LOG_LEVELS.ERROR,s=null,i=!1){if(XD(e))return e;let o=new pm(e,t,r,n,s);return i&&delete o.stack,o}a(QD,"handleHDBError");function XD(e){return e.__proto__.constructor.name===pm.name}a(XD,"isHDBError");ZD.exports={isHDBError:XD,handleHDBError:QD,ClientError:dR,ServerError:fR,hdb_errors:_u}});var mt=P((ebe,oL)=>{"use strict";var Mf=(k(),D(q)),P4=oe(),fn=le(),vf=require("path"),D4=require("minimist"),eL=require("fs-extra"),tL=require("lodash");fn.initSync();var{CONFIG_PARAMS:ha,DATABASES_PARAM_CONFIG:Cf,SYSTEM_SCHEMA_NAME:hm}=Mf,Pf,Df,Lf;function rL(){if(Pf!==void 0)return Pf;if(fn.getHdbBasePath()!==void 0)return Pf=fn.get(ha.STORAGE_PATH)||vf.join(fn.getHdbBasePath(),Mf.DATABASES_DIR_NAME),Pf}a(rL,"getBaseSchemaPath");function nL(){if(Df!==void 0)return Df;if(fn.getHdbBasePath()!==void 0)return Df=iL(hm),Df}a(nL,"getSystemSchemaPath");function sL(){if(Lf!==void 0)return Lf;if(fn.getHdbBasePath()!==void 0)return Lf=fn.get(Mf.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||vf.join(fn.getHdbBasePath(),Mf.TRANSACTIONS_DIR_NAME),Lf}a(sL,"getTransactionAuditStoreBasePath");function L4(e,t){let r=fn.get(ha.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||vf.join(sL(),e.toString())}a(L4,"getTransactionAuditStorePath");function iL(e,t){e=e.toString(),t=t&&t.toString();let r=fn.get(Mf.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||vf.join(rL(),e)}a(iL,"getSchemaPath");function M4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,D4(process.argv));let n=r[ha.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!P4.isObject(n))throw o;i=n}for(let o of i){let c=o[hm];if(!c)continue;let l=fn.get(ha.DATABASES);l=l??{};let u=c?.tables?.[t]?.[Cf.PATH];if(u)return tL.set(l,[hm,Cf.TABLES,t,Cf.PATH],u),fn.setProperty(ha.DATABASES,l),u;let f=c?.[Cf.PATH];if(f)return tL.set(l,[hm,Cf.PATH],f),fn.setProperty(ha.DATABASES,l),f}}let s=r[ha.STORAGE_PATH.toUpperCase()];if(s){if(!eL.pathExistsSync(s))throw new Error(s+" does not exist");let i=vf.join(s,e);return eL.mkdirsSync(i),fn.setProperty(ha.STORAGE_PATH,s),i}return nL()}a(M4,"initSystemSchemaPaths");function v4(){Pf=void 0,Df=void 0,Lf=void 0}a(v4,"resetPaths");oL.exports={getBaseSchemaPath:rL,getSystemSchemaPath:nL,getTransactionAuditStorePath:L4,getTransactionAuditStoreBasePath:sL,getSchemaPath:iL,initSystemSchemaPaths:M4,resetPaths:v4}});var _n=P((sbe,dL)=>{"use strict";var U4=Hn().LMDB_ERRORS_ENUM,rbe=require("lmdb"),x4=xt(),nbe=require("buffer").Buffer,{OVERFLOW_MARKER:aL,MAX_SEARCH_KEY_LENGTH:mm}=x4,cL=["number","string","symbol","boolean","bigint"];function B4(e){if(e=e?.primaryStore||e,!e)throw new Error(U4.ENV_REQUIRED)}a(B4,"validateEnv");function H4(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(H4,"stringifyData");function k4(e){return e instanceof Date?e.valueOf():e}a(k4,"convertKeyValueToWrite");function F4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(cL.includes(typeof e))return e.length>mm?[e.slice(0,mm)+aL]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(cL.includes(typeof i))i.length>mm?r.push(i.slice(0,mm)+aL):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(F4,"getIndexedValues");var Em=0,lL=0;function uL(){lL=Date.now()-performance.now()}a(uL,"adjustStartTime");uL();var G4=6e4;setInterval(uL,G4).unref();function q4(){let e=performance.now()+lL;return e>Em?(Em=e,e):(Em+=488e-6,Em)}a(q4,"getNextMonotonicTime");dL.exports={validateEnv:B4,stringifyData:H4,convertKeyValueToWrite:k4,getNextMonotonicTime:q4,getIndexedValues:F4}});var Uf=P((obe,fL)=>{"use strict";var $4=(k(),D(q)).OPERATIONS_ENUM,_R=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=$4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};fL.exports=_R});var xf=P((lbe,mL)=>{"use strict";var cbe=Uf(),gm=(k(),D(q)),pR=oe(),_L=z(),V4=require("uuid"),{handleHDBError:Sm,hdb_errors:K4}=he(),{HDB_ERROR_MSGS:Tm,HTTP_STATUS_CODES:Am}=K4;mL.exports=pL;function pL(e,t,r){for(let s=0;s<t.length;s++)hL(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];Y4(i,r,e.operation)}}a(pL,"processRows");pL.validateAttribute=hL;function hL(e){if(Buffer.byteLength(String(e))>gm.INSERT_MAX_CHARACTER_SIZE)throw Sm(new Error,Tm.ATTR_NAME_LENGTH_ERR(e),Am.BAD_REQUEST,void 0,void 0,!0);if(pR.isEmptyOrZeroLength(e)||pR.isEmpty(e.trim()))throw Sm(new Error,Tm.ATTR_NAME_NULLISH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(hL,"validateAttribute");function Y4(e,t,r){if(!e.hasOwnProperty(t)||pR.isEmptyOrZeroLength(e[t])){if(r===gm.OPERATIONS_ENUM.INSERT||r===gm.OPERATIONS_ENUM.UPSERT){e[t]=V4.v4();return}throw _L.error("Update transaction aborted due to record with no hash value:",e),Sm(new Error,Tm.RECORD_MISSING_HASH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>gm.INSERT_MAX_CHARACTER_SIZE)throw _L.error(e),Sm(new Error,Tm.HASH_VAL_LENGTH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(Y4,"validateHash")});var EL,kn,hR,pu=be(()=>{EL=require("events"),kn=class extends EL.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new hR;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)}},hR=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 bL(e){ER=e}function J4(){j4=setInterval(function(){for(let e of mR)if(e.stale){let t=e.getContext()?.url;AL.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},z4).unref()}var gR,TL,AL,RL,yL,gL,mR,W4,Bf,SL,ER,Nc,Rm,z4,j4,ym=be(()=>{gR=M(_n()),TL=M(he()),AL=M(z()),RL=M(le());k();yL=M(oe()),gL=100,mR=new Set,W4=(0,yL.convertToMS)(RL.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(bL,"replicationConfirmation");Nc=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),mR.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(mR.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Bf&&!this.overloadChecked&&performance.now()-SL>W4)throw new TL.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,gR.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 p=d;p<this.validated;p++)this.writes[p]?.validate?.(this.timestamp);let _;for(let p=d;p<this.validated;p++){let h=this.writes[p];h&&(h.before||h.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let p=0;p<2;p++){let h;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let R=g[p===0?"before":"beforeIntermediate"];if(R){let E=R();h?h.push?h.push(E):h=[h,E]:h=E}}h&&await(h.push?Promise.all(h):h)}}catch(p){throw this.abort(),p}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)<gL>>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 Bf||(Bf=s,SL=performance.now(),Bf.then(()=>{Bf=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,p=this.writes[this.writes.length-1];ER&&p&&i.push(ER(_,p.store.getEntry(p.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+gL/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}},Rm=class extends Nc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,gR.getNextMonotonicTime)())}getReadTxn(){}},z4=3e4;a(J4,"startMonitoringTxns");J4()});function wt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Nc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.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 OL,wc=be(()=>{OL=M(Ri());ym();a(wt,"transaction");(0,OL._assignPackageExport)("transaction",wt);wt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};wt.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 TR(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let p=1;p<e.length;p++){let h=e[p],S=u(h);d=d.concat(S)}let _=new Set;return d.filter(p=>{let h=p.key??p;return _.has(h)?!1:(_.add(h),!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?TR(d.conditions,d.operator,r,n,s,i,o,c):Eu(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,p){return d.map((h,S)=>{if(h.conditions){let E=h.operator==="or",T=f(h.conditions,!E,p);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(h.attribute||h[0])===r.primaryKey,R=Ff(h,r,i,c,g,p);return _&&S<d.length-1&&p&&(p=i3(r.primaryStore,h.estimated_count,p)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Eu(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 hn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=Ni(n.attributes,E);if(T.relationship){if(o.length<2)throw new hn.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,H=Eu({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 $=!!Ni(w.attributes,T.relationship.to)?.elements;H=t3(H,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Eu({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=r3(H,T,w.primaryStore,v,$)):H=H.flatMap($)}return H}else if(o.length===1)o=o[0];else throw new hn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let p;switch(AR[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]=Oi.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,p=!0;break;default:throw new hn.ClientError(`Unknown query comparator "${l}"`)}let h,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>gs.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,gs.MAX_SEARCH_KEY_LENGTH)+gs.OVERFLOW_MARKER,_=!1,h=Ff(e,n,null,i,S)),typeof f=="string"&&f.length>gs.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,gs.MAX_SEARCH_KEY_LENGTH)+gs.OVERFLOW_MARKER,d=!0,h=h??Ff(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||p||c===null&&!g.indexNulls){if(s===!1&&!g)throw new hn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&p)throw new hn.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 hn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new hn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(h=h??Ff(e,n,null,i,S),!h)throw new hn.ClientError(`Unknown search operator ${e.comparator}`)}let R={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(R).map(h?function({key:T,value:w}){return this?.isSync?w&&h(w)?T:ma.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&h(w)?T:ma.SKIP)}catch($){H($)}}))}:T=>T.value==null&&!(T.metadataFlags&(mn|ga))?ma.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(h?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>gs.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?h(w)?T:ma.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(h(w)?T:ma.SKIP)}catch($){H($)}}))}:({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&&h(T)?E:ma.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&h(T)?E:ma.SKIP)}catch(H){v(H)}}))})}function Ni(e,t){if(Array.isArray(t))if(t.length>1){let r=Ni(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Ni(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 t3(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 r3(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 Ff(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=Ni(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,p=n?.[f],h=Ff({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,p?.[f]?.joined,c[1]===_.primaryKey,i);if(!h)return;if(p){p.filters||(p.filters=[]),p.filters.push(h);return}let S=t.propertyResolvers?.[f],g,R=a((E,T)=>{let w,v;if(S){if(S.from&&h.idFilter){if(!g)if(h.idFilter.idSet?.size===1){for(let $ of h.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,h.idFilter,!0,!0)}else g=u(S.from,h.idFilter,!1,!0);let H=g(E);return g.idFilter&&(R.idFilter=g.idFilter),H}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(h):h(w,v):!1},"recordFilter");return R}}switch(l instanceof Date&&(l=l.getTime()),AR[o]||o){case gs.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,Oi.compareKeys)(f,l[0])>=0&&(0,Oi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,Oi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,Oi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,Oi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,Oi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,Oi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new hn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,p){let h;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Om(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(_=!1));let S=0,g=3;function R(E){let T=E[f],w;if(typeof T!="object"||!T||p?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!R.idFilter&&++S/g*(i-g)>h)){let v=Eu(e,r.transaction.getReadTxn(),!1,t).map(gu),H=new Set(v);R.idFilter=$=>H.has(gu($)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Om(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/lo(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=AR[n]||n,n===gs.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=Ni(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Om(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*lo(e.indices[i.relationship.from])/(lo(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=lo(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Z4*lo(e.primaryStore)+1:n==="between"?r.estimated_count=X4*lo(e.primaryStore)+1:n==="sort"?r.estimated_count=lo(e.primaryStore)+1:r.estimated_count=Q4*lo(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Nm(e){if(e)if(Ea=e,hu.lastIndex=0,n3.test(e))try{let t=Hf(new mu,"");if(pn!==Ea.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 ${pn} in '${Ea}'`,t}else return new URLSearchParams(e)}function Hf(e,t){let r=hu,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Ea);){pn=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=NL}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=kf(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=e3[d],l=SR[i]?NL:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=kf(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 h={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&wL(h,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(h),S.operator=u}else bm(e,u),e.conditions.push(h)}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(kf(f)),s=void 0;break;case"(":hu.lastIndex=pn;let p=Hf(f?[]:new mu,")");switch(f){case"":bm(e,u),e.conditions.push(p);break;case"limit":switch(p.length){case 1:e.limit=+p[0];break;case 2:e.offset=+p[0],e.limit=p[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(p[0])&&p.length===1&&!p[0].name?(e.select=p[0],e.select.asArray=!0):p.length===1?e.select=p[0]:p.length===2&&p[1]===""?e.select=p.slice(0,1):e.select=p;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=IL(p);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Ea[pn]===","?r.lastIndex=++pn: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");hu.lastIndex=pn,_=Hf([],"}"),_.name=f,e.push(_),Ea[pn]===","?r.lastIndex=++pn:o=!0;break;case"[":hu.lastIndex=pn,f?(_=Hf(new mu,"]"),_.name=f):_=Hf(e.conditions?new mu:[],"]"),e.conditions?(bm(e,u),e.conditions.push(_),s=null):e.push(_),Ea[pn]===","?r.lastIndex=++pn:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&wL(h,f),bm(e,u),e.conditions.push(h)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(kf(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?s3:hu,r.lastIndex=pn),pn===Ea.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function bm(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 kf(e){return e.indexOf(".")>-1?e.split(".").map(kf):decodeURIComponent(e)}function NL(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 hn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function wL(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new hn.ClientError("wildcard can only be used at the end of a string")}function IL(e){let t=CL(e[0]);return e.length>1&&(t.next=IL(e.slice(1))),t}function CL(e){if(Array.isArray(e)){let t=CL(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 gu(e){return Array.isArray(e)?e.join("\0"):e}function lo(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function i3(e,t,r){return t*r/lo(e)}var hn,gs,Oi,ma,Q4,X4,Z4,e3,SR,AR,n3,hu,s3,pn,Ea,mu,Ic,Gf=be(()=>{hn=M(he()),gs=M(xt()),Oi=require("ordered-binary"),ma=require("lmdb");qf();Q4=.3,X4=.1,Z4=.05,e3={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},SR={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(TR,"executeConditions");a(Eu,"searchByIndex");a(Ni,"findAttribute");a(t3,"joinTo");a(r3,"joinFrom");AR={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(Ff,"filterByType");a(Om,"estimateCondition");n3=/[()[\]|!<>.]|(=\w*=)/,hu=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,s3=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Nm,"parseQuery");a(Hf,"parseBlock");a(bm,"assignOperator");a(kf,"decodeProperty");a(NL,"typedDecoding");a(wL,"wildcardDecoding");a(IL,"toSortObject");a(CL,"toSortEntry");mu=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(gu,"flattenKey");a(lo,"estimatedEntryCount");a(i3,"intersectionEstimate");Ic=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var yR={};Ue(yR,{MultiPartId:()=>Im,Resource:()=>Kr,snake_case:()=>a3,transformForSelect:()=>Cm});function a3(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function PL(e,t){if(Cc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Cc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Im;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Cc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Cc=!0,null;e[e.length-1]==="/"&&(Cc=!0)}return t.coerceId(decodeURIComponent(e))}function Fn(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 p=c.indexOf("?");if(p>-1){let S=this.parseQuery(c.slice(p+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,p)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=h.query),u=h.isCollection,c=h.id):c=h}else if(s[Symbol.iterator]){c=[],u=!0;for(let p of s){if(typeof p=="object"&&p)break;c.push(p)}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 Ic(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 p=this.getResource(c,o,d);return p.then?p.then(_):_(p)}else return wt(o,()=>{let p=this.getResource(c,o,d);return p.then?p.then(_):_(p)},d);function _(p){if(o.authorize){o.authorize=!1;let h=t.type==="read"?p.allowRead(o.user,l,o):t.type==="update"?p.doesExist?.()===!1?p.allowCreate(o.user,f,o):p.allowUpdate(o.user,f,o):t.type==="create"?p.allowCreate(o.user,f,o):p.allowDelete(o.user,l,o);if(h?.then)return h.then(S=>{if(!S)throw new wm(o.user);return typeof f?.then=="function"?f.then(g=>e(p,l,o,g)):e(p,l,o,f)});if(!h)throw new wm(o.user)}return typeof f?.then=="function"?f.then(h=>e(p,l,o,h)):e(p,l,o,f)}a(_,"authorizeActionOnResource")}}function Gn(e,t){let r=new ML.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 RR(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 Cm(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):RR(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(RR(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(RR(l,r,n)),d;for(let _ of e){let p=f(_);p===void 0&&o&&(p=null),p?.then?(d||(d=[]),d.push(p.then(h=>u[_.name||_]=h))):u[_.name||_]=p}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]=Cm(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var DL,LL,ML,o3,Kr,wm,Cc,Im,Sa=be(()=>{DL=require("crypto");pu();LL=M(Ri()),ML=M(he());wc();Gf();o3={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Kr=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=Fn(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=Cm(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=Fn(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):Gn(t,"put")},{hasContent:!0,type:"update"});static patch=Fn(function(t,r,n,s){return t.patch?t.patch(s,r):Gn(t,"patch")},{hasContent:!0,type:"update"});static delete=Fn(function(t,r,n,s){return t.delete?t.delete(r):Gn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,DL.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),wt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Gn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Fn(function(t,r,n,s){return t.invalidate?t.invalidate(r):Gn(t,"delete")},{hasContent:!1,type:"update"});static post=Fn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Fn(function(t,r,n,s){return t.connect?t.connect(s,r):Gn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Fn(function(t,r,n,s){return t.subscribe?t.subscribe(r):Gn(t,"subscribe")},{type:"read"});static publish=Fn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Gn(t,"publish")},{hasContent:!0,type:"create"});static search=Fn(function(t,r,n,s){let i=t.search?t.search(r):Gn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Cm(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Fn(function(t,r,n,s){return t.search?t.search(s,r):Gn(t,"search")},{hasContent:!0,type:"read"});static copy=Fn(function(t,r,n,s){return t.copy?t.copy(s,r):Gn(t,"copy")},{hasContent:!0,type:"create"});static move=Fn(function(t,r,n,s){return t.move?t.move(s,r):Gn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Gn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Nm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&o3[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:PL(t,this),isCollection:Cc}}let i=PL(t,this);return Cc?{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 kn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new kn}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,LL._assignPackageExport)("Resource",Kr);a(a3,"snake_case");wm=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(PL,"pathToId");Im=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Fn,"transactional");a(Gn,"missingMethod");a(RR,"selectFromObject");a(Cm,"transformForSelect")});var Ta,bR=be(()=>{Ta=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 Su={};Ue(Su,{server:()=>Ke});var vL,Ke,Lr=be(()=>{vL=M(Ri()),Ke={};(0,vL._assignPackageExport)("server",Ke)});var BL={};Ue(BL,{Resources:()=>Pm,keyArrayToString:()=>Tu,resetResources:()=>c3,resources:()=>Ss});function c3(){return Ss=new Pm,Ke.resources=Ss,Ss}function Tu(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var UL,xL,Pm,Ss,Au=be(()=>{wc();bR();UL=M(z()),xL=M(he());Lr();Pm=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 xL.ServerError(`Conflicting paths for ${t}`);UL.default.error(c),i.Resource=new Ta(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 wt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(c3,"resetResources");a(Tu,"keyArrayToString")});var wR={};Ue(wR,{loadGQLSchema:()=>d3,start:()=>NR,startOnMainThread:()=>u3});function NR({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,p=[],h;for(let R of d.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(W){if(W.kind==="NonNullType"){let Y=H(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:H(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(H,"getProperty");let E=R.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of R.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,p.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 R.fields){let te=H(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"&&(h=w)}function S(R){let E=_.get(R.type);E?(Object.defineProperty(R,"properties",{value:E.properties}),Object.defineProperty(R,"definition",{value:E})):R.type==="array"?S(R.elements):l3.includes(R.type)||(0,kL.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let R of _.values())for(let E of R.properties)S(E);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,OR.dirname)(n),R.tableClass):i.set((0,OR.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new HL.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var OR,HL,kL,l3,u3,d3,FL=be(()=>{OR=require("path"),HL=require("node:vm");Le();kL=M(tt()),l3=["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(NR,"start");u3=NR,d3=NR({ensureTable:dt}).handleFile});var WL={};Ue(WL,{parse:()=>CR,streamAsJSON:()=>$f,stringify:()=>Pc});function $f(e){return new IR({value:e})}function GL(e){return console.error(e),JSON.stringify(e.toString())}function qL(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Pc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===KL)return YL(e);if(t.resolution)return t.resolution.then(()=>Pc(e));throw t}}function YL(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+=YL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Pc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function CR(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),p3.test(e)?f3.parse(e):JSON.parse(e)):null}var $L,VL,f3,_3,KL,IR,p3,PR=be(()=>{$L=require("stream"),VL=M(require("json-bigint-fixes")),f3=(0,VL.default)({useNativeBigInt:!0}),_3=1e4,KL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw KL};a($f,"streamAsJSON");IR=class extends $L.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),GL)}catch(s){yield GL(s)}else yield Pc(t)}else yield Pc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);qL(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>_3?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 qL(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(GL,"handleError");a(qL,"when");a(Pc,"stringify");a(YL,"jsStringify");p3=/[[,:]\s*-?\d{16,}/;a(CR,"parse")});var wi=P(Lm=>{var Dm=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])Dm.logsAtLevel(e)&&(Lm[e]=Dm[e]);Lm.loggerWithTag=e=>Dm.loggerWithTag(e,!0);Lm.setLogLevel=Dm.setLogLevel});var $m={};Ue($m,{Blob:()=>Ii,blobsWereEncoded:()=>Lc,databasePaths:()=>LR,decodeBlobsWithWrites:()=>Gm,decodeFromDatabase:()=>Mc,decodeWithBlobCallback:()=>qm,deleteBlob:()=>Hm,deleteBlobsInObject:()=>Aa,deleteRootBlobPathsForDB:()=>vR,encodeBlobsAsBuffers:()=>b3,encodeBlobsWithFilePath:()=>Fm,findBlobsInObject:()=>yu,getFileId:()=>km,getFilePathForBlob:()=>nM,getRootBlobPathsForDB:()=>Wf,setDeletionDelay:()=>g3});function eM(){}function Hm(e){let t=nM(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&uo.default.debug?.("Error trying to remove blob file",r)})},tM)}function g3(e){tM=e}function rM(e){let t=En.get(e);if(!t)t={storageIndex:0,fileId:null,store:gn},En.set(e,t);else{if(t.saving)return t;t.store=gn}return T3(t),t.source?DR(e,t.source,t):t.contentBuffer?S3(e,t):DR(e,Kf.Readable.from(e.stream()),t),t}function DR(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([h(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(h(e.size)),_=!0);let p;o?(_||d.write(m3),p=(0,xm.createDeflate)(),t.pipe(p).pipe(d)):(_||d.write(h3),t.pipe(d)),t.on("error",S);function h(g){let R=BigInt(g),E=new Uint8Array(mr),T=new DataView(E.buffer);return R|=BigInt(o?MR:ZL)<<48n,T.setBigInt64(0,R),E}a(h,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,je.close)(R),u(g)):c?(0,je.fdatasync)(R,E=>{E&&u(E),l(),(0,je.close)(R)}):(l(),(0,je.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=p?p.bytesWritten:d.bytesWritten-mr;e.size=g,(0,je.write)(d.fd,h(g),0,mr,0,S)}})}),e}function km(e){return En.get(e)?.fileId}function nM(e){let t=En.get(e);return t?.fileId&&Yf(t)}function Wf(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=LR.get(e);if(!t){if(!e.databaseName)return uo.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,Bm.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,_o.join)(n,e.databaseName)):t=[(0,_o.join)((0,Bm.getHdbBasePath)(),"blobs",e.databaseName)],LR.set(e,t)}return t}async function vR(e){let t=Wf(e);t&&await Promise.all(t.map(r=>sM(r)))}async function sM(e){if((0,je.existsSync)(e)){for(let t of await(0,Xs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await sM((0,_o.join)(e,t.name));else try{await(0,Xs.unlink)((0,_o.join)(e,t.name))}catch(r){uo.default.warn?.("Error deleting file",r)}try{await(0,Xs.rmdir)(e)}catch(t){uo.default.warn?.("Error deleting directory",t)}}}function Yf({storageIndex:e,fileId:t,store:r}){let n=Wf(r);return(0,_o.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 S3(e,t){let r=t.contentBuffer,n=r.length;if(!(n<XL))return e.size=n,DR(e,Kf.Readable.from([r]),t)}function T3(e){let t=Wf(e.store),r=A3(),n=t?.length>1?R3(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Yf(e),o=(0,_o.dirname)(i);(0,je.existsSync)(o)||(0,QL.ensureDirSync)(o),e.filePath=i}function A3(){let e=JL.get(gn);if(!e){let t=0,r=Wf(gn);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,_o.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(gn.getUserSharedBuffer("blob-file-id",e.buffer)),JL.set(gn,e)}return Number(Atomics.add(e,0,1n))}function R3(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(Um);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,y3(e)),e.frequencyTable[t%Um]}async function y3(e){if(!Xs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Xs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(Um),n=t.map(s=>1/s);for(let s=0;s<Um;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 Fm(e,t,r){Ru=t,gn=r,Lc=!1;try{return e()}finally{Ru=void 0,gn=void 0}}function b3(e){Mr=[];let t;try{t=e()}catch(n){throw Mr=void 0,n}let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r?r.then(()=>e()):t}function Gm(e,t){try{Mr=[],Dc=t,e()}catch(n){throw Dc=void 0,Mr=void 0,n}Dc=void 0;let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r}function qm(e,t,r){gn=r;try{return Dc=t,e()}finally{Dc=void 0}}function Mc(e,t){return gn=t,e()}function Aa(e){yu(e,t=>{Hm(t)})}function yu(e,t){if(e instanceof Ii)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&yu(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&yu(e[r],t)}}function O3(){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 fo,Xs,je,xm,Kf,QL,Bm,_o,uo,XL,mr,ZL,MR,zL,h3,m3,jL,En,Dc,Ii,Ru,Mr,gn,Lc,Vf,Mm,E3,vm,tM,LR,JL,Um,Ts=be(()=>{fo=require("msgpackr"),Xs=require("node:fs/promises"),je=require("node:fs"),xm=require("node:zlib"),Kf=require("node:stream"),QL=require("fs-extra"),Bm=M(le());k();_o=require("path"),uo=M(wi());po();XL=8192,mr=8,ZL=0,MR=1,zL=255,h3=new Uint8Array([0,ZL,255,255,255,255,255,255]),m3=new Uint8Array([0,MR,255,255,255,255,255,255]),jL=0xffffffffffff,En=new WeakMap,Ii=global.Blob||O3(),Lc=!1,Vf=new Uint8Array(8),Mm=new DataView(Vf.buffer),E3=6e4;a(eM,"InstanceOfBlobWithNoConstructor");eM.prototype=Ii.prototype;vm=class e extends eM{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=En.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):(xR()&&UR(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=En.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=Yf(t),o,c=a(async()=>{let l,u=mr;try{if(l=await(0,Xs.readFile)(i),l.length>=mr){l.copy(Vf,0,0,mr);let d=Mm.getBigUint64(0);if(Number(d>>48n)===zL)throw new Error("Error in blob: "+buffer.subarray(mr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<jL&&(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,p=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((h,S)=>{if(_.attemptLock(p,0,()=>(o=!0,_.unlock(p,0),h(c()))))return o=!0,_.unlock(p,0),h(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===MR?new Promise((d,_)=>{(0,xm.deflate)(l.subarray(mr),(p,h)=>{p?_(p):d(f(h))})}):f(l.subarray(mr))},"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=En.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=Yf(t),o,c=0,l=0,u,f,d,_=!1,p=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(uo.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{h(),g(R,E)},20).unref();E(T),p.#e?.forEach(v=>v(T))}else o=w,R(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,R=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),p.#e?.forEach(W=>W($))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,je.read)(o,H,0,H.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<mr){R-- >0&&d!==!1?(h(),uo.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(uo.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(Vf,0,0,mr);let se=Mm.getBigUint64(0);if(Number(se>>48n)===zL)return v(new Error("Error in blob: "+te.subarray(mr)));if(g=Number(se&0xffffffffffffn),g<jL&&p.size!==g&&(p.size=g,p.#t))for(let Y of p.#t)Y(g);te=te.subarray(mr,W),l-=mr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,mr,0,Y=>{if(Y)return v(Y);if(Vf.set(se),g=Number(Mm.getBigUint64(0)&0xffffffffffffn),g>l){h()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},E3).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 uo.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 h(){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=En.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};En.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)};En.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(gn=t?.primaryStore?.rootStore,!gn)throw new Error("No target table specified");return rM(this).saving??Promise.resolve()}},tM=500;a(Hm,"deleteBlob");a(g3,"setDeletionDelay");global.createBlob=function(e,t){let r=new vm(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(En.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Kf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Kf.Readable.from(e);else throw new Error("Invalid source type");return r};a(rM,"saveBlob");a(DR,"writeBlobWithStream");a(km,"getFileId");a(nM,"getFilePathForBlob");LR=new Map;a(Wf,"getRootBlobPathsForDB");a(vR,"deleteRootBlobPathsForDB");a(sM,"rimrafSteadily");a(Yf,"getFilePath");a(S3,"writeBlobWithBuffer");a(T3,"generateFilePath");JL=new Map;a(A3,"getNextFileId");Um=128;a(R3,"getNextStorageIndex");a(y3,"createFrequencyTableForStoragePaths");a(Fm,"encodeBlobsWithFilePath");a(b3,"encodeBlobsAsBuffers");a(Gm,"decodeBlobsWithWrites");a(qm,"decodeWithBlobCallback");a(Mc,"decodeFromDatabase");a(Aa,"deleteBlobsInObject");a(yu,"findBlobsInObject");(0,fo.addExtension)({Class:Ii,type:11,unpack:a(function(e){let t=(0,fo.unpack)(e),r=new vm;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(En.set(r,{storageIndex:t[1],fileId:t[2],store:gn}),Dc)return Dc(r)??r;if(!gn)throw new Error("No store specified, cannot load blob from storage")}else En.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=En.get(e);if(Ru!==void 0&&(Lc=!0,t?.recordId!==void 0&&t.recordId!==Ru))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<XL)return r.size=t.contentBuffer.length,(0,fo.pack)([r,t.contentBuffer])}if(Ru!==void 0){if(t=rM(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Ru,(0,fo.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Yf(t));if(n.length>=mr&&(n.copy(Vf,0,0,mr),Number(Mm.getBigUint64(0)&0xffffffffffffn)===n.length-mr))return Buffer.concat([(0,fo.pack)([r]),n]);if(Mr)Mr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Mr)return Mr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,fo.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(O3,"polyfillBlob")});var fM={};Ue(fM,{asyncSerialization:()=>UR,contentTypes:()=>FR,findBestSerializer:()=>Km,getDeserializer:()=>Eo,hasAsyncSerialization:()=>xR,registerContentHandlers:()=>Jf,serialize:()=>Qf,serializeMessage:()=>Ra,toCsvStream:()=>Vm});function w3(e){try{return e?.[0]===123?kR(e):e}catch{return e}}function Jf(e){e.register(C3,{serializers:[{regex:/^application\/json$/,serializer:$f},{regex:/^application\/cbor$/,serializer:a(function(t){return new vc.EncoderStream(jf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Uc.Readable.from((0,Ci.encodeIter)(t,jf)):(0,Ci.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),Vm(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ci.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,vc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Km(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 h of f){let S=h.indexOf("=");_[h.substring(0,S)]=h.substring(S+1)}d=+_.q;let p=Yr.get(u);if(p){let h=(p.q||1)*d;h>s&&(n=p,i=p.type||u,s=h,o=_)}}if(!n){if(r)throw new aM.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Yr.keys()).join(", "),406);n=Yr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Qf(e,t,r){let n=oM&&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 Ii)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=Km(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}),HR.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,mo.createBrotliCompress)({params:{[mo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?mo.constants.BROTLI_MODE_TEXT:mo.constants.BROTLI_MODE_GENERIC,[mo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>oM?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,mo.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;ho=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=Km(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=zf(e);return ho?.length>0?(ho.length===1?ho[0]:Promise.all(ho)).then(()=>Ra(e,t,!0)):n}finally{ho=void 0}}function UR(e){if(ho)ho.push(e);else throw new Error("Unable to serialize asynchronously")}function xR(){return!!ho}function P3(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 L3(e){return D3.includes(e)}function M3(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 Eo(e="",t=!1){let r=M3(e),n=r.type&&Yr.get(r.type)?.deserialize||v3(r);return t?s=>P3(s).then(n):n}function v3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!L3(e.parameters.charset)&&HR.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 kR(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function U3(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 Vm(e,t){let r=Uc.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 N3(n,s);return r.pipe(i)}var Ci,vc,mo,aM,Uc,cM,BR,lM,HR,N3,uM,zf,kR,jf,Yr,FR,iM,dM,I3,C3,oM,ho,D3,po=be(()=>{PR();Ci=require("msgpackr"),vc=require("cbor-x"),mo=require("zlib"),aM=M(he()),Uc=M(require("stream"));Lr();cM=M(Ri()),BR=M(le());k();lM=M(require("yaml")),HR=M(wi());Ts();({Transform:N3}=require("json2csv")),uM=BR.default.get(U.SERIALIZATION_BIGINT)!==!1,zf=uM?Pc:JSON.stringify,kR=uM?CR:JSON.parse,jf={useRecords:!1,useToJSON:!0},Yr=new Map,FR=Yr;Ke.contentTypes=FR;(0,cM._assignPackageExport)("contentTypes",FR);Yr.set("application/json",{serializeStream:$f,serialize:zf,deserialize(e){return kR(e)},q:.8});iM=new vc.Encoder(jf);Yr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new vc.EncoderStream(jf).end(e)},serialize:iM.encode,deserialize:iM.decode,q:1});Yr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Uc.Readable.from((0,Ci.encodeIter)(e,jf)):(0,Ci.pack)(e)},serialize:Ci.pack,deserialize:Ci.unpack,q:.9});Yr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),Vm(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]),Vm(e,e?.getColumns?.())},q:.1});Yr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return Uc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Yr.set("text/yaml",{serialize(e){return lM.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Yr.set("text/event-stream",{serializeStream:a(function(e){return Uc.Readable.from(U3(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
|
+
`).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:t4.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(i4,"findPs")});var xt=P((jye,GD)=>{"use strict";var o4="__dbis__",a4="__txns__",c4="__environment_name__",l4="__dbi_defintion__",u4={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"},d4=["__createdtime__","__updatedtime__"],f4="\uFFFF",FD={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},_4=Object.values(FD);GD.exports={AUDIT_STORE_NAME:a4,INTERNAL_DBIS_NAME:o4,DBI_DEFINITION_NAME:l4,SEARCH_TYPES:u4,TIMESTAMP_NAMES:d4,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:c4,TRANSACTIONS_DBI_NAMES_ENUM:FD,TRANSACTIONS_DBIS:_4,OVERFLOW_MARKER:f4}});var Hn=P((Jye,JD)=>{"use strict";var qD=(k(),D(q)),$D=xt(),VD={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},KD=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),YD={500:KD("There was an error processing your request."),400:"Invalid request"},p4=YD[VD.INTERNAL_SERVER_ERROR],h4={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")},m4={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},E4={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"},g4={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 ${$D.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${$D.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"},S4={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${qD.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 ${qD.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"},WD={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"},T4={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."},A4={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")},R4={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"},y4={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},b4={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")},zD={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")},jD={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")},O4={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"},N4={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},w4={...WD,...E4,...h4,...T4,...A4,...R4,...y4,...b4,...S4,...zD,...jD,...O4,...N4,...m4};JD.exports={CHECK_LOGS_WRAPPER:KD,HDB_ERROR_MSGS:w4,DEFAULT_ERROR_MSGS:YD,DEFAULT_ERROR_RESP:p4,HTTP_STATUS_CODES:VD,LMDB_ERRORS_ENUM:g4,AUTHENTICATION_ERROR_MSGS:WD,VALIDATION_ERROR_MSGS:zD,ITC_ERRORS:jD}});var he=P((Xye,ZD)=>{"use strict";var _u=Hn(),I4=z(),C4=(k(),D(q)),pm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,QD),this.statusCode=n||_u.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(_u.DEFAULT_ERROR_MSGS[n]?_u.DEFAULT_ERROR_MSGS[n]:_u.DEFAULT_ERROR_MSGS[_u.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&&I4[s](i)}},dR=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}},fR=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function QD(e,t,r,n=C4.LOG_LEVELS.ERROR,s=null,i=!1){if(XD(e))return e;let o=new pm(e,t,r,n,s);return i&&delete o.stack,o}a(QD,"handleHDBError");function XD(e){return e.__proto__.constructor.name===pm.name}a(XD,"isHDBError");ZD.exports={isHDBError:XD,handleHDBError:QD,ClientError:dR,ServerError:fR,hdb_errors:_u}});var mt=P((ebe,oL)=>{"use strict";var Mf=(k(),D(q)),P4=oe(),fn=le(),vf=require("path"),D4=require("minimist"),eL=require("fs-extra"),tL=require("lodash");fn.initSync();var{CONFIG_PARAMS:ha,DATABASES_PARAM_CONFIG:Cf,SYSTEM_SCHEMA_NAME:hm}=Mf,Pf,Df,Lf;function rL(){if(Pf!==void 0)return Pf;if(fn.getHdbBasePath()!==void 0)return Pf=fn.get(ha.STORAGE_PATH)||vf.join(fn.getHdbBasePath(),Mf.DATABASES_DIR_NAME),Pf}a(rL,"getBaseSchemaPath");function nL(){if(Df!==void 0)return Df;if(fn.getHdbBasePath()!==void 0)return Df=iL(hm),Df}a(nL,"getSystemSchemaPath");function sL(){if(Lf!==void 0)return Lf;if(fn.getHdbBasePath()!==void 0)return Lf=fn.get(Mf.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||vf.join(fn.getHdbBasePath(),Mf.TRANSACTIONS_DIR_NAME),Lf}a(sL,"getTransactionAuditStoreBasePath");function L4(e,t){let r=fn.get(ha.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||vf.join(sL(),e.toString())}a(L4,"getTransactionAuditStorePath");function iL(e,t){e=e.toString(),t=t&&t.toString();let r=fn.get(Mf.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||vf.join(rL(),e)}a(iL,"getSchemaPath");function M4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,D4(process.argv));let n=r[ha.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!P4.isObject(n))throw o;i=n}for(let o of i){let c=o[hm];if(!c)continue;let l=fn.get(ha.DATABASES);l=l??{};let u=c?.tables?.[t]?.[Cf.PATH];if(u)return tL.set(l,[hm,Cf.TABLES,t,Cf.PATH],u),fn.setProperty(ha.DATABASES,l),u;let f=c?.[Cf.PATH];if(f)return tL.set(l,[hm,Cf.PATH],f),fn.setProperty(ha.DATABASES,l),f}}let s=r[ha.STORAGE_PATH.toUpperCase()];if(s){if(!eL.pathExistsSync(s))throw new Error(s+" does not exist");let i=vf.join(s,e);return eL.mkdirsSync(i),fn.setProperty(ha.STORAGE_PATH,s),i}return nL()}a(M4,"initSystemSchemaPaths");function v4(){Pf=void 0,Df=void 0,Lf=void 0}a(v4,"resetPaths");oL.exports={getBaseSchemaPath:rL,getSystemSchemaPath:nL,getTransactionAuditStorePath:L4,getTransactionAuditStoreBasePath:sL,getSchemaPath:iL,initSystemSchemaPaths:M4,resetPaths:v4}});var _n=P((sbe,dL)=>{"use strict";var U4=Hn().LMDB_ERRORS_ENUM,rbe=require("lmdb"),x4=xt(),nbe=require("buffer").Buffer,{OVERFLOW_MARKER:aL,MAX_SEARCH_KEY_LENGTH:mm}=x4,cL=["number","string","symbol","boolean","bigint"];function B4(e){if(e=e?.primaryStore||e,!e)throw new Error(U4.ENV_REQUIRED)}a(B4,"validateEnv");function H4(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(H4,"stringifyData");function k4(e){return e instanceof Date?e.valueOf():e}a(k4,"convertKeyValueToWrite");function F4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(cL.includes(typeof e))return e.length>mm?[e.slice(0,mm)+aL]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(cL.includes(typeof i))i.length>mm?r.push(i.slice(0,mm)+aL):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(F4,"getIndexedValues");var Em=0,lL=0;function uL(){lL=Date.now()-performance.now()}a(uL,"adjustStartTime");uL();var G4=6e4;setInterval(uL,G4).unref();function q4(){let e=performance.now()+lL;return e>Em?(Em=e,e):(Em+=488e-6,Em)}a(q4,"getNextMonotonicTime");dL.exports={validateEnv:B4,stringifyData:H4,convertKeyValueToWrite:k4,getNextMonotonicTime:q4,getIndexedValues:F4}});var Uf=P((obe,fL)=>{"use strict";var $4=(k(),D(q)).OPERATIONS_ENUM,_R=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=$4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};fL.exports=_R});var xf=P((lbe,mL)=>{"use strict";var cbe=Uf(),gm=(k(),D(q)),pR=oe(),_L=z(),V4=require("uuid"),{handleHDBError:Sm,hdb_errors:K4}=he(),{HDB_ERROR_MSGS:Tm,HTTP_STATUS_CODES:Am}=K4;mL.exports=pL;function pL(e,t,r){for(let s=0;s<t.length;s++)hL(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];Y4(i,r,e.operation)}}a(pL,"processRows");pL.validateAttribute=hL;function hL(e){if(Buffer.byteLength(String(e))>gm.INSERT_MAX_CHARACTER_SIZE)throw Sm(new Error,Tm.ATTR_NAME_LENGTH_ERR(e),Am.BAD_REQUEST,void 0,void 0,!0);if(pR.isEmptyOrZeroLength(e)||pR.isEmpty(e.trim()))throw Sm(new Error,Tm.ATTR_NAME_NULLISH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(hL,"validateAttribute");function Y4(e,t,r){if(!e.hasOwnProperty(t)||pR.isEmptyOrZeroLength(e[t])){if(r===gm.OPERATIONS_ENUM.INSERT||r===gm.OPERATIONS_ENUM.UPSERT){e[t]=V4.v4();return}throw _L.error("Update transaction aborted due to record with no hash value:",e),Sm(new Error,Tm.RECORD_MISSING_HASH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>gm.INSERT_MAX_CHARACTER_SIZE)throw _L.error(e),Sm(new Error,Tm.HASH_VAL_LENGTH_ERR,Am.BAD_REQUEST,void 0,void 0,!0)}a(Y4,"validateHash")});var EL,kn,hR,pu=be(()=>{EL=require("events"),kn=class extends EL.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new hR;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)}},hR=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 bL(e){ER=e}function J4(){j4=setInterval(function(){for(let e of mR)if(e.stale){let t=e.getContext()?.url;AL.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},z4).unref()}var gR,TL,AL,RL,yL,gL,mR,W4,Bf,SL,ER,Nc,Rm,z4,j4,ym=be(()=>{gR=M(_n()),TL=M(he()),AL=M(z()),RL=M(le());k();yL=M(oe()),gL=100,mR=new Set,W4=(0,yL.convertToMS)(RL.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(bL,"replicationConfirmation");Nc=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),mR.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(mR.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(Bf&&!this.overloadChecked&&performance.now()-SL>W4)throw new TL.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,gR.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 p=d;p<this.validated;p++)this.writes[p]?.validate?.(this.timestamp);let _;for(let p=d;p<this.validated;p++){let h=this.writes[p];h&&(h.before||h.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let p=0;p<2;p++){let h;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let R=g[p===0?"before":"beforeIntermediate"];if(R){let E=R();h?h.push?h.push(E):h=[h,E]:h=E}}h&&await(h.push?Promise.all(h):h)}}catch(p){throw this.abort(),p}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)<gL>>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 Bf||(Bf=s,SL=performance.now(),Bf.then(()=>{Bf=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,p=this.writes[this.writes.length-1];ER&&p&&i.push(ER(_,p.store.getEntry(p.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+gL/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}},Rm=class extends Nc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,gR.getNextMonotonicTime)())}getReadTxn(){}},z4=3e4;a(J4,"startMonitoringTxns");J4()});function wt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Nc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.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 OL,wc=be(()=>{OL=M(Ri());ym();a(wt,"transaction");(0,OL._assignPackageExport)("transaction",wt);wt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};wt.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 TR(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let p=1;p<e.length;p++){let h=e[p],S=u(h);d=d.concat(S)}let _=new Set;return d.filter(p=>{let h=p.key??p;return _.has(h)?!1:(_.add(h),!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?TR(d.conditions,d.operator,r,n,s,i,o,c):Eu(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,p){return d.map((h,S)=>{if(h.conditions){let E=h.operator==="or",T=f(h.conditions,!E,p);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(h.attribute||h[0])===r.primaryKey,R=Ff(h,r,i,c,g,p);return _&&S<d.length-1&&p&&(p=i3(r.primaryStore,h.estimated_count,p)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Eu(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 hn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=Ni(n.attributes,E);if(T.relationship){if(o.length<2)throw new hn.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,H=Eu({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 $=!!Ni(w.attributes,T.relationship.to)?.elements;H=t3(H,T,w.primaryStore,$,v)}if(T.relationship.from){let $=a(W=>(W?.key!==void 0&&(W=W.key),Eu({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=r3(H,T,w.primaryStore,v,$)):H=H.flatMap($)}return H}else if(o.length===1)o=o[0];else throw new hn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let p;switch(AR[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]=Oi.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,p=!0;break;default:throw new hn.ClientError(`Unknown query comparator "${l}"`)}let h,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>gs.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,gs.MAX_SEARCH_KEY_LENGTH)+gs.OVERFLOW_MARKER,_=!1,h=Ff(e,n,null,i,S)),typeof f=="string"&&f.length>gs.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,gs.MAX_SEARCH_KEY_LENGTH)+gs.OVERFLOW_MARKER,d=!0,h=h??Ff(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||p||c===null&&!g.indexNulls){if(s===!1&&!g)throw new hn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&p)throw new hn.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 hn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new hn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(h=h??Ff(e,n,null,i,S),!h)throw new hn.ClientError(`Unknown search operator ${e.comparator}`)}let R={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(R).map(h?function({key:T,value:w}){return this?.isSync?w&&h(w)?T:ma.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&h(w)?T:ma.SKIP)}catch($){H($)}}))}:T=>T.value==null&&!(T.metadataFlags&(mn|ga))?ma.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(h?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>gs.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?h(w)?T:ma.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(h(w)?T:ma.SKIP)}catch($){H($)}}))}:({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&&h(T)?E:ma.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&h(T)?E:ma.SKIP)}catch(H){v(H)}}))})}function Ni(e,t){if(Array.isArray(t))if(t.length>1){let r=Ni(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?Ni(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 t3(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 r3(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 Ff(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=Ni(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,p=n?.[f],h=Ff({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,p?.[f]?.joined,c[1]===_.primaryKey,i);if(!h)return;if(p){p.filters||(p.filters=[]),p.filters.push(h);return}let S=t.propertyResolvers?.[f],g,R=a((E,T)=>{let w,v;if(S){if(S.from&&h.idFilter){if(!g)if(h.idFilter.idSet?.size===1){for(let $ of h.idFilter.idSet)e={attribute:S.from,value:$};g=u(S.from,h.idFilter,!0,!0)}else g=u(S.from,h.idFilter,!1,!0);let H=g(E);return g.idFilter&&(R.idFilter=g.idFilter),H}v=S(E,r,T),w=v?.value}else w=E[f];return w?Array.isArray(w)?w.some(h):h(w,v):!1},"recordFilter");return R}}switch(l instanceof Date&&(l=l.getTime()),AR[o]||o){case gs.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,Oi.compareKeys)(f,l[0])>=0&&(0,Oi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,Oi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,Oi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,Oi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,Oi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,Oi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new hn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,p){let h;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Om(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(_=!1));let S=0,g=3;function R(E){let T=E[f],w;if(typeof T!="object"||!T||p?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!R.idFilter&&++S/g*(i-g)>h)){let v=Eu(e,r.transaction.getReadTxn(),!1,t).map(gu),H=new Set(v);R.idFilter=$=>H.has(gu($)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Om(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/lo(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=AR[n]||n,n===gs.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=Ni(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Om(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*lo(e.indices[i.relationship.from])/(lo(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=lo(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Z4*lo(e.primaryStore)+1:n==="between"?r.estimated_count=X4*lo(e.primaryStore)+1:n==="sort"?r.estimated_count=lo(e.primaryStore)+1:r.estimated_count=Q4*lo(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Nm(e){if(e)if(Ea=e,hu.lastIndex=0,n3.test(e))try{let t=Hf(new mu,"");if(pn!==Ea.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 ${pn} in '${Ea}'`,t}else return new URLSearchParams(e)}function Hf(e,t){let r=hu,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Ea);){pn=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=NL}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=kf(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=e3[d],l=SR[i]?NL:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=kf(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 h={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&wL(h,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(h),S.operator=u}else bm(e,u),e.conditions.push(h)}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(kf(f)),s=void 0;break;case"(":hu.lastIndex=pn;let p=Hf(f?[]:new mu,")");switch(f){case"":bm(e,u),e.conditions.push(p);break;case"limit":switch(p.length){case 1:e.limit=+p[0];break;case 2:e.offset=+p[0],e.limit=p[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(p[0])&&p.length===1&&!p[0].name?(e.select=p[0],e.select.asArray=!0):p.length===1?e.select=p[0]:p.length===2&&p[1]===""?e.select=p.slice(0,1):e.select=p;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=IL(p);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Ea[pn]===","?r.lastIndex=++pn: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");hu.lastIndex=pn,_=Hf([],"}"),_.name=f,e.push(_),Ea[pn]===","?r.lastIndex=++pn:o=!0;break;case"[":hu.lastIndex=pn,f?(_=Hf(new mu,"]"),_.name=f):_=Hf(e.conditions?new mu:[],"]"),e.conditions?(bm(e,u),e.conditions.push(_),s=null):e.push(_),Ea[pn]===","?r.lastIndex=++pn:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&wL(h,f),bm(e,u),e.conditions.push(h)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(kf(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?s3:hu,r.lastIndex=pn),pn===Ea.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function bm(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 kf(e){return e.indexOf(".")>-1?e.split(".").map(kf):decodeURIComponent(e)}function NL(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 hn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function wL(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new hn.ClientError("wildcard can only be used at the end of a string")}function IL(e){let t=CL(e[0]);return e.length>1&&(t.next=IL(e.slice(1))),t}function CL(e){if(Array.isArray(e)){let t=CL(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 gu(e){return Array.isArray(e)?e.join("\0"):e}function lo(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function i3(e,t,r){return t*r/lo(e)}var hn,gs,Oi,ma,Q4,X4,Z4,e3,SR,AR,n3,hu,s3,pn,Ea,mu,Ic,Gf=be(()=>{hn=M(he()),gs=M(xt()),Oi=require("ordered-binary"),ma=require("lmdb");qf();Q4=.3,X4=.1,Z4=.05,e3={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},SR={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(TR,"executeConditions");a(Eu,"searchByIndex");a(Ni,"findAttribute");a(t3,"joinTo");a(r3,"joinFrom");AR={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(Ff,"filterByType");a(Om,"estimateCondition");n3=/[()[\]|!<>.]|(=\w*=)/,hu=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,s3=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Nm,"parseQuery");a(Hf,"parseBlock");a(bm,"assignOperator");a(kf,"decodeProperty");a(NL,"typedDecoding");a(wL,"wildcardDecoding");a(IL,"toSortObject");a(CL,"toSortEntry");mu=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(gu,"flattenKey");a(lo,"estimatedEntryCount");a(i3,"intersectionEstimate");Ic=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var yR={};Ue(yR,{MultiPartId:()=>Im,Resource:()=>Kr,snake_case:()=>a3,transformForSelect:()=>Cm});function a3(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function PL(e,t){if(Cc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(Cc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Im;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Cc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return Cc=!0,null;e[e.length-1]==="/"&&(Cc=!0)}return t.coerceId(decodeURIComponent(e))}function Fn(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 p=c.indexOf("?");if(p>-1){let S=this.parseQuery(c.slice(p+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,p)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=h.query),u=h.isCollection,c=h.id):c=h}else if(s[Symbol.iterator]){c=[],u=!0;for(let p of s){if(typeof p=="object"&&p)break;c.push(p)}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 Ic(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 p=this.getResource(c,o,d);return p.then?p.then(_):_(p)}else return wt(o,()=>{let p=this.getResource(c,o,d);return p.then?p.then(_):_(p)},d);function _(p){if(o.authorize){o.authorize=!1;let h=t.type==="read"?p.allowRead(o.user,l,o):t.type==="update"?p.doesExist?.()===!1?p.allowCreate(o.user,f,o):p.allowUpdate(o.user,f,o):t.type==="create"?p.allowCreate(o.user,f,o):p.allowDelete(o.user,l,o);if(h?.then)return h.then(S=>{if(!S)throw new wm(o.user);return typeof f?.then=="function"?f.then(g=>e(p,l,o,g)):e(p,l,o,f)});if(!h)throw new wm(o.user)}return typeof f?.then=="function"?f.then(h=>e(p,l,o,h)):e(p,l,o,f)}a(_,"authorizeActionOnResource")}}function Gn(e,t){let r=new ML.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 RR(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 Cm(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):RR(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(RR(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(RR(l,r,n)),d;for(let _ of e){let p=f(_);p===void 0&&o&&(p=null),p?.then?(d||(d=[]),d.push(p.then(h=>u[_.name||_]=h))):u[_.name||_]=p}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]=Cm(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var DL,LL,ML,o3,Kr,wm,Cc,Im,Sa=be(()=>{DL=require("crypto");pu();LL=M(Ri()),ML=M(he());wc();Gf();o3={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Kr=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=Fn(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=Cm(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=Fn(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):Gn(t,"put")},{hasContent:!0,type:"update"});static patch=Fn(function(t,r,n,s){return t.patch?t.patch(s,r):Gn(t,"patch")},{hasContent:!0,type:"update"});static delete=Fn(function(t,r,n,s){return t.delete?t.delete(r):Gn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,DL.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),wt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Gn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Fn(function(t,r,n,s){return t.invalidate?t.invalidate(r):Gn(t,"delete")},{hasContent:!1,type:"update"});static post=Fn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Fn(function(t,r,n,s){return t.connect?t.connect(s,r):Gn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Fn(function(t,r,n,s){return t.subscribe?t.subscribe(r):Gn(t,"subscribe")},{type:"read"});static publish=Fn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Gn(t,"publish")},{hasContent:!0,type:"create"});static search=Fn(function(t,r,n,s){let i=t.search?t.search(r):Gn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Cm(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Fn(function(t,r,n,s){return t.search?t.search(s,r):Gn(t,"search")},{hasContent:!0,type:"read"});static copy=Fn(function(t,r,n,s){return t.copy?t.copy(s,r):Gn(t,"copy")},{hasContent:!0,type:"create"});static move=Fn(function(t,r,n,s){return t.move?t.move(s,r):Gn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Gn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Nm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&o3[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:PL(t,this),isCollection:Cc}}let i=PL(t,this);return Cc?{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 kn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new kn}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,LL._assignPackageExport)("Resource",Kr);a(a3,"snake_case");wm=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(PL,"pathToId");Im=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Fn,"transactional");a(Gn,"missingMethod");a(RR,"selectFromObject");a(Cm,"transformForSelect")});var Ta,bR=be(()=>{Ta=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 Su={};Ue(Su,{server:()=>Ke});var vL,Ke,Lr=be(()=>{vL=M(Ri()),Ke={};(0,vL._assignPackageExport)("server",Ke)});var BL={};Ue(BL,{Resources:()=>Pm,keyArrayToString:()=>Tu,resetResources:()=>c3,resources:()=>Ss});function c3(){return Ss=new Pm,Ke.resources=Ss,Ss}function Tu(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var UL,xL,Pm,Ss,Au=be(()=>{wc();bR();UL=M(z()),xL=M(he());Lr();Pm=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 xL.ServerError(`Conflicting paths for ${t}`);UL.default.error(c),i.Resource=new Ta(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 wt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(c3,"resetResources");a(Tu,"keyArrayToString")});var wR={};Ue(wR,{loadGQLSchema:()=>d3,start:()=>NR,startOnMainThread:()=>u3});function NR({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,p=[],h;for(let R of d.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(W){if(W.kind==="NonNullType"){let Y=H(W.type);return Y.nullable=!1,Y}if(W.kind==="ListType")return{type:"array",elements:H(W.type)};let se={type:W.name?.value};return Object.defineProperty(se,"location",{value:W.loc.startToken}),se};a(H,"getProperty");let E=R.name.value,T=[],w={table:null,database:null,properties:T};_.set(E,w);for(let W of R.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,p.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 R.fields){let te=H(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"&&(h=w)}function S(R){let E=_.get(R.type);E?(Object.defineProperty(R,"properties",{value:E.properties}),Object.defineProperty(R,"definition",{value:E})):R.type==="array"?S(R.elements):l3.includes(R.type)||(0,kL.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let R of _.values())for(let E of R.properties)S(E);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,OR.dirname)(n),R.tableClass):i.set((0,OR.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new HL.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:E.loc.startToken.line-1,columnOffset:E.loc.startToken.column}).runInThisContext()(T)}a(g,"createComputedFrom")}}var OR,HL,kL,l3,u3,d3,FL=be(()=>{OR=require("path"),HL=require("node:vm");Le();kL=M(tt()),l3=["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(NR,"start");u3=NR,d3=NR({ensureTable:dt}).handleFile});var WL={};Ue(WL,{parse:()=>CR,streamAsJSON:()=>$f,stringify:()=>Pc});function $f(e){return new IR({value:e})}function GL(e){return console.error(e),JSON.stringify(e.toString())}function qL(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Pc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===KL)return YL(e);if(t.resolution)return t.resolution.then(()=>Pc(e));throw t}}function YL(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+=YL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Pc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function CR(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),p3.test(e)?f3.parse(e):JSON.parse(e)):null}var $L,VL,f3,_3,KL,IR,p3,PR=be(()=>{$L=require("stream"),VL=M(require("json-bigint-fixes")),f3=(0,VL.default)({useNativeBigInt:!0}),_3=1e4,KL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw KL};a($f,"streamAsJSON");IR=class extends $L.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),GL)}catch(s){yield GL(s)}else yield Pc(t)}else yield Pc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);qL(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>_3?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 qL(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(GL,"handleError");a(qL,"when");a(Pc,"stringify");a(YL,"jsStringify");p3=/[[,:]\s*-?\d{16,}/;a(CR,"parse")});var wi=P(Lm=>{var Dm=z();for(let e of["trace","debug","info","warn","error","fatal","notify"])Dm.logsAtLevel(e)&&(Lm[e]=Dm[e]);Lm.loggerWithTag=e=>Dm.loggerWithTag(e,!0);Lm.setLogLevel=Dm.setLogLevel});var $m={};Ue($m,{Blob:()=>Ii,blobsWereEncoded:()=>Lc,databasePaths:()=>LR,decodeBlobsWithWrites:()=>Gm,decodeFromDatabase:()=>Mc,decodeWithBlobCallback:()=>qm,deleteBlob:()=>Hm,deleteBlobsInObject:()=>Aa,deleteRootBlobPathsForDB:()=>vR,encodeBlobsAsBuffers:()=>b3,encodeBlobsWithFilePath:()=>Fm,findBlobsInObject:()=>yu,getFileId:()=>km,getFilePathForBlob:()=>nM,getRootBlobPathsForDB:()=>Wf,setDeletionDelay:()=>g3});function eM(){}function Hm(e){let t=nM(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&uo.default.debug?.("Error trying to remove blob file",r)})},tM)}function g3(e){tM=e}function rM(e){let t=En.get(e);if(!t)t={storageIndex:0,fileId:null,store:gn},En.set(e,t);else{if(t.saving)return t;t.store=gn}return T3(t),t.source?DR(e,t.source,t):t.contentBuffer?S3(e,t):DR(e,Kf.Readable.from(e.stream()),t),t}function DR(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([h(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(h(e.size)),_=!0);let p;o?(_||d.write(m3),p=(0,xm.createDeflate)(),t.pipe(p).pipe(d)):(_||d.write(h3),t.pipe(d)),t.on("error",S);function h(g){let R=BigInt(g),E=new Uint8Array(mr),T=new DataView(E.buffer);return R|=BigInt(o?MR:ZL)<<48n,T.setBigInt64(0,R),E}a(h,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,je.close)(R),u(g)):c?(0,je.fdatasync)(R,E=>{E&&u(E),l(),(0,je.close)(R)}):(l(),(0,je.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=p?p.bytesWritten:d.bytesWritten-mr;e.size=g,(0,je.write)(d.fd,h(g),0,mr,0,S)}})}),e}function km(e){return En.get(e)?.fileId}function nM(e){let t=En.get(e);return t?.fileId&&Yf(t)}function Wf(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=LR.get(e);if(!t){if(!e.databaseName)return uo.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,Bm.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,_o.join)(n,e.databaseName)):t=[(0,_o.join)((0,Bm.getHdbBasePath)(),"blobs",e.databaseName)],LR.set(e,t)}return t}async function vR(e){let t=Wf(e);t&&await Promise.all(t.map(r=>sM(r)))}async function sM(e){if((0,je.existsSync)(e)){for(let t of await(0,Xs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await sM((0,_o.join)(e,t.name));else try{await(0,Xs.unlink)((0,_o.join)(e,t.name))}catch(r){uo.default.warn?.("Error deleting file",r)}try{await(0,Xs.rmdir)(e)}catch(t){uo.default.warn?.("Error deleting directory",t)}}}function Yf({storageIndex:e,fileId:t,store:r}){let n=Wf(r);return(0,_o.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 S3(e,t){let r=t.contentBuffer,n=r.length;if(!(n<XL))return e.size=n,DR(e,Kf.Readable.from([r]),t)}function T3(e){let t=Wf(e.store),r=A3(),n=t?.length>1?R3(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Yf(e),o=(0,_o.dirname)(i);(0,je.existsSync)(o)||(0,QL.ensureDirSync)(o),e.filePath=i}function A3(){let e=JL.get(gn);if(!e){let t=0,r=Wf(gn);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,_o.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(gn.getUserSharedBuffer("blob-file-id",e.buffer)),JL.set(gn,e)}return Number(Atomics.add(e,0,1n))}function R3(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(Um);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,y3(e)),e.frequencyTable[t%Um]}async function y3(e){if(!Xs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Xs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(Um),n=t.map(s=>1/s);for(let s=0;s<Um;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 Fm(e,t,r){Ru=t,gn=r,Lc=!1;try{return e()}finally{Ru=void 0,gn=void 0}}function b3(e){Mr=[];let t;try{t=e()}catch(n){throw Mr=void 0,n}let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r?r.then(()=>e()):t}function Gm(e,t){try{Mr=[],Dc=t,e()}catch(n){throw Dc=void 0,Mr=void 0,n}Dc=void 0;let r=Mr.length<2?Mr[0]:Promise.all(Mr);return Mr=void 0,r}function qm(e,t,r){gn=r;try{return Dc=t,e()}finally{Dc=void 0}}function Mc(e,t){return gn=t,e()}function Aa(e){yu(e,t=>{Hm(t)})}function yu(e,t){if(e instanceof Ii)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&yu(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&yu(e[r],t)}}function O3(){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 fo,Xs,je,xm,Kf,QL,Bm,_o,uo,XL,mr,ZL,MR,zL,h3,m3,jL,En,Dc,Ii,Ru,Mr,gn,Lc,Vf,Mm,E3,vm,tM,LR,JL,Um,Ts=be(()=>{fo=require("msgpackr"),Xs=require("node:fs/promises"),je=require("node:fs"),xm=require("node:zlib"),Kf=require("node:stream"),QL=require("fs-extra"),Bm=M(le());k();_o=require("path"),uo=M(wi());po();XL=8192,mr=8,ZL=0,MR=1,zL=255,h3=new Uint8Array([0,ZL,255,255,255,255,255,255]),m3=new Uint8Array([0,MR,255,255,255,255,255,255]),jL=0xffffffffffff,En=new WeakMap,Ii=global.Blob||O3(),Lc=!1,Vf=new Uint8Array(8),Mm=new DataView(Vf.buffer),E3=6e4;a(eM,"InstanceOfBlobWithNoConstructor");eM.prototype=Ii.prototype;vm=class e extends eM{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=En.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):(xR()&&UR(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=En.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=Yf(t),o,c=a(async()=>{let l,u=mr;try{if(l=await(0,Xs.readFile)(i),l.length>=mr){l.copy(Vf,0,0,mr);let d=Mm.getBigUint64(0);if(Number(d>>48n)===zL)throw new Error("Error in blob: "+buffer.subarray(mr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<jL&&(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,p=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((h,S)=>{if(_.attemptLock(p,0,()=>(o=!0,h(c()))))return o=!0,_.unlock(p,0),h(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===MR?new Promise((d,_)=>{(0,xm.deflate)(l.subarray(mr),(p,h)=>{p?_(p):d(f(h))})}):f(l.subarray(mr))},"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=En.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=Yf(t),o,c=0,l=0,u,f,d,_=!1,p=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(uo.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{h(),g(R,E)},20).unref();E(T),p.#e?.forEach(v=>v(T))}else o=w,R(w)})},"openFile");return new Promise(g)},pull:a(S=>{let g=0,R=100;return new Promise(a(function E(T,w){function v($){(0,je.close)(o),clearTimeout(f),u&&u.close(),w($),p.#e?.forEach(W=>W($))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,je.read)(o,H,0,H.length,c,($,W,te)=>{if(l+=W,$)return v($);if(c===0){if(W<mr){R-- >0&&d!==!1?(h(),uo.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(uo.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(Vf,0,0,mr);let se=Mm.getBigUint64(0);if(Number(se>>48n)===zL)return v(new Error("Error in blob: "+te.subarray(mr)));if(g=Number(se&0xffffffffffffn),g<jL&&p.size!==g&&(p.size=g,p.#t))for(let Y of p.#t)Y(g);te=te.subarray(mr,W),l-=mr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,mr,0,Y=>{if(Y)return v(Y);if(Vf.set(se),g=Number(Mm.getBigUint64(0)&0xffffffffffffn),g>l){h()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},E3).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 uo.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 h(){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=En.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};En.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)};En.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(gn=t?.primaryStore?.rootStore,!gn)throw new Error("No target table specified");return rM(this).saving??Promise.resolve()}},tM=500;a(Hm,"deleteBlob");a(g3,"setDeletionDelay");global.createBlob=function(e,t){let r=new vm(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(En.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Kf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Kf.Readable.from(e);else throw new Error("Invalid source type");return r};a(rM,"saveBlob");a(DR,"writeBlobWithStream");a(km,"getFileId");a(nM,"getFilePathForBlob");LR=new Map;a(Wf,"getRootBlobPathsForDB");a(vR,"deleteRootBlobPathsForDB");a(sM,"rimrafSteadily");a(Yf,"getFilePath");a(S3,"writeBlobWithBuffer");a(T3,"generateFilePath");JL=new Map;a(A3,"getNextFileId");Um=128;a(R3,"getNextStorageIndex");a(y3,"createFrequencyTableForStoragePaths");a(Fm,"encodeBlobsWithFilePath");a(b3,"encodeBlobsAsBuffers");a(Gm,"decodeBlobsWithWrites");a(qm,"decodeWithBlobCallback");a(Mc,"decodeFromDatabase");a(Aa,"deleteBlobsInObject");a(yu,"findBlobsInObject");(0,fo.addExtension)({Class:Ii,type:11,unpack:a(function(e){let t=(0,fo.unpack)(e),r=new vm;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(En.set(r,{storageIndex:t[1],fileId:t[2],store:gn}),Dc)return Dc(r)??r;if(!gn)throw new Error("No store specified, cannot load blob from storage")}else En.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=En.get(e);if(Ru!==void 0&&(Lc=!0,t?.recordId!==void 0&&t.recordId!==Ru))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<XL)return r.size=t.contentBuffer.length,(0,fo.pack)([r,t.contentBuffer])}if(Ru!==void 0){if(t=rM(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Ru,(0,fo.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Yf(t));if(n.length>=mr&&(n.copy(Vf,0,0,mr),Number(Mm.getBigUint64(0)&0xffffffffffffn)===n.length-mr))return Buffer.concat([(0,fo.pack)([r]),n]);if(Mr)Mr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Mr)return Mr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,fo.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(O3,"polyfillBlob")});var fM={};Ue(fM,{asyncSerialization:()=>UR,contentTypes:()=>FR,findBestSerializer:()=>Km,getDeserializer:()=>Eo,hasAsyncSerialization:()=>xR,registerContentHandlers:()=>Jf,serialize:()=>Qf,serializeMessage:()=>Ra,toCsvStream:()=>Vm});function w3(e){try{return e?.[0]===123?kR(e):e}catch{return e}}function Jf(e){e.register(C3,{serializers:[{regex:/^application\/json$/,serializer:$f},{regex:/^application\/cbor$/,serializer:a(function(t){return new vc.EncoderStream(jf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Uc.Readable.from((0,Ci.encodeIter)(t,jf)):(0,Ci.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),Vm(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ci.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,vc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Km(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 h of f){let S=h.indexOf("=");_[h.substring(0,S)]=h.substring(S+1)}d=+_.q;let p=Yr.get(u);if(p){let h=(p.q||1)*d;h>s&&(n=p,i=p.type||u,s=h,o=_)}}if(!n){if(r)throw new aM.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Yr.keys()).join(", "),406);n=Yr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Qf(e,t,r){let n=oM&&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 Ii)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=Km(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}),HR.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,mo.createBrotliCompress)({params:{[mo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?mo.constants.BROTLI_MODE_TEXT:mo.constants.BROTLI_MODE_GENERIC,[mo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>oM?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,mo.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;ho=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=Km(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=zf(e);return ho?.length>0?(ho.length===1?ho[0]:Promise.all(ho)).then(()=>Ra(e,t,!0)):n}finally{ho=void 0}}function UR(e){if(ho)ho.push(e);else throw new Error("Unable to serialize asynchronously")}function xR(){return!!ho}function P3(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 L3(e){return D3.includes(e)}function M3(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 Eo(e="",t=!1){let r=M3(e),n=r.type&&Yr.get(r.type)?.deserialize||v3(r);return t?s=>P3(s).then(n):n}function v3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!L3(e.parameters.charset)&&HR.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 kR(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function U3(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 Vm(e,t){let r=Uc.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 N3(n,s);return r.pipe(i)}var Ci,vc,mo,aM,Uc,cM,BR,lM,HR,N3,uM,zf,kR,jf,Yr,FR,iM,dM,I3,C3,oM,ho,D3,po=be(()=>{PR();Ci=require("msgpackr"),vc=require("cbor-x"),mo=require("zlib"),aM=M(he()),Uc=M(require("stream"));Lr();cM=M(Ri()),BR=M(le());k();lM=M(require("yaml")),HR=M(wi());Ts();({Transform:N3}=require("json2csv")),uM=BR.default.get(U.SERIALIZATION_BIGINT)!==!1,zf=uM?Pc:JSON.stringify,kR=uM?CR:JSON.parse,jf={useRecords:!1,useToJSON:!0},Yr=new Map,FR=Yr;Ke.contentTypes=FR;(0,cM._assignPackageExport)("contentTypes",FR);Yr.set("application/json",{serializeStream:$f,serialize:zf,deserialize(e){return kR(e)},q:.8});iM=new vc.Encoder(jf);Yr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new vc.EncoderStream(jf).end(e)},serialize:iM.encode,deserialize:iM.decode,q:1});Yr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Uc.Readable.from((0,Ci.encodeIter)(e,jf)):(0,Ci.pack)(e)},serialize:Ci.pack,deserialize:Ci.unpack,q:.9});Yr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),Vm(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]),Vm(e,e?.getColumns?.())},q:.1});Yr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return Uc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Yr.set("text/yaml",{serialize(e){return lM.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Yr.set("text/event-stream",{serializeStream:a(function(e){return Uc.Readable.from(U3(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+`
|
|
9
9
|
`),e.data){let r=e.data;typeof r=="object"&&(r=zf(r)),t+="data: "+r+`
|
|
10
10
|
`}return e.id&&(t+="id: "+e.id+`
|
|
11
11
|
`),e.retry&&(t+="retry: "+e.retry+`
|