harperdb 4.5.15 → 4.5.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +1 -1
- package/bin/lite.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +1 -1
- package/launchServiceScripts/launchNatsReplyService.js +1 -1
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +1 -1
- package/npm-shrinkwrap.json +77 -63
- package/package.json +2 -2
- package/server/jobs/jobProcess.js +1 -1
- package/server/threads/threadServer.js +1 -1
- package/utility/scripts/restartHdb.js +1 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`+JSON.stringify(u)),u.cause&&(t[c--]=u.cause,u&&(n+=`
|
|
5
5
|
Caused by:`));else if(typeof u=="object")try{n+=JSON.stringify(u)}catch{n+="Object ["+Object.keys(u)+"]"}else n+=u;c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
6
6
|
`}a(Us,"createLogRecord");function jd(e){if(li){if(SP(e),is){Wo=!1;try{process.stdout.write(e)}finally{Wo=!0}}}else is&&process.stdout.write(e)}a(jd,"logStdOut");function Cm(e){if(li){if(SP(e),is){Wo=!1;try{process.stderr.write(e)}finally{Wo=!0}}}else is&&process.stderr.write(e)}a(Cm,"logStdErr");function SP(e){uA(),Yo?Wi.appendFileSync(Yo,e):lA||console.log(e)}a(SP,"logToFile");function fA(){try{Wi.closeSync(Yo)}catch{}Yo=null}a(fA,"closeLogFile");function uA(){if(!Yo){try{Yo=Wi.openSync(wm,"a")}catch(e){lA||(lA=!0,console.error(e))}setTimeout(()=>{fA()},zj).unref()}}a(uA,"openLogFile");function TP(...e){fr[Cr]<=fr.info&&jd(Us("info",e))}a(TP,"info");function AP(...e){fr[Cr]<=fr.trace&&jd(Us("trace",e))}a(AP,"trace");function Im(...e){fr[Cr]<=fr.error&&Cm(Us("error",e))}a(Im,"error");function RP(...e){fr[Cr]<=fr.debug&&jd(Us("debug",e))}a(RP,"debug");function yP(...e){fr[Cr]<=fr.notify&&jd(Us("notify",e))}a(yP,"notify");function bP(...e){fr[Cr]<=fr.fatal&&Cm(Us("fatal",e))}a(bP,"fatal");function OP(...e){fr[Cr]<=fr.warn&&Cm(Us("warn",e))}a(OP,"warn");function e2(e,t,...r){t===EP.STDERR?Cm(Us(e,r)):jd(Us(e,r))}a(e2,"logCustomLevel");function t2(){let e;try{e=Vj.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ui.join(e,qt.HDB_HOME_DIR_NAME,qt.BOOT_PROPS_FILE_NAME);return Wi.existsSync(t)||(t=ui.join(dA,"utility/hdb_boot_properties.file")),t}a(t2,"getPropsFilePath");function r2(e){Cr=e}a(r2,"setLogLevel");function hP(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(hP,"autoCastBoolean");function n2(e){try{if(e.includes("config/settings.js")){let o=pP(e);return{level:o.get(qt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ui.dirname(o.get(qt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(qt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(qt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=mP.parseDocument(Wi.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===qt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(n2,"getLogConfig");function s2(){try{let e=mP.parseDocument(Wi.readFileSync(Wj,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(s2,"getDefaultConfig");function i2(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(i2,"AuthAuditLog")});var _A=P((VTe,IP)=>{"use strict";var o2=require("util"),a2=require("path"),c2=require("child_process"),l2=o2.promisify(c2.execFile),u2=1e3*1e3*10;IP.exports={findPs:d2};async function d2(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await l2("ps",["wwxo",`pid,${r}`],{maxBuffer:u2});for(let s of n.trim().split(`
|
|
7
|
-
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:a2.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(d2,"findPs")});var Ut=P((YTe,PP)=>{"use strict";var f2="__dbis__",_2="__txns__",h2="__environment_name__",m2="__dbi_defintion__",p2={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"},E2=["__createdtime__","__updatedtime__"],g2="\uFFFF",CP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},S2=Object.values(CP);PP.exports={AUDIT_STORE_NAME:_2,INTERNAL_DBIS_NAME:f2,DBI_DEFINITION_NAME:m2,SEARCH_TYPES:p2,TIMESTAMP_NAMES:E2,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:h2,TRANSACTIONS_DBI_NAMES_ENUM:CP,TRANSACTIONS_DBIS:S2,OVERFLOW_MARKER:g2}});var Pn=P((WTe,kP)=>{"use strict";var DP=(k(),D($)),LP=Ut(),MP={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},vP=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),UP={500:vP("There was an error processing your request."),400:"Invalid request"},T2=UP[MP.INTERNAL_SERVER_ERROR],A2={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")},R2={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},y2={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"},b2={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 ${LP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${LP.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"},O2={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${DP.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 ${DP.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"},xP={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"},N2={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."},w2={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")},I2={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"},C2={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},P2={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")},BP={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")},HP={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")},D2={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"},L2={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},M2={...xP,...y2,...A2,...N2,...w2,...I2,...C2,...P2,...O2,...BP,...HP,...D2,...L2,...R2};kP.exports={CHECK_LOGS_WRAPPER:vP,HDB_ERROR_MSGS:M2,DEFAULT_ERROR_MSGS:UP,DEFAULT_ERROR_RESP:T2,HTTP_STATUS_CODES:MP,LMDB_ERRORS_ENUM:b2,AUTHENTICATION_ERROR_MSGS:xP,VALIDATION_ERROR_MSGS:BP,ITC_ERRORS:HP}});var me=P((QTe,qP)=>{"use strict";var Fl=Pn(),v2=j(),U2=(k(),D($)),Pm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,FP),this.statusCode=n||Fl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Fl.DEFAULT_ERROR_MSGS[n]?Fl.DEFAULT_ERROR_MSGS[n]:Fl.DEFAULT_ERROR_MSGS[Fl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&v2[s](i)}},hA=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}},mA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function FP(e,t,r,n=U2.LOG_LEVELS.ERROR,s=null,i=!1){if(GP(e))return e;let o=new Pm(e,t,r,n,s);return i&&delete o.stack,o}a(FP,"handleHDBError");function GP(e){return e.__proto__.constructor.name===Pm.name}a(GP,"isHDBError");qP.exports={isHDBError:GP,handleHDBError:FP,ClientError:hA,ServerError:mA,hdb_errors:Fl}});var pt=P((JTe,QP)=>{"use strict";var tf=(k(),D($)),x2=ae(),on=le(),rf=require("path"),B2=require("minimist"),$P=require("fs-extra"),VP=require("lodash");on.initSync();var{CONFIG_PARAMS:zo,DATABASES_PARAM_CONFIG:Jd,SYSTEM_SCHEMA_NAME:Dm}=tf,Xd,Zd,ef;function KP(){if(Xd!==void 0)return Xd;if(on.getHdbBasePath()!==void 0)return Xd=on.get(zo.STORAGE_PATH)||rf.join(on.getHdbBasePath(),tf.DATABASES_DIR_NAME),Xd}a(KP,"getBaseSchemaPath");function YP(){if(Zd!==void 0)return Zd;if(on.getHdbBasePath()!==void 0)return Zd=zP(Dm),Zd}a(YP,"getSystemSchemaPath");function WP(){if(ef!==void 0)return ef;if(on.getHdbBasePath()!==void 0)return ef=on.get(tf.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||rf.join(on.getHdbBasePath(),tf.TRANSACTIONS_DIR_NAME),ef}a(WP,"getTransactionAuditStoreBasePath");function H2(e,t){let r=on.get(zo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||rf.join(WP(),e.toString())}a(H2,"getTransactionAuditStorePath");function zP(e,t){e=e.toString(),t=t&&t.toString();let r=on.get(tf.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||rf.join(KP(),e)}a(zP,"getSchemaPath");function k2(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,B2(process.argv));let n=r[zo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!x2.isObject(n))throw o;i=n}for(let o of i){let c=o[Dm];if(!c)continue;let l=on.get(zo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[Jd.PATH];if(u)return VP.set(l,[Dm,Jd.TABLES,t,Jd.PATH],u),on.setProperty(zo.DATABASES,l),u;let f=c?.[Jd.PATH];if(f)return VP.set(l,[Dm,Jd.PATH],f),on.setProperty(zo.DATABASES,l),f}}let s=r[zo.STORAGE_PATH.toUpperCase()];if(s){if(!$P.pathExistsSync(s))throw new Error(s+" does not exist");let i=rf.join(s,e);return $P.mkdirsSync(i),on.setProperty(zo.STORAGE_PATH,s),i}return YP()}a(k2,"initSystemSchemaPaths");function F2(){Xd=void 0,Zd=void 0,ef=void 0}a(F2,"resetPaths");QP.exports={getBaseSchemaPath:KP,getSystemSchemaPath:YP,getTransactionAuditStorePath:H2,getTransactionAuditStoreBasePath:WP,getSchemaPath:zP,initSystemSchemaPaths:k2,resetPaths:F2}});var an=P((tAe,eD)=>{"use strict";var G2=Pn().LMDB_ERRORS_ENUM,ZTe=require("lmdb"),q2=Ut(),eAe=require("buffer").Buffer,{OVERFLOW_MARKER:jP,MAX_SEARCH_KEY_LENGTH:Lm}=q2,JP=["number","string","symbol","boolean","bigint"];function $2(e){if(e=e?.primaryStore||e,!e)throw new Error(G2.ENV_REQUIRED)}a($2,"validateEnv");function V2(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(V2,"stringifyData");function K2(e){return e instanceof Date?e.valueOf():e}a(K2,"convertKeyValueToWrite");function Y2(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(JP.includes(typeof e))return e.length>Lm?[e.slice(0,Lm)+jP]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(JP.includes(typeof i))i.length>Lm?r.push(i.slice(0,Lm)+jP):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(Y2,"getIndexedValues");var Mm=0,XP=0;function ZP(){XP=Date.now()-performance.now()}a(ZP,"adjustStartTime");ZP();var W2=6e4;setInterval(ZP,W2).unref();function z2(){let e=performance.now()+XP;return e>Mm?(Mm=e,e):(Mm+=488e-6,Mm)}a(z2,"getNextMonotonicTime");eD.exports={validateEnv:$2,stringifyData:V2,convertKeyValueToWrite:K2,getNextMonotonicTime:z2,getIndexedValues:Y2}});var nf=P((nAe,tD)=>{"use strict";var Q2=(k(),D($)).OPERATIONS_ENUM,pA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=Q2.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};tD.exports=pA});var sf=P((oAe,iD)=>{"use strict";var iAe=nf(),vm=(k(),D($)),EA=ae(),rD=j(),j2=require("uuid"),{handleHDBError:Um,hdb_errors:J2}=me(),{HDB_ERROR_MSGS:xm,HTTP_STATUS_CODES:Bm}=J2;iD.exports=nD;function nD(e,t,r){for(let s=0;s<t.length;s++)sD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];X2(i,r,e.operation)}}a(nD,"processRows");nD.validateAttribute=sD;function sD(e){if(Buffer.byteLength(String(e))>vm.INSERT_MAX_CHARACTER_SIZE)throw Um(new Error,xm.ATTR_NAME_LENGTH_ERR(e),Bm.BAD_REQUEST,void 0,void 0,!0);if(EA.isEmptyOrZeroLength(e)||EA.isEmpty(e.trim()))throw Um(new Error,xm.ATTR_NAME_NULLISH_ERR,Bm.BAD_REQUEST,void 0,void 0,!0)}a(sD,"validateAttribute");function X2(e,t,r){if(!e.hasOwnProperty(t)||EA.isEmptyOrZeroLength(e[t])){if(r===vm.OPERATIONS_ENUM.INSERT||r===vm.OPERATIONS_ENUM.UPSERT){e[t]=j2.v4();return}throw rD.error("Update transaction aborted due to record with no hash value:",e),Um(new Error,xm.RECORD_MISSING_HASH_ERR,Bm.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>vm.INSERT_MAX_CHARACTER_SIZE)throw rD.error(e),Um(new Error,xm.HASH_VAL_LENGTH_ERR,Bm.BAD_REQUEST,void 0,void 0,!0)}a(X2,"validateHash")});var oD,Dn,gA,Gl=be(()=>{oD=require("events"),Dn=class extends oD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new gA;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)}},gA=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 _D(e){TA=e}function rJ(){tJ=setInterval(function(){for(let e of SA)if(e.stale){let t=e.getContext()?.url;uD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},eJ).unref()}var AA,lD,uD,dD,fD,aD,SA,Z2,of,cD,TA,nc,Hm,eJ,tJ,km=be(()=>{AA=M(an()),lD=M(me()),uD=M(j()),dD=M(le());k();fD=M(ae()),aD=100,SA=new Set,Z2=(0,fD.convertToMS)(dD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(_D,"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),SA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(SA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(of&&!this.overloadChecked&&performance.now()-cD>Z2)throw new lD.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,AA.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let h=d;h<this.validated;h++)this.writes[h]?.validate?.(this.timestamp);let _;for(let h=d;h<this.validated;h++){let m=this.writes[h];m&&(m.before||m.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let h=0;h<2;h++){let m;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let R=g[h===0?"before":"beforeIntermediate"];if(R){let E=R();m?m.push?m.push(E):m=[m,E]:m=E}}m&&await(m.push?Promise.all(m):m)}}catch(h){throw this.abort(),h}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),l=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<aD>>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 of||(of=s,cD=performance.now(),of.then(()=>{of=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];TA&&h&&i.push(TA(_,h.store.getEntry(h.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+aD/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}},Hm=class extends nc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,AA.getNextMonotonicTime)())}getReadTxn(){}},eJ=3e4;a(rJ,"startMonitoringTxns");rJ()});function Ot(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 hD,sc=be(()=>{hD=M(ci());km();a(Ot,"transaction");(0,hD._assignPackageExport)("transaction",Ot);Ot.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ot.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 yA(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let h=1;h<e.length;h++){let m=e[h],S=u(m);d=d.concat(S)}let _=new Set;return d.filter(h=>{let m=h.key??h;return _.has(m)?!1:(_.add(m),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?yA(d.conditions,d.operator,r,n,s,i,o,c):Vl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(m.attribute||m[0])===r.primaryKey,R=lf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=dJ(r.primaryStore,m.estimated_count,h)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Vl(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 ln.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=fi(n.attributes,E);if(T.relationship){if(o.length<2)throw new ln.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=Vl({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 q=!!fi(w.attributes,T.relationship.to)?.elements;H=aJ(H,T,w.primaryStore,q,v)}if(T.relationship.from){let q=a(W=>(W?.key!==void 0&&(W=W.key),Vl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=cJ(H,T,w.primaryStore,v,q)):H=H.flatMap(q)}return H}else if(o.length===1)o=o[0];else throw new ln.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(bA[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]=di.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new ln.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>os.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,_=!1,m=lf(e,n,null,i,S)),typeof f=="string"&&f.length>os.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,d=!0,m=m??lf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new ln.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new ln.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 ln.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new ln.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??lf(e,n,null,i,S),!m)throw new ln.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(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:T=>T.value==null&&!(T.metadataFlags&(un|Jo))?Qo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>os.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:Qo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Qo.SKIP)}catch(H){v(H)}}))})}function fi(e,t){if(Array.isArray(t))if(t.length>1){let r=fi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?fi(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function aJ(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 cJ(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 lf(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=fi(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=lf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,R=a((E,T)=>{let w,v;if(S){if(S.from&&m.idFilter){if(!g)if(m.idFilter.idSet?.size===1){for(let q of m.idFilter.idSet)e={attribute:S.from,value:q};g=u(S.from,m.idFilter,!0,!0)}else g=u(S.from,m.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(m):m(w,v):!1},"recordFilter");return R}}switch(l instanceof Date&&(l=l.getTime()),bA[o]||o){case os.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,di.compareKeys)(f,l[0])>=0&&(0,di.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,di.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,di.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,di.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,di.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,di.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new ln.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Gm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function R(E){let T=E[f],w;if(typeof T!="object"||!T||h?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!R.idFilter&&++S/g*(i-g)>m)){let v=Vl(e,r.transaction.getReadTxn(),!1,t).map(Kl),H=new Set(v);R.idFilter=q=>H.has(Kl(q)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Gm(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/zi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=bA[n]||n,n===os.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=fi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Gm(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*zi(e.indices[i.relationship.from])/(zi(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=zi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=iJ*zi(e.primaryStore)+1:n==="between"?r.estimated_count=sJ*zi(e.primaryStore)+1:n==="sort"?r.estimated_count=zi(e.primaryStore)+1:r.estimated_count=nJ*zi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function qm(e){if(e)if(jo=e,ql.lastIndex=0,lJ.test(e))try{let t=af(new $l,"");if(cn!==jo.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${cn} in '${jo}'`,t}else return new URLSearchParams(e)}function af(e,t){let r=ql,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(jo);){cn=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=mD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=cf(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=oJ[d],l=RA[i]?mD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=cf(f);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&pD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else Fm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(cf(f)),s=void 0;break;case"(":ql.lastIndex=cn;let h=af(f?[]:new $l,")");switch(f){case"":Fm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=ED(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}jo[cn]===","?r.lastIndex=++cn: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");ql.lastIndex=cn,_=af([],"}"),_.name=f,e.push(_),jo[cn]===","?r.lastIndex=++cn:o=!0;break;case"[":ql.lastIndex=cn,f?(_=af(new $l,"]"),_.name=f):_=af(e.conditions?new $l:[],"]"),e.conditions?(Fm(e,u),e.conditions.push(_),s=null):e.push(_),jo[cn]===","?r.lastIndex=++cn:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let m={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&pD(m,f),Fm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(cf(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?uJ:ql,r.lastIndex=cn),cn===jo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Fm(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 cf(e){return e.indexOf(".")>-1?e.split(".").map(cf):decodeURIComponent(e)}function mD(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 ln.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function pD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new ln.ClientError("wildcard can only be used at the end of a string")}function ED(e){let t=gD(e[0]);return e.length>1&&(t.next=ED(e.slice(1))),t}function gD(e){if(Array.isArray(e)){let t=gD(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 Kl(e){return Array.isArray(e)?e.join("\0"):e}function zi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function dJ(e,t,r){return t*r/zi(e)}var ln,os,di,Qo,nJ,sJ,iJ,oJ,RA,bA,lJ,ql,uJ,cn,jo,$l,ic,uf=be(()=>{ln=M(me()),os=M(Ut()),di=require("ordered-binary"),Qo=require("lmdb");df();nJ=.3,sJ=.1,iJ=.05,oJ={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},RA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(yA,"executeConditions");a(Vl,"searchByIndex");a(fi,"findAttribute");a(aJ,"joinTo");a(cJ,"joinFrom");bA={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(lf,"filterByType");a(Gm,"estimateCondition");lJ=/[()[\]|!<>.]|(=\w*=)/,ql=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,uJ=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(qm,"parseQuery");a(af,"parseBlock");a(Fm,"assignOperator");a(cf,"decodeProperty");a(mD,"typedDecoding");a(pD,"wildcardDecoding");a(ED,"toSortObject");a(gD,"toSortEntry");$l=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(Kl,"flattenKey");a(zi,"estimatedEntryCount");a(dJ,"intersectionEstimate");ic=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var NA={};Ue(NA,{MultiPartId:()=>Vm,Resource:()=>qr,snake_case:()=>_J,transformForSelect:()=>Km});function _J(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function SD(e,t){if(oc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(oc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Vm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){oc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return oc=!0,null;e[e.length-1]==="/"&&(oc=!0)}return t.coerceId(decodeURIComponent(e))}function Ln(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new 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 h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return Ot(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new $m(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new $m(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Mn(e,t){let r=new RD.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 OA(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 Km(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):OA(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(OA(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(OA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=Km(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var TD,AD,RD,fJ,qr,$m,oc,Vm,Xo=be(()=>{TD=require("crypto");Gl();AD=M(ci()),RD=M(me());sc();uf();fJ={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},qr=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Ln(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=Km(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Ln(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Mn(t,"put")},{hasContent:!0,type:"update"});static patch=Ln(function(t,r,n,s){return t.patch?t.patch(s,r):Mn(t,"patch")},{hasContent:!0,type:"update"});static delete=Ln(function(t,r,n,s){return t.delete?t.delete(r):Mn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,TD.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={}),Ot(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Mn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Ln(function(t,r,n,s){return t.invalidate?t.invalidate(r):Mn(t,"delete")},{hasContent:!1,type:"update"});static post=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Ln(function(t,r,n,s){return t.connect?t.connect(s,r):Mn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Ln(function(t,r,n,s){return t.subscribe?t.subscribe(r):Mn(t,"subscribe")},{type:"read"});static publish=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Mn(t,"publish")},{hasContent:!0,type:"create"});static search=Ln(function(t,r,n,s){let i=t.search?t.search(r):Mn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Km(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Ln(function(t,r,n,s){return t.search?t.search(s,r):Mn(t,"search")},{hasContent:!0,type:"read"});static copy=Ln(function(t,r,n,s){return t.copy?t.copy(s,r):Mn(t,"copy")},{hasContent:!0,type:"create"});static move=Ln(function(t,r,n,s){return t.move?t.move(s,r):Mn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Mn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return qm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&fJ[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:SD(t,this),isCollection:oc}}let i=SD(t,this);return oc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Dn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Dn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,AD._assignPackageExport)("Resource",qr);a(_J,"snake_case");$m=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(SD,"pathToId");Vm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Ln,"transactional");a(Mn,"missingMethod");a(OA,"selectFromObject");a(Km,"transformForSelect")});var Zo,wA=be(()=>{Zo=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 Yl={};Ue(Yl,{server:()=>Ke});var yD,Ke,Pr=be(()=>{yD=M(ci()),Ke={};(0,yD._assignPackageExport)("server",Ke)});var ND={};Ue(ND,{Resources:()=>Ym,keyArrayToString:()=>Wl,resetResources:()=>hJ,resources:()=>as});function hJ(){return as=new Ym,Ke.resources=as,as}function Wl(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var bD,OD,Ym,as,zl=be(()=>{sc();wA();bD=M(j()),OD=M(me());Pr();Ym=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 OD.ServerError(`Conflicting paths for ${t}`);bD.default.error(c),i.Resource=new Zo(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 Ot(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(hJ,"resetResources");a(Wl,"keyArrayToString")});var IA=P((DAe,wD)=>{if(__filename.endsWith("dev.js")){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n}=require("node:path"),{existsSync:s,statSync:i,readFileSync:o,writeFileSync:c,unlinkSync:l}=require("node:fs"),{isMainThread:u}=require("node:worker_threads"),{spawnSync:f,spawn:d}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:_}=mt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],m="ts-build";if(u){let R=!1,E=!1;if(E=s(n(_,m))){let T=new Set;e.sync(h.map(w=>`${w}/**/*.ts`),{cwd:_}).forEach(w=>{let v=0,H=0;try{T.add(w),v=i(n(_,w)).mtimeMs-5e3,H=i(n(_,m,w.replace(/.ts$/,".js"))).mtimeMs}catch{}v>H&&(R=!0)}),e.sync(h.map(w=>`${w}/**/*.js`),{cwd:n(_,m)}).forEach(w=>{if(!T.has(w.replace(/.js$/,".ts")))try{l(n(_,m,w))}catch{}})}else R=!0;if(R){console.log("Compiling TypeScript...");let T=f("npx",["tsc"],{cwd:_});if(T.stdout?.length&&console.log(T.stdout.toString()),T.stderr?.length&&console.log(T.stderr.toString()),E){let w=n(t(),"harperdb-tsc.pid"),v=!1;if(s(w))try{process.kill(+o(w,"utf8"),0),v=!0}catch{}if(!v){console.log("Starting background TypeScript compilation...");let H=d("npx",["tsc","--watch"],{detached:!0,cwd:_,stdio:"ignore"});H.on("error",q=>{console.error("Error trying to compile TypeScript",q)}),H.pid&&c(w,String(H.pid),"utf-8"),H.unref()}}}}let S=wD.constructor,g=S._findPath;S._findPath=function(R,E,T){if(R.startsWith(".")&&!T&&E.length===1&&E[0].startsWith(_)&&!E[0].includes("node_modules")){let w=r(_,E[0]),v;w.startsWith(m)?v=n(_,r(m,w)):v=n(_,m,w);let H=n(v,R),q=H+".js";if(s(q))return q;if(H.includes(".")&&s(H))return H}return g(R,E,T)}}});var DA={};Ue(DA,{loadGQLSchema:()=>EJ,start:()=>PA,startOnMainThread:()=>pJ});function PA({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,h=[],m;for(let 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,h.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,q={};for(let W of R.fields){let te=H(W.type);te.name=W.name.value,T.push(te),q[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,q)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(m=w)}function S(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):mJ.includes(R.type)||(0,CD.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 h)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,CA.dirname)(n),R.tableClass):i.set((0,CA.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new ID.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 CA,ID,CD,mJ,pJ,EJ,PD=be(()=>{CA=require("path"),ID=require("node:vm");ve();CD=M(tt()),mJ=["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(PA,"start");pJ=PA,EJ=PA({ensureTable:ut}).handleFile});var BD={};Ue(BD,{parse:()=>MA,streamAsJSON:()=>ff,stringify:()=>ac});function ff(e){return new LA({value:e})}function DD(e){return console.error(e),JSON.stringify(e.toString())}function LD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function ac(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===UD)return xD(e);if(t.resolution)return t.resolution.then(()=>ac(e));throw t}}function xD(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+=xD(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+ac(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function MA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),TJ.test(e)?gJ.parse(e):JSON.parse(e)):null}var MD,vD,gJ,SJ,UD,LA,TJ,vA=be(()=>{MD=require("stream"),vD=M(require("json-bigint-fixes")),gJ=(0,vD.default)({useNativeBigInt:!0}),SJ=1e4,UD={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw UD};a(ff,"streamAsJSON");LA=class extends MD.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),DD)}catch(s){yield DD(s)}else yield ac(t)}else yield ac(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);LD(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>SJ?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 LD(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(DD,"handleError");a(LD,"when");a(ac,"stringify");a(xD,"jsStringify");TJ=/[[,:]\s*-?\d{16,}/;a(MA,"parse")});var _i=P(zm=>{var Wm=j();for(let e of["trace","debug","info","warn","error","fatal","notify"])Wm.logsAtLevel(e)&&(zm[e]=Wm[e]);zm.loggerWithTag=e=>Wm.loggerWithTag(e,!0);zm.setLogLevel=Wm.setLogLevel});var ip={};Ue(ip,{Blob:()=>hi,blobsWereEncoded:()=>lc,databasePaths:()=>xA,decodeBlobsWithWrites:()=>np,decodeFromDatabase:()=>uc,decodeWithBlobCallback:()=>sp,deleteBlob:()=>ep,deleteBlobsInObject:()=>ea,deleteRootBlobPathsForDB:()=>HA,encodeBlobsAsBuffers:()=>PJ,encodeBlobsWithFilePath:()=>rp,findBlobsInObject:()=>jl,getFileId:()=>tp,getFilePathForBlob:()=>WD,getRootBlobPathsForDB:()=>pf,setDeletionDelay:()=>bJ});function VD(){}function ep(e){let t=WD(e);t&&setTimeout(()=>{(0,Qe.unlink)(t,r=>{r&&Qi.default.debug?.("Error trying to remove blob file",r)})},KD)}function bJ(e){KD=e}function YD(e){let t=dn.get(e);if(!t)t={storageIndex:0,fileId:null,store:fn},dn.set(e,t);else{if(t.saving)return t;t.store=fn}return NJ(t),t.source?UA(e,t.source,t):t.contentBuffer?OJ(e,t):UA(e,hf.Readable.from(e.stream()),t),t}function UA(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,Qe.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(RJ),h=(0,Xm.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(AJ),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(_r),T=new DataView(E.buffer);return R|=BigInt(o?BA:$D)<<48n,T.setBigInt64(0,R),E}a(m,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,Qe.close)(R),u(g)):c?(0,Qe.fdatasync)(R,E=>{E&&u(E),l(),(0,Qe.close)(R)}):(l(),(0,Qe.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-_r;e.size=g,(0,Qe.write)(d.fd,m(g),0,_r,0,S)}})}),e}function tp(e){return dn.get(e)?.fileId}function WD(e){let t=dn.get(e);return t?.fileId&&mf(t)}function pf(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=xA.get(e);if(!t){if(!e.databaseName)return Qi.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,Zm.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Ji.join)(n,e.databaseName)):t=[(0,Ji.join)((0,Zm.getHdbBasePath)(),"blobs",e.databaseName)],xA.set(e,t)}return t}async function HA(e){let t=pf(e);t&&await Promise.all(t.map(r=>zD(r)))}async function zD(e){if((0,Qe.existsSync)(e)){for(let t of await(0,xs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await zD((0,Ji.join)(e,t.name));else try{await(0,xs.unlink)((0,Ji.join)(e,t.name))}catch(r){Qi.default.warn?.("Error deleting file",r)}try{await(0,xs.rmdir)(e)}catch(t){Qi.default.warn?.("Error deleting directory",t)}}}function mf({storageIndex:e,fileId:t,store:r}){let n=pf(r);return(0,Ji.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 OJ(e,t){let r=t.contentBuffer,n=r.length;if(!(n<qD))return e.size=n,UA(e,hf.Readable.from([r]),t)}function NJ(e){let t=pf(e.store),r=wJ(),n=t?.length>1?IJ(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=mf(e),o=(0,Ji.dirname)(i);(0,Qe.existsSync)(o)||(0,GD.ensureDirSync)(o),e.filePath=i}function wJ(){let e=FD.get(fn);if(!e){let t=0,r=pf(fn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,Qe.existsSync)(n))for(let c of(0,Qe.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,Ji.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(fn.getUserSharedBuffer("blob-file-id",e.buffer)),FD.set(fn,e)}return Number(Atomics.add(e,0,1n))}function IJ(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(Jm);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,CJ(e)),e.frequencyTable[t%Jm]}async function CJ(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(Jm),n=t.map(s=>1/s);for(let s=0;s<Jm;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 rp(e,t,r){Ql=t,fn=r,lc=!1;try{return e()}finally{Ql=void 0,fn=void 0}}function PJ(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function np(e,t){try{Dr=[],cc=t,e()}catch(n){throw cc=void 0,Dr=void 0,n}cc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function sp(e,t,r){fn=r;try{return cc=t,e()}finally{cc=void 0}}function uc(e,t){return fn=t,e()}function ea(e){jl(e,t=>{ep(t)})}function jl(e,t){if(e instanceof hi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&jl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&jl(e[r],t)}}function DJ(){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 ji,xs,Qe,Xm,hf,GD,Zm,Ji,Qi,qD,_r,$D,BA,HD,AJ,RJ,kD,dn,cc,hi,Ql,Dr,fn,lc,_f,Qm,yJ,jm,KD,xA,FD,Jm,cs=be(()=>{ji=require("msgpackr"),xs=require("node:fs/promises"),Qe=require("node:fs"),Xm=require("node:zlib"),hf=require("node:stream"),GD=require("fs-extra"),Zm=M(le());k();Ji=require("path"),Qi=M(_i());Xi();qD=8192,_r=8,$D=0,BA=1,HD=255,AJ=new Uint8Array([0,$D,255,255,255,255,255,255]),RJ=new Uint8Array([0,BA,255,255,255,255,255,255]),kD=0xffffffffffff,dn=new WeakMap,hi=global.Blob||DJ(),lc=!1,_f=new Uint8Array(8),Qm=new DataView(_f.buffer),yJ=6e4;a(VD,"InstanceOfBlobWithNoConstructor");VD.prototype=hi.prototype;jm=class e extends VD{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=dn.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):(FA()&&kA(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=dn.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=mf(t),o,c=a(async()=>{let l,u=_r;try{if(l=await(0,xs.readFile)(i),l.length>=_r){l.copy(_f,0,0,_r);let d=Qm.getBigUint64(0);if(Number(d>>48n)===HD)throw new Error("Error in blob: "+buffer.subarray(_r));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<kD&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,h=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((m,S)=>{if(_.attemptLock(h,0,()=>(o=!0,_.unlock(h,0),m(c()))))return o=!0,_.unlock(h,0),m(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===BA?new Promise((d,_)=>{(0,Xm.deflate)(l.subarray(_r),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(_r))},"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=dn.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=mf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,Qe.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(Qi.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(R,E)},20).unref();E(T),h.#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(q){(0,Qe.close)(o),clearTimeout(f),u&&u.close(),w(q),h.#e?.forEach(W=>W(q))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,Qe.read)(o,H,0,H.length,c,(q,W,te)=>{if(l+=W,q)return v(q);if(c===0){if(W<_r){R-- >0&&d!==!1?(m(),Qi.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(Qi.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(_f,0,0,_r);let se=Qm.getBigUint64(0);if(Number(se>>48n)===HD)return v(new Error("Error in blob: "+te.subarray(_r)));if(g=Number(se&0xffffffffffffn),g<kD&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(_r,W),l-=_r}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,Qe.read)(o,se,0,_r,0,Y=>{if(Y)return v(Y);if(_f.set(se),g=Number(Qm.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},yJ).unref():(u=(0,Qe.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,Qe.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 Qi.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,Qe.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,Qe.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1,S.unlock(g,0)}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=dn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};dn.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)};dn.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(fn=t?.primaryStore?.rootStore,!fn)throw new Error("No target table specified");return YD(this).saving??Promise.resolve()}},KD=500;a(ep,"deleteBlob");a(bJ,"setDeletionDelay");global.createBlob=function(e,t){let r=new jm(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(dn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof hf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=hf.Readable.from(e);else throw new Error("Invalid source type");return r};a(YD,"saveBlob");a(UA,"writeBlobWithStream");a(tp,"getFileId");a(WD,"getFilePathForBlob");xA=new Map;a(pf,"getRootBlobPathsForDB");a(HA,"deleteRootBlobPathsForDB");a(zD,"rimrafSteadily");a(mf,"getFilePath");a(OJ,"writeBlobWithBuffer");a(NJ,"generateFilePath");FD=new Map;a(wJ,"getNextFileId");Jm=128;a(IJ,"getNextStorageIndex");a(CJ,"createFrequencyTableForStoragePaths");a(rp,"encodeBlobsWithFilePath");a(PJ,"encodeBlobsAsBuffers");a(np,"decodeBlobsWithWrites");a(sp,"decodeWithBlobCallback");a(uc,"decodeFromDatabase");a(ea,"deleteBlobsInObject");a(jl,"findBlobsInObject");(0,ji.addExtension)({Class:hi,type:11,unpack:a(function(e){let t=(0,ji.unpack)(e),r=new jm;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(dn.set(r,{storageIndex:t[1],fileId:t[2],store:fn}),cc)return cc(r)??r;if(!fn)throw new Error("No store specified, cannot load blob from storage")}else dn.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=dn.get(e);if(Ql!==void 0&&(lc=!0,t?.recordId!==void 0&&t.recordId!==Ql))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<qD)return r.size=t.contentBuffer.length,(0,ji.pack)([r,t.contentBuffer])}if(Ql!==void 0){if(t=YD(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Ql,(0,ji.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,Qe.readFileSync)(mf(t));if(n.length>=_r&&(n.copy(_f,0,0,_r),Number(Qm.getBigUint64(0)&0xffffffffffffn)===n.length-_r))return Buffer.concat([(0,ji.pack)([r]),n]);if(Dr)Dr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Dr)return Dr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,ji.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(DJ,"polyfillBlob")});var rL={};Ue(rL,{asyncSerialization:()=>kA,contentTypes:()=>VA,findBestSerializer:()=>ap,getDeserializer:()=>to,hasAsyncSerialization:()=>FA,registerContentHandlers:()=>Sf,serialize:()=>Tf,serializeMessage:()=>ta,toCsvStream:()=>op});function MJ(e){try{return e?.[0]===123?$A(e):e}catch{return e}}function Sf(e){e.register(UJ,{serializers:[{regex:/^application\/json$/,serializer:ff},{regex:/^application\/cbor$/,serializer:a(function(t){return new dc.EncoderStream(gf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?fc.Readable.from((0,mi.encodeIter)(t,gf)):(0,mi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),op(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,dc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function ap(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=$r.get(u);if(h){let m=(h.q||1)*d;m>s&&(n=h,i=h.type||u,s=m,o=_)}}if(!n){if(r)throw new JD.ClientError("No supported content types found in Accept header, supported types include: "+Array.from($r.keys()).join(", "),406);n=$r.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Tf(e,t,r){let n=jD&&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 hi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=ap(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}),qA.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,eo.createBrotliCompress)({params:{[eo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?eo.constants.BROTLI_MODE_TEXT:eo.constants.BROTLI_MODE_GENERIC,[eo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>jD?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,eo.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ta(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Zi=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=ap(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Ef(e);return Zi?.length>0?(Zi.length===1?Zi[0]:Promise.all(Zi)).then(()=>ta(e,t,!0)):n}finally{Zi=void 0}}function kA(e){if(Zi)Zi.push(e);else throw new Error("Unable to serialize asynchronously")}function FA(){return!!Zi}function xJ(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 HJ(e){return BJ.includes(e)}function kJ(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 to(e="",t=!1){let r=kJ(e),n=r.type&&$r.get(r.type)?.deserialize||FJ(r);return t?s=>xJ(s).then(n):n}function FJ(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!HJ(e.parameters.charset)&&qA.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 $A(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function GJ(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 op(e,t){let r=fc.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 LJ(n,s);return r.pipe(i)}var mi,dc,eo,JD,fc,XD,GA,ZD,qA,LJ,eL,Ef,$A,gf,$r,VA,QD,tL,vJ,UJ,jD,Zi,BJ,Xi=be(()=>{vA();mi=require("msgpackr"),dc=require("cbor-x"),eo=require("zlib"),JD=M(me()),fc=M(require("stream"));Pr();XD=M(ci()),GA=M(le());k();ZD=M(require("yaml")),qA=M(_i());cs();({Transform:LJ}=require("json2csv")),eL=GA.default.get(U.SERIALIZATION_BIGINT)!==!1,Ef=eL?ac:JSON.stringify,$A=eL?MA:JSON.parse,gf={useRecords:!1,useToJSON:!0},$r=new Map,VA=$r;Ke.contentTypes=VA;(0,XD._assignPackageExport)("contentTypes",VA);$r.set("application/json",{serializeStream:ff,serialize:Ef,deserialize(e){return $A(e)},q:.8});QD=new dc.Encoder(gf);$r.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new dc.EncoderStream(gf).end(e)},serialize:QD.encode,deserialize:QD.decode,q:1});$r.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?fc.Readable.from((0,mi.encodeIter)(e,gf)):(0,mi.pack)(e)},serialize:mi.pack,deserialize:mi.unpack,q:.9});$r.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),op(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]),op(e,e?.getColumns?.())},q:.1});$r.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return fc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});$r.set("text/yaml",{serialize(e){return ZD.stringify(e,{aliasDuplicateObjects:!1})},q:.7});$r.set("text/event-stream",{serializeStream:a(function(e){return fc.Readable.from(GJ(e,this.serialize))},"serializeStream"),serialize:a(function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
7
|
+
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:a2.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(d2,"findPs")});var Ut=P((YTe,PP)=>{"use strict";var f2="__dbis__",_2="__txns__",h2="__environment_name__",m2="__dbi_defintion__",p2={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"},E2=["__createdtime__","__updatedtime__"],g2="\uFFFF",CP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},S2=Object.values(CP);PP.exports={AUDIT_STORE_NAME:_2,INTERNAL_DBIS_NAME:f2,DBI_DEFINITION_NAME:m2,SEARCH_TYPES:p2,TIMESTAMP_NAMES:E2,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:h2,TRANSACTIONS_DBI_NAMES_ENUM:CP,TRANSACTIONS_DBIS:S2,OVERFLOW_MARKER:g2}});var Pn=P((WTe,kP)=>{"use strict";var DP=(k(),D($)),LP=Ut(),MP={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},vP=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),UP={500:vP("There was an error processing your request."),400:"Invalid request"},T2=UP[MP.INTERNAL_SERVER_ERROR],A2={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")},R2={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},y2={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"},b2={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 ${LP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${LP.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"},O2={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${DP.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 ${DP.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"},xP={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"},N2={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."},w2={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")},I2={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"},C2={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},P2={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")},BP={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")},HP={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")},D2={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"},L2={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},M2={...xP,...y2,...A2,...N2,...w2,...I2,...C2,...P2,...O2,...BP,...HP,...D2,...L2,...R2};kP.exports={CHECK_LOGS_WRAPPER:vP,HDB_ERROR_MSGS:M2,DEFAULT_ERROR_MSGS:UP,DEFAULT_ERROR_RESP:T2,HTTP_STATUS_CODES:MP,LMDB_ERRORS_ENUM:b2,AUTHENTICATION_ERROR_MSGS:xP,VALIDATION_ERROR_MSGS:BP,ITC_ERRORS:HP}});var me=P((QTe,qP)=>{"use strict";var Fl=Pn(),v2=j(),U2=(k(),D($)),Pm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,FP),this.statusCode=n||Fl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Fl.DEFAULT_ERROR_MSGS[n]?Fl.DEFAULT_ERROR_MSGS[n]:Fl.DEFAULT_ERROR_MSGS[Fl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&v2[s](i)}},hA=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}},mA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function FP(e,t,r,n=U2.LOG_LEVELS.ERROR,s=null,i=!1){if(GP(e))return e;let o=new Pm(e,t,r,n,s);return i&&delete o.stack,o}a(FP,"handleHDBError");function GP(e){return e.__proto__.constructor.name===Pm.name}a(GP,"isHDBError");qP.exports={isHDBError:GP,handleHDBError:FP,ClientError:hA,ServerError:mA,hdb_errors:Fl}});var pt=P((JTe,QP)=>{"use strict";var tf=(k(),D($)),x2=ae(),on=le(),rf=require("path"),B2=require("minimist"),$P=require("fs-extra"),VP=require("lodash");on.initSync();var{CONFIG_PARAMS:zo,DATABASES_PARAM_CONFIG:Jd,SYSTEM_SCHEMA_NAME:Dm}=tf,Xd,Zd,ef;function KP(){if(Xd!==void 0)return Xd;if(on.getHdbBasePath()!==void 0)return Xd=on.get(zo.STORAGE_PATH)||rf.join(on.getHdbBasePath(),tf.DATABASES_DIR_NAME),Xd}a(KP,"getBaseSchemaPath");function YP(){if(Zd!==void 0)return Zd;if(on.getHdbBasePath()!==void 0)return Zd=zP(Dm),Zd}a(YP,"getSystemSchemaPath");function WP(){if(ef!==void 0)return ef;if(on.getHdbBasePath()!==void 0)return ef=on.get(tf.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||rf.join(on.getHdbBasePath(),tf.TRANSACTIONS_DIR_NAME),ef}a(WP,"getTransactionAuditStoreBasePath");function H2(e,t){let r=on.get(zo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||rf.join(WP(),e.toString())}a(H2,"getTransactionAuditStorePath");function zP(e,t){e=e.toString(),t=t&&t.toString();let r=on.get(tf.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||rf.join(KP(),e)}a(zP,"getSchemaPath");function k2(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,B2(process.argv));let n=r[zo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!x2.isObject(n))throw o;i=n}for(let o of i){let c=o[Dm];if(!c)continue;let l=on.get(zo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[Jd.PATH];if(u)return VP.set(l,[Dm,Jd.TABLES,t,Jd.PATH],u),on.setProperty(zo.DATABASES,l),u;let f=c?.[Jd.PATH];if(f)return VP.set(l,[Dm,Jd.PATH],f),on.setProperty(zo.DATABASES,l),f}}let s=r[zo.STORAGE_PATH.toUpperCase()];if(s){if(!$P.pathExistsSync(s))throw new Error(s+" does not exist");let i=rf.join(s,e);return $P.mkdirsSync(i),on.setProperty(zo.STORAGE_PATH,s),i}return YP()}a(k2,"initSystemSchemaPaths");function F2(){Xd=void 0,Zd=void 0,ef=void 0}a(F2,"resetPaths");QP.exports={getBaseSchemaPath:KP,getSystemSchemaPath:YP,getTransactionAuditStorePath:H2,getTransactionAuditStoreBasePath:WP,getSchemaPath:zP,initSystemSchemaPaths:k2,resetPaths:F2}});var an=P((tAe,eD)=>{"use strict";var G2=Pn().LMDB_ERRORS_ENUM,ZTe=require("lmdb"),q2=Ut(),eAe=require("buffer").Buffer,{OVERFLOW_MARKER:jP,MAX_SEARCH_KEY_LENGTH:Lm}=q2,JP=["number","string","symbol","boolean","bigint"];function $2(e){if(e=e?.primaryStore||e,!e)throw new Error(G2.ENV_REQUIRED)}a($2,"validateEnv");function V2(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(V2,"stringifyData");function K2(e){return e instanceof Date?e.valueOf():e}a(K2,"convertKeyValueToWrite");function Y2(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(JP.includes(typeof e))return e.length>Lm?[e.slice(0,Lm)+jP]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(JP.includes(typeof i))i.length>Lm?r.push(i.slice(0,Lm)+jP):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(Y2,"getIndexedValues");var Mm=0,XP=0;function ZP(){XP=Date.now()-performance.now()}a(ZP,"adjustStartTime");ZP();var W2=6e4;setInterval(ZP,W2).unref();function z2(){let e=performance.now()+XP;return e>Mm?(Mm=e,e):(Mm+=488e-6,Mm)}a(z2,"getNextMonotonicTime");eD.exports={validateEnv:$2,stringifyData:V2,convertKeyValueToWrite:K2,getNextMonotonicTime:z2,getIndexedValues:Y2}});var nf=P((nAe,tD)=>{"use strict";var Q2=(k(),D($)).OPERATIONS_ENUM,pA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=Q2.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};tD.exports=pA});var sf=P((oAe,iD)=>{"use strict";var iAe=nf(),vm=(k(),D($)),EA=ae(),rD=j(),j2=require("uuid"),{handleHDBError:Um,hdb_errors:J2}=me(),{HDB_ERROR_MSGS:xm,HTTP_STATUS_CODES:Bm}=J2;iD.exports=nD;function nD(e,t,r){for(let s=0;s<t.length;s++)sD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];X2(i,r,e.operation)}}a(nD,"processRows");nD.validateAttribute=sD;function sD(e){if(Buffer.byteLength(String(e))>vm.INSERT_MAX_CHARACTER_SIZE)throw Um(new Error,xm.ATTR_NAME_LENGTH_ERR(e),Bm.BAD_REQUEST,void 0,void 0,!0);if(EA.isEmptyOrZeroLength(e)||EA.isEmpty(e.trim()))throw Um(new Error,xm.ATTR_NAME_NULLISH_ERR,Bm.BAD_REQUEST,void 0,void 0,!0)}a(sD,"validateAttribute");function X2(e,t,r){if(!e.hasOwnProperty(t)||EA.isEmptyOrZeroLength(e[t])){if(r===vm.OPERATIONS_ENUM.INSERT||r===vm.OPERATIONS_ENUM.UPSERT){e[t]=j2.v4();return}throw rD.error("Update transaction aborted due to record with no hash value:",e),Um(new Error,xm.RECORD_MISSING_HASH_ERR,Bm.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>vm.INSERT_MAX_CHARACTER_SIZE)throw rD.error(e),Um(new Error,xm.HASH_VAL_LENGTH_ERR,Bm.BAD_REQUEST,void 0,void 0,!0)}a(X2,"validateHash")});var oD,Dn,gA,Gl=be(()=>{oD=require("events"),Dn=class extends oD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new gA;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)}},gA=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 _D(e){TA=e}function rJ(){tJ=setInterval(function(){for(let e of SA)if(e.stale){let t=e.getContext()?.url;uD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},eJ).unref()}var AA,lD,uD,dD,fD,aD,SA,Z2,of,cD,TA,nc,Hm,eJ,tJ,km=be(()=>{AA=M(an()),lD=M(me()),uD=M(j()),dD=M(le());k();fD=M(ae()),aD=100,SA=new Set,Z2=(0,fD.convertToMS)(dD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(_D,"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),SA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(SA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(of&&!this.overloadChecked&&performance.now()-cD>Z2)throw new lD.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,AA.getNextMonotonicTime)()),t.timestamp||(t.timestamp=r);let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let h=d;h<this.validated;h++)this.writes[h]?.validate?.(this.timestamp);let _;for(let h=d;h<this.validated;h++){let m=this.writes[h];m&&(m.before||m.beforeIntermediate)&&(_=!0)}if(_)return(async()=>{try{for(let h=0;h<2;h++){let m;for(let S=d;S<this.validated;S++){let g=this.writes[S];if(!g)continue;let R=g[h===0?"before":"beforeIntermediate"];if(R){let E=R();m?m.push?m.push(E):m=[m,E]:m=E}}m&&await(m.push?Promise.all(m):m)}}catch(h){throw this.abort(),h}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.doneWriting?2:1;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),l=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let _=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||_}else l();else for(let _ of this.writes)c(_)},"nextCondition"),u=this.lmdbDb;if(this.writes.length>0&&(u?.retryRisk&&(u.retryRisk*=.99),this.writes.length+(u?.retryRisk||0)<aD>>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 of||(of=s,cD=performance.now(),of.then(()=>{of=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];TA&&h&&i.push(TA(_,h.store.getEntry(h.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return u&&(u.retryRisk=(u.retryRisk||0)+aD/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}},Hm=class extends nc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,AA.getNextMonotonicTime)())}getReadTxn(){}},eJ=3e4;a(rJ,"startMonitoringTxns");rJ()});function Ot(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 hD,sc=be(()=>{hD=M(ci());km();a(Ot,"transaction");(0,hD._assignPackageExport)("transaction",Ot);Ot.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ot.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 yA(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=u(l);for(let h=1;h<e.length;h++){let m=e[h],S=u(m);d=d.concat(S)}let _=new Set;return d.filter(h=>{let m=h.key??h;return _.has(m)?!1:(_.add(m),!0)})}else{let d=u(l),_=f(e.slice(1),!0,l.estimated_count);return _.length>0?o(d,_):d}function u(d){return d.conditions?yA(d.conditions,d.operator,r,n,s,i,o,c):Vl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(m.attribute||m[0])===r.primaryKey,R=lf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=dJ(r.primaryStore,m.estimated_count,h)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Vl(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 ln.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=fi(n.attributes,E);if(T.relationship){if(o.length<2)throw new ln.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=Vl({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 q=!!fi(w.attributes,T.relationship.to)?.elements;H=aJ(H,T,w.primaryStore,q,v)}if(T.relationship.from){let q=a(W=>(W?.key!==void 0&&(W=W.key),Vl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=cJ(H,T,w.primaryStore,v,q)):H=H.flatMap(q)}return H}else if(o.length===1)o=o[0];else throw new ln.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(bA[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]=di.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new ln.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>os.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,_=!1,m=lf(e,n,null,i,S)),typeof f=="string"&&f.length>os.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,os.MAX_SEARCH_KEY_LENGTH)+os.OVERFLOW_MARKER,d=!0,m=m??lf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new ln.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new ln.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 ln.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new ln.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??lf(e,n,null,i,S),!m)throw new ln.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(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:T=>T.value==null&&!(T.metadataFlags&(un|Jo))?Qo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>os.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:Qo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Qo.SKIP)}catch(H){v(H)}}))})}function fi(e,t){if(Array.isArray(t))if(t.length>1){let r=fi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?fi(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function aJ(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 cJ(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 lf(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=fi(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=lf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,R=a((E,T)=>{let w,v;if(S){if(S.from&&m.idFilter){if(!g)if(m.idFilter.idSet?.size===1){for(let q of m.idFilter.idSet)e={attribute:S.from,value:q};g=u(S.from,m.idFilter,!0,!0)}else g=u(S.from,m.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(m):m(w,v):!1},"recordFilter");return R}}switch(l instanceof Date&&(l=l.getTime()),bA[o]||o){case os.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,di.compareKeys)(f,l[0])>=0&&(0,di.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,di.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,di.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,di.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,di.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,di.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new ln.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Gm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function R(E){let T=E[f],w;if(typeof T!="object"||!T||h?w=d(T):Array.isArray(T)?w=T.some(d):T instanceof Date&&(w=d(T.getTime())),_&&(g++,!w&&!R.idFilter&&++S/g*(i-g)>m)){let v=Vl(e,r.transaction.getReadTxn(),!1,t).map(Kl),H=new Set(v);R.idFilter=q=>H.has(Kl(q)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Gm(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/zi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=bA[n]||n,n===os.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=fi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Gm(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*zi(e.indices[i.relationship.from])/(zi(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=zi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=iJ*zi(e.primaryStore)+1:n==="between"?r.estimated_count=sJ*zi(e.primaryStore)+1:n==="sort"?r.estimated_count=zi(e.primaryStore)+1:r.estimated_count=nJ*zi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function qm(e){if(e)if(jo=e,ql.lastIndex=0,lJ.test(e))try{let t=af(new $l,"");if(cn!==jo.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${cn} in '${jo}'`,t}else return new URLSearchParams(e)}function af(e,t){let r=ql,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(jo);){cn=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=mD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=cf(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=oJ[d],l=RA[i]?mD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=cf(f);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&pD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else Fm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(cf(f)),s=void 0;break;case"(":ql.lastIndex=cn;let h=af(f?[]:new $l,")");switch(f){case"":Fm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=ED(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}jo[cn]===","?r.lastIndex=++cn: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");ql.lastIndex=cn,_=af([],"}"),_.name=f,e.push(_),jo[cn]===","?r.lastIndex=++cn:o=!0;break;case"[":ql.lastIndex=cn,f?(_=af(new $l,"]"),_.name=f):_=af(e.conditions?new $l:[],"]"),e.conditions?(Fm(e,u),e.conditions.push(_),s=null):e.push(_),jo[cn]===","?r.lastIndex=++cn:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let m={comparator:i||"equals",attribute:s,value:l(f)};i==="eq"&&pD(m,f),Fm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(cf(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?uJ:ql,r.lastIndex=cn),cn===jo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Fm(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 cf(e){return e.indexOf(".")>-1?e.split(".").map(cf):decodeURIComponent(e)}function mD(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 ln.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function pD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new ln.ClientError("wildcard can only be used at the end of a string")}function ED(e){let t=gD(e[0]);return e.length>1&&(t.next=ED(e.slice(1))),t}function gD(e){if(Array.isArray(e)){let t=gD(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 Kl(e){return Array.isArray(e)?e.join("\0"):e}function zi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function dJ(e,t,r){return t*r/zi(e)}var ln,os,di,Qo,nJ,sJ,iJ,oJ,RA,bA,lJ,ql,uJ,cn,jo,$l,ic,uf=be(()=>{ln=M(me()),os=M(Ut()),di=require("ordered-binary"),Qo=require("lmdb");df();nJ=.3,sJ=.1,iJ=.05,oJ={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},RA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(yA,"executeConditions");a(Vl,"searchByIndex");a(fi,"findAttribute");a(aJ,"joinTo");a(cJ,"joinFrom");bA={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(lf,"filterByType");a(Gm,"estimateCondition");lJ=/[()[\]|!<>.]|(=\w*=)/,ql=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,uJ=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(qm,"parseQuery");a(af,"parseBlock");a(Fm,"assignOperator");a(cf,"decodeProperty");a(mD,"typedDecoding");a(pD,"wildcardDecoding");a(ED,"toSortObject");a(gD,"toSortEntry");$l=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(Kl,"flattenKey");a(zi,"estimatedEntryCount");a(dJ,"intersectionEstimate");ic=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var NA={};Ue(NA,{MultiPartId:()=>Vm,Resource:()=>qr,snake_case:()=>_J,transformForSelect:()=>Km});function _J(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function SD(e,t){if(oc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(oc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Vm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){oc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return oc=!0,null;e[e.length-1]==="/"&&(oc=!0)}return t.coerceId(decodeURIComponent(e))}function Ln(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new 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 h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return Ot(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new $m(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new $m(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Mn(e,t){let r=new RD.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 OA(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 Km(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):OA(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(OA(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(OA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=Km(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var TD,AD,RD,fJ,qr,$m,oc,Vm,Xo=be(()=>{TD=require("crypto");Gl();AD=M(ci()),RD=M(me());sc();uf();fJ={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},qr=class{static{a(this,"Resource")}#e;#t;#n;static transactions;static directURLMapping=!1;constructor(t,r){this.#e=t;let n=r?.getContext?r.getContext()??null:void 0;this.#t=n!==void 0?n:r||null}static get=Ln(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=Km(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Ln(function(t,r,n,s){if(Array.isArray(s)&&t.#n){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,u=l.getResource(c[l.primaryKey],n,{async:!0});u.then?i.push(u.then(f=>f.put(c,n))):i.push(u.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Mn(t,"put")},{hasContent:!0,type:"update"});static patch=Ln(function(t,r,n,s){return t.patch?t.patch(s,r):Mn(t,"patch")},{hasContent:!0,type:"update"});static delete=Ln(function(t,r,n,s){return t.delete?t.delete(r):Mn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,TD.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={}),Ot(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Mn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=Ln(function(t,r,n,s){return t.invalidate?t.invalidate(r):Mn(t,"delete")},{hasContent:!1,type:"update"});static post=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Ln(function(t,r,n,s){return t.connect?t.connect(s,r):Mn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Ln(function(t,r,n,s){return t.subscribe?t.subscribe(r):Mn(t,"subscribe")},{type:"read"});static publish=Ln(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Mn(t,"publish")},{hasContent:!0,type:"create"});static search=Ln(function(t,r,n,s){let i=t.search?t.search(r):Mn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Km(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Ln(function(t,r,n,s){return t.search?t.search(s,r):Mn(t,"search")},{hasContent:!0,type:"read"});static copy=Ln(function(t,r,n,s){return t.copy?t.copy(s,r):Mn(t,"copy")},{hasContent:!0,type:"create"});static move=Ln(function(t,r,n,s){return t.move?t.move(s,r):Mn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Mn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return qm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&fJ[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:SD(t,this),isCollection:oc}}let i=SD(t,this);return oc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Dn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Dn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,AD._assignPackageExport)("Resource",qr);a(_J,"snake_case");$m=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(SD,"pathToId");Vm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(Ln,"transactional");a(Mn,"missingMethod");a(OA,"selectFromObject");a(Km,"transformForSelect")});var Zo,wA=be(()=>{Zo=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 Yl={};Ue(Yl,{server:()=>Ke});var yD,Ke,Pr=be(()=>{yD=M(ci()),Ke={};(0,yD._assignPackageExport)("server",Ke)});var ND={};Ue(ND,{Resources:()=>Ym,keyArrayToString:()=>Wl,resetResources:()=>hJ,resources:()=>as});function hJ(){return as=new Ym,Ke.resources=as,as}function Wl(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var bD,OD,Ym,as,zl=be(()=>{sc();wA();bD=M(j()),OD=M(me());Pr();Ym=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 OD.ServerError(`Conflicting paths for ${t}`);bD.default.error(c),i.Resource=new Zo(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 Ot(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(hJ,"resetResources");a(Wl,"keyArrayToString")});var IA=P((DAe,wD)=>{if(__filename.endsWith("dev.js")){let e=require("fast-glob"),{tmpdir:t}=require("node:os"),{relative:r,join:n}=require("node:path"),{existsSync:s,statSync:i,readFileSync:o,writeFileSync:c,unlinkSync:l}=require("node:fs"),{isMainThread:u}=require("node:worker_threads"),{spawnSync:f,spawn:d}=require("node:child_process");process.setSourceMapsEnabled(!0);let{PACKAGE_ROOT:_}=mt(),h=["bin","components","dataLayer","resources","server","sqlTranslator","upgrade","utility","validation"],m="ts-build";if(u){let R=!1,E=!1;if(E=s(n(_,m))){let T=new Set;e.sync(h.map(w=>`${w}/**/*.ts`),{cwd:_}).forEach(w=>{let v=0,H=0;try{T.add(w),v=i(n(_,w)).mtimeMs-5e3,H=i(n(_,m,w.replace(/.ts$/,".js"))).mtimeMs}catch{}v>H&&(R=!0)}),e.sync(h.map(w=>`${w}/**/*.js`),{cwd:n(_,m)}).forEach(w=>{if(!T.has(w.replace(/.js$/,".ts")))try{l(n(_,m,w))}catch{}})}else R=!0;if(R){console.log("Compiling TypeScript...");let T=f("npx",["tsc"],{cwd:_});if(T.stdout?.length&&console.log(T.stdout.toString()),T.stderr?.length&&console.log(T.stderr.toString()),E){let w=n(t(),"harperdb-tsc.pid"),v=!1;if(s(w))try{process.kill(+o(w,"utf8"),0),v=!0}catch{}if(!v){console.log("Starting background TypeScript compilation...");let H=d("npx",["tsc","--watch"],{detached:!0,cwd:_,stdio:"ignore"});H.on("error",q=>{console.error("Error trying to compile TypeScript",q)}),H.pid&&c(w,String(H.pid),"utf-8"),H.unref()}}}}let S=wD.constructor,g=S._findPath;S._findPath=function(R,E,T){if(R.startsWith(".")&&!T&&E.length===1&&E[0].startsWith(_)&&!E[0].includes("node_modules")){let w=r(_,E[0]),v;w.startsWith(m)?v=n(_,r(m,w)):v=n(_,m,w);let H=n(v,R),q=H+".js";if(s(q))return q;if(H.includes(".")&&s(H))return H}return g(R,E,T)}}});var DA={};Ue(DA,{loadGQLSchema:()=>EJ,start:()=>PA,startOnMainThread:()=>pJ});function PA({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:f}=await import("graphql"),d=o(new c(r.toString(),s)),_=new Map,h=[],m;for(let 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,h.push(w)}if(W.name.value==="sealed"&&(w.sealed=!0),W.name.value==="splitSegments"&&(w.splitSegments=!0),W.name.value==="replicate"&&(w.replicate=!0),W.name.value==="export"){w.export=!0;for(let se of W.arguments)typeof w.export!="object"&&(w.export={}),w.export[se.name.value]=se.value.value}}let v=!1,q={};for(let W of R.fields){let te=H(W.type);te.name=W.name.value,T.push(te),q[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,q)},te.version==null&&(te.version=ue)}else ne.name.value==="version"&&(te.version=ne.value.value);te.computed=te.computed||!0}else if(Y==="relationship"){let ne={};for(let ue of se.arguments)ne[ue.name.value]=ue.value.value;te.relationship=ne}else if(Y==="createdTime")te.assignCreatedTime=!0;else if(Y==="updatedTime")te.assignUpdatedTime=!0;else if(Y==="expiresAt")te.expiresAt=!0;else if(Y==="allow"){let ne=te.authorizedRoles=[];for(let ue of se.arguments)ue.name.value==="role"&&ne.push(ue.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,se.loc)}}w.type=E,E==="Query"&&(m=w)}function S(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):mJ.includes(R.type)||(0,CD.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 h)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,CA.dirname)(n),R.tableClass):i.set((0,CA.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new ID.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 CA,ID,CD,mJ,pJ,EJ,PD=be(()=>{CA=require("path"),ID=require("node:vm");ve();CD=M(tt()),mJ=["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(PA,"start");pJ=PA,EJ=PA({ensureTable:ut}).handleFile});var BD={};Ue(BD,{parse:()=>MA,streamAsJSON:()=>ff,stringify:()=>ac});function ff(e){return new LA({value:e})}function DD(e){return console.error(e),JSON.stringify(e.toString())}function LD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function ac(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===UD)return xD(e);if(t.resolution)return t.resolution.then(()=>ac(e));throw t}}function xD(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+=xD(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+ac(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function MA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),TJ.test(e)?gJ.parse(e):JSON.parse(e)):null}var MD,vD,gJ,SJ,UD,LA,TJ,vA=be(()=>{MD=require("stream"),vD=M(require("json-bigint-fixes")),gJ=(0,vD.default)({useNativeBigInt:!0}),SJ=1e4,UD={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw UD};a(ff,"streamAsJSON");LA=class extends MD.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),DD)}catch(s){yield DD(s)}else yield ac(t)}else yield ac(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);LD(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>SJ?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 LD(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(DD,"handleError");a(LD,"when");a(ac,"stringify");a(xD,"jsStringify");TJ=/[[,:]\s*-?\d{16,}/;a(MA,"parse")});var _i=P(zm=>{var Wm=j();for(let e of["trace","debug","info","warn","error","fatal","notify"])Wm.logsAtLevel(e)&&(zm[e]=Wm[e]);zm.loggerWithTag=e=>Wm.loggerWithTag(e,!0);zm.setLogLevel=Wm.setLogLevel});var ip={};Ue(ip,{Blob:()=>hi,blobsWereEncoded:()=>lc,databasePaths:()=>xA,decodeBlobsWithWrites:()=>np,decodeFromDatabase:()=>uc,decodeWithBlobCallback:()=>sp,deleteBlob:()=>ep,deleteBlobsInObject:()=>ea,deleteRootBlobPathsForDB:()=>HA,encodeBlobsAsBuffers:()=>PJ,encodeBlobsWithFilePath:()=>rp,findBlobsInObject:()=>jl,getFileId:()=>tp,getFilePathForBlob:()=>WD,getRootBlobPathsForDB:()=>pf,setDeletionDelay:()=>bJ});function VD(){}function ep(e){let t=WD(e);t&&setTimeout(()=>{(0,Qe.unlink)(t,r=>{r&&Qi.default.debug?.("Error trying to remove blob file",r)})},KD)}function bJ(e){KD=e}function YD(e){let t=dn.get(e);if(!t)t={storageIndex:0,fileId:null,store:fn},dn.set(e,t);else{if(t.saving)return t;t.store=fn}return NJ(t),t.source?UA(e,t.source,t):t.contentBuffer?OJ(e,t):UA(e,hf.Readable.from(e.stream()),t),t}function UA(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,Qe.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(RJ),h=(0,Xm.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(AJ),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(_r),T=new DataView(E.buffer);return R|=BigInt(o?BA:$D)<<48n,T.setBigInt64(0,R),E}a(m,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,Qe.close)(R),u(g)):c?(0,Qe.fdatasync)(R,E=>{E&&u(E),l(),(0,Qe.close)(R)}):(l(),(0,Qe.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-_r;e.size=g,(0,Qe.write)(d.fd,m(g),0,_r,0,S)}})}),e}function tp(e){return dn.get(e)?.fileId}function WD(e){let t=dn.get(e);return t?.fileId&&mf(t)}function pf(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=xA.get(e);if(!t){if(!e.databaseName)return Qi.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,Zm.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Ji.join)(n,e.databaseName)):t=[(0,Ji.join)((0,Zm.getHdbBasePath)(),"blobs",e.databaseName)],xA.set(e,t)}return t}async function HA(e){let t=pf(e);t&&await Promise.all(t.map(r=>zD(r)))}async function zD(e){if((0,Qe.existsSync)(e)){for(let t of await(0,xs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await zD((0,Ji.join)(e,t.name));else try{await(0,xs.unlink)((0,Ji.join)(e,t.name))}catch(r){Qi.default.warn?.("Error deleting file",r)}try{await(0,xs.rmdir)(e)}catch(t){Qi.default.warn?.("Error deleting directory",t)}}}function mf({storageIndex:e,fileId:t,store:r}){let n=pf(r);return(0,Ji.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 OJ(e,t){let r=t.contentBuffer,n=r.length;if(!(n<qD))return e.size=n,UA(e,hf.Readable.from([r]),t)}function NJ(e){let t=pf(e.store),r=wJ(),n=t?.length>1?IJ(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=mf(e),o=(0,Ji.dirname)(i);(0,Qe.existsSync)(o)||(0,GD.ensureDirSync)(o),e.filePath=i}function wJ(){let e=FD.get(fn);if(!e){let t=0,r=pf(fn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,Qe.existsSync)(n))for(let c of(0,Qe.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,Ji.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(fn.getUserSharedBuffer("blob-file-id",e.buffer)),FD.set(fn,e)}return Number(Atomics.add(e,0,1n))}function IJ(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(Jm);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,CJ(e)),e.frequencyTable[t%Jm]}async function CJ(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(Jm),n=t.map(s=>1/s);for(let s=0;s<Jm;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 rp(e,t,r){Ql=t,fn=r,lc=!1;try{return e()}finally{Ql=void 0,fn=void 0}}function PJ(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function np(e,t){try{Dr=[],cc=t,e()}catch(n){throw cc=void 0,Dr=void 0,n}cc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function sp(e,t,r){fn=r;try{return cc=t,e()}finally{cc=void 0}}function uc(e,t){return fn=t,e()}function ea(e){jl(e,t=>{ep(t)})}function jl(e,t){if(e instanceof hi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&jl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&jl(e[r],t)}}function DJ(){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 ji,xs,Qe,Xm,hf,GD,Zm,Ji,Qi,qD,_r,$D,BA,HD,AJ,RJ,kD,dn,cc,hi,Ql,Dr,fn,lc,_f,Qm,yJ,jm,KD,xA,FD,Jm,cs=be(()=>{ji=require("msgpackr"),xs=require("node:fs/promises"),Qe=require("node:fs"),Xm=require("node:zlib"),hf=require("node:stream"),GD=require("fs-extra"),Zm=M(le());k();Ji=require("path"),Qi=M(_i());Xi();qD=8192,_r=8,$D=0,BA=1,HD=255,AJ=new Uint8Array([0,$D,255,255,255,255,255,255]),RJ=new Uint8Array([0,BA,255,255,255,255,255,255]),kD=0xffffffffffff,dn=new WeakMap,hi=global.Blob||DJ(),lc=!1,_f=new Uint8Array(8),Qm=new DataView(_f.buffer),yJ=6e4;a(VD,"InstanceOfBlobWithNoConstructor");VD.prototype=hi.prototype;jm=class e extends VD{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=dn.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):(FA()&&kA(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=dn.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=mf(t),o,c=a(async()=>{let l,u=_r;try{if(l=await(0,xs.readFile)(i),l.length>=_r){l.copy(_f,0,0,_r);let d=Qm.getBigUint64(0);if(Number(d>>48n)===HD)throw new Error("Error in blob: "+buffer.subarray(_r));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<kD&&(this.size=u,this.#t))for(let _ of this.#t)_(u)}}catch(d){if(d.code!=="ENOENT")throw d;l=Buffer.alloc(0)}function f(d){if(u>d.length){let _=t.store,h=t.fileId+":blob";if(o)throw new Error("Incomplete blob");return new Promise((m,S)=>{if(_.attemptLock(h,0,()=>(o=!0,m(c()))))return o=!0,_.unlock(h,0),m(c())})}return(n!=null||r!=null)&&(d=d.subarray(r??0,n??d.length)),d}return a(f,"checkCompletion"),l[1]===BA?new Promise((d,_)=>{(0,Xm.deflate)(l.subarray(_r),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(_r))},"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=dn.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=mf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,Qe.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(Qi.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(R,E)},20).unref();E(T),h.#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(q){(0,Qe.close)(o),clearTimeout(f),u&&u.close(),w(q),h.#e?.forEach(W=>W(q))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,Qe.read)(o,H,0,H.length,c,(q,W,te)=>{if(l+=W,q)return v(q);if(c===0){if(W<_r){R-- >0&&d!==!1?(m(),Qi.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(Qi.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(_f,0,0,_r);let se=Qm.getBigUint64(0);if(Number(se>>48n)===HD)return v(new Error("Error in blob: "+te.subarray(_r)));if(g=Number(se&0xffffffffffffn),g<kD&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(_r,W),l-=_r}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,Qe.read)(o,se,0,_r,0,Y=>{if(Y)return v(Y);if(_f.set(se),g=Number(Qm.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},yJ).unref():(u=(0,Qe.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,Qe.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 Qi.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,Qe.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,Qe.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=dn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};dn.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)};dn.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(fn=t?.primaryStore?.rootStore,!fn)throw new Error("No target table specified");return YD(this).saving??Promise.resolve()}},KD=500;a(ep,"deleteBlob");a(bJ,"setDeletionDelay");global.createBlob=function(e,t){let r=new jm(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(dn.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof hf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=hf.Readable.from(e);else throw new Error("Invalid source type");return r};a(YD,"saveBlob");a(UA,"writeBlobWithStream");a(tp,"getFileId");a(WD,"getFilePathForBlob");xA=new Map;a(pf,"getRootBlobPathsForDB");a(HA,"deleteRootBlobPathsForDB");a(zD,"rimrafSteadily");a(mf,"getFilePath");a(OJ,"writeBlobWithBuffer");a(NJ,"generateFilePath");FD=new Map;a(wJ,"getNextFileId");Jm=128;a(IJ,"getNextStorageIndex");a(CJ,"createFrequencyTableForStoragePaths");a(rp,"encodeBlobsWithFilePath");a(PJ,"encodeBlobsAsBuffers");a(np,"decodeBlobsWithWrites");a(sp,"decodeWithBlobCallback");a(uc,"decodeFromDatabase");a(ea,"deleteBlobsInObject");a(jl,"findBlobsInObject");(0,ji.addExtension)({Class:hi,type:11,unpack:a(function(e){let t=(0,ji.unpack)(e),r=new jm;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(dn.set(r,{storageIndex:t[1],fileId:t[2],store:fn}),cc)return cc(r)??r;if(!fn)throw new Error("No store specified, cannot load blob from storage")}else dn.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=dn.get(e);if(Ql!==void 0&&(lc=!0,t?.recordId!==void 0&&t.recordId!==Ql))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<qD)return r.size=t.contentBuffer.length,(0,ji.pack)([r,t.contentBuffer])}if(Ql!==void 0){if(t=YD(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Ql,(0,ji.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,Qe.readFileSync)(mf(t));if(n.length>=_r&&(n.copy(_f,0,0,_r),Number(Qm.getBigUint64(0)&0xffffffffffffn)===n.length-_r))return Buffer.concat([(0,ji.pack)([r]),n]);if(Dr)Dr.push(e.bytes());else throw new Error("Incomplete blob");return Buffer.alloc(0)}catch(n){if(n.code==="ENOENT"&&Dr)return Dr.push(e.bytes()),Buffer.alloc(0);throw n}else throw new Error("Blob has no storage info or buffer attached to it")},"pack")});(0,ji.addExtension)({Class:Promise,type:12,pack(){throw new Error("Cannot encode a promise")}});a(DJ,"polyfillBlob")});var rL={};Ue(rL,{asyncSerialization:()=>kA,contentTypes:()=>VA,findBestSerializer:()=>ap,getDeserializer:()=>to,hasAsyncSerialization:()=>FA,registerContentHandlers:()=>Sf,serialize:()=>Tf,serializeMessage:()=>ta,toCsvStream:()=>op});function MJ(e){try{return e?.[0]===123?$A(e):e}catch{return e}}function Sf(e){e.register(UJ,{serializers:[{regex:/^application\/json$/,serializer:ff},{regex:/^application\/cbor$/,serializer:a(function(t){return new dc.EncoderStream(gf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?fc.Readable.from((0,mi.encodeIter)(t,gf)):(0,mi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),op(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,dc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function ap(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=$r.get(u);if(h){let m=(h.q||1)*d;m>s&&(n=h,i=h.type||u,s=m,o=_)}}if(!n){if(r)throw new JD.ClientError("No supported content types found in Accept header, supported types include: "+Array.from($r.keys()).join(", "),406);n=$r.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Tf(e,t,r){let n=jD&&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 hi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=ap(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}),qA.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,eo.createBrotliCompress)({params:{[eo.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?eo.constants.BROTLI_MODE_TEXT:eo.constants.BROTLI_MODE_GENERIC,[eo.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>jD?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,eo.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ta(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Zi=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=ap(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Ef(e);return Zi?.length>0?(Zi.length===1?Zi[0]:Promise.all(Zi)).then(()=>ta(e,t,!0)):n}finally{Zi=void 0}}function kA(e){if(Zi)Zi.push(e);else throw new Error("Unable to serialize asynchronously")}function FA(){return!!Zi}function xJ(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 HJ(e){return BJ.includes(e)}function kJ(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 to(e="",t=!1){let r=kJ(e),n=r.type&&$r.get(r.type)?.deserialize||FJ(r);return t?s=>xJ(s).then(n):n}function FJ(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!HJ(e.parameters.charset)&&qA.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 $A(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function GJ(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 op(e,t){let r=fc.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 LJ(n,s);return r.pipe(i)}var mi,dc,eo,JD,fc,XD,GA,ZD,qA,LJ,eL,Ef,$A,gf,$r,VA,QD,tL,vJ,UJ,jD,Zi,BJ,Xi=be(()=>{vA();mi=require("msgpackr"),dc=require("cbor-x"),eo=require("zlib"),JD=M(me()),fc=M(require("stream"));Pr();XD=M(ci()),GA=M(le());k();ZD=M(require("yaml")),qA=M(_i());cs();({Transform:LJ}=require("json2csv")),eL=GA.default.get(U.SERIALIZATION_BIGINT)!==!1,Ef=eL?ac:JSON.stringify,$A=eL?MA:JSON.parse,gf={useRecords:!1,useToJSON:!0},$r=new Map,VA=$r;Ke.contentTypes=VA;(0,XD._assignPackageExport)("contentTypes",VA);$r.set("application/json",{serializeStream:ff,serialize:Ef,deserialize(e){return $A(e)},q:.8});QD=new dc.Encoder(gf);$r.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new dc.EncoderStream(gf).end(e)},serialize:QD.encode,deserialize:QD.decode,q:1});$r.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?fc.Readable.from((0,mi.encodeIter)(e,gf)):(0,mi.pack)(e)},serialize:mi.pack,deserialize:mi.unpack,q:.9});$r.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),op(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]),op(e,e?.getColumns?.())},q:.1});$r.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return fc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});$r.set("text/yaml",{serialize(e){return ZD.stringify(e,{aliasDuplicateObjects:!1})},q:.7});$r.set("text/event-stream",{serializeStream:a(function(e){return fc.Readable.from(GJ(e,this.serialize))},"serializeStream"),serialize:a(function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
8
8
|
`),e.data){let r=e.data;typeof r=="object"&&(r=Ef(r)),t+="data: "+r+`
|
|
9
9
|
`}return e.id&&(t+="id: "+e.id+`
|
|
10
10
|
`),e.retry&&(t+="retry: "+e.retry+`
|