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.
@@ -7,7 +7,7 @@ Caused by:`));else if(typeof u=="object")try{n+=JSON.stringify(u)}catch{n+="Obje
7
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:l2.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(_2,"findPs")});var Ut=P((WTe,DP)=>{"use strict";var h2="__dbis__",m2="__txns__",p2="__environment_name__",E2="__dbi_defintion__",g2={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"},S2=["__createdtime__","__updatedtime__"],T2="\uFFFF",PP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},A2=Object.values(PP);DP.exports={AUDIT_STORE_NAME:m2,INTERNAL_DBIS_NAME:h2,DBI_DEFINITION_NAME:E2,SEARCH_TYPES:g2,TIMESTAMP_NAMES:S2,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:p2,TRANSACTIONS_DBI_NAMES_ENUM:PP,TRANSACTIONS_DBIS:A2,OVERFLOW_MARKER:T2}});var Pn=P((zTe,FP)=>{"use strict";var LP=(k(),D($)),MP=Ut(),vP={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},UP=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),xP={500:UP("There was an error processing your request."),400:"Invalid request"},R2=xP[vP.INTERNAL_SERVER_ERROR],y2={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")},b2={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},O2={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"},N2={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 ${MP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${MP.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"},w2={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${LP.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 ${LP.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"},BP={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"},I2={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."},C2={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")},P2={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"},D2={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},L2={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")},HP={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")},kP={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")},M2={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"},v2={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},U2={...BP,...O2,...y2,...I2,...C2,...P2,...D2,...L2,...w2,...HP,...kP,...M2,...v2,...b2};FP.exports={CHECK_LOGS_WRAPPER:UP,HDB_ERROR_MSGS:U2,DEFAULT_ERROR_MSGS:xP,DEFAULT_ERROR_RESP:R2,HTTP_STATUS_CODES:vP,LMDB_ERRORS_ENUM:N2,AUTHENTICATION_ERROR_MSGS:BP,VALIDATION_ERROR_MSGS:HP,ITC_ERRORS:kP}});var me=P((jTe,$P)=>{"use strict";var Fl=Pn(),x2=j(),B2=(k(),D($)),Pm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,GP),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&&x2[s](i)}},_A=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}},hA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function GP(e,t,r,n=B2.LOG_LEVELS.ERROR,s=null,i=!1){if(qP(e))return e;let o=new Pm(e,t,r,n,s);return i&&delete o.stack,o}a(GP,"handleHDBError");function qP(e){return e.__proto__.constructor.name===Pm.name}a(qP,"isHDBError");$P.exports={isHDBError:qP,handleHDBError:GP,ClientError:_A,ServerError:hA,hdb_errors:Fl}});var mA=P(VP=>{"use strict";var H2={cert:"-----BEGIN CERTIFICATE-----\rMIIDXDCCAkSgAwIBAgIFNTE4MzQwDQYJKoZIhvcNAQELBQAwXTEXMBUGA1UEAxMO\rSGFycGVyREIsIEluYy4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UE\rBxMGRGVudmVyMRcwFQYDVQQKEw5IYXJwZXJEQiwgSW5jLjAeFw0yMjAzMTEyMzAz\rNDlaFw0yNzAzMTAyMzAzNDlaMF0xFzAVBgNVBAMTDkhhcnBlckRCLCBJbmMuMQsw\rCQYDVQQGEwJVUzELMAkGA1UECBMCQ08xDzANBgNVBAcTBkRlbnZlcjEXMBUGA1UE\rChMOSGFycGVyREIsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\rAQCsEUlBF8WImS78rCFXVKyntxfrW++4qZ3hGnoD2MHZAuDHyeP/5eGnaE9GQhKc\r4DwG4DGvh0wP2zIYnBfiQ3L2ZtnlDR9ZkKIQYGlVxTUn6T43krhK5nZKqDF43Yg3\rZEvO3cbJBjiKZx0eA2/toehdSsTAHHQx5gTDcggNe2tgoJHYPwi9YF/AxSBZrbgb\ryWlYgtYDmF32ytHP03GUCIdKOFuBPsHTGu4SkdEIdLIqO9oglW1YFH5qZ6NiwApW\rsP+GCuqOwDXXbdjr75iq9Tq/CDrjGFLaTPmvd2Q0qG/BtaCll0ghpG+yIHvt/iQs\rajS+LxEWAnVlGMaDdFErbDUtAgMBAAGjIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYD\rVR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4IBAQASR4YW/rPK7PNArHVe9zzM\rb0rKNX/2T9/0nybRhmE/+hdlSgliTAeebmwkUS2APckmekYt/q2ZY2NS65Fo/jjp\rG8TJrtcF4h+ylVqUp0ZXQLFtIsr7r2JZA7hJ6njW6G4DHSZ0gxtECLi4CBlTjzm5\rNmnmIDObvGRTuqmcdAZmXeObbta/He2XIzietukPAYX062pNM+G5XT5UM1eG/Vlp\rN86vjhpyI+ffKy+C60SJqxmKM3ydgN7oLscE7+2wLPN25XqN4W99OwGsp5dTdu/f\r5lPtFayXdJ55e/sNQKmGN+UGLrL05c2MWgjb8U/LFilnupUianceoeSERZmVjzKX\r-----END CERTIFICATE-----\r".replace(/\r/g,`\r
8
8
  `),key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
9
9
  `)},k2="certificate.pem",F2="privateKey.pem",G2="caCertificate.pem",q2="natsCertificate.pem",$2="natsCaCertificate.pem",Tt={DEFAULT:"default","DEFAULT-CA":"default-ca",SERVER:"server",CA:"ca","OPERATIONS-API":"operations-api","OPERATIONS-CA":"operations-ca"},V2={tls_certificate:Tt.SERVER,tls_certificateAuthority:Tt.CA,customFunctions_tls_certificate:Tt.SERVER,customFunctions_tls_certificateAuthority:Tt.CA,operationsApi_tls_certificate:Tt["OPERATIONS-API"],operationsApi_tls_certificateAuthority:Tt["OPERATIONS-CA"]},K2={[Tt.SERVER]:2,[Tt.DEFAULT]:1},Y2={[Tt["OPERATIONS-API"]]:3,[Tt.SERVER]:2,[Tt.DEFAULT]:1},W2={[Tt["OPERATIONS-API"]]:3,[Tt.SERVER]:2,[Tt.DEFAULT]:1},z2={[Tt["OPERATIONS-CA"]]:3,[Tt.CA]:2,[Tt["DEFAULT-CA"]]:1},Q2={[Tt["OPERATIONS-CA"]]:3,[Tt.CA]:2,[Tt["DEFAULT-CA"]]:1},j2={[Tt.CA]:2,[Tt["DEFAULT-CA"]]:1};Object.assign(VP,{CERTIFICATE_PEM_NAME:k2,PRIVATEKEY_PEM_NAME:F2,CA_PEM_NAME:G2,CERT_NAME:Tt,CERT_CONFIG_NAME_MAP:V2,CERT_PREFERENCE_APP:K2,CERT_PREFERENCE_OPS:Y2,CERT_PREFERENCE_REP:W2,CA_CERT_PREFERENCE_REP:z2,CA_CERT_PREFERENCE_OPS:Q2,CA_CERT_PREFERENCE_APP:j2,CERTIFICATE_VALUES:H2,NATS_CERTIFICATE_PEM_NAME:q2,NATS_CA_PEM_NAME:$2})});var tt=P((ZTe,KP)=>{"use strict";var on=require("validate.js");on.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||on.validators.type.checks[t](e)?null:` must be a '${t}' value`};on.validators.type.checks={Object:a(function(e){return on.isObject(e)&&!on.isArray(e)},"Object"),Array:on.isArray,Integer:on.isInteger,Number:on.isNumber,String:on.isString,Date:on.isDate,Boolean:a(function(e){return typeof e=="boolean"},"Boolean")};on.validators.hasValidFileExt=function(e,t){return on.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};KP.exports={validateObject:J2,validateObjectAsync:X2,validateBySchema:Z2};function J2(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=on(e,t,{format:"flat"});return r?new Error(r):null}a(J2,"validateObject");async function X2(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await on.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(X2,"validateObjectAsync");function Z2(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(Z2,"validateBySchema")});var EA=P((rAe,JP)=>{"use strict";var QP=require("fs-extra"),Ee=require("joi"),eJ=require("os"),{boolean:He,string:ut,number:jt,array:zo}=Ee.types(),{totalmem:YP}=require("os"),nc=require("path"),tJ=j(),pA=ae(),tAe=mA(),WP=(k(),D($)),rJ=tt(),zP="log",nJ="components",sJ="Invalid logging.rotation.maxSize unit. Available units are G, M or K",iJ="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",oJ="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",aJ="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",cJ="rootPath config parameter is undefined",an=Ee.alternatives([jt.min(0),ut]).optional().empty(null),Dm=Ee.alternatives([zo.items(ut,{host:ut.required(),port:an},{hostname:ut.required(),port:an}).empty(null),zo.items(ut)]),di,jP=!1;JP.exports={configValidator:lJ,routesValidator:mJ,route_constraints:Dm};function lJ(e,t=!1){if(jP=t,di=e.rootPath,pA.isEmpty(di))throw cJ;let r=He.optional(),n=jt.min(0).max(1e3).empty(null).default(hJ),s=ut.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Xd),i=ut.optional().empty(null),o=ut.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=Ee.string().empty(null).default(Xd),l=Ee.custom(dJ).empty(null).default(Xd),u=e.clustering?.enabled,f=Ee.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return u===!0?d=Ee.object({enabled:r,hubServer:Ee.object({cluster:Ee.object({name:Ee.required().empty(null),network:Ee.object({port:an,routes:Dm}).required()}).required(),leafNodes:Ee.object({network:Ee.object({port:an}).required()}).required(),network:Ee.object({port:an}).required()}).required(),leafServer:Ee.object({network:Ee.object({port:an,routes:Dm}).required(),streams:Ee.object({maxAge:jt.min(120).allow(null).optional(),maxBytes:jt.min(1).allow(null).optional(),maxMsgs:jt.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:Ee.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:He.optional(),databaseLevel:He.optional(),tls:Ee.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:He.required(),verify:He.optional()}),user:ut.optional().empty(null)}).optional():d=Ee.object({enabled:r,tls:Ee.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:He.optional()})}).optional(),Ee.object({authentication:Ee.alternatives(Ee.object({authorizeLocal:He,cacheTTL:jt.required(),cookie:Ee.object({domains:zo.items(ut).optional(),expires:ut.optional()}),enableSessions:He,hashFunction:ut.valid("md5","sha256","argon2id").optional().empty(null)}),He).optional(),analytics:Ee.object({aggregatePeriod:jt}),replication:Ee.object({hostname:Ee.alternatives(ut,jt).optional().empty(null),url:ut.optional().empty(null),port:an,securePort:an,routes:zo.optional().empty(null),databases:Ee.alternatives(ut,zo),enableRootCAs:He.optional(),copyTablesToCatchUp:He.optional()}).optional(),componentsRoot:s.optional(),clustering:d,localStudio:Ee.object({enabled:r}).required(),logging:Ee.object({auditAuthEvents:Ee.object({logFailed:He,logSuccessful:He}),file:He.required(),level:Ee.valid("notify","fatal","error","warn","info","debug","trace"),rotation:Ee.object({enabled:He.optional(),compress:He.optional(),interval:ut.custom(_J).optional().empty(null),maxSize:ut.custom(fJ).optional().empty(null),path:ut.optional().empty(null).default(Xd)}).required(),root:s,stdStreams:He.required(),auditLog:He.required()}).required(),operationsApi:Ee.object({network:Ee.object({cors:He.optional(),corsAccessList:zo.optional(),headersTimeout:jt.min(1).optional(),keepAliveTimeout:jt.min(1).optional(),port:an,domainSocket:Ee.optional().empty("hdb/operations-server").default(Xd),securePort:an,timeout:jt.min(1).optional()}).optional(),tls:Ee.alternatives([Ee.array().items(f),f])}).required(),rootPath:ut.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:Ee.object({network:Ee.object({port:an,securePort:an,mtls:Ee.alternatives([He.optional(),Ee.object({user:ut.optional(),certificateAuthority:i,required:He.optional()})])}).required(),webSocket:He.optional(),requireAuthentication:He.optional()}),http:Ee.object({compressionThreshold:jt.optional(),cors:He.optional(),corsAccessList:zo.optional(),headersTimeout:jt.min(1).optional(),port:an,securePort:an,maxHeaderSize:jt.optional(),mtls:Ee.alternatives([He.optional(),Ee.object({user:ut.optional(),certificateAuthority:i,required:He.optional()})]),threadRange:Ee.alternatives([zo.optional(),ut.optional()])}).required(),threads:Ee.alternatives(n.optional(),Ee.object({count:n.optional(),debug:Ee.alternatives(He.optional(),Ee.object({startingPort:jt.min(1).optional(),host:ut.optional(),waitForDebugger:He.optional()})),maxHeapMemory:jt.min(0).optional()})),storage:Ee.object({writeAsync:He.required(),overlappingSync:He.optional(),caching:He.optional(),compression:Ee.alternatives([He.optional(),Ee.object({dictionary:ut.optional(),threshold:jt.optional()})]),compactOnStart:He.optional(),compactOnStartKeepBackup:He.optional(),noReadAhead:He.optional(),path:l,prefetchWrites:He.optional(),maxFreeSpaceToLoad:jt.optional(),maxFreeSpaceToRetain:jt.optional()}).required(),ignoreScripts:He.optional(),tls:Ee.alternatives([Ee.array().items(f),f])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(lJ,"configValidator");function uJ(e){return jP||QP.existsSync(e)?null:`Specified path ${e} does not exist.`}a(uJ,"doesPathExist");function dJ(e,t){Ee.assert(e,ut.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=uJ(e);if(r)return t.message(r)}a(dJ,"validatePath");function fJ(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(sJ);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(oJ):e}a(fJ,"validateRotationMaxSize");function _J(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(iJ);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(aJ):e}a(_J,"validateRotationInterval");function hJ(e,t){let r=t.state.path.join("."),n=eJ.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||YP();return i=Math.round(Math.min(i,YP())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),tJ.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(hJ,"setDefaultThreads");function Xd(e,t){let r=t.state.path.join(".");if(!pA.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(pA.isEmpty(di))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return nc.join(di,nJ);case"logging.root":return nc.join(di,zP);case"clustering.leafServer.streams.path":return nc.join(di,"clustering","leaf");case"storage.path":let n=nc.join(di,WP.LEGACY_DATABASES_DIR_NAME);return QP.existsSync(n)?n:nc.join(di,WP.DATABASES_DIR_NAME);case"logging.rotation.path":return nc.join(di,zP);case"operationsApi.network.domainSocket":return r==null?null:nc.join(di,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Xd,"setDefaultRoot");function mJ(e){let t=Ee.object({routes:Dm});return rJ.validateBySchema({routes:e},t)}a(mJ,"routesValidator")});var Gl={};Ue(Gl,{server:()=>Ke});var XP,Ke,Pr=be(()=>{XP=M(ci()),Ke={};(0,XP._assignPackageExport)("server",Ke)});var Nt=P(lD=>{"use strict";var os=(k(),D($)),_r=ae(),Jt=j(),{configValidator:pJ,routesValidator:ZP}=EA(),qr=require("fs-extra"),tD=require("yaml"),Ln=require("path"),EJ=require("is-number"),rD=require("properties-reader"),gJ=require("lodash"),{handleHDBError:SJ}=me(),{HTTP_STATUS_CODES:TJ,HDB_ERROR_MSGS:ql}=Pn(),{server:AJ}=(Pr(),D(Gl)),{PACKAGE_ROOT:nD}=mt(),{DATABASES_PARAM_CONFIG:Zd,CONFIG_PARAMS:Dn,CONFIG_PARAM_MAP:xs}=os,RJ="Unable to get config value because config is uninitialized",yJ="Config successfully initialized",bJ="Error backing up config file",OJ="Empty parameter sent to getConfigValue",sD=Ln.join(nD,"config","yaml",os.HDB_DEFAULT_CONFIG_FILE),NJ=Ln.join(nD,"config","yaml","defaultNatsConfig.yaml"),wJ="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",eD={logging_rotation_retain:"logging.rotation.retain",logging_rotation_rotate:"logging.rotation.rotate",logging_rotation_rotateinterval:"logging.rotation.rotateInterval",logging_rotation_rotatemodule:"logging.rotation.rotateModule",logging_rotation_timezone:"logging.rotation.timezone",logging_rotation_workerinterval:"logging.rotation.workerInterval"},Lm,Ot,Mm;Object.assign(lD,{createConfigFile:IJ,getDefaultConfig:CJ,getConfigValue:oD,initConfig:vm,flattenConfig:$l,updateConfigValue:aD,updateConfigObject:DJ,getConfiguration:vJ,setConfiguration:UJ,readConfigFile:AA,getClusteringRoutes:xJ,initOldConfig:cD,getConfigFromFile:BJ,getConfigFilePath:sc,addConfig:HJ,deleteConfigFromFile:kJ,getConfigObj:FJ,resolvePath:gA,getFlatConfigObj:GJ});function gA(e){if(e?.startsWith("~/"))return Ln.join(_r.getHomeDir(),e.slice(1));let t=le();try{return Ln.resolve(t.getHdbBasePath(),e)}catch(r){return console.error("Unable to resolve path",e,r),e}}a(gA,"resolvePath");function IJ(e,t=!1){let r=Qo(sD);if(e.clustering_enabled||e.CLUSTERING_ENABLED||e.clustering){let c=tD.parseDocument(qr.readFileSync(NJ,"utf8"),{simpleKeys:!0});r.addIn(["clustering"],c.toJSON().clustering)}Lm=$l(r.toJSON());let n;for(let c in e){let l=xs[c.toLowerCase()];if(l===Dn.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(u=>({[u]:e[c][u]}));continue}if(!l&&(c.endsWith("_package")||c.endsWith("_port"))&&(l=c),l!==void 0){let u=l.split("_"),f=SA(l,e[c]);l==="rootPath"&&f?.endsWith("/")&&(f=f.slice(0,-1));try{r.setIn([...u],f)}catch(d){Jt.error(d)}}}n&&iD(r,n),TA(r,t);let s=r.toJSON();Ot=$l(s);let i=r.getIn(["rootPath"]),o=Ln.join(i,os.HDB_CONFIG_FILE);if(qr.createFileSync(o),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);qr.writeFileSync(o,String(r)),Jt.trace(`Config file written to ${o}`)}a(IJ,"createConfigFile");function iD(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!_r.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Zd.TABLES))for(let i in n[s][Zd.TABLES])for(let o in n[s][Zd.TABLES][i]){let c=n[s][Zd.TABLES][i][o],l=[Dn.DATABASES,s,Zd.TABLES,i,o];e.hasIn(l)?e.setIn(l,c):e.addIn(l,c)}else for(let i in n[s]){let o=n[s][i],c=[Dn.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){Jt.error("Error parsing schemas CLI/env config arguments",n)}}a(iD,"setSchemasConfig");function CJ(e){if(Lm===void 0){let r=Qo(sD);Lm=$l(r.toJSON())}let t=xs[e.toLowerCase()];if(t!==void 0)return Lm[t.toLowerCase()]}a(CJ,"getDefaultConfig");function oD(e){if(e==null){Jt.info(OJ);return}if(Ot===void 0){Jt.trace(RJ);return}let t=xs[e.toLowerCase()];if(t!==void 0)return Ot[t.toLowerCase()]}a(oD,"getConfigValue");function sc(e=_r.getPropsFilePath()){let t=_r.getEnvCliRootPath();if(t)return gA(Ln.join(t,os.HDB_CONFIG_FILE));let r=rD(e);return gA(r.get(os.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}a(sc,"getConfigFilePath");function vm(e=!1){if(Ot===void 0||e){let t;if(!_r.noBootFile()){t=_r.getPropsFilePath();try{qr.accessSync(t,qr.constants.F_OK|qr.constants.R_OK)}catch(i){throw Jt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=sc(t),n;if(r.includes("config/settings.js"))try{cD(r);return}catch(i){if(i.code!==os.NODE_ERROR_CODES.ENOENT)throw i}try{n=Qo(r)}catch(i){if(i.code===os.NODE_ERROR_CODES.ENOENT){Jt.trace(`HarperDB config file not found at ${r}.
10
- This can occur during early stages of install where the config file has not yet been created`);return}else throw Jt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}PJ(n,r),TA(n);let s=n.toJSON();if(AJ.config=s,Ot=$l(s),Ot.logging_rotation_rotate)for(let i in eD)Ot[i]&&Jt.error(`Config ${eD[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Jt.trace(yJ)}}a(vm,"initConfig");function PJ(e,t){let r=e.getIn(["rootPath"]),n=!1;if(e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Ln.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Ln.join(r,"log")),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n){if(Jt.trace("Updating config file with missing config params"),e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${e.errors}`);qr.writeFileSync(t,String(e))}}a(PJ,"checkForUpdatedConfig");function TA(e,t=!1){let r=e.toJSON();if(r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads),r.http?.port&&r.http?.port===r.http?.securePort)throw ql.CONFIG_VALIDATION("http.port and http.securePort cannot be the same value");if(r.operationsApi?.network?.port&&r.operationsApi?.network?.port===r.operationsApi?.network?.securePort)throw ql.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=pJ(r,t);if(n.error)throw ql.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket),r?.clustering?.enabled&&e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path)}a(TA,"validateConfig");function DJ(e,t){Ot===void 0&&(Ot={});let r=xs[e.toLowerCase()];if(r===void 0){Jt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Ot[r.toLowerCase()]=t}a(DJ,"updateConfigObject");function aD(e,t,r=void 0,n=!1,s=!1,i=!1){Ot===void 0&&vm();let o=oD(xs.hdb_root),c=Ln.join(o,os.HDB_CONFIG_FILE),l=Qo(c),u;if(r&&Ot){let _=!1;for(let h in r)if(r[h]!=Ot[h.toLowerCase()]){_=!0;break}if(!_){Jt.trace("No changes detected in config parameters, skipping update");return}}if(r===void 0&&e.toLowerCase()===Dn.DATABASES)u=t;else if(r===void 0){let _;if(i)_=e;else if(_=xs[e.toLowerCase()],_===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let h=_.split("_"),m=SA(_,t);l.setIn([...h],m)}else for(let _ in r){let h=xs[_.toLowerCase()];if(h===Dn.HTTP_SECUREPORT&&r[_]===Ot[Dn.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),h===Dn.OPERATIONSAPI_NETWORK_SECUREPORT&&r[_]===Ot[Dn.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),h===Dn.DATABASES){u=r[_];continue}if(h?.startsWith("threads_")){let m=l.getIn(["threads"]);m>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],m))}if(!h&&(_.endsWith("_package")||_.endsWith("_port"))&&(h=_),h!==void 0){let m=h.split("_"),S=os.LEGACY_CONFIG_PARAMS[_.toUpperCase()];S&&S.startsWith("customFunctions")&&l.hasIn(S.split("_"))&&(h=S,m=S.split("_"));let g=SA(h,r[_]);h==="rootPath"&&g?.endsWith("/")&&(g=g.slice(0,-1));try{m.length>1&&typeof l.getIn(m.slice(0,-1))=="boolean"&&l.deleteIn(m.slice(0,-1)),l.setIn([...m],g)}catch(R){Jt.error(R)}}}u&&iD(l,u),TA(l);let f=l.getIn(["rootPath"]),d=Ln.join(f,os.HDB_CONFIG_FILE);if(n===!0&&LJ(c,f),l.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${l.errors}`);qr.writeFileSync(d,String(l)),s&&(Ot=$l(l.toJSON())),Jt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(aD,"updateConfigValue");function LJ(e,t){try{let r=Ln.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${os.HDB_CONFIG_FILE}.bak`);qr.copySync(e,r),Jt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Jt.error(bJ),Jt.error(r)}}a(LJ,"backupConfigFile");var MJ=["databases"];function $l(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network={...e.http,...e.operationsApi.network}),e?.operationsApi&&(e.operationsApi.tls={...e.tls,...e.operationsApi.tls}),Mm=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!MJ.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!Dn[l.toUpperCase()]&&xs[l]&&(s[xs[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a($l,"flattenConfig");function SA(e,t){if(e===Dn.CLUSTERING_NODENAME||e===Dn.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(EJ(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||_r.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return _r.autoCast(t)}a(SA,"castConfigValue");function vJ(){let e=_r.getPropsFilePath(),t=sc(e);return Qo(t).toJSON()}a(vJ,"getConfiguration");async function UJ(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return aD(void 0,void 0,s,!0),wJ}catch(i){throw typeof i=="string"||i instanceof String?SJ(i,i,TJ.BAD_REQUEST,void 0,void 0,!0):i}}a(UJ,"setConfiguration");function AA(){let e=_r.getPropsFilePath();try{qr.accessSync(e,qr.constants.F_OK|qr.constants.R_OK)}catch(n){if(!_r.noBootFile())throw Jt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=sc(e);return Qo(t).toJSON()}a(AA,"readConfigFile");function Qo(e){return tD.parseDocument(qr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Qo,"parseYamlDoc");function xJ(){let e=AA(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=_r.isEmptyOrZeroLength(t)?[]:t;let r=ZP(t);if(r)throw ql.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=_r.isEmptyOrZeroLength(n)?[]:n;let s=ZP(n);if(s)throw ql.CONFIG_VALIDATION(s.message);if(!_r.isEmptyOrZeroLength(n)&&!_r.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!_r.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw ql.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(xJ,"getClusteringRoutes");function cD(e){let t=rD(e);Ot={};for(let r in xs){let n=t.get(r.toUpperCase());if(_r.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=xs[r].toLowerCase();s===Dn.LOGGING_ROOT?Ot[s]=Ln.dirname(n):Ot[s]=n}return Ot}a(cD,"initOldConfig");function BJ(e){let t=AA();return gJ.get(t,e.replaceAll("_","."))}a(BJ,"getConfigFromFile");async function HJ(e,t){let r=Qo(sc());if(r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);await qr.writeFile(sc(),String(r))}a(HJ,"addConfig");function kJ(e){let t=sc(_r.getPropsFilePath()),r=Qo(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Ln.join(n,os.HDB_CONFIG_FILE);qr.writeFileSync(s,String(r))}a(kJ,"deleteConfigFromFile");function FJ(){return Mm||(vm(),Mm)}a(FJ,"getConfigObj");function GJ(){return Ot||vm(),Ot}a(GJ,"getFlatConfigObj")});var le=P((hD,mD)=>{"use strict";var RA=require("fs-extra"),ic=require("path"),uD=require("os"),qJ=require("properties-reader"),tf=j(),ef=ae(),Le=(k(),D($)),Um=Nt(),$J="Error initializing environment manager",xm="BOOT_PROPS_FILE_PATH",dD=!1,VJ={[Le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},zi={};Object.assign(hD,mD.exports={BOOT_PROPS_FILE_PATH:xm,getHdbBasePath:KJ,setHdbBasePath:YJ,get:fD,initSync:zJ,setProperty:Ye,initTestEnvironment:jJ,setCloneVar:QJ});function KJ(){return zi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(KJ,"getHdbBasePath");function YJ(e){zi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(YJ,"setHdbBasePath");function fD(e){let t=Um.getConfigValue(e);return t===void 0?zi[e]:t}a(fD,"get");function Ye(e,t){VJ[e]&&(zi[e]=t),Um.updateConfigObject(e,t)}a(Ye,"setProperty");function WJ(){let e;try{e=ef.getPropsFilePath(),RA.accessSync(e,RA.constants.F_OK|RA.constants.R_OK),dD=!0;let t=qJ(e);return zi[Le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Le.HDB_SETTINGS_NAMES.INSTALL_USER),zi[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),zi[xm]=e,!0}catch{return tf.trace(`Environment manager found no properties file at ${e}`),!1}}a(WJ,"doesPropFileExist");function zJ(e=!1){try{((dD||WJ()||ef.noBootFile())&&!_D||e)&&(Um.initConfig(e),zi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Um.getConfigValue(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){tf.error($J),tf.error(t),console.error(t),process.exit(1)}}a(zJ,"initSync");var _D=!1;function QJ(e){_D=e}a(QJ,"setCloneVar");function jJ(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,l=ic.join(__dirname,"../../","unitTests");zi[xm]=ic.join(l,"hdb_boot_properties.file"),Ye(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,ic.join(l,"settings.test")),Ye(Le.HDB_SETTINGS_NAMES.INSTALL_USER,uD.userInfo()?uD.userInfo().username:void 0),Ye(Le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ye(Le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,ic.join(l,"envDir","log")),Ye(Le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ye(Le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ye(Le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ye(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,ic.join(l,"envDir")),Ye(Le.CONFIG_PARAMS.STORAGE_PATH,ic.join(l,"envDir")),s&&(Ye(Le.CONFIG_PARAMS.HTTP_SECUREPORT,fD(Le.CONFIG_PARAMS.HTTP_PORT)),Ye(Le.CONFIG_PARAMS.HTTP_PORT,null)),Ye(Le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Ye(Le.CONFIG_PARAMS.HTTP_PORT,9926),Ye(Le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ye(Le.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Ye(Le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,ef.isEmpty(i)?!1:i),Ye(Le.CONFIG_PARAMS.HTTP_CORS,ef.isEmpty(i)?!1:i),Ye(Le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ye(Le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ye(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ye(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ye(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,ic.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ye(Le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,ef.isEmpty(c)?!1:c),o&&(Ye("CORS_ACCESSLIST",o),Ye(Le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Ye(Le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Ye(Le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Ye(Le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ye(Le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ye(Le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ye(Le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${xm}. Please check your boot props and settings files`;tf.fatal(r),tf.error(t)}}a(jJ,"initTestEnvironment")});var pt=P((aAe,RD)=>{"use strict";var af=(k(),D($)),JJ=ae(),cn=le(),cf=require("path"),XJ=require("minimist"),pD=require("fs-extra"),ED=require("lodash");cn.initSync();var{CONFIG_PARAMS:jo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Bm}=af,nf,sf,of;function gD(){if(nf!==void 0)return nf;if(cn.getHdbBasePath()!==void 0)return nf=cn.get(jo.STORAGE_PATH)||cf.join(cn.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(gD,"getBaseSchemaPath");function SD(){if(sf!==void 0)return sf;if(cn.getHdbBasePath()!==void 0)return sf=AD(Bm),sf}a(SD,"getSystemSchemaPath");function TD(){if(of!==void 0)return of;if(cn.getHdbBasePath()!==void 0)return of=cn.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(cn.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(TD,"getTransactionAuditStoreBasePath");function ZJ(e,t){let r=cn.get(jo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(TD(),e.toString())}a(ZJ,"getTransactionAuditStorePath");function AD(e,t){e=e.toString(),t=t&&t.toString();let r=cn.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(gD(),e)}a(AD,"getSchemaPath");function e4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,XJ(process.argv));let n=r[jo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!JJ.isObject(n))throw o;i=n}for(let o of i){let c=o[Bm];if(!c)continue;let l=cn.get(jo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return ED.set(l,[Bm,rf.TABLES,t,rf.PATH],u),cn.setProperty(jo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return ED.set(l,[Bm,rf.PATH],f),cn.setProperty(jo.DATABASES,l),f}}let s=r[jo.STORAGE_PATH.toUpperCase()];if(s){if(!pD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return pD.mkdirsSync(i),cn.setProperty(jo.STORAGE_PATH,s),i}return SD()}a(e4,"initSystemSchemaPaths");function t4(){nf=void 0,sf=void 0,of=void 0}a(t4,"resetPaths");RD.exports={getBaseSchemaPath:gD,getSystemSchemaPath:SD,getTransactionAuditStorePath:ZJ,getTransactionAuditStoreBasePath:TD,getSchemaPath:AD,initSystemSchemaPaths:e4,resetPaths:t4}});var ln=P((dAe,wD)=>{"use strict";var r4=Pn().LMDB_ERRORS_ENUM,lAe=require("lmdb"),n4=Ut(),uAe=require("buffer").Buffer,{OVERFLOW_MARKER:yD,MAX_SEARCH_KEY_LENGTH:Hm}=n4,bD=["number","string","symbol","boolean","bigint"];function s4(e){if(e=e?.primaryStore||e,!e)throw new Error(r4.ENV_REQUIRED)}a(s4,"validateEnv");function i4(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(i4,"stringifyData");function o4(e){return e instanceof Date?e.valueOf():e}a(o4,"convertKeyValueToWrite");function a4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(bD.includes(typeof e))return e.length>Hm?[e.slice(0,Hm)+yD]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(bD.includes(typeof i))i.length>Hm?r.push(i.slice(0,Hm)+yD):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(a4,"getIndexedValues");var km=0,OD=0;function ND(){OD=Date.now()-performance.now()}a(ND,"adjustStartTime");ND();var c4=6e4;setInterval(ND,c4).unref();function l4(){let e=performance.now()+OD;return e>km?(km=e,e):(km+=488e-6,km)}a(l4,"getNextMonotonicTime");wD.exports={validateEnv:s4,stringifyData:i4,convertKeyValueToWrite:o4,getNextMonotonicTime:l4,getIndexedValues:a4}});var lf=P((_Ae,ID)=>{"use strict";var u4=(k(),D($)).OPERATIONS_ENUM,yA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=u4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};ID.exports=yA});var uf=P((pAe,LD)=>{"use strict";var mAe=lf(),Fm=(k(),D($)),bA=ae(),CD=j(),d4=require("uuid"),{handleHDBError:Gm,hdb_errors:f4}=me(),{HDB_ERROR_MSGS:qm,HTTP_STATUS_CODES:$m}=f4;LD.exports=PD;function PD(e,t,r){for(let s=0;s<t.length;s++)DD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];_4(i,r,e.operation)}}a(PD,"processRows");PD.validateAttribute=DD;function DD(e){if(Buffer.byteLength(String(e))>Fm.INSERT_MAX_CHARACTER_SIZE)throw Gm(new Error,qm.ATTR_NAME_LENGTH_ERR(e),$m.BAD_REQUEST,void 0,void 0,!0);if(bA.isEmptyOrZeroLength(e)||bA.isEmpty(e.trim()))throw Gm(new Error,qm.ATTR_NAME_NULLISH_ERR,$m.BAD_REQUEST,void 0,void 0,!0)}a(DD,"validateAttribute");function _4(e,t,r){if(!e.hasOwnProperty(t)||bA.isEmptyOrZeroLength(e[t])){if(r===Fm.OPERATIONS_ENUM.INSERT||r===Fm.OPERATIONS_ENUM.UPSERT){e[t]=d4.v4();return}throw CD.error("Update transaction aborted due to record with no hash value:",e),Gm(new Error,qm.RECORD_MISSING_HASH_ERR,$m.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>Fm.INSERT_MAX_CHARACTER_SIZE)throw CD.error(e),Gm(new Error,qm.HASH_VAL_LENGTH_ERR,$m.BAD_REQUEST,void 0,void 0,!0)}a(_4,"validateHash")});var MD,Mn,OA,Vl=be(()=>{MD=require("events"),Mn=class extends MD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new OA;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)}},OA=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 FD(e){wA=e}function E4(){p4=setInterval(function(){for(let e of NA)if(e.stale){let t=e.getContext()?.url;BD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},m4).unref()}var IA,xD,BD,HD,kD,vD,NA,h4,df,UD,wA,oc,Vm,m4,p4,Km=be(()=>{IA=M(ln()),xD=M(me()),BD=M(j()),HD=M(le());k();kD=M(ae()),vD=100,NA=new Set,h4=(0,kD.convertToMS)(HD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(FD,"replicationConfirmation");oc=class e{static{a(this,"DatabaseTransaction")}#e;writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),NA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(NA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-UD>h4)throw new xD.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,IA.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)<vD>>n?l():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return df||(df=s,UD=performance.now(),df.then(()=>{df=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];wA&&h&&i.push(wA(_,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)+vD/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}},Vm=class extends oc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,IA.getNextMonotonicTime)())}getReadTxn(){}},m4=3e4;a(E4,"startMonitoringTxns");E4()});function wt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new oc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(e),e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var GD,ac=be(()=>{GD=M(ci());Km();a(wt,"transaction");(0,GD._assignPackageExport)("transaction",wt);wt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};wt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function PA(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?PA(d.conditions,d.operator,r,n,s,i,o,c):Wl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(m.attribute||m[0])===r.primaryKey,R=hf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=N4(r.primaryStore,m.estimated_count,h)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Wl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new dn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=_i(n.attributes,E);if(T.relationship){if(o.length<2)throw new dn.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=Wl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let q=!!_i(w.attributes,T.relationship.to)?.elements;H=R4(H,T,w.primaryStore,q,v)}if(T.relationship.from){let q=a(W=>(W?.key!==void 0&&(W=W.key),Wl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=y4(H,T,w.primaryStore,v,q)):H=H.flatMap(q)}return H}else if(o.length===1)o=o[0];else throw new dn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(DA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=fi.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new dn.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>as.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>as.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,d=!0,m=m??hf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new dn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new dn.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 dn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new dn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??hf(e,n,null,i,S),!m)throw new dn.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:Jo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&m(w)?T:Jo.SKIP)}catch(q){H(q)}}))}:T=>T.value==null&&!(T.metadataFlags&(fn|Zo))?Jo.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>as.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Jo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(m(w)?T:Jo.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:Jo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Jo.SKIP)}catch(H){v(H)}}))})}function _i(e,t){if(Array.isArray(t))if(t.length>1){let r=_i(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?_i(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function R4(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 y4(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hf(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let f=c[0],d=_i(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=hf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,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()),DA[o]||o){case as.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,fi.compareKeys)(f,l[0])>=0&&(0,fi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,fi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,fi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,fi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,fi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,fi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new dn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Wm(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=Wl(e,r.transaction.getReadTxn(),!1,t).map(zl),H=new Set(v);R.idFilter=q=>H.has(zl(q)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Wm(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Qi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=DA[n]||n,n===as.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=_i(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Wm(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Qi(e.indices[i.relationship.from])/(Qi(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Qi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=T4*Qi(e.primaryStore)+1:n==="between"?r.estimated_count=S4*Qi(e.primaryStore)+1:n==="sort"?r.estimated_count=Qi(e.primaryStore)+1:r.estimated_count=g4*Qi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function zm(e){if(e)if(Xo=e,Kl.lastIndex=0,b4.test(e))try{let t=ff(new Yl,"");if(un!==Xo.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 ${un} in '${Xo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Kl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Xo);){un=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=qD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=_f(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=A4[d],l=CA[i]?qD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_f(f);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&$D(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else Ym(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Kl.lastIndex=un;let h=ff(f?[]:new Yl,")");switch(f){case"":Ym(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=VD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Xo[un]===","?r.lastIndex=++un:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");Kl.lastIndex=un,_=ff([],"}"),_.name=f,e.push(_),Xo[un]===","?r.lastIndex=++un:o=!0;break;case"[":Kl.lastIndex=un,f?(_=ff(new Yl,"]"),_.name=f):_=ff(e.conditions?new Yl:[],"]"),e.conditions?(Ym(e,u),e.conditions.push(_),s=null):e.push(_),Xo[un]===","?r.lastIndex=++un: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"&&$D(m,f),Ym(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?O4:Kl,r.lastIndex=un),un===Xo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Ym(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function qD(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 dn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function $D(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new dn.ClientError("wildcard can only be used at the end of a string")}function VD(e){let t=KD(e[0]);return e.length>1&&(t.next=VD(e.slice(1))),t}function KD(e){if(Array.isArray(e)){let t=KD(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function zl(e){return Array.isArray(e)?e.join("\0"):e}function Qi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function N4(e,t,r){return t*r/Qi(e)}var dn,as,fi,Jo,g4,S4,T4,A4,CA,DA,b4,Kl,O4,un,Xo,Yl,cc,mf=be(()=>{dn=M(me()),as=M(Ut()),fi=require("ordered-binary"),Jo=require("lmdb");pf();g4=.3,S4=.1,T4=.05,A4={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},CA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(PA,"executeConditions");a(Wl,"searchByIndex");a(_i,"findAttribute");a(R4,"joinTo");a(y4,"joinFrom");DA={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hf,"filterByType");a(Wm,"estimateCondition");b4=/[()[\]|!<>.]|(=\w*=)/,Kl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,O4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(zm,"parseQuery");a(ff,"parseBlock");a(Ym,"assignOperator");a(_f,"decodeProperty");a(qD,"typedDecoding");a($D,"wildcardDecoding");a(VD,"toSortObject");a(KD,"toSortEntry");Yl=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(zl,"flattenKey");a(Qi,"estimatedEntryCount");a(N4,"intersectionEstimate");cc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var MA={};Ue(MA,{MultiPartId:()=>jm,Resource:()=>$r,snake_case:()=>I4,transformForSelect:()=>Jm});function I4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function YD(e,t){if(lc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(lc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new jm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){lc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return lc=!0,null;e[e.length-1]==="/"&&(lc=!0)}return t.coerceId(decodeURIComponent(e))}function vn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new cc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return wt(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 Qm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Qm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Un(e,t){let r=new QD.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 LA(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 Jm(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):LA(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(LA(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(LA(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]=Jm(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var WD,zD,QD,w4,$r,Qm,lc,jm,ea=be(()=>{WD=require("crypto");Vl();zD=M(ci()),QD=M(me());ac();mf();w4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$r=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=vn(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=Jm(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=vn(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):Un(t,"put")},{hasContent:!0,type:"update"});static patch=vn(function(t,r,n,s){return t.patch?t.patch(s,r):Un(t,"patch")},{hasContent:!0,type:"update"});static delete=vn(function(t,r,n,s){return t.delete?t.delete(r):Un(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,WD.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),wt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Un(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=vn(function(t,r,n,s){return t.invalidate?t.invalidate(r):Un(t,"delete")},{hasContent:!1,type:"update"});static post=vn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=vn(function(t,r,n,s){return t.connect?t.connect(s,r):Un(t,"connect")},{hasContent:!0,type:"read"});static subscribe=vn(function(t,r,n,s){return t.subscribe?t.subscribe(r):Un(t,"subscribe")},{type:"read"});static publish=vn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Un(t,"publish")},{hasContent:!0,type:"create"});static search=vn(function(t,r,n,s){let i=t.search?t.search(r):Un(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Jm(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=vn(function(t,r,n,s){return t.search?t.search(s,r):Un(t,"search")},{hasContent:!0,type:"read"});static copy=vn(function(t,r,n,s){return t.copy?t.copy(s,r):Un(t,"copy")},{hasContent:!0,type:"create"});static move=vn(function(t,r,n,s){return t.move?t.move(s,r):Un(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Un(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return zm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&w4[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:YD(t,this),isCollection:lc}}let i=YD(t,this);return lc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Mn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Mn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,zD._assignPackageExport)("Resource",$r);a(I4,"snake_case");Qm=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(YD,"pathToId");jm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(vn,"transactional");a(Un,"missingMethod");a(LA,"selectFromObject");a(Jm,"transformForSelect")});var ta,vA=be(()=>{ta=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var XD={};Ue(XD,{Resources:()=>Xm,keyArrayToString:()=>Ql,resetResources:()=>C4,resources:()=>cs});function C4(){return cs=new Xm,Ke.resources=cs,cs}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var jD,JD,Xm,cs,jl=be(()=>{ac();vA();jD=M(j()),JD=M(me());Pr();Xm=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 JD.ServerError(`Conflicting paths for ${t}`);jD.default.error(c),i.Resource=new ta(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return wt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(C4,"resetResources");a(Ql,"keyArrayToString")});var UA=P((GAe,ZD)=>{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=ZD.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 HA={};Ue(HA,{loadGQLSchema:()=>L4,start:()=>BA,startOnMainThread:()=>D4});function BA({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):P4.includes(R.type)||(0,tL.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,xA.dirname)(n),R.tableClass):i.set((0,xA.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new eL.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 xA,eL,tL,P4,D4,L4,rL=be(()=>{xA=require("path"),eL=require("node:vm");ve();tL=M(rt()),P4=["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(BA,"start");D4=BA,L4=BA({ensureTable:dt}).handleFile});var lL={};Ue(lL,{parse:()=>FA,streamAsJSON:()=>Ef,stringify:()=>uc});function Ef(e){return new kA({value:e})}function nL(e){return console.error(e),JSON.stringify(e.toString())}function sL(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function uc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===aL)return cL(e);if(t.resolution)return t.resolution.then(()=>uc(e));throw t}}function cL(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+=cL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+uc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function FA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),U4.test(e)?M4.parse(e):JSON.parse(e)):null}var iL,oL,M4,v4,aL,kA,U4,GA=be(()=>{iL=require("stream"),oL=M(require("json-bigint-fixes")),M4=(0,oL.default)({useNativeBigInt:!0}),v4=1e4,aL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw aL};a(Ef,"streamAsJSON");kA=class extends iL.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),nL)}catch(s){yield nL(s)}else yield uc(t)}else yield uc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);sL(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>v4?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 sL(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(nL,"handleError");a(sL,"when");a(uc,"stringify");a(cL,"jsStringify");U4=/[[,:]\s*-?\d{16,}/;a(FA,"parse")});var hi=P(ep=>{var Zm=j();for(let e of["trace","debug","info","warn","error","fatal","notify"])Zm.logsAtLevel(e)&&(ep[e]=Zm[e]);ep.loggerWithTag=e=>Zm.loggerWithTag(e,!0);ep.setLogLevel=Zm.setLogLevel});var dp={};Ue(dp,{Blob:()=>mi,blobsWereEncoded:()=>fc,databasePaths:()=>$A,decodeBlobsWithWrites:()=>lp,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>up,deleteBlob:()=>op,deleteBlobsInObject:()=>ra,deleteRootBlobPathsForDB:()=>KA,encodeBlobsAsBuffers:()=>K4,encodeBlobsWithFilePath:()=>cp,findBlobsInObject:()=>Xl,getFileId:()=>ap,getFilePathForBlob:()=>SL,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>k4});function pL(){}function op(e){let t=SL(e);t&&setTimeout(()=>{(0,Qe.unlink)(t,r=>{r&&ji.default.debug?.("Error trying to remove blob file",r)})},EL)}function k4(e){EL=e}function gL(e){let t=_n.get(e);if(!t)t={storageIndex:0,fileId:null,store:hn},_n.set(e,t);else{if(t.saving)return t;t.store=hn}return G4(t),t.source?qA(e,t.source,t):t.contentBuffer?F4(e,t):qA(e,Sf.Readable.from(e.stream()),t),t}function qA(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(B4),h=(0,sp.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(x4),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(hr),T=new DataView(E.buffer);return R|=BigInt(o?VA:mL)<<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-hr;e.size=g,(0,Qe.write)(d.fd,m(g),0,hr,0,S)}})}),e}function ap(e){return _n.get(e)?.fileId}function SL(e){let t=_n.get(e);return t?.fileId&&Tf(t)}function Af(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=$A.get(e);if(!t){if(!e.databaseName)return ji.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,ip.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Xi.join)(n,e.databaseName)):t=[(0,Xi.join)((0,ip.getHdbBasePath)(),"blobs",e.databaseName)],$A.set(e,t)}return t}async function KA(e){let t=Af(e);t&&await Promise.all(t.map(r=>TL(r)))}async function TL(e){if((0,Qe.existsSync)(e)){for(let t of await(0,Bs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await TL((0,Xi.join)(e,t.name));else try{await(0,Bs.unlink)((0,Xi.join)(e,t.name))}catch(r){ji.default.warn?.("Error deleting file",r)}try{await(0,Bs.rmdir)(e)}catch(t){ji.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Xi.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 F4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<hL))return e.size=n,qA(e,Sf.Readable.from([r]),t)}function G4(e){let t=Af(e.store),r=q4(),n=t?.length>1?$4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Xi.dirname)(i);(0,Qe.existsSync)(o)||(0,_L.ensureDirSync)(o),e.filePath=i}function q4(){let e=fL.get(hn);if(!e){let t=0,r=Af(hn);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,Xi.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(hn.getUserSharedBuffer("blob-file-id",e.buffer)),fL.set(hn,e)}return Number(Atomics.add(e,0,1n))}function $4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(np);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,V4(e)),e.frequencyTable[t%np]}async function V4(e){if(!Bs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Bs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(np),n=t.map(s=>1/s);for(let s=0;s<np;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 cp(e,t,r){Jl=t,hn=r,fc=!1;try{return e()}finally{Jl=void 0,hn=void 0}}function K4(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 lp(e,t){try{Dr=[],dc=t,e()}catch(n){throw dc=void 0,Dr=void 0,n}dc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function up(e,t,r){hn=r;try{return dc=t,e()}finally{dc=void 0}}function _c(e,t){return hn=t,e()}function ra(e){Xl(e,t=>{op(t)})}function Xl(e,t){if(e instanceof mi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Xl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&Xl(e[r],t)}}function Y4(){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,Bs,Qe,sp,Sf,_L,ip,Xi,ji,hL,hr,mL,VA,uL,x4,B4,dL,_n,dc,mi,Jl,Dr,hn,fc,gf,tp,H4,rp,EL,$A,fL,np,ls=be(()=>{Ji=require("msgpackr"),Bs=require("node:fs/promises"),Qe=require("node:fs"),sp=require("node:zlib"),Sf=require("node:stream"),_L=require("fs-extra"),ip=M(le());k();Xi=require("path"),ji=M(hi());Zi();hL=8192,hr=8,mL=0,VA=1,uL=255,x4=new Uint8Array([0,mL,255,255,255,255,255,255]),B4=new Uint8Array([0,VA,255,255,255,255,255,255]),dL=0xffffffffffff,_n=new WeakMap,mi=global.Blob||Y4(),fc=!1,gf=new Uint8Array(8),tp=new DataView(gf.buffer),H4=6e4;a(pL,"InstanceOfBlobWithNoConstructor");pL.prototype=mi.prototype;rp=class e extends pL{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=_n.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):(WA()&&YA(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=_n.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Tf(t),o,c=a(async()=>{let l,u=hr;try{if(l=await(0,Bs.readFile)(i),l.length>=hr){l.copy(gf,0,0,hr);let d=tp.getBigUint64(0);if(Number(d>>48n)===uL)throw new Error("Error in blob: "+buffer.subarray(hr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<dL&&(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]===VA?new Promise((d,_)=>{(0,sp.deflate)(l.subarray(hr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(hr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=_n.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Tf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,Qe.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(ji.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(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<hr){R-- >0&&d!==!1?(m(),ji.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(ji.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,hr);let se=tp.getBigUint64(0);if(Number(se>>48n)===uL)return v(new Error("Error in blob: "+te.subarray(hr)));if(g=Number(se&0xffffffffffffn),g<dL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(hr,W),l-=hr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,Qe.read)(o,se,0,hr,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(tp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},H4).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 ji.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=_n.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};_n.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)};_n.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(hn=t?.primaryStore?.rootStore,!hn)throw new Error("No target table specified");return gL(this).saving??Promise.resolve()}},EL=500;a(op,"deleteBlob");a(k4,"setDeletionDelay");global.createBlob=function(e,t){let r=new rp(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(_n.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Sf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Sf.Readable.from(e);else throw new Error("Invalid source type");return r};a(gL,"saveBlob");a(qA,"writeBlobWithStream");a(ap,"getFileId");a(SL,"getFilePathForBlob");$A=new Map;a(Af,"getRootBlobPathsForDB");a(KA,"deleteRootBlobPathsForDB");a(TL,"rimrafSteadily");a(Tf,"getFilePath");a(F4,"writeBlobWithBuffer");a(G4,"generateFilePath");fL=new Map;a(q4,"getNextFileId");np=128;a($4,"getNextStorageIndex");a(V4,"createFrequencyTableForStoragePaths");a(cp,"encodeBlobsWithFilePath");a(K4,"encodeBlobsAsBuffers");a(lp,"decodeBlobsWithWrites");a(up,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ra,"deleteBlobsInObject");a(Xl,"findBlobsInObject");(0,Ji.addExtension)({Class:mi,type:11,unpack:a(function(e){let t=(0,Ji.unpack)(e),r=new rp;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(_n.set(r,{storageIndex:t[1],fileId:t[2],store:hn}),dc)return dc(r)??r;if(!hn)throw new Error("No store specified, cannot load blob from storage")}else _n.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=_n.get(e);if(Jl!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Jl))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<hL)return r.size=t.contentBuffer.length,(0,Ji.pack)([r,t.contentBuffer])}if(Jl!==void 0){if(t=gL(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Jl,(0,Ji.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,Qe.readFileSync)(Tf(t));if(n.length>=hr&&(n.copy(gf,0,0,hr),Number(tp.getBigUint64(0)&0xffffffffffffn)===n.length-hr))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(Y4,"polyfillBlob")});var IL={};Ue(IL,{asyncSerialization:()=>YA,contentTypes:()=>JA,findBestSerializer:()=>_p,getDeserializer:()=>ro,hasAsyncSerialization:()=>WA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>na,toCsvStream:()=>fp});function z4(e){try{return e?.[0]===123?jA(e):e}catch{return e}}function bf(e){e.register(j4,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new hc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?mc.Readable.from((0,pi.encodeIter)(t,yf)):(0,pi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),fp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,pi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,hc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function _p(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=Vr.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 yL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Vr.keys()).join(", "),406);n=Vr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=RL&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array||e instanceof mi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=_p(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,to.createBrotliCompress)({params:{[to.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?to.constants.BROTLI_MODE_TEXT:to.constants.BROTLI_MODE_GENERIC,[to.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>RL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,to.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function na(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;eo=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=_p(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return eo?.length>0?(eo.length===1?eo[0]:Promise.all(eo)).then(()=>na(e,t,!0)):n}finally{eo=void 0}}function YA(e){if(eo)eo.push(e);else throw new Error("Unable to serialize asynchronously")}function WA(){return!!eo}function J4(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 Z4(e){return X4.includes(e)}function e3(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 ro(e="",t=!1){let r=e3(e),n=r.type&&Vr.get(r.type)?.deserialize||t3(r);return t?s=>J4(s).then(n):n}function t3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!Z4(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 jA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function r3(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 fp(e,t){let r=mc.default.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new W4(n,s);return r.pipe(i)}var pi,hc,to,yL,mc,bL,zA,OL,QA,W4,NL,Rf,jA,yf,Vr,JA,AL,wL,Q4,j4,RL,eo,X4,Zi=be(()=>{GA();pi=require("msgpackr"),hc=require("cbor-x"),to=require("zlib"),yL=M(me()),mc=M(require("stream"));Pr();bL=M(ci()),zA=M(le());k();OL=M(require("yaml")),QA=M(hi());ls();({Transform:W4}=require("json2csv")),NL=zA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=NL?uc:JSON.stringify,jA=NL?FA:JSON.parse,yf={useRecords:!1,useToJSON:!0},Vr=new Map,JA=Vr;Ke.contentTypes=JA;(0,bL._assignPackageExport)("contentTypes",JA);Vr.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return jA(e)},q:.8});AL=new hc.Encoder(yf);Vr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new hc.EncoderStream(yf).end(e)},serialize:AL.encode,deserialize:AL.decode,q:1});Vr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?mc.Readable.from((0,pi.encodeIter)(e,yf)):(0,pi.pack)(e)},serialize:pi.pack,deserialize:pi.unpack,q:.9});Vr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),fp(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]),fp(e,e?.getColumns?.())},q:.1});Vr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return mc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Vr.set("text/yaml",{serialize(e){return OL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Vr.set("text/event-stream",{serializeStream:a(function(e){return mc.Readable.from(r3(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+`
10
+ This can occur during early stages of install where the config file has not yet been created`);return}else throw Jt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}PJ(n,r),TA(n);let s=n.toJSON();if(AJ.config=s,Ot=$l(s),Ot.logging_rotation_rotate)for(let i in eD)Ot[i]&&Jt.error(`Config ${eD[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Jt.trace(yJ)}}a(vm,"initConfig");function PJ(e,t){let r=e.getIn(["rootPath"]),n=!1;if(e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Ln.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Ln.join(r,"log")),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n){if(Jt.trace("Updating config file with missing config params"),e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${e.errors}`);qr.writeFileSync(t,String(e))}}a(PJ,"checkForUpdatedConfig");function TA(e,t=!1){let r=e.toJSON();if(r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads),r.http?.port&&r.http?.port===r.http?.securePort)throw ql.CONFIG_VALIDATION("http.port and http.securePort cannot be the same value");if(r.operationsApi?.network?.port&&r.operationsApi?.network?.port===r.operationsApi?.network?.securePort)throw ql.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=pJ(r,t);if(n.error)throw ql.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket),r?.clustering?.enabled&&e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path)}a(TA,"validateConfig");function DJ(e,t){Ot===void 0&&(Ot={});let r=xs[e.toLowerCase()];if(r===void 0){Jt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Ot[r.toLowerCase()]=t}a(DJ,"updateConfigObject");function aD(e,t,r=void 0,n=!1,s=!1,i=!1){Ot===void 0&&vm();let o=oD(xs.hdb_root),c=Ln.join(o,os.HDB_CONFIG_FILE),l=Qo(c),u;if(r&&Ot){let _=!1;for(let h in r)if(r[h]!=Ot[h.toLowerCase()]){_=!0;break}if(!_){Jt.trace("No changes detected in config parameters, skipping update");return}}if(r===void 0&&e.toLowerCase()===Dn.DATABASES)u=t;else if(r===void 0){let _;if(i)_=e;else if(_=xs[e.toLowerCase()],_===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let h=_.split("_"),m=SA(_,t);l.setIn([...h],m)}else for(let _ in r){let h=xs[_.toLowerCase()];if(h===Dn.HTTP_SECUREPORT&&r[_]===Ot[Dn.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),h===Dn.OPERATIONSAPI_NETWORK_SECUREPORT&&r[_]===Ot[Dn.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),h===Dn.DATABASES){u=r[_];continue}if(h?.startsWith("threads_")){let m=l.getIn(["threads"]);m>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],m))}if(!h&&(_.endsWith("_package")||_.endsWith("_port"))&&(h=_),h!==void 0){let m=h.split("_"),S=os.LEGACY_CONFIG_PARAMS[_.toUpperCase()];S&&S.startsWith("customFunctions")&&l.hasIn(S.split("_"))&&(h=S,m=S.split("_"));let g=SA(h,r[_]);h==="rootPath"&&g?.endsWith("/")&&(g=g.slice(0,-1));try{m.length>1&&typeof l.getIn(m.slice(0,-1))=="boolean"&&l.deleteIn(m.slice(0,-1)),l.setIn([...m],g)}catch(R){Jt.error(R)}}}u&&iD(l,u),TA(l);let f=l.getIn(["rootPath"]),d=Ln.join(f,os.HDB_CONFIG_FILE);if(n===!0&&LJ(c,f),l.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${l.errors}`);qr.writeFileSync(d,String(l)),s&&(Ot=$l(l.toJSON())),Jt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(aD,"updateConfigValue");function LJ(e,t){try{let r=Ln.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${os.HDB_CONFIG_FILE}.bak`);qr.copySync(e,r),Jt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Jt.error(bJ),Jt.error(r)}}a(LJ,"backupConfigFile");var MJ=["databases"];function $l(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network={...e.http,...e.operationsApi.network}),e?.operationsApi&&(e.operationsApi.tls={...e.tls,...e.operationsApi.tls}),Mm=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!MJ.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!Dn[l.toUpperCase()]&&xs[l]&&(s[xs[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a($l,"flattenConfig");function SA(e,t){if(e===Dn.CLUSTERING_NODENAME||e===Dn.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(EJ(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||_r.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return _r.autoCast(t)}a(SA,"castConfigValue");function vJ(){let e=_r.getPropsFilePath(),t=sc(e);return Qo(t).toJSON()}a(vJ,"getConfiguration");async function UJ(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return aD(void 0,void 0,s,!0),wJ}catch(i){throw typeof i=="string"||i instanceof String?SJ(i,i,TJ.BAD_REQUEST,void 0,void 0,!0):i}}a(UJ,"setConfiguration");function AA(){let e=_r.getPropsFilePath();try{qr.accessSync(e,qr.constants.F_OK|qr.constants.R_OK)}catch(n){if(!_r.noBootFile())throw Jt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=sc(e);return Qo(t).toJSON()}a(AA,"readConfigFile");function Qo(e){return tD.parseDocument(qr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Qo,"parseYamlDoc");function xJ(){let e=AA(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=_r.isEmptyOrZeroLength(t)?[]:t;let r=ZP(t);if(r)throw ql.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=_r.isEmptyOrZeroLength(n)?[]:n;let s=ZP(n);if(s)throw ql.CONFIG_VALIDATION(s.message);if(!_r.isEmptyOrZeroLength(n)&&!_r.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!_r.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw ql.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(xJ,"getClusteringRoutes");function cD(e){let t=rD(e);Ot={};for(let r in xs){let n=t.get(r.toUpperCase());if(_r.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=xs[r].toLowerCase();s===Dn.LOGGING_ROOT?Ot[s]=Ln.dirname(n):Ot[s]=n}return Ot}a(cD,"initOldConfig");function BJ(e){let t=AA();return gJ.get(t,e.replaceAll("_","."))}a(BJ,"getConfigFromFile");async function HJ(e,t){let r=Qo(sc());if(r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);await qr.writeFile(sc(),String(r))}a(HJ,"addConfig");function kJ(e){let t=sc(_r.getPropsFilePath()),r=Qo(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Ln.join(n,os.HDB_CONFIG_FILE);qr.writeFileSync(s,String(r))}a(kJ,"deleteConfigFromFile");function FJ(){return Mm||(vm(),Mm)}a(FJ,"getConfigObj");function GJ(){return Ot||vm(),Ot}a(GJ,"getFlatConfigObj")});var le=P((hD,mD)=>{"use strict";var RA=require("fs-extra"),ic=require("path"),uD=require("os"),qJ=require("properties-reader"),tf=j(),ef=ae(),Le=(k(),D($)),Um=Nt(),$J="Error initializing environment manager",xm="BOOT_PROPS_FILE_PATH",dD=!1,VJ={[Le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},zi={};Object.assign(hD,mD.exports={BOOT_PROPS_FILE_PATH:xm,getHdbBasePath:KJ,setHdbBasePath:YJ,get:fD,initSync:zJ,setProperty:Ye,initTestEnvironment:jJ,setCloneVar:QJ});function KJ(){return zi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(KJ,"getHdbBasePath");function YJ(e){zi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(YJ,"setHdbBasePath");function fD(e){let t=Um.getConfigValue(e);return t===void 0?zi[e]:t}a(fD,"get");function Ye(e,t){VJ[e]&&(zi[e]=t),Um.updateConfigObject(e,t)}a(Ye,"setProperty");function WJ(){let e;try{e=ef.getPropsFilePath(),RA.accessSync(e,RA.constants.F_OK|RA.constants.R_OK),dD=!0;let t=qJ(e);return zi[Le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Le.HDB_SETTINGS_NAMES.INSTALL_USER),zi[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),zi[xm]=e,!0}catch{return tf.trace(`Environment manager found no properties file at ${e}`),!1}}a(WJ,"doesPropFileExist");function zJ(e=!1){try{((dD||WJ()||ef.noBootFile())&&!_D||e)&&(Um.initConfig(e),zi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Um.getConfigValue(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){tf.error($J),tf.error(t),console.error(t),process.exit(1)}}a(zJ,"initSync");var _D=!1;function QJ(e){_D=e}a(QJ,"setCloneVar");function jJ(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,l=ic.join(__dirname,"../../","unitTests");zi[xm]=ic.join(l,"hdb_boot_properties.file"),Ye(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,ic.join(l,"settings.test")),Ye(Le.HDB_SETTINGS_NAMES.INSTALL_USER,uD.userInfo()?uD.userInfo().username:void 0),Ye(Le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ye(Le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,ic.join(l,"envDir","log")),Ye(Le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ye(Le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ye(Le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ye(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,ic.join(l,"envDir")),Ye(Le.CONFIG_PARAMS.STORAGE_PATH,ic.join(l,"envDir")),s&&(Ye(Le.CONFIG_PARAMS.HTTP_SECUREPORT,fD(Le.CONFIG_PARAMS.HTTP_PORT)),Ye(Le.CONFIG_PARAMS.HTTP_PORT,null)),Ye(Le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Ye(Le.CONFIG_PARAMS.HTTP_PORT,9926),Ye(Le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ye(Le.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Ye(Le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,ef.isEmpty(i)?!1:i),Ye(Le.CONFIG_PARAMS.HTTP_CORS,ef.isEmpty(i)?!1:i),Ye(Le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ye(Le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ye(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ye(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ye(Le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,ic.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ye(Le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,ef.isEmpty(c)?!1:c),o&&(Ye("CORS_ACCESSLIST",o),Ye(Le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Ye(Le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Ye(Le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Ye(Le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ye(Le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ye(Le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ye(Le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${xm}. Please check your boot props and settings files`;tf.fatal(r),tf.error(t)}}a(jJ,"initTestEnvironment")});var pt=P((aAe,RD)=>{"use strict";var af=(k(),D($)),JJ=ae(),cn=le(),cf=require("path"),XJ=require("minimist"),pD=require("fs-extra"),ED=require("lodash");cn.initSync();var{CONFIG_PARAMS:jo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Bm}=af,nf,sf,of;function gD(){if(nf!==void 0)return nf;if(cn.getHdbBasePath()!==void 0)return nf=cn.get(jo.STORAGE_PATH)||cf.join(cn.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(gD,"getBaseSchemaPath");function SD(){if(sf!==void 0)return sf;if(cn.getHdbBasePath()!==void 0)return sf=AD(Bm),sf}a(SD,"getSystemSchemaPath");function TD(){if(of!==void 0)return of;if(cn.getHdbBasePath()!==void 0)return of=cn.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(cn.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(TD,"getTransactionAuditStoreBasePath");function ZJ(e,t){let r=cn.get(jo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(TD(),e.toString())}a(ZJ,"getTransactionAuditStorePath");function AD(e,t){e=e.toString(),t=t&&t.toString();let r=cn.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(gD(),e)}a(AD,"getSchemaPath");function e4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,XJ(process.argv));let n=r[jo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!JJ.isObject(n))throw o;i=n}for(let o of i){let c=o[Bm];if(!c)continue;let l=cn.get(jo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return ED.set(l,[Bm,rf.TABLES,t,rf.PATH],u),cn.setProperty(jo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return ED.set(l,[Bm,rf.PATH],f),cn.setProperty(jo.DATABASES,l),f}}let s=r[jo.STORAGE_PATH.toUpperCase()];if(s){if(!pD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return pD.mkdirsSync(i),cn.setProperty(jo.STORAGE_PATH,s),i}return SD()}a(e4,"initSystemSchemaPaths");function t4(){nf=void 0,sf=void 0,of=void 0}a(t4,"resetPaths");RD.exports={getBaseSchemaPath:gD,getSystemSchemaPath:SD,getTransactionAuditStorePath:ZJ,getTransactionAuditStoreBasePath:TD,getSchemaPath:AD,initSystemSchemaPaths:e4,resetPaths:t4}});var ln=P((dAe,wD)=>{"use strict";var r4=Pn().LMDB_ERRORS_ENUM,lAe=require("lmdb"),n4=Ut(),uAe=require("buffer").Buffer,{OVERFLOW_MARKER:yD,MAX_SEARCH_KEY_LENGTH:Hm}=n4,bD=["number","string","symbol","boolean","bigint"];function s4(e){if(e=e?.primaryStore||e,!e)throw new Error(r4.ENV_REQUIRED)}a(s4,"validateEnv");function i4(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(i4,"stringifyData");function o4(e){return e instanceof Date?e.valueOf():e}a(o4,"convertKeyValueToWrite");function a4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(bD.includes(typeof e))return e.length>Hm?[e.slice(0,Hm)+yD]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(bD.includes(typeof i))i.length>Hm?r.push(i.slice(0,Hm)+yD):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(a4,"getIndexedValues");var km=0,OD=0;function ND(){OD=Date.now()-performance.now()}a(ND,"adjustStartTime");ND();var c4=6e4;setInterval(ND,c4).unref();function l4(){let e=performance.now()+OD;return e>km?(km=e,e):(km+=488e-6,km)}a(l4,"getNextMonotonicTime");wD.exports={validateEnv:s4,stringifyData:i4,convertKeyValueToWrite:o4,getNextMonotonicTime:l4,getIndexedValues:a4}});var lf=P((_Ae,ID)=>{"use strict";var u4=(k(),D($)).OPERATIONS_ENUM,yA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=u4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};ID.exports=yA});var uf=P((pAe,LD)=>{"use strict";var mAe=lf(),Fm=(k(),D($)),bA=ae(),CD=j(),d4=require("uuid"),{handleHDBError:Gm,hdb_errors:f4}=me(),{HDB_ERROR_MSGS:qm,HTTP_STATUS_CODES:$m}=f4;LD.exports=PD;function PD(e,t,r){for(let s=0;s<t.length;s++)DD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];_4(i,r,e.operation)}}a(PD,"processRows");PD.validateAttribute=DD;function DD(e){if(Buffer.byteLength(String(e))>Fm.INSERT_MAX_CHARACTER_SIZE)throw Gm(new Error,qm.ATTR_NAME_LENGTH_ERR(e),$m.BAD_REQUEST,void 0,void 0,!0);if(bA.isEmptyOrZeroLength(e)||bA.isEmpty(e.trim()))throw Gm(new Error,qm.ATTR_NAME_NULLISH_ERR,$m.BAD_REQUEST,void 0,void 0,!0)}a(DD,"validateAttribute");function _4(e,t,r){if(!e.hasOwnProperty(t)||bA.isEmptyOrZeroLength(e[t])){if(r===Fm.OPERATIONS_ENUM.INSERT||r===Fm.OPERATIONS_ENUM.UPSERT){e[t]=d4.v4();return}throw CD.error("Update transaction aborted due to record with no hash value:",e),Gm(new Error,qm.RECORD_MISSING_HASH_ERR,$m.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>Fm.INSERT_MAX_CHARACTER_SIZE)throw CD.error(e),Gm(new Error,qm.HASH_VAL_LENGTH_ERR,$m.BAD_REQUEST,void 0,void 0,!0)}a(_4,"validateHash")});var MD,Mn,OA,Vl=be(()=>{MD=require("events"),Mn=class extends MD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new OA;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)}},OA=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 FD(e){wA=e}function E4(){p4=setInterval(function(){for(let e of NA)if(e.stale){let t=e.getContext()?.url;BD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},m4).unref()}var IA,xD,BD,HD,kD,vD,NA,h4,df,UD,wA,oc,Vm,m4,p4,Km=be(()=>{IA=M(ln()),xD=M(me()),BD=M(j()),HD=M(le());k();kD=M(ae()),vD=100,NA=new Set,h4=(0,kD.convertToMS)(HD.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(FD,"replicationConfirmation");oc=class e{static{a(this,"DatabaseTransaction")}#e;writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxnsUsed=1,this.readTxn.openTimer&&(this.readTxn.openTimer=0),NA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(NA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-UD>h4)throw new xD.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,IA.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)<vD>>n?l():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return df||(df=s,UD=performance.now(),df.then(()=>{df=null})),s.then(d=>{if(d){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let _=this.writes[0].store.rootStore.databaseName,h=this.writes[this.writes.length-1];wA&&h&&i.push(wA(_,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)+vD/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}},Vm=class extends oc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,IA.getNextMonotonicTime)())}getReadTxn(){}},m4=3e4;a(E4,"startMonitoringTxns");E4()});function wt(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new oc;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n.setContext(e),e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let l=n.commit({doneWriting:!0});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var GD,ac=be(()=>{GD=M(ci());Km();a(wt,"transaction");(0,GD._assignPackageExport)("transaction",wt);wt.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};wt.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function PA(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?PA(d.conditions,d.operator,r,n,s,i,o,c):Wl(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(u,"executeCondition");function f(d,_,h){return d.map((m,S)=>{if(m.conditions){let E=m.operator==="or",T=f(m.conditions,!E,h);return E?(w,v)=>T.some(H=>H(w,v)):(w,v)=>T.every(H=>H(w,v))}let g=(m.attribute||m[0])===r.primaryKey,R=hf(m,r,i,c,g,h);return _&&S<d.length-1&&h&&(h=N4(r.primaryStore,m.estimated_count,h)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function Wl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(c===void 0&&l!=="sort")throw new dn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=_i(n.attributes,E);if(T.relationship){if(o.length<2)throw new dn.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=Wl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let q=!!_i(w.attributes,T.relationship.to)?.elements;H=R4(H,T,w.primaryStore,q,v)}if(T.relationship.from){let q=a(W=>(W?.key!==void 0&&(W=W.key),Wl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=y4(H,T,w.primaryStore,v,q)):H=H.flatMap(q)}return H}else if(o.length===1)o=o[0];else throw new dn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(DA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=fi.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new dn.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>as.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>as.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,as.MAX_SEARCH_KEY_LENGTH)+as.OVERFLOW_MARKER,d=!0,m=m??hf(e,n,null,i,S)),r){let E=u;u=f,f=E,E=!_,_=!d,d=E}let g=S?n.primaryStore:n.indices[o];if(!g||g.isIndexing||h||c===null&&!g.indexNulls){if(s===!1&&!g)throw new dn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new dn.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 dn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new dn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(m=m??hf(e,n,null,i,S),!m)throw new dn.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:Jo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&m(w)?T:Jo.SKIP)}catch(q){H(q)}}))}:T=>T.value==null&&!(T.metadataFlags&(fn|Zo))?Jo.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>as.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Jo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(m(w)?T:Jo.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:Jo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Jo.SKIP)}catch(H){v(H)}}))})}function _i(e,t){if(Array.isArray(t))if(t.length>1){let r=_i(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?_i(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function R4(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 y4(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let l;if(o)for(;l=o.next(),!l.done;){let u=l.value;if(!c.has(u))return c.add(u),l}if(!i){let u=new Set;n.fromRecord=f=>f[t.relationship.from]?.filter?.(d=>u.has(d));for(let f of e){if(n.filters){let d=r.get(f);if(n.filters.some(_=>!_(d)))continue}u.add(f)}return i=u[Symbol.iterator](),this.next()}do{let u=i.next();return u.done?u:(o=s(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hf(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,l=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let f=c[0],d=_i(t.attributes,f),_=d.definition?.tableClass||d.elements.definition?.tableClass,h=n?.[f],m=hf({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},_,r,h?.[f]?.joined,c[1]===_.primaryKey,i);if(!m)return;if(h){h.filters||(h.filters=[]),h.filters.push(m);return}let S=t.propertyResolvers?.[f],g,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()),DA[o]||o){case as.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,fi.compareKeys)(f,l[0])>=0&&(0,fi.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,fi.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,fi.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,fi.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,fi.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,fi.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new dn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Wm(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=Wl(e,r.transaction.getReadTxn(),!1,t).map(zl),H=new Set(v);R.idFilter=q=>H.has(zl(q)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Wm(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Qi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=DA[n]||n,n===as.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=_i(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Wm(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Qi(e.indices[i.relationship.from])/(Qi(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Qi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=T4*Qi(e.primaryStore)+1:n==="between"?r.estimated_count=S4*Qi(e.primaryStore)+1:n==="sort"?r.estimated_count=Qi(e.primaryStore)+1:r.estimated_count=g4*Qi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function zm(e){if(e)if(Xo=e,Kl.lastIndex=0,b4.test(e))try{let t=ff(new Yl,"");if(un!==Xo.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 ${un} in '${Xo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Kl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Xo);){un=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=qD}else{if(l=decodeURIComponent,i="equals",!f)throw new SyntaxError("attribute must be specified before equality comparator");s=_f(f)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=A4[d],l=CA[i]?qD:decodeURIComponent,!f)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_f(f);break;case"&=":case"|=":case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let m={comparator:i,attribute:s||null,value:l(f)};if(i==="eq"&&$D(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else Ym(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Kl.lastIndex=un;let h=ff(f?[]:new Yl,")");switch(f){case"":Ym(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=VD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Xo[un]===","?r.lastIndex=++un:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!f)throw new SyntaxError("property sets must have a defined parent property name");Kl.lastIndex=un,_=ff([],"}"),_.name=f,e.push(_),Xo[un]===","?r.lastIndex=++un:o=!0;break;case"[":Kl.lastIndex=un,f?(_=ff(new Yl,"]"),_.name=f):_=ff(e.conditions?new Yl:[],"]"),e.conditions?(Ym(e,u),e.conditions.push(_),s=null):e.push(_),Xo[un]===","?r.lastIndex=++un: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"&&$D(m,f),Ym(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?O4:Kl,r.lastIndex=un),un===Xo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Ym(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function qD(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 dn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function $D(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new dn.ClientError("wildcard can only be used at the end of a string")}function VD(e){let t=KD(e[0]);return e.length>1&&(t.next=VD(e.slice(1))),t}function KD(e){if(Array.isArray(e)){let t=KD(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function zl(e){return Array.isArray(e)?e.join("\0"):e}function Qi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function N4(e,t,r){return t*r/Qi(e)}var dn,as,fi,Jo,g4,S4,T4,A4,CA,DA,b4,Kl,O4,un,Xo,Yl,cc,mf=be(()=>{dn=M(me()),as=M(Ut()),fi=require("ordered-binary"),Jo=require("lmdb");pf();g4=.3,S4=.1,T4=.05,A4={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},CA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(PA,"executeConditions");a(Wl,"searchByIndex");a(_i,"findAttribute");a(R4,"joinTo");a(y4,"joinFrom");DA={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hf,"filterByType");a(Wm,"estimateCondition");b4=/[()[\]|!<>.]|(=\w*=)/,Kl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,O4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(zm,"parseQuery");a(ff,"parseBlock");a(Ym,"assignOperator");a(_f,"decodeProperty");a(qD,"typedDecoding");a($D,"wildcardDecoding");a(VD,"toSortObject");a(KD,"toSortEntry");Yl=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(zl,"flattenKey");a(Qi,"estimatedEntryCount");a(N4,"intersectionEstimate");cc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var MA={};Ue(MA,{MultiPartId:()=>jm,Resource:()=>$r,snake_case:()=>I4,transformForSelect:()=>Jm});function I4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function YD(e,t){if(lc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(lc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new jm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){lc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return lc=!0,null;e[e.length-1]==="/"&&(lc=!0)}return t.coerceId(decodeURIComponent(e))}function vn(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,u,f;if(r?(o?(f=i,o=o.getContext?.()||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(f=s,c=f[this.primaryKey]??null,o=i.getContext?.()||i):f=i:(f=s,s=void 0,c=f.getId?.()??f[this.primaryKey]),c===null&&(u=!0)):i?o=i.getContext?.()||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="object"&&s){if(l=s,typeof(c=s.url)=="string")if(this.directURLMapping)c=c.slice(1);else{let h=c.indexOf("?");if(h>-1){let S=this.parseQuery(c.slice(h+1));l?S&&(l=Object.assign(S,l)):l=S,c=c.slice(0,h)}let m=this.parsePath(c,o,l);m?.id!==void 0?(m.query&&(l?l=Object.assign(m.query,l):l=m.query),u=m.isCollection,c=m.id):c=m}else if(s[Symbol.iterator]){c=[],u=!0;for(let h of s){if(typeof h=="object"&&h)break;c.push(h)}c.length===0?c=null:(c.length===1&&(c=c[0]),l.slice&&(l=l.slice(c.length,l.length),l.length===0&&(l=null,u=!1)))}c===void 0&&(c=s.id??null,c==null&&(u=!0))}else c=s,l=new cc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return wt(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 Qm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Qm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Un(e,t){let r=new QD.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 LA(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 Jm(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):LA(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(LA(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(LA(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]=Jm(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var WD,zD,QD,w4,$r,Qm,lc,jm,ea=be(()=>{WD=require("crypto");Vl();zD=M(ci()),QD=M(me());ac();mf();w4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$r=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=vn(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=Jm(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=vn(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):Un(t,"put")},{hasContent:!0,type:"update"});static patch=vn(function(t,r,n,s){return t.patch?t.patch(s,r):Un(t,"patch")},{hasContent:!0,type:"update"});static delete=vn(function(t,r,n,s){return t.delete?t.delete(r):Un(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,WD.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),wt(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Un(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=vn(function(t,r,n,s){return t.invalidate?t.invalidate(r):Un(t,"delete")},{hasContent:!1,type:"update"});static post=vn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=vn(function(t,r,n,s){return t.connect?t.connect(s,r):Un(t,"connect")},{hasContent:!0,type:"read"});static subscribe=vn(function(t,r,n,s){return t.subscribe?t.subscribe(r):Un(t,"subscribe")},{type:"read"});static publish=vn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Un(t,"publish")},{hasContent:!0,type:"create"});static search=vn(function(t,r,n,s){let i=t.search?t.search(r):Un(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=Jm(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=vn(function(t,r,n,s){return t.search?t.search(s,r):Un(t,"search")},{hasContent:!0,type:"read"});static copy=vn(function(t,r,n,s){return t.copy?t.copy(s,r):Un(t,"copy")},{hasContent:!0,type:"create"});static move=vn(function(t,r,n,s){return t.move?t.move(s,r):Un(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Un(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return zm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&w4[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:YD(t,this),isCollection:lc}}let i=YD(t,this);return lc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r.getContext?.(),o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let l;if(i.resourceCache?l=i.resourceCache:l=i.resourceCache=[],l.asMap){let u=l.asMap.get(t);if(s=u?.find(f=>f.constructor===c),s)return s;u||l.asMap.set(t,u=[]),u.push(s=new c(t,i))}else{if(s=l.find(u=>u.#e===t&&u.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let u=new Map;for(let f of l){let d=f.#e,_=u.get(d);_?_.push(f):u.set(d,[f])}i.resourceCache.length=0,i.resourceCache.asMap=u}}}else s=new c(t,i);return o&&(s.#n=!0),s}subscribe(t){return new Mn}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Mn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this.#e}getContext(){return this.#t}};(0,zD._assignPackageExport)("Resource",$r);a(I4,"snake_case");Qm=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(YD,"pathToId");jm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(vn,"transactional");a(Un,"missingMethod");a(LA,"selectFromObject");a(Jm,"transformForSelect")});var ta,vA=be(()=>{ta=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var XD={};Ue(XD,{Resources:()=>Xm,keyArrayToString:()=>Ql,resetResources:()=>C4,resources:()=>cs});function C4(){return cs=new Xm,Ke.resources=cs,cs}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var jD,JD,Xm,cs,jl=be(()=>{ac();vA();jD=M(j()),JD=M(me());Pr();Xm=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 JD.ServerError(`Conflicting paths for ${t}`);jD.default.error(c),i.Resource=new ta(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return wt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(C4,"resetResources");a(Ql,"keyArrayToString")});var UA=P((GAe,ZD)=>{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=ZD.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 HA={};Ue(HA,{loadGQLSchema:()=>L4,start:()=>BA,startOnMainThread:()=>D4});function BA({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):P4.includes(R.type)||(0,tL.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,xA.dirname)(n),R.tableClass):i.set((0,xA.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new eL.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 xA,eL,tL,P4,D4,L4,rL=be(()=>{xA=require("path"),eL=require("node:vm");ve();tL=M(rt()),P4=["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(BA,"start");D4=BA,L4=BA({ensureTable:dt}).handleFile});var lL={};Ue(lL,{parse:()=>FA,streamAsJSON:()=>Ef,stringify:()=>uc});function Ef(e){return new kA({value:e})}function nL(e){return console.error(e),JSON.stringify(e.toString())}function sL(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function uc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===aL)return cL(e);if(t.resolution)return t.resolution.then(()=>uc(e));throw t}}function cL(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+=cL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+uc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function FA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),U4.test(e)?M4.parse(e):JSON.parse(e)):null}var iL,oL,M4,v4,aL,kA,U4,GA=be(()=>{iL=require("stream"),oL=M(require("json-bigint-fixes")),M4=(0,oL.default)({useNativeBigInt:!0}),v4=1e4,aL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw aL};a(Ef,"streamAsJSON");kA=class extends iL.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),nL)}catch(s){yield nL(s)}else yield uc(t)}else yield uc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);sL(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>v4?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 sL(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(nL,"handleError");a(sL,"when");a(uc,"stringify");a(cL,"jsStringify");U4=/[[,:]\s*-?\d{16,}/;a(FA,"parse")});var hi=P(ep=>{var Zm=j();for(let e of["trace","debug","info","warn","error","fatal","notify"])Zm.logsAtLevel(e)&&(ep[e]=Zm[e]);ep.loggerWithTag=e=>Zm.loggerWithTag(e,!0);ep.setLogLevel=Zm.setLogLevel});var dp={};Ue(dp,{Blob:()=>mi,blobsWereEncoded:()=>fc,databasePaths:()=>$A,decodeBlobsWithWrites:()=>lp,decodeFromDatabase:()=>_c,decodeWithBlobCallback:()=>up,deleteBlob:()=>op,deleteBlobsInObject:()=>ra,deleteRootBlobPathsForDB:()=>KA,encodeBlobsAsBuffers:()=>K4,encodeBlobsWithFilePath:()=>cp,findBlobsInObject:()=>Xl,getFileId:()=>ap,getFilePathForBlob:()=>SL,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>k4});function pL(){}function op(e){let t=SL(e);t&&setTimeout(()=>{(0,Qe.unlink)(t,r=>{r&&ji.default.debug?.("Error trying to remove blob file",r)})},EL)}function k4(e){EL=e}function gL(e){let t=_n.get(e);if(!t)t={storageIndex:0,fileId:null,store:hn},_n.set(e,t);else{if(t.saving)return t;t.store=hn}return G4(t),t.source?qA(e,t.source,t):t.contentBuffer?F4(e,t):qA(e,Sf.Readable.from(e.stream()),t),t}function qA(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(B4),h=(0,sp.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(x4),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(hr),T=new DataView(E.buffer);return R|=BigInt(o?VA:mL)<<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-hr;e.size=g,(0,Qe.write)(d.fd,m(g),0,hr,0,S)}})}),e}function ap(e){return _n.get(e)?.fileId}function SL(e){let t=_n.get(e);return t?.fileId&&Tf(t)}function Af(e){if(!e)throw new Error("No store specified, can not determine blob storage path");let t=$A.get(e);if(!t){if(!e.databaseName)return ji.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,ip.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Xi.join)(n,e.databaseName)):t=[(0,Xi.join)((0,ip.getHdbBasePath)(),"blobs",e.databaseName)],$A.set(e,t)}return t}async function KA(e){let t=Af(e);t&&await Promise.all(t.map(r=>TL(r)))}async function TL(e){if((0,Qe.existsSync)(e)){for(let t of await(0,Bs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await TL((0,Xi.join)(e,t.name));else try{await(0,Bs.unlink)((0,Xi.join)(e,t.name))}catch(r){ji.default.warn?.("Error deleting file",r)}try{await(0,Bs.rmdir)(e)}catch(t){ji.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Xi.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 F4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<hL))return e.size=n,qA(e,Sf.Readable.from([r]),t)}function G4(e){let t=Af(e.store),r=q4(),n=t?.length>1?$4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Xi.dirname)(i);(0,Qe.existsSync)(o)||(0,_L.ensureDirSync)(o),e.filePath=i}function q4(){let e=fL.get(hn);if(!e){let t=0,r=Af(hn);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,Xi.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(hn.getUserSharedBuffer("blob-file-id",e.buffer)),fL.set(hn,e)}return Number(Atomics.add(e,0,1n))}function $4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(np);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,V4(e)),e.frequencyTable[t%np]}async function V4(e){if(!Bs.statfs)return;let t=await Promise.all(e.map(async(s,i)=>{let o=await(0,Bs.statfs)(s),c=o.bavail*o.bsize;return Math.pow(c,.8)})),r=new Array(np),n=t.map(s=>1/s);for(let s=0;s<np;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 cp(e,t,r){Jl=t,hn=r,fc=!1;try{return e()}finally{Jl=void 0,hn=void 0}}function K4(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 lp(e,t){try{Dr=[],dc=t,e()}catch(n){throw dc=void 0,Dr=void 0,n}dc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function up(e,t,r){hn=r;try{return dc=t,e()}finally{dc=void 0}}function _c(e,t){return hn=t,e()}function ra(e){Xl(e,t=>{op(t)})}function Xl(e,t){if(e instanceof mi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Xl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&Xl(e[r],t)}}function Y4(){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,Bs,Qe,sp,Sf,_L,ip,Xi,ji,hL,hr,mL,VA,uL,x4,B4,dL,_n,dc,mi,Jl,Dr,hn,fc,gf,tp,H4,rp,EL,$A,fL,np,ls=be(()=>{Ji=require("msgpackr"),Bs=require("node:fs/promises"),Qe=require("node:fs"),sp=require("node:zlib"),Sf=require("node:stream"),_L=require("fs-extra"),ip=M(le());k();Xi=require("path"),ji=M(hi());Zi();hL=8192,hr=8,mL=0,VA=1,uL=255,x4=new Uint8Array([0,mL,255,255,255,255,255,255]),B4=new Uint8Array([0,VA,255,255,255,255,255,255]),dL=0xffffffffffff,_n=new WeakMap,mi=global.Blob||Y4(),fc=!1,gf=new Uint8Array(8),tp=new DataView(gf.buffer),H4=6e4;a(pL,"InstanceOfBlobWithNoConstructor");pL.prototype=mi.prototype;rp=class e extends pL{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=_n.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):(WA()&&YA(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=_n.get(this),{start:r,end:n,contentBuffer:s}=t;if(s)return(n!==void 0||r!==void 0)&&(s=s.subarray(r??0,n??t.contentBuffer.length)),Promise.resolve(s);let i=Tf(t),o,c=a(async()=>{let l,u=hr;try{if(l=await(0,Bs.readFile)(i),l.length>=hr){l.copy(gf,0,0,hr);let d=tp.getBigUint64(0);if(Number(d>>48n)===uL)throw new Error("Error in blob: "+buffer.subarray(hr));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<dL&&(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]===VA?new Promise((d,_)=>{(0,sp.deflate)(l.subarray(hr),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(hr))},"readContents");return c()}async arrayBuffer(){let t=await this.bytes(),r=new ArrayBuffer(t.length);return new Uint8Array(r).set(t),r}stream(){let t=_n.get(this),{contentBuffer:r,start:n,end:s}=t;if(r)return(s!=null||n!=null)&&(r=r.subarray(n??0,s??t.contentBuffer.length)),new ReadableStream({pull(S){S.enqueue(r),S.close()}});let i=Tf(t),o,c=0,l=0,u,f,d,_=!1,h=this;return new ReadableStream({start(){let S=1e3,g=a((R,E)=>{(0,Qe.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(ji.default.debug?.("File does not exist yet, waiting for it to be created",i,S),S-- >0))return setTimeout(()=>{m(),g(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<hr){R-- >0&&d!==!1?(m(),ji.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(ji.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,hr);let se=tp.getBigUint64(0);if(Number(se>>48n)===uL)return v(new Error("Error in blob: "+te.subarray(hr)));if(g=Number(se&0xffffffffffffn),g<dL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(hr,W),l-=hr}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,Qe.read)(o,se,0,hr,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(tp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},H4).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 ji.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=_n.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};_n.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)};_n.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(hn=t?.primaryStore?.rootStore,!hn)throw new Error("No target table specified");return gL(this).saving??Promise.resolve()}},EL=500;a(op,"deleteBlob");a(k4,"setDeletionDelay");global.createBlob=function(e,t){let r=new rp(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(_n.set(r,n),e instanceof Uint8Array)r.size=e.length,n.contentBuffer=e;else if(e instanceof Sf.Readable)n.source=e;else if(typeof e=="string")n.contentBuffer=Buffer.from(e);else if(e?.[Symbol.asyncIterator]||e?.[Symbol.iterator])n.source=Sf.Readable.from(e);else throw new Error("Invalid source type");return r};a(gL,"saveBlob");a(qA,"writeBlobWithStream");a(ap,"getFileId");a(SL,"getFilePathForBlob");$A=new Map;a(Af,"getRootBlobPathsForDB");a(KA,"deleteRootBlobPathsForDB");a(TL,"rimrafSteadily");a(Tf,"getFilePath");a(F4,"writeBlobWithBuffer");a(G4,"generateFilePath");fL=new Map;a(q4,"getNextFileId");np=128;a($4,"getNextStorageIndex");a(V4,"createFrequencyTableForStoragePaths");a(cp,"encodeBlobsWithFilePath");a(K4,"encodeBlobsAsBuffers");a(lp,"decodeBlobsWithWrites");a(up,"decodeWithBlobCallback");a(_c,"decodeFromDatabase");a(ra,"deleteBlobsInObject");a(Xl,"findBlobsInObject");(0,Ji.addExtension)({Class:mi,type:11,unpack:a(function(e){let t=(0,Ji.unpack)(e),r=new rp;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(_n.set(r,{storageIndex:t[1],fileId:t[2],store:hn}),dc)return dc(r)??r;if(!hn)throw new Error("No store specified, cannot load blob from storage")}else _n.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=_n.get(e);if(Jl!==void 0&&(fc=!0,t?.recordId!==void 0&&t.recordId!==Jl))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<hL)return r.size=t.contentBuffer.length,(0,Ji.pack)([r,t.contentBuffer])}if(Jl!==void 0){if(t=gL(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Jl,(0,Ji.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,Qe.readFileSync)(Tf(t));if(n.length>=hr&&(n.copy(gf,0,0,hr),Number(tp.getBigUint64(0)&0xffffffffffffn)===n.length-hr))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(Y4,"polyfillBlob")});var IL={};Ue(IL,{asyncSerialization:()=>YA,contentTypes:()=>JA,findBestSerializer:()=>_p,getDeserializer:()=>ro,hasAsyncSerialization:()=>WA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>na,toCsvStream:()=>fp});function z4(e){try{return e?.[0]===123?jA(e):e}catch{return e}}function bf(e){e.register(j4,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new hc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?mc.Readable.from((0,pi.encodeIter)(t,yf)):(0,pi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),fp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,pi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,hc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function _p(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=Vr.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 yL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Vr.keys()).join(", "),406);n=Vr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=RL&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array||e instanceof mi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=_p(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,to.createBrotliCompress)({params:{[to.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?to.constants.BROTLI_MODE_TEXT:to.constants.BROTLI_MODE_GENERIC,[to.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>RL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,to.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function na(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;eo=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=_p(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return eo?.length>0?(eo.length===1?eo[0]:Promise.all(eo)).then(()=>na(e,t,!0)):n}finally{eo=void 0}}function YA(e){if(eo)eo.push(e);else throw new Error("Unable to serialize asynchronously")}function WA(){return!!eo}function J4(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 Z4(e){return X4.includes(e)}function e3(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 ro(e="",t=!1){let r=e3(e),n=r.type&&Vr.get(r.type)?.deserialize||t3(r);return t?s=>J4(s).then(n):n}function t3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!Z4(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 jA(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function r3(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 fp(e,t){let r=mc.default.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new W4(n,s);return r.pipe(i)}var pi,hc,to,yL,mc,bL,zA,OL,QA,W4,NL,Rf,jA,yf,Vr,JA,AL,wL,Q4,j4,RL,eo,X4,Zi=be(()=>{GA();pi=require("msgpackr"),hc=require("cbor-x"),to=require("zlib"),yL=M(me()),mc=M(require("stream"));Pr();bL=M(ci()),zA=M(le());k();OL=M(require("yaml")),QA=M(hi());ls();({Transform:W4}=require("json2csv")),NL=zA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=NL?uc:JSON.stringify,jA=NL?FA:JSON.parse,yf={useRecords:!1,useToJSON:!0},Vr=new Map,JA=Vr;Ke.contentTypes=JA;(0,bL._assignPackageExport)("contentTypes",JA);Vr.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return jA(e)},q:.8});AL=new hc.Encoder(yf);Vr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new hc.EncoderStream(yf).end(e)},serialize:AL.encode,deserialize:AL.decode,q:1});Vr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?mc.Readable.from((0,pi.encodeIter)(e,yf)):(0,pi.pack)(e)},serialize:pi.pack,deserialize:pi.unpack,q:.9});Vr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),fp(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]),fp(e,e?.getColumns?.())},q:.1});Vr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return mc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Vr.set("text/yaml",{serialize(e){return OL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Vr.set("text/event-stream",{serializeStream:a(function(e){return mc.Readable.from(r3(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+`
11
11
  `),e.data){let r=e.data;typeof r=="object"&&(r=Rf(r)),t+="data: "+r+`
12
12
  `}return e.id&&(t+="id: "+e.id+`
13
13
  `),e.retry&&(t+="retry: "+e.retry+`