harperdb 4.5.12 → 4.5.13

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:hJ.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(gJ,"findPs")});var vt=P((oAe,xP)=>{"use strict";var SJ="__dbis__",TJ="__txns__",AJ="__environment_name__",RJ="__dbi_defintion__",yJ={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"},bJ=["__createdtime__","__updatedtime__"],OJ="\uFFFF",UP={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},NJ=Object.values(UP);xP.exports={AUDIT_STORE_NAME:TJ,INTERNAL_DBIS_NAME:SJ,DBI_DEFINITION_NAME:RJ,SEARCH_TYPES:yJ,TIMESTAMP_NAMES:bJ,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:AJ,TRANSACTIONS_DBI_NAMES_ENUM:UP,TRANSACTIONS_DBIS:NJ,OVERFLOW_MARKER:OJ}});var Ln=P((aAe,KP)=>{"use strict";var BP=(k(),D($)),HP=vt(),kP={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},FP=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),GP={500:FP("There was an error processing your request."),400:"Invalid request"},wJ=GP[kP.INTERNAL_SERVER_ERROR],IJ={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")},CJ={CONFIG_VALIDATION:a(e=>`HarperDB config file validation error: ${e}`,"CONFIG_VALIDATION")},PJ={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"},DJ={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 ${HP.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${HP.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"},LJ={ATTR_NAME_LENGTH_ERR:a(e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${BP.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 ${BP.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"},qP={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"},MJ={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."},vJ={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")},UJ={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"},xJ={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},BJ={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")},$P={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")},VP={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")},HJ={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"},kJ={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},FJ={...qP,...PJ,...IJ,...MJ,...vJ,...UJ,...xJ,...BJ,...LJ,...$P,...VP,...HJ,...kJ,...CJ};KP.exports={CHECK_LOGS_WRAPPER:FP,HDB_ERROR_MSGS:FJ,DEFAULT_ERROR_MSGS:GP,DEFAULT_ERROR_RESP:wJ,HTTP_STATUS_CODES:kP,LMDB_ERRORS_ENUM:DJ,AUTHENTICATION_ERROR_MSGS:qP,VALIDATION_ERROR_MSGS:$P,ITC_ERRORS:VP}});var me=P((lAe,zP)=>{"use strict";var Gl=Ln(),GJ=j(),qJ=(k(),D($)),Mm=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,YP),this.statusCode=n||Gl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Gl.DEFAULT_ERROR_MSGS[n]?Gl.DEFAULT_ERROR_MSGS[n]:Gl.DEFAULT_ERROR_MSGS[Gl.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&&GJ[s](i)}},SA=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}},TA=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function YP(e,t,r,n=qJ.LOG_LEVELS.ERROR,s=null,i=!1){if(WP(e))return e;let o=new Mm(e,t,r,n,s);return i&&delete o.stack,o}a(YP,"handleHDBError");function WP(e){return e.__proto__.constructor.name===Mm.name}a(WP,"isHDBError");zP.exports={isHDBError:WP,handleHDBError:YP,ClientError:SA,ServerError:TA,hdb_errors:Gl}});var AA=P(jP=>{"use strict";var $J={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
  `)},VJ="certificate.pem",KJ="privateKey.pem",YJ="caCertificate.pem",WJ="natsCertificate.pem",zJ="natsCaCertificate.pem",St={DEFAULT:"default","DEFAULT-CA":"default-ca",SERVER:"server",CA:"ca","OPERATIONS-API":"operations-api","OPERATIONS-CA":"operations-ca"},jJ={tls_certificate:St.SERVER,tls_certificateAuthority:St.CA,customFunctions_tls_certificate:St.SERVER,customFunctions_tls_certificateAuthority:St.CA,operationsApi_tls_certificate:St["OPERATIONS-API"],operationsApi_tls_certificateAuthority:St["OPERATIONS-CA"]},QJ={[St.SERVER]:2,[St.DEFAULT]:1},JJ={[St["OPERATIONS-API"]]:3,[St.SERVER]:2,[St.DEFAULT]:1},XJ={[St["OPERATIONS-API"]]:3,[St.SERVER]:2,[St.DEFAULT]:1},ZJ={[St["OPERATIONS-CA"]]:3,[St.CA]:2,[St["DEFAULT-CA"]]:1},e2={[St["OPERATIONS-CA"]]:3,[St.CA]:2,[St["DEFAULT-CA"]]:1},t2={[St.CA]:2,[St["DEFAULT-CA"]]:1};Object.assign(jP,{CERTIFICATE_PEM_NAME:VJ,PRIVATEKEY_PEM_NAME:KJ,CA_PEM_NAME:YJ,CERT_NAME:St,CERT_CONFIG_NAME_MAP:jJ,CERT_PREFERENCE_APP:QJ,CERT_PREFERENCE_OPS:JJ,CERT_PREFERENCE_REP:XJ,CA_CERT_PREFERENCE_REP:ZJ,CA_CERT_PREFERENCE_OPS:e2,CA_CERT_PREFERENCE_APP:t2,CERTIFICATE_VALUES:$J,NATS_CERTIFICATE_PEM_NAME:WJ,NATS_CA_PEM_NAME:zJ})});var tt=P((fAe,QP)=>{"use strict";var an=require("validate.js");an.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||an.validators.type.checks[t](e)?null:` must be a '${t}' value`};an.validators.type.checks={Object:a(function(e){return an.isObject(e)&&!an.isArray(e)},"Object"),Array:an.isArray,Integer:an.isInteger,Number:an.isNumber,String:an.isString,Date:an.isDate,Boolean:a(function(e){return typeof e=="boolean"},"Boolean")};an.validators.hasValidFileExt=function(e,t){return an.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};QP.exports={validateObject:r2,validateObjectAsync:n2,validateBySchema:s2};function r2(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=an(e,t,{format:"flat"});return r?new Error(r):null}a(r2,"validateObject");async function n2(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await an.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(n2,"validateObjectAsync");function s2(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(s2,"validateBySchema")});var yA=P((mAe,rD)=>{"use strict";var eD=require("fs-extra"),Ee=require("joi"),i2=require("os"),{boolean:He,string:ut,number:Jt,array:Wo}=Ee.types(),{totalmem:JP}=require("os"),sc=require("path"),o2=j(),RA=ae(),hAe=AA(),XP=(k(),D($)),a2=tt(),ZP="log",c2="components",l2="Invalid logging.rotation.maxSize unit. Available units are G, M or K",u2="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",d2="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",f2="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",_2="rootPath config parameter is undefined",cn=Ee.alternatives([Jt.min(0),ut]).optional().empty(null),vm=Ee.alternatives([Wo.items(ut,{host:ut.required(),port:cn},{hostname:ut.required(),port:cn}).empty(null),Wo.items(ut)]),ui,tD=!1;rD.exports={configValidator:h2,routesValidator:T2,route_constraints:vm};function h2(e,t=!1){if(tD=t,ui=e.rootPath,RA.isEmpty(ui))throw _2;let r=He.optional(),n=Jt.min(0).max(1e3).empty(null).default(S2),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(p2).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:cn,routes:vm}).required()}).required(),leafNodes:Ee.object({network:Ee.object({port:cn}).required()}).required(),network:Ee.object({port:cn}).required()}).required(),leafServer:Ee.object({network:Ee.object({port:cn,routes:vm}).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:Wo.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:cn,securePort:cn,routes:Wo.optional().empty(null),databases:Ee.alternatives(ut,Wo),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(g2).optional().empty(null),maxSize:ut.custom(E2).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:Wo.optional(),headersTimeout:Jt.min(1).optional(),keepAliveTimeout:Jt.min(1).optional(),port:cn,domainSocket:Ee.optional().empty("hdb/operations-server").default(Xd),securePort:cn,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:cn,securePort:cn,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:Wo.optional(),headersTimeout:Jt.min(1).optional(),port:cn,securePort:cn,maxHeaderSize:Jt.optional(),mtls:Ee.alternatives([He.optional(),Ee.object({user:ut.optional(),certificateAuthority:i,required:He.optional()})]),threadRange:Ee.alternatives([Wo.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(h2,"configValidator");function m2(e){return tD||eD.existsSync(e)?null:`Specified path ${e} does not exist.`}a(m2,"doesPathExist");function p2(e,t){Ee.assert(e,ut.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=m2(e);if(r)return t.message(r)}a(p2,"validatePath");function E2(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(l2);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(d2):e}a(E2,"validateRotationMaxSize");function g2(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(u2);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(f2):e}a(g2,"validateRotationInterval");function S2(e,t){let r=t.state.path.join("."),n=i2.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||JP();return i=Math.round(Math.min(i,JP())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),o2.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(S2,"setDefaultThreads");function Xd(e,t){let r=t.state.path.join(".");if(!RA.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(RA.isEmpty(ui))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return sc.join(ui,c2);case"logging.root":return sc.join(ui,ZP);case"clustering.leafServer.streams.path":return sc.join(ui,"clustering","leaf");case"storage.path":let n=sc.join(ui,XP.LEGACY_DATABASES_DIR_NAME);return eD.existsSync(n)?n:sc.join(ui,XP.DATABASES_DIR_NAME);case"logging.rotation.path":return sc.join(ui,ZP);case"operationsApi.network.domainSocket":return r==null?null:sc.join(ui,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Xd,"setDefaultRoot");function T2(e){let t=Ee.object({routes:vm});return a2.validateBySchema({routes:e},t)}a(T2,"routesValidator")});var ql={};Ue(ql,{server:()=>Ke});var nD,Ke,Pr=be(()=>{nD=M(ai()),Ke={};(0,nD._assignPackageExport)("server",Ke)});var bt=P(hD=>{"use strict";var as=(k(),D($)),pr=ae(),Xt=j(),{configValidator:A2,routesValidator:sD}=yA(),$r=require("fs-extra"),oD=require("yaml"),vn=require("path"),R2=require("is-number"),aD=require("properties-reader"),y2=require("lodash"),{handleHDBError:b2}=me(),{HTTP_STATUS_CODES:O2,HDB_ERROR_MSGS:$l}=Ln(),{server:N2}=(Pr(),D(ql)),{PACKAGE_ROOT:cD}=mt(),{DATABASES_PARAM_CONFIG:Zd,CONFIG_PARAMS:Mn,CONFIG_PARAM_MAP:xs}=as,w2="Unable to get config value because config is uninitialized",I2="Config successfully initialized",C2="Error backing up config file",P2="Empty parameter sent to getConfigValue",lD=vn.join(cD,"config","yaml",as.HDB_DEFAULT_CONFIG_FILE),D2=vn.join(cD,"config","yaml","defaultNatsConfig.yaml"),L2="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",iD={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"},Um,yt,xm;Object.assign(hD,{createConfigFile:M2,getDefaultConfig:v2,getConfigValue:dD,initConfig:Bm,flattenConfig:Vl,updateConfigValue:fD,updateConfigObject:x2,getConfiguration:k2,setConfiguration:F2,readConfigFile:wA,getClusteringRoutes:G2,initOldConfig:_D,getConfigFromFile:q2,getConfigFilePath:ic,addConfig:$2,deleteConfigFromFile:V2,getConfigObj:K2,resolvePath:bA,getFlatConfigObj:Y2});function bA(e){if(e?.startsWith("~/"))return vn.join(pr.getHomeDir(),e.slice(1));let t=le();try{return vn.resolve(t.getHdbBasePath(),e)}catch(r){return console.error("Unable to resolve path",e,r),e}}a(bA,"resolvePath");function M2(e,t=!1){let r=zo(lD);if(e.clustering_enabled||e.CLUSTERING_ENABLED||e.clustering){let c=oD.parseDocument($r.readFileSync(D2,"utf8"),{simpleKeys:!0});r.addIn(["clustering"],c.toJSON().clustering)}Um=Vl(r.toJSON());let n;for(let c in e){let l=xs[c.toLowerCase()];if(l===Mn.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=OA(l,e[c]);l==="rootPath"&&f?.endsWith("/")&&(f=f.slice(0,-1));try{r.setIn([...u],f)}catch(d){Xt.error(d)}}}n&&uD(r,n),NA(r,t);let s=r.toJSON();yt=Vl(s);let i=r.getIn(["rootPath"]),o=vn.join(i,as.HDB_CONFIG_FILE);if($r.createFileSync(o),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);$r.writeFileSync(o,String(r)),Xt.trace(`Config file written to ${o}`)}a(M2,"createConfigFile");function uD(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!pr.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=[Mn.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=[Mn.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){Xt.error("Error parsing schemas CLI/env config arguments",n)}}a(uD,"setSchemasConfig");function v2(e){if(Um===void 0){let r=zo(lD);Um=Vl(r.toJSON())}let t=xs[e.toLowerCase()];if(t!==void 0)return Um[t.toLowerCase()]}a(v2,"getDefaultConfig");function dD(e){if(e==null){Xt.info(P2);return}if(yt===void 0){Xt.trace(w2);return}let t=xs[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(dD,"getConfigValue");function ic(e=pr.getPropsFilePath()){let t=pr.getEnvCliRootPath();if(t)return bA(vn.join(t,as.HDB_CONFIG_FILE));let r=aD(e);return bA(r.get(as.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}a(ic,"getConfigFilePath");function Bm(e=!1){if(yt===void 0||e){let t;if(!pr.noBootFile()){t=pr.getPropsFilePath();try{$r.accessSync(t,$r.constants.F_OK|$r.constants.R_OK)}catch(i){throw Xt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=ic(t),n;if(r.includes("config/settings.js"))try{_D(r);return}catch(i){if(i.code!==as.NODE_ERROR_CODES.ENOENT)throw i}try{n=zo(r)}catch(i){if(i.code===as.NODE_ERROR_CODES.ENOENT){Xt.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 Xt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}U2(n,r),NA(n);let s=n.toJSON();if(N2.config=s,yt=Vl(s),yt.logging_rotation_rotate)for(let i in iD)yt[i]&&Xt.error(`Config ${iD[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Xt.trace(I2)}}a(Bm,"initConfig");function U2(e,t){let r=e.getIn(["rootPath"]),n=!1;if(e.hasIn(["storage","path"])||(e.setIn(["storage","path"],vn.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],vn.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(Xt.trace("Updating config file with missing config params"),e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${e.errors}`);$r.writeFileSync(t,String(e))}}a(U2,"checkForUpdatedConfig");function NA(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 $l.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 $l.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=A2(r,t);if(n.error)throw $l.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(NA,"validateConfig");function x2(e,t){yt===void 0&&(yt={});let r=xs[e.toLowerCase()];if(r===void 0){Xt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(x2,"updateConfigObject");function fD(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&Bm();let o=dD(xs.hdb_root),c=vn.join(o,as.HDB_CONFIG_FILE),l=zo(c),u;if(r&&yt){let _=!1;for(let h in r)if(r[h]!=yt[h.toLowerCase()]){_=!0;break}if(!_){Xt.trace("No changes detected in config parameters, skipping update");return}}if(r===void 0&&e.toLowerCase()===Mn.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=OA(_,t);l.setIn([...h],m)}else for(let _ in r){let h=xs[_.toLowerCase()];if(h===Mn.HTTP_SECUREPORT&&r[_]===yt[Mn.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),h===Mn.OPERATIONSAPI_NETWORK_SECUREPORT&&r[_]===yt[Mn.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),h===Mn.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=as.LEGACY_CONFIG_PARAMS[_.toUpperCase()];S&&S.startsWith("customFunctions")&&l.hasIn(S.split("_"))&&(h=S,m=S.split("_"));let g=OA(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){Xt.error(R)}}}u&&uD(l,u),NA(l);let f=l.getIn(["rootPath"]),d=vn.join(f,as.HDB_CONFIG_FILE);if(n===!0&&B2(c,f),l.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${l.errors}`);$r.writeFileSync(d,String(l)),s&&(yt=Vl(l.toJSON())),Xt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(fD,"updateConfigValue");function B2(e,t){try{let r=vn.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${as.HDB_CONFIG_FILE}.bak`);$r.copySync(e,r),Xt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Xt.error(C2),Xt.error(r)}}a(B2,"backupConfigFile");var H2=["databases"];function Vl(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}),xm=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])&&!H2.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;!Mn[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(Vl,"flattenConfig");function OA(e,t){if(e===Mn.CLUSTERING_NODENAME||e===Mn.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(R2(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||pr.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 pr.autoCast(t)}a(OA,"castConfigValue");function k2(){let e=pr.getPropsFilePath(),t=ic(e);return zo(t).toJSON()}a(k2,"getConfiguration");async function F2(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return fD(void 0,void 0,s,!0),L2}catch(i){throw typeof i=="string"||i instanceof String?b2(i,i,O2.BAD_REQUEST,void 0,void 0,!0):i}}a(F2,"setConfiguration");function wA(){let e=pr.getPropsFilePath();try{$r.accessSync(e,$r.constants.F_OK|$r.constants.R_OK)}catch(n){if(!pr.noBootFile())throw Xt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=ic(e);return zo(t).toJSON()}a(wA,"readConfigFile");function zo(e){return oD.parseDocument($r.readFileSync(e,"utf8"),{simpleKeys:!0})}a(zo,"parseYamlDoc");function G2(){let e=wA(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=pr.isEmptyOrZeroLength(t)?[]:t;let r=sD(t);if(r)throw $l.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=pr.isEmptyOrZeroLength(n)?[]:n;let s=sD(n);if(s)throw $l.CONFIG_VALIDATION(s.message);if(!pr.isEmptyOrZeroLength(n)&&!pr.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!pr.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw $l.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(G2,"getClusteringRoutes");function _D(e){let t=aD(e);yt={};for(let r in xs){let n=t.get(r.toUpperCase());if(pr.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=xs[r].toLowerCase();s===Mn.LOGGING_ROOT?yt[s]=vn.dirname(n):yt[s]=n}return yt}a(_D,"initOldConfig");function q2(e){let t=wA();return y2.get(t,e.replaceAll("_","."))}a(q2,"getConfigFromFile");async function $2(e,t){let r=zo(ic());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 $r.writeFile(ic(),String(r))}a($2,"addConfig");function V2(e){let t=ic(pr.getPropsFilePath()),r=zo(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=vn.join(n,as.HDB_CONFIG_FILE);$r.writeFileSync(s,String(r))}a(V2,"deleteConfigFromFile");function K2(){return xm||(Bm(),xm)}a(K2,"getConfigObj");function Y2(){return yt||Bm(),yt}a(Y2,"getFlatConfigObj")});var le=P((SD,TD)=>{"use strict";var IA=require("fs-extra"),oc=require("path"),mD=require("os"),W2=require("properties-reader"),tf=j(),ef=ae(),Le=(k(),D($)),Hm=bt(),z2="Error initializing environment manager",km="BOOT_PROPS_FILE_PATH",pD=!1,j2={[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},Yi={};Object.assign(SD,TD.exports={BOOT_PROPS_FILE_PATH:km,getHdbBasePath:Q2,setHdbBasePath:J2,get:ED,initSync:Z2,setProperty:Ye,initTestEnvironment:t4,setCloneVar:e4});function Q2(){return Yi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Q2,"getHdbBasePath");function J2(e){Yi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(J2,"setHdbBasePath");function ED(e){let t=Hm.getConfigValue(e);return t===void 0?Yi[e]:t}a(ED,"get");function Ye(e,t){j2[e]&&(Yi[e]=t),Hm.updateConfigObject(e,t)}a(Ye,"setProperty");function X2(){let e;try{e=ef.getPropsFilePath(),IA.accessSync(e,IA.constants.F_OK|IA.constants.R_OK),pD=!0;let t=W2(e);return Yi[Le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Le.HDB_SETTINGS_NAMES.INSTALL_USER),Yi[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Yi[km]=e,!0}catch{return tf.trace(`Environment manager found no properties file at ${e}`),!1}}a(X2,"doesPropFileExist");function Z2(e=!1){try{((pD||X2()||ef.noBootFile())&&!gD||e)&&(Hm.initConfig(e),Yi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Hm.getConfigValue(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){tf.error(z2),tf.error(t),console.error(t),process.exit(1)}}a(Z2,"initSync");var gD=!1;function e4(e){gD=e}a(e4,"setCloneVar");function t4(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=oc.join(__dirname,"../../","unitTests");Yi[km]=oc.join(l,"hdb_boot_properties.file"),Ye(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,oc.join(l,"settings.test")),Ye(Le.HDB_SETTINGS_NAMES.INSTALL_USER,mD.userInfo()?mD.userInfo().username:void 0),Ye(Le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ye(Le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,oc.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,oc.join(l,"envDir")),Ye(Le.CONFIG_PARAMS.STORAGE_PATH,oc.join(l,"envDir")),s&&(Ye(Le.CONFIG_PARAMS.HTTP_SECUREPORT,ED(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,oc.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 ${km}. Please check your boot props and settings files`;tf.fatal(r),tf.error(t)}}a(t4,"initTestEnvironment")});var pt=P((TAe,wD)=>{"use strict";var af=(k(),D($)),r4=ae(),ln=le(),cf=require("path"),n4=require("minimist"),AD=require("fs-extra"),RD=require("lodash");ln.initSync();var{CONFIG_PARAMS:jo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Fm}=af,nf,sf,of;function yD(){if(nf!==void 0)return nf;if(ln.getHdbBasePath()!==void 0)return nf=ln.get(jo.STORAGE_PATH)||cf.join(ln.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(yD,"getBaseSchemaPath");function bD(){if(sf!==void 0)return sf;if(ln.getHdbBasePath()!==void 0)return sf=ND(Fm),sf}a(bD,"getSystemSchemaPath");function OD(){if(of!==void 0)return of;if(ln.getHdbBasePath()!==void 0)return of=ln.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(ln.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(OD,"getTransactionAuditStoreBasePath");function s4(e,t){let r=ln.get(jo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(OD(),e.toString())}a(s4,"getTransactionAuditStorePath");function ND(e,t){e=e.toString(),t=t&&t.toString();let r=ln.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(yD(),e)}a(ND,"getSchemaPath");function i4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,n4(process.argv));let n=r[jo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!r4.isObject(n))throw o;i=n}for(let o of i){let c=o[Fm];if(!c)continue;let l=ln.get(jo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return RD.set(l,[Fm,rf.TABLES,t,rf.PATH],u),ln.setProperty(jo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return RD.set(l,[Fm,rf.PATH],f),ln.setProperty(jo.DATABASES,l),f}}let s=r[jo.STORAGE_PATH.toUpperCase()];if(s){if(!AD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return AD.mkdirsSync(i),ln.setProperty(jo.STORAGE_PATH,s),i}return bD()}a(i4,"initSystemSchemaPaths");function o4(){nf=void 0,sf=void 0,of=void 0}a(o4,"resetPaths");wD.exports={getBaseSchemaPath:yD,getSystemSchemaPath:bD,getTransactionAuditStorePath:s4,getTransactionAuditStoreBasePath:OD,getSchemaPath:ND,initSystemSchemaPaths:i4,resetPaths:o4}});var un=P((bAe,LD)=>{"use strict";var a4=Ln().LMDB_ERRORS_ENUM,RAe=require("lmdb"),c4=vt(),yAe=require("buffer").Buffer,{OVERFLOW_MARKER:ID,MAX_SEARCH_KEY_LENGTH:Gm}=c4,CD=["number","string","symbol","boolean","bigint"];function l4(e){if(e=e?.primaryStore||e,!e)throw new Error(a4.ENV_REQUIRED)}a(l4,"validateEnv");function u4(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(u4,"stringifyData");function d4(e){return e instanceof Date?e.valueOf():e}a(d4,"convertKeyValueToWrite");function f4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(CD.includes(typeof e))return e.length>Gm?[e.slice(0,Gm)+ID]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(CD.includes(typeof i))i.length>Gm?r.push(i.slice(0,Gm)+ID):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(f4,"getIndexedValues");var qm=0,PD=0;function DD(){PD=Date.now()-performance.now()}a(DD,"adjustStartTime");DD();var _4=6e4;setInterval(DD,_4).unref();function h4(){let e=performance.now()+PD;return e>qm?(qm=e,e):(qm+=488e-6,qm)}a(h4,"getNextMonotonicTime");LD.exports={validateEnv:l4,stringifyData:u4,convertKeyValueToWrite:d4,getNextMonotonicTime:h4,getIndexedValues:f4}});var lf=P((NAe,MD)=>{"use strict";var m4=(k(),D($)).OPERATIONS_ENUM,CA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=m4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};MD.exports=CA});var uf=P((CAe,BD)=>{"use strict";var IAe=lf(),$m=(k(),D($)),PA=ae(),vD=j(),p4=require("uuid"),{handleHDBError:Vm,hdb_errors:E4}=me(),{HDB_ERROR_MSGS:Km,HTTP_STATUS_CODES:Ym}=E4;BD.exports=UD;function UD(e,t,r){for(let s=0;s<t.length;s++)xD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];g4(i,r,e.operation)}}a(UD,"processRows");UD.validateAttribute=xD;function xD(e){if(Buffer.byteLength(String(e))>$m.INSERT_MAX_CHARACTER_SIZE)throw Vm(new Error,Km.ATTR_NAME_LENGTH_ERR(e),Ym.BAD_REQUEST,void 0,void 0,!0);if(PA.isEmptyOrZeroLength(e)||PA.isEmpty(e.trim()))throw Vm(new Error,Km.ATTR_NAME_NULLISH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(xD,"validateAttribute");function g4(e,t,r){if(!e.hasOwnProperty(t)||PA.isEmptyOrZeroLength(e[t])){if(r===$m.OPERATIONS_ENUM.INSERT||r===$m.OPERATIONS_ENUM.UPSERT){e[t]=p4.v4();return}throw vD.error("Update transaction aborted due to record with no hash value:",e),Vm(new Error,Km.RECORD_MISSING_HASH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>$m.INSERT_MAX_CHARACTER_SIZE)throw vD.error(e),Vm(new Error,Km.HASH_VAL_LENGTH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(g4,"validateHash")});var HD,Un,DA,Kl=be(()=>{HD=require("events"),Un=class extends HD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new DA;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)}},DA=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 KD(e){MA=e}function R4(){A4=setInterval(function(){for(let e of LA)if(e.stale){let t=e.getContext()?.url;qD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},T4).unref()}var vA,GD,qD,$D,VD,kD,LA,S4,df,FD,MA,ac,Wm,T4,A4,zm=be(()=>{vA=M(un()),GD=M(me()),qD=M(j()),$D=M(le());k();VD=M(ae()),kD=100,LA=new Set,S4=(0,VD.convertToMS)($D.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(KD,"replicationConfirmation");ac=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),LA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(LA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-FD>S4)throw new GD.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,vA.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)<kD>>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,FD=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];MA&&h&&i.push(MA(_,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)+kD/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Wm=class extends ac{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,vA.getNextMonotonicTime)())}getReadTxn(){}},T4=3e4;a(R4,"startMonitoringTxns");R4()});function Ot(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new ac;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 YD,cc=be(()=>{YD=M(ai());zm();a(Ot,"transaction");(0,YD._assignPackageExport)("transaction",Ot);Ot.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ot.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function xA(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?xA(d.conditions,d.operator,r,n,s,i,o,c):zl(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=D4(r.primaryStore,m.estimated_count,h)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function zl(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 fn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=fi(n.attributes,E);if(T.relationship){if(o.length<2)throw new fn.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=zl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let q=!!fi(w.attributes,T.relationship.to)?.elements;H=w4(H,T,w.primaryStore,q,v)}if(T.relationship.from){let q=a(W=>(W?.key!==void 0&&(W=W.key),zl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=I4(H,T,w.primaryStore,v,q)):H=H.flatMap(q)}return H}else if(o.length===1)o=o[0];else throw new fn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(BA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=di.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new fn.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>cs.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,cs.MAX_SEARCH_KEY_LENGTH)+cs.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>cs.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,cs.MAX_SEARCH_KEY_LENGTH)+cs.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 fn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new fn.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 fn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new fn.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 fn.ClientError(`Unknown search operator ${e.comparator}`)}let R={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(R).map(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:T=>T.value==null&&!(T.metadataFlags&(_n|Xo))?Qo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>cs.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:Qo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Qo.SKIP)}catch(H){v(H)}}))})}function fi(e,t){if(Array.isArray(t))if(t.length>1){let r=fi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?fi(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function w4(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 I4(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=fi(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()),BA[o]||o){case cs.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,di.compareKeys)(f,l[0])>=0&&(0,di.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,di.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,di.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,di.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,di.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,di.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new fn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Qm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function 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=zl(e,r.transaction.getReadTxn(),!1,t).map(jl),H=new Set(v);R.idFilter=q=>H.has(jl(q)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Qm(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Wi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=BA[n]||n,n===cs.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=fi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qm(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Wi(e.indices[i.relationship.from])/(Wi(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=Wi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=O4*Wi(e.primaryStore)+1:n==="between"?r.estimated_count=b4*Wi(e.primaryStore)+1:n==="sort"?r.estimated_count=Wi(e.primaryStore)+1:r.estimated_count=y4*Wi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jm(e){if(e)if(Jo=e,Yl.lastIndex=0,C4.test(e))try{let t=ff(new Wl,"");if(dn!==Jo.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${dn} in '${Jo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Yl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Jo);){dn=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=WD}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=N4[d],l=UA[i]?WD: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"&&zD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else jm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Yl.lastIndex=dn;let h=ff(f?[]:new Wl,")");switch(f){case"":jm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=jD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Jo[dn]===","?r.lastIndex=++dn: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");Yl.lastIndex=dn,_=ff([],"}"),_.name=f,e.push(_),Jo[dn]===","?r.lastIndex=++dn:o=!0;break;case"[":Yl.lastIndex=dn,f?(_=ff(new Wl,"]"),_.name=f):_=ff(e.conditions?new Wl:[],"]"),e.conditions?(jm(e,u),e.conditions.push(_),s=null):e.push(_),Jo[dn]===","?r.lastIndex=++dn: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"&&zD(m,f),jm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?P4:Yl,r.lastIndex=dn),dn===Jo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jm(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function WD(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 fn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function zD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new fn.ClientError("wildcard can only be used at the end of a string")}function jD(e){let t=QD(e[0]);return e.length>1&&(t.next=jD(e.slice(1))),t}function QD(e){if(Array.isArray(e)){let t=QD(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 jl(e){return Array.isArray(e)?e.join("\0"):e}function Wi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function D4(e,t,r){return t*r/Wi(e)}var fn,cs,di,Qo,y4,b4,O4,N4,UA,BA,C4,Yl,P4,dn,Jo,Wl,lc,mf=be(()=>{fn=M(me()),cs=M(vt()),di=require("ordered-binary"),Qo=require("lmdb");pf();y4=.3,b4=.1,O4=.05,N4={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},UA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(xA,"executeConditions");a(zl,"searchByIndex");a(fi,"findAttribute");a(w4,"joinTo");a(I4,"joinFrom");BA={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hf,"filterByType");a(Qm,"estimateCondition");C4=/[()[\]|!<>.]|(=\w*=)/,Yl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,P4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jm,"parseQuery");a(ff,"parseBlock");a(jm,"assignOperator");a(_f,"decodeProperty");a(WD,"typedDecoding");a(zD,"wildcardDecoding");a(jD,"toSortObject");a(QD,"toSortEntry");Wl=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(jl,"flattenKey");a(Wi,"estimatedEntryCount");a(D4,"intersectionEstimate");lc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var kA={};Ue(kA,{MultiPartId:()=>Zm,Resource:()=>Vr,snake_case:()=>M4,transformForSelect:()=>ep});function M4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function JD(e,t){if(uc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(uc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Zm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){uc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return uc=!0,null;e[e.length-1]==="/"&&(uc=!0)}return t.coerceId(decodeURIComponent(e))}function xn(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 lc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return Ot(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new Xm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Xm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Bn(e,t){let r=new eL.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 HA(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function ep(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):HA(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(HA(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(HA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=ep(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var XD,ZD,eL,L4,Vr,Xm,uc,Zm,Zo=be(()=>{XD=require("crypto");Kl();ZD=M(ai()),eL=M(me());cc();mf();L4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Vr=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=xn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=ep(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=xn(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):Bn(t,"put")},{hasContent:!0,type:"update"});static patch=xn(function(t,r,n,s){return t.patch?t.patch(s,r):Bn(t,"patch")},{hasContent:!0,type:"update"});static delete=xn(function(t,r,n,s){return t.delete?t.delete(r):Bn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,XD.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),Ot(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Bn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=xn(function(t,r,n,s){return t.invalidate?t.invalidate(r):Bn(t,"delete")},{hasContent:!1,type:"update"});static post=xn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=xn(function(t,r,n,s){return t.connect?t.connect(s,r):Bn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=xn(function(t,r,n,s){return t.subscribe?t.subscribe(r):Bn(t,"subscribe")},{type:"read"});static publish=xn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Bn(t,"publish")},{hasContent:!0,type:"create"});static search=xn(function(t,r,n,s){let i=t.search?t.search(r):Bn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ep(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=xn(function(t,r,n,s){return t.search?t.search(s,r):Bn(t,"search")},{hasContent:!0,type:"read"});static copy=xn(function(t,r,n,s){return t.copy?t.copy(s,r):Bn(t,"copy")},{hasContent:!0,type:"create"});static move=xn(function(t,r,n,s){return t.move?t.move(s,r):Bn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Bn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Jm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&L4[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:JD(t,this),isCollection:uc}}let i=JD(t,this);return uc?{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 Un}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Un}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",Vr);a(M4,"snake_case");Xm=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(JD,"pathToId");Zm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(xn,"transactional");a(Bn,"missingMethod");a(HA,"selectFromObject");a(ep,"transformForSelect")});var ea,FA=be(()=>{ea=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var nL={};Ue(nL,{Resources:()=>tp,keyArrayToString:()=>Ql,resetResources:()=>v4,resources:()=>ls});function v4(){return ls=new tp,Ke.resources=ls,ls}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var tL,rL,tp,ls,Jl=be(()=>{cc();FA();tL=M(j()),rL=M(me());Pr();tp=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,exportTypes:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s){let c=new rL.ServerError(`Conflicting paths for ${t}`);tL.default.error(c),i.Resource=new ea(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ot(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(v4,"resetResources");a(Ql,"keyArrayToString")});var $A={};Ue($A,{loadGQLSchema:()=>B4,start:()=>qA,startOnMainThread:()=>x4});function qA({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):U4.includes(R.type)||(0,iL.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,GA.dirname)(n),R.tableClass):i.set((0,GA.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new sL.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 GA,sL,iL,U4,x4,B4,oL=be(()=>{GA=require("path"),sL=require("node:vm");ve();iL=M(rt()),U4=["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(qA,"start");x4=qA,B4=qA({ensureTable:dt}).handleFile});var _L={};Ue(_L,{parse:()=>KA,streamAsJSON:()=>Ef,stringify:()=>dc});function Ef(e){return new VA({value:e})}function aL(e){return console.error(e),JSON.stringify(e.toString())}function cL(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function dc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===dL)return fL(e);if(t.resolution)return t.resolution.then(()=>dc(e));throw t}}function fL(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+=fL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+dc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function KA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),F4.test(e)?H4.parse(e):JSON.parse(e)):null}var lL,uL,H4,k4,dL,VA,F4,YA=be(()=>{lL=require("stream"),uL=M(require("json-bigint-fixes")),H4=(0,uL.default)({useNativeBigInt:!0}),k4=1e4,dL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw dL};a(Ef,"streamAsJSON");VA=class extends lL.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),aL)}catch(s){yield aL(s)}else yield dc(t)}else yield dc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);cL(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>k4?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 cL(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(aL,"handleError");a(cL,"when");a(dc,"stringify");a(fL,"jsStringify");F4=/[[,:]\s*-?\d{16,}/;a(KA,"parse")});var _i=P(np=>{var rp=j();for(let e of["trace","debug","info","warn","error","fatal","notify"])rp.logsAtLevel(e)&&(np[e]=rp[e]);np.loggerWithTag=e=>rp.loggerWithTag(e,!0);np.setLogLevel=rp.setLogLevel});var hp={};Ue(hp,{Blob:()=>hi,blobsWereEncoded:()=>_c,databasePaths:()=>zA,decodeBlobsWithWrites:()=>fp,decodeFromDatabase:()=>hc,decodeWithBlobCallback:()=>_p,deleteBlob:()=>lp,deleteBlobsInObject:()=>ta,deleteRootBlobPathsForDB:()=>QA,encodeBlobsAsBuffers:()=>Q4,encodeBlobsWithFilePath:()=>dp,findBlobsInObject:()=>Zl,getFileId:()=>up,getFilePathForBlob:()=>yL,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>V4});function TL(){}function lp(e){let t=yL(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&zi.default.debug?.("Error trying to remove blob file",r)})},AL)}function V4(e){AL=e}function RL(e){let t=hn.get(e);if(!t)t={storageIndex:0,fileId:null,store:mn},hn.set(e,t);else{if(t.saving)return t;t.store=mn}return Y4(t),t.source?WA(e,t.source,t):t.contentBuffer?K4(e,t):WA(e,Sf.Readable.from(e.stream()),t),t}function WA(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,je.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(q4),h=(0,ap.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(G4),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(Er),T=new DataView(E.buffer);return R|=BigInt(o?jA:SL)<<48n,T.setBigInt64(0,R),E}a(m,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,je.close)(R),u(g)):c?(0,je.fdatasync)(R,E=>{E&&u(E),l(),(0,je.close)(R)}):(l(),(0,je.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-Er;e.size=g,(0,je.write)(d.fd,m(g),0,Er,0,S)}})}),e}function up(e){return hn.get(e)?.fileId}function yL(e){let t=hn.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=zA.get(e);if(!t){if(!e.databaseName)return zi.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,cp.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Qi.join)(n,e.databaseName)):t=[(0,Qi.join)((0,cp.getHdbBasePath)(),"blobs",e.databaseName)],zA.set(e,t)}return t}async function QA(e){let t=Af(e);t&&await Promise.all(t.map(r=>bL(r)))}async function bL(e){if((0,je.existsSync)(e)){for(let t of await(0,Bs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await bL((0,Qi.join)(e,t.name));else try{await(0,Bs.unlink)((0,Qi.join)(e,t.name))}catch(r){zi.default.warn?.("Error deleting file",r)}try{await(0,Bs.rmdir)(e)}catch(t){zi.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Qi.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 K4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<gL))return e.size=n,WA(e,Sf.Readable.from([r]),t)}function Y4(e){let t=Af(e.store),r=W4(),n=t?.length>1?z4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Qi.dirname)(i);(0,je.existsSync)(o)||(0,EL.ensureDirSync)(o),e.filePath=i}function W4(){let e=pL.get(mn);if(!e){let t=0,r=Af(mn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,Qi.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(mn.getUserSharedBuffer("blob-file-id",e.buffer)),pL.set(mn,e)}return Number(Atomics.add(e,0,1n))}function z4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(op);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,j4(e)),e.frequencyTable[t%op]}async function j4(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(op),n=t.map(s=>1/s);for(let s=0;s<op;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function dp(e,t,r){Xl=t,mn=r,_c=!1;try{return e()}finally{Xl=void 0,mn=void 0}}function Q4(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function fp(e,t){try{Dr=[],fc=t,e()}catch(n){throw fc=void 0,Dr=void 0,n}fc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function _p(e,t,r){mn=r;try{return fc=t,e()}finally{fc=void 0}}function hc(e,t){return mn=t,e()}function ta(e){Zl(e,t=>{lp(t)})}function Zl(e,t){if(e instanceof hi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Zl(r,t);else if(e.constructor===Object)for(let r in e){let n=e[r];typeof n=="object"&&n&&Zl(e[r],t)}}function J4(){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,je,ap,Sf,EL,cp,Qi,zi,gL,Er,SL,jA,hL,G4,q4,mL,hn,fc,hi,Xl,Dr,mn,_c,gf,sp,$4,ip,AL,zA,pL,op,us=be(()=>{ji=require("msgpackr"),Bs=require("node:fs/promises"),je=require("node:fs"),ap=require("node:zlib"),Sf=require("node:stream"),EL=require("fs-extra"),cp=M(le());k();Qi=require("path"),zi=M(_i());Ji();gL=8192,Er=8,SL=0,jA=1,hL=255,G4=new Uint8Array([0,SL,255,255,255,255,255,255]),q4=new Uint8Array([0,jA,255,255,255,255,255,255]),mL=0xffffffffffff,hn=new WeakMap,hi=global.Blob||J4(),_c=!1,gf=new Uint8Array(8),sp=new DataView(gf.buffer),$4=6e4;a(TL,"InstanceOfBlobWithNoConstructor");TL.prototype=hi.prototype;ip=class e extends TL{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=hn.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):(XA()&&JA(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=hn.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=Er;try{if(l=await(0,Bs.readFile)(i),l.length>=Er){l.copy(gf,0,0,Er);let d=sp.getBigUint64(0);if(Number(d>>48n)===hL)throw new Error("Error in blob: "+buffer.subarray(Er));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<mL&&(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]===jA?new Promise((d,_)=>{(0,ap.deflate)(l.subarray(Er),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(Er))},"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=hn.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,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(zi.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,je.close)(o),clearTimeout(f),u&&u.close(),w(q),h.#e?.forEach(W=>W(q))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,je.read)(o,H,0,H.length,c,(q,W,te)=>{if(l+=W,q)return v(q);if(c===0){if(W<Er){R-- >0&&d!==!1?(m(),zi.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(zi.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,Er);let se=sp.getBigUint64(0);if(Number(se>>48n)===hL)return v(new Error("Error in blob: "+te.subarray(Er)));if(g=Number(se&0xffffffffffffn),g<mL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(Er,W),l-=Er}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,Er,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(sp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},$4).unref():(u=(0,je.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,je.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return zi.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1,S.unlock(g,0)}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=hn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};hn.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)};hn.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(mn=t?.primaryStore?.rootStore,!mn)throw new Error("No target table specified");return RL(this).saving??Promise.resolve()}},AL=500;a(lp,"deleteBlob");a(V4,"setDeletionDelay");global.createBlob=function(e,t){let r=new ip(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(hn.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(RL,"saveBlob");a(WA,"writeBlobWithStream");a(up,"getFileId");a(yL,"getFilePathForBlob");zA=new Map;a(Af,"getRootBlobPathsForDB");a(QA,"deleteRootBlobPathsForDB");a(bL,"rimrafSteadily");a(Tf,"getFilePath");a(K4,"writeBlobWithBuffer");a(Y4,"generateFilePath");pL=new Map;a(W4,"getNextFileId");op=128;a(z4,"getNextStorageIndex");a(j4,"createFrequencyTableForStoragePaths");a(dp,"encodeBlobsWithFilePath");a(Q4,"encodeBlobsAsBuffers");a(fp,"decodeBlobsWithWrites");a(_p,"decodeWithBlobCallback");a(hc,"decodeFromDatabase");a(ta,"deleteBlobsInObject");a(Zl,"findBlobsInObject");(0,ji.addExtension)({Class:hi,type:11,unpack:a(function(e){let t=(0,ji.unpack)(e),r=new ip;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(hn.set(r,{storageIndex:t[1],fileId:t[2],store:mn}),fc)return fc(r)??r;if(!mn)throw new Error("No store specified, cannot load blob from storage")}else hn.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=hn.get(e);if(Xl!==void 0&&(_c=!0,t?.recordId!==void 0&&t.recordId!==Xl))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<gL)return r.size=t.contentBuffer.length,(0,ji.pack)([r,t.contentBuffer])}if(Xl!==void 0){if(t=RL(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Xl,(0,ji.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Tf(t));if(n.length>=Er&&(n.copy(gf,0,0,Er),Number(sp.getBigUint64(0)&0xffffffffffffn)===n.length-Er))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(J4,"polyfillBlob")});var LL={};Ue(LL,{asyncSerialization:()=>JA,contentTypes:()=>rR,findBestSerializer:()=>pp,getDeserializer:()=>eo,hasAsyncSerialization:()=>XA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>ra,toCsvStream:()=>mp});function Z4(e){try{return e?.[0]===123?tR(e):e}catch{return e}}function bf(e){e.register(t3,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new mc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?pc.Readable.from((0,mi.encodeIter)(t,yf)):(0,mi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),mp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function pp(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=Kr.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 wL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Kr.keys()).join(", "),406);n=Kr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=NL&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array||e instanceof hi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=pp(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&e&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),eR.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,Zi.createBrotliCompress)({params:{[Zi.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Zi.constants.BROTLI_MODE_TEXT:Zi.constants.BROTLI_MODE_GENERIC,[Zi.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>NL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Zi.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ra(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Xi=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=pp(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return Xi?.length>0?(Xi.length===1?Xi[0]:Promise.all(Xi)).then(()=>ra(e,t,!0)):n}finally{Xi=void 0}}function JA(e){if(Xi)Xi.push(e);else throw new Error("Unable to serialize asynchronously")}function XA(){return!!Xi}function r3(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 s3(e){return n3.includes(e)}function i3(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function eo(e="",t=!1){let r=i3(e),n=r.type&&Kr.get(r.type)?.deserialize||o3(r);return t?s=>r3(s).then(n):n}function o3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!s3(e.parameters.charset)&&eR.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 tR(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function a3(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}function mp(e,t){let r=pc.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 X4(n,s);return r.pipe(i)}var mi,mc,Zi,wL,pc,IL,ZA,CL,eR,X4,PL,Rf,tR,yf,Kr,rR,OL,DL,e3,t3,NL,Xi,n3,Ji=be(()=>{YA();mi=require("msgpackr"),mc=require("cbor-x"),Zi=require("zlib"),wL=M(me()),pc=M(require("stream"));Pr();IL=M(ai()),ZA=M(le());k();CL=M(require("yaml")),eR=M(_i());us();({Transform:X4}=require("json2csv")),PL=ZA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=PL?dc:JSON.stringify,tR=PL?KA:JSON.parse,yf={useRecords:!1,useToJSON:!0},Kr=new Map,rR=Kr;Ke.contentTypes=rR;(0,IL._assignPackageExport)("contentTypes",rR);Kr.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return tR(e)},q:.8});OL=new mc.Encoder(yf);Kr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new mc.EncoderStream(yf).end(e)},serialize:OL.encode,deserialize:OL.decode,q:1});Kr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?pc.Readable.from((0,mi.encodeIter)(e,yf)):(0,mi.pack)(e)},serialize:mi.pack,deserialize:mi.unpack,q:.9});Kr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),mp(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),mp(e,e?.getColumns?.())},q:.1});Kr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return pc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Kr.set("text/yaml",{serialize(e){return CL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Kr.set("text/event-stream",{serializeStream:a(function(e){return pc.Readable.from(a3(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 Xt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}U2(n,r),NA(n);let s=n.toJSON();if(N2.config=s,yt=Vl(s),yt.logging_rotation_rotate)for(let i in iD)yt[i]&&Xt.error(`Config ${iD[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Xt.trace(I2)}}a(Bm,"initConfig");function U2(e,t){let r=e.getIn(["rootPath"]),n=!1;if(e.hasIn(["storage","path"])||(e.setIn(["storage","path"],vn.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],vn.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(Xt.trace("Updating config file with missing config params"),e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${e.errors}`);$r.writeFileSync(t,String(e))}}a(U2,"checkForUpdatedConfig");function NA(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 $l.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 $l.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=A2(r,t);if(n.error)throw $l.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(NA,"validateConfig");function x2(e,t){yt===void 0&&(yt={});let r=xs[e.toLowerCase()];if(r===void 0){Xt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(x2,"updateConfigObject");function fD(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&Bm();let o=dD(xs.hdb_root),c=vn.join(o,as.HDB_CONFIG_FILE),l=zo(c),u;if(r&&yt){let _=!1;for(let h in r)if(r[h]!=yt[h.toLowerCase()]){_=!0;break}if(!_){Xt.trace("No changes detected in config parameters, skipping update");return}}if(r===void 0&&e.toLowerCase()===Mn.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=OA(_,t);l.setIn([...h],m)}else for(let _ in r){let h=xs[_.toLowerCase()];if(h===Mn.HTTP_SECUREPORT&&r[_]===yt[Mn.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),h===Mn.OPERATIONSAPI_NETWORK_SECUREPORT&&r[_]===yt[Mn.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),h===Mn.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=as.LEGACY_CONFIG_PARAMS[_.toUpperCase()];S&&S.startsWith("customFunctions")&&l.hasIn(S.split("_"))&&(h=S,m=S.split("_"));let g=OA(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){Xt.error(R)}}}u&&uD(l,u),NA(l);let f=l.getIn(["rootPath"]),d=vn.join(f,as.HDB_CONFIG_FILE);if(n===!0&&B2(c,f),l.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${l.errors}`);$r.writeFileSync(d,String(l)),s&&(yt=Vl(l.toJSON())),Xt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(fD,"updateConfigValue");function B2(e,t){try{let r=vn.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${as.HDB_CONFIG_FILE}.bak`);$r.copySync(e,r),Xt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Xt.error(C2),Xt.error(r)}}a(B2,"backupConfigFile");var H2=["databases"];function Vl(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}),xm=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])&&!H2.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;!Mn[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(Vl,"flattenConfig");function OA(e,t){if(e===Mn.CLUSTERING_NODENAME||e===Mn.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(R2(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||pr.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 pr.autoCast(t)}a(OA,"castConfigValue");function k2(){let e=pr.getPropsFilePath(),t=ic(e);return zo(t).toJSON()}a(k2,"getConfiguration");async function F2(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return fD(void 0,void 0,s,!0),L2}catch(i){throw typeof i=="string"||i instanceof String?b2(i,i,O2.BAD_REQUEST,void 0,void 0,!0):i}}a(F2,"setConfiguration");function wA(){let e=pr.getPropsFilePath();try{$r.accessSync(e,$r.constants.F_OK|$r.constants.R_OK)}catch(n){if(!pr.noBootFile())throw Xt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=ic(e);return zo(t).toJSON()}a(wA,"readConfigFile");function zo(e){return oD.parseDocument($r.readFileSync(e,"utf8"),{simpleKeys:!0})}a(zo,"parseYamlDoc");function G2(){let e=wA(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=pr.isEmptyOrZeroLength(t)?[]:t;let r=sD(t);if(r)throw $l.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=pr.isEmptyOrZeroLength(n)?[]:n;let s=sD(n);if(s)throw $l.CONFIG_VALIDATION(s.message);if(!pr.isEmptyOrZeroLength(n)&&!pr.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!pr.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw $l.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(G2,"getClusteringRoutes");function _D(e){let t=aD(e);yt={};for(let r in xs){let n=t.get(r.toUpperCase());if(pr.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=xs[r].toLowerCase();s===Mn.LOGGING_ROOT?yt[s]=vn.dirname(n):yt[s]=n}return yt}a(_D,"initOldConfig");function q2(e){let t=wA();return y2.get(t,e.replaceAll("_","."))}a(q2,"getConfigFromFile");async function $2(e,t){let r=zo(ic());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 $r.writeFile(ic(),String(r))}a($2,"addConfig");function V2(e){let t=ic(pr.getPropsFilePath()),r=zo(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=vn.join(n,as.HDB_CONFIG_FILE);$r.writeFileSync(s,String(r))}a(V2,"deleteConfigFromFile");function K2(){return xm||(Bm(),xm)}a(K2,"getConfigObj");function Y2(){return yt||Bm(),yt}a(Y2,"getFlatConfigObj")});var le=P((SD,TD)=>{"use strict";var IA=require("fs-extra"),oc=require("path"),mD=require("os"),W2=require("properties-reader"),tf=j(),ef=ae(),Le=(k(),D($)),Hm=bt(),z2="Error initializing environment manager",km="BOOT_PROPS_FILE_PATH",pD=!1,j2={[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},Yi={};Object.assign(SD,TD.exports={BOOT_PROPS_FILE_PATH:km,getHdbBasePath:Q2,setHdbBasePath:J2,get:ED,initSync:Z2,setProperty:Ye,initTestEnvironment:t4,setCloneVar:e4});function Q2(){return Yi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Q2,"getHdbBasePath");function J2(e){Yi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(J2,"setHdbBasePath");function ED(e){let t=Hm.getConfigValue(e);return t===void 0?Yi[e]:t}a(ED,"get");function Ye(e,t){j2[e]&&(Yi[e]=t),Hm.updateConfigObject(e,t)}a(Ye,"setProperty");function X2(){let e;try{e=ef.getPropsFilePath(),IA.accessSync(e,IA.constants.F_OK|IA.constants.R_OK),pD=!0;let t=W2(e);return Yi[Le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(Le.HDB_SETTINGS_NAMES.INSTALL_USER),Yi[Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Yi[km]=e,!0}catch{return tf.trace(`Environment manager found no properties file at ${e}`),!1}}a(X2,"doesPropFileExist");function Z2(e=!1){try{((pD||X2()||ef.noBootFile())&&!gD||e)&&(Hm.initConfig(e),Yi[Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Hm.getConfigValue(Le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){tf.error(z2),tf.error(t),console.error(t),process.exit(1)}}a(Z2,"initSync");var gD=!1;function e4(e){gD=e}a(e4,"setCloneVar");function t4(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=oc.join(__dirname,"../../","unitTests");Yi[km]=oc.join(l,"hdb_boot_properties.file"),Ye(Le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,oc.join(l,"settings.test")),Ye(Le.HDB_SETTINGS_NAMES.INSTALL_USER,mD.userInfo()?mD.userInfo().username:void 0),Ye(Le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ye(Le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,oc.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,oc.join(l,"envDir")),Ye(Le.CONFIG_PARAMS.STORAGE_PATH,oc.join(l,"envDir")),s&&(Ye(Le.CONFIG_PARAMS.HTTP_SECUREPORT,ED(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,oc.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 ${km}. Please check your boot props and settings files`;tf.fatal(r),tf.error(t)}}a(t4,"initTestEnvironment")});var pt=P((TAe,wD)=>{"use strict";var af=(k(),D($)),r4=ae(),ln=le(),cf=require("path"),n4=require("minimist"),AD=require("fs-extra"),RD=require("lodash");ln.initSync();var{CONFIG_PARAMS:jo,DATABASES_PARAM_CONFIG:rf,SYSTEM_SCHEMA_NAME:Fm}=af,nf,sf,of;function yD(){if(nf!==void 0)return nf;if(ln.getHdbBasePath()!==void 0)return nf=ln.get(jo.STORAGE_PATH)||cf.join(ln.getHdbBasePath(),af.DATABASES_DIR_NAME),nf}a(yD,"getBaseSchemaPath");function bD(){if(sf!==void 0)return sf;if(ln.getHdbBasePath()!==void 0)return sf=ND(Fm),sf}a(bD,"getSystemSchemaPath");function OD(){if(of!==void 0)return of;if(ln.getHdbBasePath()!==void 0)return of=ln.get(af.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cf.join(ln.getHdbBasePath(),af.TRANSACTIONS_DIR_NAME),of}a(OD,"getTransactionAuditStoreBasePath");function s4(e,t){let r=ln.get(jo.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cf.join(OD(),e.toString())}a(s4,"getTransactionAuditStorePath");function ND(e,t){e=e.toString(),t=t&&t.toString();let r=ln.get(af.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cf.join(yD(),e)}a(ND,"getSchemaPath");function i4(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,n4(process.argv));let n=r[jo.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!r4.isObject(n))throw o;i=n}for(let o of i){let c=o[Fm];if(!c)continue;let l=ln.get(jo.DATABASES);l=l??{};let u=c?.tables?.[t]?.[rf.PATH];if(u)return RD.set(l,[Fm,rf.TABLES,t,rf.PATH],u),ln.setProperty(jo.DATABASES,l),u;let f=c?.[rf.PATH];if(f)return RD.set(l,[Fm,rf.PATH],f),ln.setProperty(jo.DATABASES,l),f}}let s=r[jo.STORAGE_PATH.toUpperCase()];if(s){if(!AD.pathExistsSync(s))throw new Error(s+" does not exist");let i=cf.join(s,e);return AD.mkdirsSync(i),ln.setProperty(jo.STORAGE_PATH,s),i}return bD()}a(i4,"initSystemSchemaPaths");function o4(){nf=void 0,sf=void 0,of=void 0}a(o4,"resetPaths");wD.exports={getBaseSchemaPath:yD,getSystemSchemaPath:bD,getTransactionAuditStorePath:s4,getTransactionAuditStoreBasePath:OD,getSchemaPath:ND,initSystemSchemaPaths:i4,resetPaths:o4}});var un=P((bAe,LD)=>{"use strict";var a4=Ln().LMDB_ERRORS_ENUM,RAe=require("lmdb"),c4=vt(),yAe=require("buffer").Buffer,{OVERFLOW_MARKER:ID,MAX_SEARCH_KEY_LENGTH:Gm}=c4,CD=["number","string","symbol","boolean","bigint"];function l4(e){if(e=e?.primaryStore||e,!e)throw new Error(a4.ENV_REQUIRED)}a(l4,"validateEnv");function u4(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(u4,"stringifyData");function d4(e){return e instanceof Date?e.valueOf():e}a(d4,"convertKeyValueToWrite");function f4(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(CD.includes(typeof e))return e.length>Gm?[e.slice(0,Gm)+ID]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(CD.includes(typeof i))i.length>Gm?r.push(i.slice(0,Gm)+ID):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(f4,"getIndexedValues");var qm=0,PD=0;function DD(){PD=Date.now()-performance.now()}a(DD,"adjustStartTime");DD();var _4=6e4;setInterval(DD,_4).unref();function h4(){let e=performance.now()+PD;return e>qm?(qm=e,e):(qm+=488e-6,qm)}a(h4,"getNextMonotonicTime");LD.exports={validateEnv:l4,stringifyData:u4,convertKeyValueToWrite:d4,getNextMonotonicTime:h4,getIndexedValues:f4}});var lf=P((NAe,MD)=>{"use strict";var m4=(k(),D($)).OPERATIONS_ENUM,CA=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=m4.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};MD.exports=CA});var uf=P((CAe,BD)=>{"use strict";var IAe=lf(),$m=(k(),D($)),PA=ae(),vD=j(),p4=require("uuid"),{handleHDBError:Vm,hdb_errors:E4}=me(),{HDB_ERROR_MSGS:Km,HTTP_STATUS_CODES:Ym}=E4;BD.exports=UD;function UD(e,t,r){for(let s=0;s<t.length;s++)xD(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];g4(i,r,e.operation)}}a(UD,"processRows");UD.validateAttribute=xD;function xD(e){if(Buffer.byteLength(String(e))>$m.INSERT_MAX_CHARACTER_SIZE)throw Vm(new Error,Km.ATTR_NAME_LENGTH_ERR(e),Ym.BAD_REQUEST,void 0,void 0,!0);if(PA.isEmptyOrZeroLength(e)||PA.isEmpty(e.trim()))throw Vm(new Error,Km.ATTR_NAME_NULLISH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(xD,"validateAttribute");function g4(e,t,r){if(!e.hasOwnProperty(t)||PA.isEmptyOrZeroLength(e[t])){if(r===$m.OPERATIONS_ENUM.INSERT||r===$m.OPERATIONS_ENUM.UPSERT){e[t]=p4.v4();return}throw vD.error("Update transaction aborted due to record with no hash value:",e),Vm(new Error,Km.RECORD_MISSING_HASH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>$m.INSERT_MAX_CHARACTER_SIZE)throw vD.error(e),Vm(new Error,Km.HASH_VAL_LENGTH_ERR,Ym.BAD_REQUEST,void 0,void 0,!0)}a(g4,"validateHash")});var HD,Un,DA,Kl=be(()=>{HD=require("events"),Un=class extends HD.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;drainCloseListener;currentDrainResolver;[Symbol.asyncIterator](){let t=new DA;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)}},DA=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 KD(e){MA=e}function R4(){A4=setInterval(function(){for(let e of LA)if(e.stale){let t=e.getContext()?.url;qD.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},T4).unref()}var vA,GD,qD,$D,VD,kD,LA,S4,df,FD,MA,ac,Wm,T4,A4,zm=be(()=>{vA=M(un()),GD=M(me()),qD=M(j()),$D=M(le());k();VD=M(ae()),kD=100,LA=new Set,S4=(0,VD.convertToMS)($D.get(U.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(KD,"replicationConfirmation");ac=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),LA.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn?.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(LA.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(df&&!this.overloadChecked&&performance.now()-FD>S4)throw new GD.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,vA.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)<kD>>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,FD=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];MA&&h&&i.push(MA(_,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)+kD/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let f={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(_=>({txnTime:r,next:_}));f.next=d}return f}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}getContext(){return this.#e}setContext(t){this.#e=t}},Wm=class extends ac{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,vA.getNextMonotonicTime)())}getReadTxn(){}},T4=3e4;a(R4,"startMonitoringTxns");R4()});function Ot(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new ac;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 YD,cc=be(()=>{YD=M(ai());zm();a(Ot,"transaction");(0,YD._assignPackageExport)("transaction",Ot);Ot.commit=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ot.abort=function(e){let t=(e.getContext?.()||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function xA(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?xA(d.conditions,d.operator,r,n,s,i,o,c):zl(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=D4(r.primaryStore,m.estimated_count,h)),R}).filter(Boolean)}a(f,"mapConditionsToFilters")}function zl(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 fn.ClientError(`Search condition for ${o} must have a value`);if(Array.isArray(o)){let E=o[0],T=fi(n.attributes,E);if(T.relationship){if(o.length<2)throw new fn.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=zl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,w,s,v);if(T.relationship.to){i[o[0]]=v;let q=!!fi(w.attributes,T.relationship.to)?.elements;H=w4(H,T,w.primaryStore,q,v)}if(T.relationship.from){let q=a(W=>(W?.key!==void 0&&(W=W.key),zl({attribute:T.relationship.from,value:W},t,r,n,s,v)),"searchEntry");T.elements?(i[o[0]]=v,H=I4(H,T,w.primaryStore,v,q)):H=H.flatMap(q)}return H}else if(o.length===1)o=o[0];else throw new fn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let u,f,d,_;c instanceof Date&&(c=c.getTime());let h;switch(BA[l]||l){case"lt":u=!0,f=c;break;case"le":u=!0,f=c,d=!0;break;case"gt":u=c,_=!0;break;case"ge":u=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],u=c,f=c.slice(0),f[f.length-1]=di.MAXIMUM_KEY;break;case"starts_with":u=c.toString(),f=c+"\uFFFF";break;case"between":case"gele":case"gelt":case"gtlt":case"gtle":u=c[0],u instanceof Date&&(u=u.getTime()),f=c[1],f instanceof Date&&(f=f.getTime()),d=l==="gele"||l==="gtle"||l==="between",_=l==="gtlt"||l==="gtle";break;case"equals":case void 0:u=c,f=c,d=!0;break;case"ne":if(c===null){u=c,_=!0;break}case"sort":case"contains":case"ends_with":u=!0,h=!0;break;default:throw new fn.ClientError(`Unknown query comparator "${l}"`)}let m,S=o===n.primaryKey||o==null;if(typeof u=="string"&&u.length>cs.MAX_SEARCH_KEY_LENGTH&&(u=u.slice(0,cs.MAX_SEARCH_KEY_LENGTH)+cs.OVERFLOW_MARKER,_=!1,m=hf(e,n,null,i,S)),typeof f=="string"&&f.length>cs.MAX_SEARCH_KEY_LENGTH&&(f=f.slice(0,cs.MAX_SEARCH_KEY_LENGTH)+cs.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 fn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&h)throw new fn.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 fn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&g&&!g.indexNulls)throw new fn.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 fn.ClientError(`Unknown search operator ${e.comparator}`)}let R={start:u,end:f,inclusiveEnd:d,exclusiveStart:_,values:!0,versions:S,transaction:t,reverse:r};if(S){let E=g.getRange(R).map(m?function({key:T,value:w}){return this?.isSync?w&&m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(w&&m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:T=>T.value==null&&!(T.metadataFlags&(_n|Xo))?Qo.SKIP:T);return E.hasEntries=!0,E}else return g?g.getRange(R).map(m?function({key:E,value:T}){let w;return typeof E=="string"&&E.length>cs.MAX_SEARCH_KEY_LENGTH?w=n.primaryStore.get(T):w={[o]:E},this.isSync?m(w)?T:Qo.SKIP:new Promise((v,H)=>setImmediate(()=>{try{v(m(w)?T:Qo.SKIP)}catch(q){H(q)}}))}:({value:E})=>E):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:E,value:T}){return this.isSync?T&&m(T)?E:Qo.SKIP:new Promise((w,v)=>setImmediate(()=>{try{w(T&&m(T)?E:Qo.SKIP)}catch(H){v(H)}}))})}function fi(e,t){if(Array.isArray(t))if(t.length>1){let r=fi(e,t[0]),n=(r?.definition?.tableClass||r?.elements?.definition?.tableClass)?.attributes??r?.properties;return n?fi(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function w4(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 I4(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=fi(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()),BA[o]||o){case cs.SEARCH_TYPES.EQUALS:case void 0:return u(c,f=>f===l,!0);case"contains":return u(c,f=>f?.toString().includes(l));case"ends_with":return u(c,f=>f?.toString().endsWith(l));case"starts_with":return u(c,f=>typeof f=="string"&&f.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],u(c,f=>{if(!Array.isArray(f))return!1;for(let d=0,_=l.length;d<_;d++)if(f[d]!==l[d])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),u(c,f=>(0,di.compareKeys)(f,l[0])>=0&&(0,di.compareKeys)(f,l[1])<=0,!0);case"gt":return u(c,f=>(0,di.compareKeys)(f,l)>0);case"ge":return u(c,f=>(0,di.compareKeys)(f,l)>=0);case"lt":return u(c,f=>(0,di.compareKeys)(f,l)<0);case"le":return u(c,f=>(0,di.compareKeys)(f,l)<=0);case"ne":return u(c,f=>(0,di.compareKeys)(f,l)!==0,!1,!0);case"sort":return()=>!0;default:throw new fn.ClientError(`Unknown query comparator "${o}"`)}function u(f,d,_,h){let m;_=_&&!s&&t?.indices[f]&&i>3,_&&(e.estimated_count==null&&Qm(t)(e),m=e.estimated_count>>4,(isNaN(m)||m>=i)&&(_=!1));let S=0,g=3;function 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=zl(e,r.transaction.getReadTxn(),!1,t).map(jl),H=new Set(v);R.idFilter=q=>H.has(jl(q)),R.idFilter.idSet=H}return w}return a(R,"recordFilter"),s&&(R.idFilter=d),R}a(u,"attributeComparator")}function Qm(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Wi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=BA[n]||n,n===cs.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=fi(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Qm(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),l=e.indices[i.relationship.from];r.estimated_count=c+(l?c*Wi(e.indices[i.relationship.from])/(Wi(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=Wi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=O4*Wi(e.primaryStore)+1:n==="between"?r.estimated_count=b4*Wi(e.primaryStore)+1:n==="sort"?r.estimated_count=Wi(e.primaryStore)+1:r.estimated_count=y4*Wi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jm(e){if(e)if(Jo=e,Yl.lastIndex=0,C4.test(e))try{let t=ff(new Wl,"");if(dn!==Jo.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${dn} in '${Jo}'`,t}else return new URLSearchParams(e)}function ff(e,t){let r=Yl,n,s,i,o,c,l=decodeURIComponent,u;for(;n=r.exec(Jo);){dn=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=WD}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=N4[d],l=UA[i]?WD: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"&&zD(m,f),s===""){let S=e.conditions[e.conditions.length-1];S.chainedConditions=S.chainedConditions||[],S.chainedConditions.push(m),S.operator=u}else jm(e,u),e.conditions.push(m)}d==="&"?(u="and",s=void 0):d==="|"?(u="or",s=void 0):d==="&="?(u="and",s=""):d==="|="&&(u="or",s="");break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_f(f)),s=void 0;break;case"(":Yl.lastIndex=dn;let h=ff(f?[]:new Wl,")");switch(f){case"":jm(e,u),e.conditions.push(h);break;case"limit":switch(h.length){case 1:e.limit=+h[0];break;case 2:e.offset=+h[0],e.limit=h[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(h[0])&&h.length===1&&!h[0].name?(e.select=h[0],e.select.asArray=!0):h.length===1?e.select=h[0]:h.length===2&&h[1]===""?e.select=h.slice(0,1):e.select=h;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=jD(h);break;default:throw new SyntaxError(`unknown query function call ${f}`)}Jo[dn]===","?r.lastIndex=++dn: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");Yl.lastIndex=dn,_=ff([],"}"),_.name=f,e.push(_),Jo[dn]===","?r.lastIndex=++dn:o=!0;break;case"[":Yl.lastIndex=dn,f?(_=ff(new Wl,"]"),_.name=f):_=ff(e.conditions?new Wl:[],"]"),e.conditions?(jm(e,u),e.conditions.push(_),s=null):e.push(_),Jo[dn]===","?r.lastIndex=++dn: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"&&zD(m,f),jm(e,u),e.conditions.push(m)}else if(f)throw new SyntaxError("no attribute or comparison specified")}else(f||e.length>0&&c)&&e.push(_f(f));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?P4:Yl,r.lastIndex=dn),dn===Jo.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function jm(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function _f(e){return e.indexOf(".")>-1?e.split(".").map(_f):decodeURIComponent(e)}function WD(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 fn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function zD(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new fn.ClientError("wildcard can only be used at the end of a string")}function jD(e){let t=QD(e[0]);return e.length>1&&(t.next=jD(e.slice(1))),t}function QD(e){if(Array.isArray(e)){let t=QD(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 jl(e){return Array.isArray(e)?e.join("\0"):e}function Wi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function D4(e,t,r){return t*r/Wi(e)}var fn,cs,di,Qo,y4,b4,O4,N4,UA,BA,C4,Yl,P4,dn,Jo,Wl,lc,mf=be(()=>{fn=M(me()),cs=M(vt()),di=require("ordered-binary"),Qo=require("lmdb");pf();y4=.3,b4=.1,O4=.05,N4={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},UA={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(xA,"executeConditions");a(zl,"searchByIndex");a(fi,"findAttribute");a(w4,"joinTo");a(I4,"joinFrom");BA={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hf,"filterByType");a(Qm,"estimateCondition");C4=/[()[\]|!<>.]|(=\w*=)/,Yl=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,P4=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jm,"parseQuery");a(ff,"parseBlock");a(jm,"assignOperator");a(_f,"decodeProperty");a(WD,"typedDecoding");a(zD,"wildcardDecoding");a(jD,"toSortObject");a(QD,"toSortEntry");Wl=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(jl,"flattenKey");a(Wi,"estimatedEntryCount");a(D4,"intersectionEstimate");lc=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});var kA={};Ue(kA,{MultiPartId:()=>Zm,Resource:()=>Vr,snake_case:()=>M4,transformForSelect:()=>ep});function M4(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function JD(e,t){if(uc=!1,e==="")return null;if(e=e.slice(1),t.splitSegments){if(e.indexOf("/")===-1)return e===""?(uc=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new Zm;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){uc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}else{if(e==="")return uc=!0,null;e[e.length-1]==="/"&&(uc=!0)}return t.coerceId(decodeURIComponent(e))}function xn(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 lc(c),c==null&&(u=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||u?(d={...t},l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),u&&(d.isCollection=!0)):d=t,o.transaction){let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)}else return Ot(o,()=>{let h=this.getResource(c,o,d);return h.then?h.then(_):_(h)},d);function _(h){if(o.authorize){o.authorize=!1;let m=t.type==="read"?h.allowRead(o.user,l,o):t.type==="update"?h.doesExist?.()===!1?h.allowCreate(o.user,f,o):h.allowUpdate(o.user,f,o):t.type==="create"?h.allowCreate(o.user,f,o):h.allowDelete(o.user,l,o);if(m?.then)return m.then(S=>{if(!S)throw new Xm(o.user);return typeof f?.then=="function"?f.then(g=>e(h,l,o,g)):e(h,l,o,f)});if(!m)throw new Xm(o.user)}return typeof f?.then=="function"?f.then(m=>e(h,l,o,m)):e(h,l,o,f)}a(_,"authorizeActionOnResource")}}function Bn(e,t){let r=new eL.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 HA(e,t,r){let n=e.getRecord?.();if(n){let s=e.getChanges?.();return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function ep(e,t){let r=t.propertyResolvers,n=t.getContext?.(),s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):HA(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(HA(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(HA(l,r,n)),d;for(let _ of e){let h=f(_);h===void 0&&o&&(h=null),h?.then?(d||(d=[]),d.push(h.then(m=>u[_.name||_]=m))):u[_.name||_]=h}return d?Promise.all(d).then(()=>u):u},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let l=s[c.name];if(!l){let f=r[c.name]?.definition?.tableClass;l=s[c.name]=ep(c.select||c,f)}let u=o(c.name);return l(u)}else return o(c);else return c}}a(i,"handleProperty")}var XD,ZD,eL,L4,Vr,Xm,uc,Zm,Zo=be(()=>{XD=require("crypto");Kl();ZD=M(ai()),eL=M(me());cc();mf();L4={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Vr=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=xn(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let l;if((l=r?.select)&&c!=null&&!c.selectApplied){let u=ep(l,t.constructor);return typeof c?.map=="function"?c.map(u):u(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=xn(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):Bn(t,"put")},{hasContent:!0,type:"update"});static patch=xn(function(t,r,n,s){return t.patch?t.patch(s,r):Bn(t,"patch")},{hasContent:!0,type:"update"});static delete=xn(function(t,r,n,s){return t.delete?t.delete(r):Bn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,XD.randomUUID)()}static create(t,r,n){let s;return t==null?s=r?.[this.primaryKey]??this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=r?.[this.primaryKey]??[...t,this.getNewId()]:typeof t!="object"?s=r?.[this.primaryKey]??[t,this.getNewId()]:(s=t?.[this.primaryKey]??this.getNewId(),n=r||{},r=t),n||(n={}),Ot(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Bn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>i):i})}static invalidate=xn(function(t,r,n,s){return t.invalidate?t.invalidate(r):Bn(t,"delete")},{hasContent:!1,type:"update"});static post=xn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=xn(function(t,r,n,s){return t.connect?t.connect(s,r):Bn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=xn(function(t,r,n,s){return t.subscribe?t.subscribe(r):Bn(t,"subscribe")},{type:"read"});static publish=xn(function(t,r,n,s){return t.#e!=null&&t.update?.(),t.publish?t.publish(s,r):Bn(t,"publish")},{hasContent:!0,type:"create"});static search=xn(function(t,r,n,s){let i=t.search?t.search(r):Bn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ep(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=xn(function(t,r,n,s){return t.search?t.search(s,r):Bn(t,"search")},{hasContent:!0,type:"read"});static copy=xn(function(t,r,n,s){return t.copy?t.copy(s,r):Bn(t,"copy")},{hasContent:!0,type:"create"});static move=xn(function(t,r,n,s){return t.move?t.move(s,r):Bn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this.#n)return(await this.constructor.create(this.#e,t,this.#t)).#e;Bn(this,"post")}static isCollection(t){return t&&t.#n}get isCollection(){return this.#n}static coerceId(t){return t}static parseQuery(t){return Jm(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1),c=r?.headers&&L4[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:JD(t,this),isCollection:uc}}let i=JD(t,this);return uc?{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 Un}connect(t,r){return r?.subscribe!==!1?this.subscribe?.(r):new Un}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",Vr);a(M4,"snake_case");Xm=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(JD,"pathToId");Zm=class extends Array{static{a(this,"MultiPartId")}toString(){return this.join("/")}};a(xn,"transactional");a(Bn,"missingMethod");a(HA,"selectFromObject");a(ep,"transformForSelect")});var ea,FA=be(()=>{ea=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}isError=!0;allowRead(){throw this.error}allowUpdate(){throw this.error}allowCreate(){throw this.error}allowDelete(){throw this.error}getId(){throw this.error}getContext(){throw this.error}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var nL={};Ue(nL,{Resources:()=>tp,keyArrayToString:()=>Ql,resetResources:()=>v4,resources:()=>ls});function v4(){return ls=new tp,Ke.resources=ls,ls}function Ql(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var tL,rL,tp,ls,Jl=be(()=>{cc();FA();tL=M(j()),rL=M(me());Pr();tp=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,exportTypes:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s){let c=new rL.ServerError(`Conflicting paths for ${t}`);tL.default.error(c),i.Resource=new ea(c)}super.set(t,i);for(let[c,l]of this){let u=2;for(;(u=c.indexOf("/",u))>-1;){let f=this.get(c.slice(0,u));f&&(f.hasSubPaths=!0),u+=2}}}getMatch(t,r){let n=2,s=0,i,o=t.length;for(;n<o;){s=n,n=t.indexOf("/",n),n===-1&&(n=o);let u=n===o?t:t.slice(0,n),f=this.get(u),d=-1;if(!f&&n===o&&(d=u.indexOf("?",s),d!==-1)){let _=u.slice(0,d);f=this.get(_)}if(f&&(!r||f.exportTypes?.[r]!==!1)){if(f.relativeURL=t.slice(d!==-1?d:n),!f.hasSubPaths)return f;i=f}n+=2}if(i)return i;let c=t.indexOf("?"),l=c>-1?t.slice(0,c):t;return i=this.get(l),!i&&l.indexOf(".")>-1&&(i=this.get(l.split(".")[0])),i&&(!r||i.exportTypes?.[r]!==!1)?i.relativeURL=c>-1?t.slice(c):"":i||(i=this.get(""),i&&(!r||i.exportTypes?.[r]!==!1)&&(t.charAt(0)!=="/"&&(t="/"+t),i.relativeURL=t)),i}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ot(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(v4,"resetResources");a(Ql,"keyArrayToString")});var $A={};Ue($A,{loadGQLSchema:()=>B4,start:()=>qA,startOnMainThread:()=>x4});function qA({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):U4.includes(R.type)||(0,iL.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,GA.dirname)(n),R.tableClass):i.set((0,GA.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function g(R,E,T){return new sL.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 GA,sL,iL,U4,x4,B4,oL=be(()=>{GA=require("path"),sL=require("node:vm");ve();iL=M(rt()),U4=["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(qA,"start");x4=qA,B4=qA({ensureTable:dt}).handleFile});var _L={};Ue(_L,{parse:()=>KA,streamAsJSON:()=>Ef,stringify:()=>dc});function Ef(e){return new VA({value:e})}function aL(e){return console.error(e),JSON.stringify(e.toString())}function cL(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function dc(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===dL)return fL(e);if(t.resolution)return t.resolution.then(()=>dc(e));throw t}}function fL(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+=fL(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+dc(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function KA(e){return e?.length>0?(typeof e!="string"&&(e=e.toString()),F4.test(e)?H4.parse(e):JSON.parse(e)):null}var lL,uL,H4,k4,dL,VA,F4,YA=be(()=>{lL=require("stream"),uL=M(require("json-bigint-fixes")),H4=(0,uL.default)({useNativeBigInt:!0}),k4=1e4,dL={message:"Cannot serialize BigInt to JSON"};BigInt.prototype.toJSON=function(){throw dL};a(Ef,"streamAsJSON");VA=class extends lL.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),aL)}catch(s){yield aL(s)}else yield dc(t)}else yield dc(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);cL(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>k4?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 cL(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(aL,"handleError");a(cL,"when");a(dc,"stringify");a(fL,"jsStringify");F4=/[[,:]\s*-?\d{16,}/;a(KA,"parse")});var _i=P(np=>{var rp=j();for(let e of["trace","debug","info","warn","error","fatal","notify"])rp.logsAtLevel(e)&&(np[e]=rp[e]);np.loggerWithTag=e=>rp.loggerWithTag(e,!0);np.setLogLevel=rp.setLogLevel});var hp={};Ue(hp,{Blob:()=>hi,blobsWereEncoded:()=>_c,databasePaths:()=>zA,decodeBlobsWithWrites:()=>fp,decodeFromDatabase:()=>hc,decodeWithBlobCallback:()=>_p,deleteBlob:()=>lp,deleteBlobsInObject:()=>ta,deleteRootBlobPathsForDB:()=>QA,encodeBlobsAsBuffers:()=>Q4,encodeBlobsWithFilePath:()=>dp,findBlobsInObject:()=>Zl,getFileId:()=>up,getFilePathForBlob:()=>yL,getRootBlobPathsForDB:()=>Af,setDeletionDelay:()=>V4});function TL(){}function lp(e){let t=yL(e);t&&setTimeout(()=>{(0,je.unlink)(t,r=>{r&&zi.default.debug?.("Error trying to remove blob file",r)})},AL)}function V4(e){AL=e}function RL(e){let t=hn.get(e);if(!t)t={storageIndex:0,fileId:null,store:mn},hn.set(e,t);else{if(t.saving)return t;t.store=mn}return Y4(t),t.source?WA(e,t.source,t):t.contentBuffer?K4(e,t):WA(e,Sf.Readable.from(e.stream()),t),t}function WA(e,t,r){let{filePath:n,fileId:s,store:i,compress:o,flush:c}=r;return r.saving=new Promise((l,u)=>{let f=s+":blob";if(!i.attemptLock(f,0))throw new Error(`Unable to get lock for blob file ${s}`);let d=(0,je.createWriteStream)(n,{autoClose:!1,flags:"w"});if(t.errored){let g=Buffer.from(t.errored.toString());d.end(Buffer.concat([m(BigInt(g.length)+0xff000000000000n),g]));return}let _=!1;e.size!==void 0&&(d.write(m(e.size)),_=!0);let h;o?(_||d.write(q4),h=(0,ap.createDeflate)(),t.pipe(h).pipe(d)):(_||d.write(G4),t.pipe(d)),t.on("error",S);function m(g){let R=BigInt(g),E=new Uint8Array(Er),T=new DataView(E.buffer);return R|=BigInt(o?jA:SL)<<48n,T.setBigInt64(0,R),E}a(m,"createHeader");function S(g){i.unlock(f,0);let R=d.fd;g?(R&&(0,je.close)(R),u(g)):c?(0,je.fdatasync)(R,E=>{E&&u(E),l(),(0,je.close)(R)}):(l(),(0,je.close)(R))}a(S,"finished"),d.on("error",S).on("finish",()=>{if(_)S();else{let g=h?h.bytesWritten:d.bytesWritten-Er;e.size=g,(0,je.write)(d.fd,m(g),0,Er,0,S)}})}),e}function up(e){return hn.get(e)?.fileId}function yL(e){let t=hn.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=zA.get(e);if(!t){if(!e.databaseName)return zi.default.warn?.("No database name specified, can not determine blob storage path"),[];let r=(0,cp.get)(U.STORAGE_BLOBPATHS);r?t=r.map(n=>(0,Qi.join)(n,e.databaseName)):t=[(0,Qi.join)((0,cp.getHdbBasePath)(),"blobs",e.databaseName)],zA.set(e,t)}return t}async function QA(e){let t=Af(e);t&&await Promise.all(t.map(r=>bL(r)))}async function bL(e){if((0,je.existsSync)(e)){for(let t of await(0,Bs.readdir)(e,{withFileTypes:!0}))if(t.isDirectory())await bL((0,Qi.join)(e,t.name));else try{await(0,Bs.unlink)((0,Qi.join)(e,t.name))}catch(r){zi.default.warn?.("Error deleting file",r)}try{await(0,Bs.rmdir)(e)}catch(t){zi.default.warn?.("Error deleting directory",t)}}}function Tf({storageIndex:e,fileId:t,store:r}){let n=Af(r);return(0,Qi.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 K4(e,t){let r=t.contentBuffer,n=r.length;if(!(n<gL))return e.size=n,WA(e,Sf.Readable.from([r]),t)}function Y4(e){let t=Af(e.store),r=W4(),n=t?.length>1?z4(t,r):0,s=r.toString(16);e.storageIndex=n,e.fileId=s;let i=Tf(e),o=(0,Qi.dirname)(i);(0,je.existsSync)(o)||(0,EL.ensureDirSync)(o),e.filePath=i}function W4(){let e=pL.get(mn);if(!e){let t=0,r=Af(mn);for(let n of r){let s=0;for(let i=0;i<3;i++){s=s*4096;let o=0;if((0,je.existsSync)(n))for(let c of(0,je.readdirSync)(n)){let l=parseInt(c,16);i===2&&c.length>3&&(l=parseInt(c.slice(-3),16),l+=parseInt(c.slice(0,-3),16)*68719476736),l>o&&(o=l)}s+=o,n=(0,Qi.join)(n,o.toString(16))}t=Math.max(t,s)}e=new BigInt64Array([BigInt(t)+1n]),e=new BigInt64Array(mn.getUserSharedBuffer("blob-file-id",e.buffer)),pL.set(mn,e)}return Number(Atomics.add(e,0,1n))}function z4(e,t){let r=Date.now();if(!e.frequencyTable){e.lastUpdated=0;let s=new Array(op);for(let i=0;i<s.length;i++)s[i]=i%e.length;e.frequencyTable=s}return(e.lastUpdated??0)+6e4<r&&(e.lastUpdated=r,j4(e)),e.frequencyTable[t%op]}async function j4(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(op),n=t.map(s=>1/s);for(let s=0;s<op;s++){let i=1/0,o=0;for(let c=0;c<n.length;c++)n[c]<i&&(o=c,i=n[c]);n[o]+=1/t[o],r[s]=o}e.frequencyTable=r}function dp(e,t,r){Xl=t,mn=r,_c=!1;try{return e()}finally{Xl=void 0,mn=void 0}}function Q4(e){Dr=[];let t;try{t=e()}catch(n){throw Dr=void 0,n}let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r?r.then(()=>e()):t}function fp(e,t){try{Dr=[],fc=t,e()}catch(n){throw fc=void 0,Dr=void 0,n}fc=void 0;let r=Dr.length<2?Dr[0]:Promise.all(Dr);return Dr=void 0,r}function _p(e,t,r){mn=r;try{return fc=t,e()}finally{fc=void 0}}function hc(e,t){return mn=t,e()}function ta(e){Zl(e,t=>{lp(t)})}function Zl(e,t){if(e instanceof hi)t(e);else if(Array.isArray(e))for(let r of e)typeof r=="object"&&r&&Zl(r,t);else if(e&&typeof e=="object"&&!e[Symbol.iterator])for(let r in e){let n=e[r];typeof n=="object"&&n&&Zl(e[r],t)}}function J4(){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,je,ap,Sf,EL,cp,Qi,zi,gL,Er,SL,jA,hL,G4,q4,mL,hn,fc,hi,Xl,Dr,mn,_c,gf,sp,$4,ip,AL,zA,pL,op,us=be(()=>{ji=require("msgpackr"),Bs=require("node:fs/promises"),je=require("node:fs"),ap=require("node:zlib"),Sf=require("node:stream"),EL=require("fs-extra"),cp=M(le());k();Qi=require("path"),zi=M(_i());Ji();gL=8192,Er=8,SL=0,jA=1,hL=255,G4=new Uint8Array([0,SL,255,255,255,255,255,255]),q4=new Uint8Array([0,jA,255,255,255,255,255,255]),mL=0xffffffffffff,hn=new WeakMap,hi=global.Blob||J4(),_c=!1,gf=new Uint8Array(8),sp=new DataView(gf.buffer),$4=6e4;a(TL,"InstanceOfBlobWithNoConstructor");TL.prototype=hi.prototype;ip=class e extends TL{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=hn.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):(XA()&&JA(this.bytes().then(o=>t.contentBuffer=o)),`[blob: ${this.type}, ${this.size} bytes]`))}return{description:"Blobs that are not of type text/* can not be directly serialized as JSON, use as the body of a response or convert to another type"}}async text(){return(await this.bytes()).toString()}bytes(){let t=hn.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=Er;try{if(l=await(0,Bs.readFile)(i),l.length>=Er){l.copy(gf,0,0,Er);let d=sp.getBigUint64(0);if(Number(d>>48n)===hL)throw new Error("Error in blob: "+buffer.subarray(Er));if(u=Number(d&0xffffffffffffn),u<n&&(u=n),u<mL&&(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]===jA?new Promise((d,_)=>{(0,ap.deflate)(l.subarray(Er),(h,m)=>{h?_(h):d(f(m))})}):f(l.subarray(Er))},"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=hn.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,je.open)(i,"r",(T,w)=>{if(T){if(T.code==="ENOENT"&&d!==!1&&(zi.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,je.close)(o),clearTimeout(f),u&&u.close(),w(q),h.#e?.forEach(W=>W(q))}a(v,"onError");let H=Buffer.allocUnsafe(262144);(0,je.read)(o,H,0,H.length,c,(q,W,te)=>{if(l+=W,q)return v(q);if(c===0){if(W<Er){R-- >0&&d!==!1?(m(),zi.default.debug?.("File was empty, waiting for data to be written",i,R),setTimeout(()=>E(T,w),20).unref()):(zi.default.debug?.("File was empty, throwing error",i,R),w(new Error(`Blob ${t.fileId} was empty`)));return}te.copy(gf,0,0,Er);let se=sp.getBigUint64(0);if(Number(se>>48n)===hL)return v(new Error("Error in blob: "+te.subarray(Er)));if(g=Number(se&0xffffffffffffn),g<mL&&h.size!==g&&(h.size=g,h.#t))for(let Y of h.#t)Y(g);te=te.subarray(Er,W),l-=Er}else if(W===0){let se=Buffer.allocUnsafe(8);return(0,je.read)(o,se,0,Er,0,Y=>{if(Y)return v(Y);if(gf.set(se),g=Number(sp.getBigUint64(0)&0xffffffffffffn),g>l){m()?u?f=setTimeout(()=>{v(new Error("File read timed out"))},$4).unref():(u=(0,je.watch)(i,{persistent:!1},()=>{u.close(),u=null,f&&(clearTimeout(f),f=null,E(T,w))}),E(T,w)):_?v(new Error("Blob is incomplete")):(_=!0,E(T,w));return}(0,je.close)(o),S.close(),T()})}else te=te.subarray(0,W);if(n!==void 0||s!==void 0){if(n&&l<n)return c+=W,E(T,w);s&&l>=s&&(l>s&&(te=te.subarray(0,s-c)),l=g=s),n&&n>c&&(te=te.subarray(n-c))}c+=W;try{S.enqueue(te)}catch(se){return zi.default.debug?.("Error enqueuing chunk",se),T()}l===g&&((0,je.close)(o),S.close()),T()})},"readMore"))},"pull"),cancel(){(0,je.close)(o),clearTimeout(f),u&&u.close()}});function m(){if(d===void 0){let S=t.store,g=t.fileId+":blob";d=!S.attemptLock(g,0,()=>{d=!1,S.unlock(g,0)}),d||S.unlock(g,0)}return d}}slice(t,r,n){let s=hn.get(this),i=new e(n&&{type:n});if(s?.fileId){let o={...s,start:t,end:r};hn.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)};hn.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(mn=t?.primaryStore?.rootStore,!mn)throw new Error("No target table specified");return RL(this).saving??Promise.resolve()}},AL=500;a(lp,"deleteBlob");a(V4,"setDeletionDelay");global.createBlob=function(e,t){let r=new ip(t),n={storageIndex:0,fileId:null,flush:t?.flush,compress:t?.compress};if(hn.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(RL,"saveBlob");a(WA,"writeBlobWithStream");a(up,"getFileId");a(yL,"getFilePathForBlob");zA=new Map;a(Af,"getRootBlobPathsForDB");a(QA,"deleteRootBlobPathsForDB");a(bL,"rimrafSteadily");a(Tf,"getFilePath");a(K4,"writeBlobWithBuffer");a(Y4,"generateFilePath");pL=new Map;a(W4,"getNextFileId");op=128;a(z4,"getNextStorageIndex");a(j4,"createFrequencyTableForStoragePaths");a(dp,"encodeBlobsWithFilePath");a(Q4,"encodeBlobsAsBuffers");a(fp,"decodeBlobsWithWrites");a(_p,"decodeWithBlobCallback");a(hc,"decodeFromDatabase");a(ta,"deleteBlobsInObject");a(Zl,"findBlobsInObject");(0,ji.addExtension)({Class:hi,type:11,unpack:a(function(e){let t=(0,ji.unpack)(e),r=new ip;if(Object.assign(r,t[0]),typeof t[1]!="object"){if(hn.set(r,{storageIndex:t[1],fileId:t[2],store:mn}),fc)return fc(r)??r;if(!mn)throw new Error("No store specified, cannot load blob from storage")}else hn.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=hn.get(e);if(Xl!==void 0&&(_c=!0,t?.recordId!==void 0&&t.recordId!==Xl))throw new Error("Cannot use the same blob in two different records");let r={...e};if(e.type&&(r.type=e.type),e.size!==void 0&&(r.size=e.size),t){if(t.storageBuffer)return t.storageBuffer;if(t.contentBuffer?.length<gL)return r.size=t.contentBuffer.length,(0,ji.pack)([r,t.contentBuffer])}if(Xl!==void 0){if(t=RL(e),!t.fileId)throw new Error("Unable to save blob without file id");return t.recordId=Xl,(0,ji.pack)([r,t.storageIndex,t.fileId])}if(t)try{let n=(0,je.readFileSync)(Tf(t));if(n.length>=Er&&(n.copy(gf,0,0,Er),Number(sp.getBigUint64(0)&0xffffffffffffn)===n.length-Er))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(J4,"polyfillBlob")});var LL={};Ue(LL,{asyncSerialization:()=>JA,contentTypes:()=>rR,findBestSerializer:()=>pp,getDeserializer:()=>eo,hasAsyncSerialization:()=>XA,registerContentHandlers:()=>bf,serialize:()=>Of,serializeMessage:()=>ra,toCsvStream:()=>mp});function Z4(e){try{return e?.[0]===123?tR(e):e}catch{return e}}function bf(e){e.register(t3,{serializers:[{regex:/^application\/json$/,serializer:Ef},{regex:/^application\/cbor$/,serializer:a(function(t){return new mc.EncoderStream(yf).end(t)},"serializer")},{regex:/^application\/(x-)?msgpack$/,serializer:a(function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?pc.Readable.from((0,mi.encodeIter)(t,yf)):(0,mi.pack)(t)},"serializer")},{regex:/^text\/csv$/,serializer:a(function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),mp(t)},"serializer")}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mi.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mc.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function pp(e){let t=e.headers.asObject||e.headers,r=e.requestedContentType??t.accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[u,...f]=l.split(/\s*;\s*/),d=1,_={q:1};for(let m of f){let S=m.indexOf("=");_[m.substring(0,S)]=m.substring(S+1)}d=+_.q;let h=Kr.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 wL.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Kr.keys()).join(", "),406);n=Kr.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Of(e,t,r){let n=NL&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array||e instanceof hi)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=pp(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&e&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){if(e.mapError){let c=e.getColumns;e=e.mapError(l=>(l.toJSON=()=>({error:l.name,message:l.message,...l.partialObject}),eR.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,Zi.createBrotliCompress)({params:{[Zi.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Zi.constants.BROTLI_MODE_TEXT:Zi.constants.BROTLI_MODE_GENERIC,[Zi.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>NL?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Zi.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function ra(e,t,r){if(e?.contentType!=null&&e.data!=null)return e.data;Xi=r?void 0:[];try{let n;if(t){let s=t.serialize;if(s)n=s(e);else{let i=pp(t);s=t.serialize=i.serializer.serialize,n=s(e)}}else n=Rf(e);return Xi?.length>0?(Xi.length===1?Xi[0]:Promise.all(Xi)).then(()=>ra(e,t,!0)):n}finally{Xi=void 0}}function JA(e){if(Xi)Xi.push(e);else throw new Error("Unable to serialize asynchronously")}function XA(){return!!Xi}function r3(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 s3(e){return n3.includes(e)}function i3(e){let t=e.indexOf(";"),r;if(t>-1){r={};let n=e.slice(t+1).split(";");for(let s of n){let[i,o]=s.split("=");r[i.trim()]=o.trim()}e=e.slice(0,t)}return{type:e,parameters:r}}function eo(e="",t=!1){let r=i3(e),n=r.type&&Kr.get(r.type)?.deserialize||o3(r);return t?s=>r3(s).then(n):n}function o3(e){return e.type.startsWith("text/")?(e.parameters?.charset&&!s3(e.parameters.charset)&&eR.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 tR(t)}catch{}return{contentType:e.type||"application/octet-stream",data:t}}}function a3(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}function mp(e,t){let r=pc.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 X4(n,s);return r.pipe(i)}var mi,mc,Zi,wL,pc,IL,ZA,CL,eR,X4,PL,Rf,tR,yf,Kr,rR,OL,DL,e3,t3,NL,Xi,n3,Ji=be(()=>{YA();mi=require("msgpackr"),mc=require("cbor-x"),Zi=require("zlib"),wL=M(me()),pc=M(require("stream"));Pr();IL=M(ai()),ZA=M(le());k();CL=M(require("yaml")),eR=M(_i());us();({Transform:X4}=require("json2csv")),PL=ZA.default.get(U.SERIALIZATION_BIGINT)!==!1,Rf=PL?dc:JSON.stringify,tR=PL?KA:JSON.parse,yf={useRecords:!1,useToJSON:!0},Kr=new Map,rR=Kr;Ke.contentTypes=rR;(0,IL._assignPackageExport)("contentTypes",rR);Kr.set("application/json",{serializeStream:Ef,serialize:Rf,deserialize(e){return tR(e)},q:.8});OL=new mc.Encoder(yf);Kr.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new mc.EncoderStream(yf).end(e)},serialize:OL.encode,deserialize:OL.decode,q:1});Kr.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?pc.Readable.from((0,mi.encodeIter)(e,yf)):(0,mi.pack)(e)},serialize:mi.pack,deserialize:mi.unpack,q:.9});Kr.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),mp(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),mp(e,e?.getColumns?.())},q:.1});Kr.set("text/plain",{serialize(e){return e.toString()},serializeStream(e){return pc.Readable.from(e.map?e.map(t=>t.toString()):e)},deserialize(e){return e.toString()},q:.2});Kr.set("text/yaml",{serialize(e){return CL.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Kr.set("text/event-stream",{serializeStream:a(function(e){return pc.Readable.from(a3(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+`
@@ -129,4 +129,4 @@ Connection: close\r
129
129
  \r
130
130
  `))}},25).unref()}o.close?.(()=>{if(st.get(Wt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&bd()==0)try{_W(pW(st.get(Wt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,oT),o.cantCleanupProperly||Cn.warn("Had to forcefully exit the thread",oT),process.exit(0)},5e3).unref()})}if(EW||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Cn.info("Could not close debugger",i)}}}).ref();let e;Jh&&!nge&&(e=SW()),Promise.resolve(e).then(()=>{if(bd()===0)try{ege(QI)}catch(t){console.error("Error displaying start-up log",t)}Xh?.postMessage({type:Wt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(gW,"startServers");function SW(){let e=[];for(let t in Bi){let r=Bi[t];if(t.includes?.("/")&&bd()==0){WEe(t)&&_W(t),e.push(new Promise((o,c)=>{r.listen({path:t},()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),Cn.info("Domain socket listening on "+t)}).on("error",c)}));continue}let n,s=st.get(Wt.CONFIG_PARAMS.HTTP_THREADRANGE);if(s){let o=typeof s=="string"?s.split("-"):s,c=bd();if(c<o[0]||c>o[1])continue}let i;try{let o=t.lastIndexOf(":");o>0?Jh?n={fd:Jh(+t.slice(o+1).replace(/[\[\]]/g,""),t.slice(0,o))}:n={host:+t.slice(o+1).replace(/[\[\]]/g,""),port:t.slice(0,o)}:Jh?n={fd:Jh(+t,"::")}:n={port:t}}catch(o){console.error(`Unable to bind to port ${t}`,o);continue}e.push(new Promise((o,c)=>{r.listen(n,()=>{o({port:t,name:r.name,protocol_name:r.protocol_name}),Cn.trace("Listening on port "+t,oT)}).on("error",c)}))}return Promise.all(e)}a(SW,"listenOnPorts");!zI&&!kEe?.noServerStart&&gW();function ZI(e,t,r){let n=e?.read?e:new FEe({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Bi[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=Bi[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Cn.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(ZI,"deliverSocket");var cW=new Map;function sge(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=cW.get(s),r){case"connection":i=ZI(void 0,t),cW.set(s,i),i.write=(c,l,u)=>(Xh.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),u&&u(),!0),i.end=(c,l,u)=>(Xh.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),u&&u(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Xh.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(sge,"proxyRequest");var{getComponentName:cT}=(yh(),D(Rh));function eC(e,t,r=!0){t||(t=st.get(Wt.CONFIG_PARAMS.HTTP_PORT));let n=Bi[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",fW),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else Bi[t]=e;e.on("unhandled",fW)}a(eC,"registerServer");function tC(e){let t=[],r=e?.securePort;return r&&t.push({port:r,secure:!0}),r=e?.port,r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],st.get(Wt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:st.get(Wt.CONFIG_PARAMS.HTTP_PORT),secure:st.get(Wt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),st.get(Wt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:st.get(Wt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&st.get(Wt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:pW(st.get(Wt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}a(tC,"getPorts");function rC(e,t){let r=[];for(let{port:n,secure:s}of tC(t))r.push(TW(n,s,t?.isOperationsServer,t?.mtls)),typeof e=="function"?JI[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||n}):(e.isSecure=s,eC(e,n,!1)),aT[n]=uT(JI,n);return r}a(rC,"httpServer");function lT(e,t){let r=QI.get(e)??[];QI.set(e,[...r,t])}a(lT,"setPortServerMap");function TW(e,t,r,n){if(lT(e,{protocol_name:t?"HTTPS":"HTTP",name:cT()}),!iT[e]){let s=r?"operationsApi_network":"http",i=st.get(s+"_keepAliveTimeout"),o=st.get(s+"_timeout"),c=st.get(s+"_headersTimeout"),l={keepAliveTimeout:i,headersTimeout:c,requestTimeout:o,highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,maxHeaderSize:st.get(Wt.CONFIG_PARAMS.HTTP_MAXHEADERSIZE)},u=st.get(s+"_mtls"),f=st.get(s+"_mtls_required"),d;if(t){let m=st.get("tls");d=st.get(s+"_http2"),Object.assign(l,{allowHTTP1:!0,rejectUnauthorized:!!f,requestCert:!!(u||n),ticketKeys:QEe(),SNICallback:mW(r?"operations-api":"server",u),ciphers:m.ciphers??m[0]?.ciphers})}let _=ZEe(),h=iT[e]=(t?d?KEe:VEe:qEe)(l,async(m,S)=>{try{let R=performance.now(),E=new hW(m,S);r&&(E.isOperationsServer=!0);let T=await aT[e](E);if(!T){if(E._nodeResponse.statusCode)return;T=AW(E)}if(T.headers?.set||(T.headers=new jI(T.headers)),_?T.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):T.headers?.set?.("Server","HarperDB"),T.status===-1){for(let ne of T.headers||[])S.setHeader(ne[0],ne[1]);return m.baseRequest=E,S.baseResponse=T,iT[e].emit("unhandled",m,S)}let w=T.status||200,v=performance.now(),H=v-R,q=T.body,W,te=!1;if(!T.handlesHeaders){let ne=T.headers||new jI;q?q.length>=0?(typeof q=="string"?ne.set("Content-Length",Buffer.byteLength(q)):ne.set("Content-Length",q.length),W=!0):q instanceof YEe&&(q.size?ne.set("Content-Length",q.size):q.on&&(te=!0,q.on("size",oe=>{S.headersSent||S.setHeader("Content-Length",oe)})),q=q.stream()):(ne.set("Content-Length","0"),W=!0);let ue=`hdb;dur=${H.toFixed(2)}`;if(T.wasCacheMiss&&(ue+=", miss"),XEe(ne,"Server-Timing",ue,!0),!S.headersSent)if(te){if(S.statusCode=w,ne)if(ne[Symbol.iterator])for(let[oe,pe]of ne)S.setHeader(oe,pe);else for(let oe in ne)S.setHeader(oe,ne[oe])}else S.writeHead(w,ne&&(ne[Symbol.iterator]?Array.from(ne):ne));W&&S.end(q)}let se=E.handlerPath,Y=E.method;if(jh(H,"duration",se,Y,T.wasCacheMiss==null?void 0:T.wasCacheMiss?"cache-miss":"cache-hit"),oW(w<400,"success",se,Y),oW(1,"response_"+w,se,Y),!W)if(q instanceof ReadableStream&&(q=aW.fromWeb(q)),(q[Symbol.iterator]||q[Symbol.asyncIterator])&&(q=aW.from(q)),q?.pipe){q.pipe(S),q.destroy&&S.on("close",()=>{q.destroy()});let ne=0;q.on("data",ue=>{ne+=ue.length}),q.on("end",()=>{jh(performance.now()-v,"transfer",se,Y),jh(ne,"bytes-sent",se,Y)})}else q?.then?q.then(ne=>{S.end(ne)},g):S.end(q)}catch(R){g(R)}function g(R){let E=R.headers;S.writeHead(R.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),S.end(R.toString()),R.statusCode?R.statusCode===500?Cn.warn(R):Cn.info(R):Cn.error(R)}a(g,"onError")});i>=0&&(h.keepAliveTimeout=i),c>=0&&(h.headersTimeout=c),t&&(h.ports||(h.ports=[]),h.ports.push(e),l.SNICallback.initialize(h),u&&(h.mtlsConfig=u),h.on("secureConnection",m=>{m._parent.startTime&&jh(performance.now()-m._parent.startTime,"tls-handshake",e),jh(m.isSessionReused(),"tls-reused",e)}),h.isSecure=!0),eC(h,e)}return iT[e]}a(TW,"getHTTPServer");function uT(e,t){let r=AW;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a((...c)=>s(...c,o),"next_callback")}}return r}a(uT,"makeCallbackChain");function AW(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new jI}}a(AW,"unhandled");function ige(e,t){rC(e,{requestOnly:!0,...t})}a(ige,"onRequest");function oge(e,t){let r;if(t.securePort){lT(t.securePort,{protocol_name:"TLS",name:cT()});let n=mW("server",t.mtls),s=st.get("tls");r=jEe({rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,ciphers:s.ciphers??s[0]?.ciphers,SNICallback:n},e),n.initialize(r),Bi[t.securePort]=r}return t.port&&(lT(t.port,{protocol_name:"TCP",name:cT()}),r=GEe(e,{noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600}),Bi[t.port]=r),r}a(oge,"onSocket");Object.defineProperty($Ee.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.toLowerCase().includes("upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});var lW=[],XI={};function RW(e,t){for(let{port:r}of tC(t))lW[t?.runFirst?"unshift":"push"]({listener:e,port:r}),XI[r]=uT(lW,r)}a(RW,"onUpgrade");var uW=[],dW={};function age(e,t){let r=[];for(let{port:n,secure:s}of tC(t)){lT(n,{protocol_name:s?"WSS":"WS",name:cT()});let i=TW(n,s,t?.isOperationsServer,t?.mtls);Qh[n]||(Qh[n]=new zEe({noServer:!0,maxPayload:t.maxPayload??100*1024*1024}),Qh[n].on("connection",(o,c)=>{let l=new hW(c);l.isWebSocket=!0;let u=aT[n](l);dW[n](o,l,u)}),RW((o,c,l,u)=>o.__harperdb_request_upgraded?u(o,c,l):Qh[n].handleUpgrade(o,c,l,f=>{o.__harperdb_request_upgraded=!0,u(o,c,l),Qh[n].emit("connection",f,o)}),{port:n}),i.on("upgrade",(o,c,l)=>{XI[n]&&XI[n](o,c,l)})),r.push(i),uW[t?.runFirst?"unshift":"push"]({listener:e,port:n}),dW[n]=uT(uW,n),aT[n]=uT(JI,n)}return r}a(age,"onWebSocket");function fW(e,t){t.writeHead(404),t.end(`Not found
131
131
  `)}a(fW,"defaultNotFound")});var iW={};Ue(iW,{startHTTPThreads:()=>lge,startSocketServer:()=>cC,updateWorkerIdleness:()=>DW});async function lge(e=2,t){try{if(t)oC(0,1,!0);else{let{loadRootComponents:r}=dT();if(e===0)return(0,Is.setMainIsWorker)(!0),await nC().startServers(),Promise.resolve([]);await r()}PW();for(let r=0;r<e;r++)oC(r,e);return Promise.all(CW)}finally{(0,Is.threadsHaveStarted)()}}function PW(){let e=(0,NW.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),iC=setInterval(()=>{hT.notify(e)},cge).unref())}function oC(e,t=1,r){if(sC++,(0,Is.startWorker)("server/threads/threadServer.js",{name:fA.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(u){u.type===lA.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});CW.push(s),await s,Od.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=_T.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Od.indexOf(n);o>-1&&Od.splice(o,1)}if(a(i,"removeWorker"),Nd){let o=Nd;Nd=[];for(let c of o)IW[c.localPort](null,c)}}}),r){let n=setInterval(()=>{aC?aC=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Is.shutdownWorkers)(),sC=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function cC(e=0,t){if(typeof e=="string")try{(0,mT.existsSync)(e)&&(0,mT.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=uge:r=dge(t):r=lC;let n=(0,wd.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);return n._handle&&(n._handle.onconnection=IW[e]=function(s,i){r.readsData||(i.reading=!1,i.readStop()),aC=!0,r(i,(o,c)=>{if(!o){if(yW){let u=i._socket||new wd.Socket({handle:i,writable:!0,readable:!0});yW.deliverSocket(u,e,c),u.resume()}else sC>0?(Nd.length===0&&setTimeout(()=>{Nd.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),i.localPort=e,Nd.push(i)):(console.log("start up a dynamic thread to handle request"),oC(0));tr(!1,"socket-routed");return}o.requests++;let l=i.fd;if(l>=0)o.postMessage({port:e,fd:l,data:c});else{let u=i._socket||new wd.Socket({handle:i,writable:!0,readable:!0});hge(u,o,e)}tr(!0,"socket-routed")})},hT.info(`HarperDB ${wW.packageJson.version} Server running on port ${e}`)),n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function lC(e,t){let r,n=0;for(let s of Od){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=fT)return fT=i,t(r);n=i}fT=0,t(r)}function uge(e,t){let r={};e.getpeername(r);let n=r.address,s=Id.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);lC(e,o=>{Id.set(n,{worker:o,lastUsed:i}),t(o)})}function dge(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new wd.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let l=o.toString("latin1").match(t)?.[1],u=Id.get(l),f=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=f,s(u.worker);lC(n,d=>{Id.set(l,{worker:d,lastUsed:f}),s(d,o)})})}a(r,"findByHeaderAffinity")}function DW(){fT=0;for(let e of Od)e.expectedIdle=e.recentELU.idle+fge,e.requests=1;Od.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function hge(e,t,r){let n=_ge++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),_T.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),_T.delete(n)),s.event=="destroy"&&(e.destroy(),_T.delete(n))})}var Is,wd,hT,mT,OW,NW,wW,Od,Nd,IW,yW,sC,CW,iC,cge,aC,fT,bW,Id,fge,_T,_ge,WI=be(()=>{Is=M(rt()),wd=require("net");k();hT=M(j()),mT=require("fs");Oi();OW=require("worker_threads"),NW=M(Xu()),wW=M(mt()),Od=[],Nd=[],IW=[],sC=0,CW=[];OW.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,Is.onMessageFromWorkers)(e=>{e.type===dA.RESTART&&iC&&(clearInterval(iC),PW())}));cge=6e5;a(lge,"startHTTPThreads");a(PW,"licenseWarning");a(oC,"startHTTPWorker");a(cC,"startSocketServer");fT=0;a(lC,"findMostIdleWorker");bW=36e5,Id=new Map;a(uge,"findByRemoteAddressAffinity");a(dge,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Id)r.lastUsed+bW<e&&Id.delete(t)},bW).unref();fge=1e3;a(DW,"updateWorkerIdleness");(0,Is.setMonitorListener)(DW);_T=new Map,_ge=1;a(hge,"proxySocket")});var YW=P((fMe,KW)=>{var MW=M(require("cluster")),Va=M(le());k();var Hi=M(j()),vW=M(require("fastify")),UW=M(require("@fastify/cors")),xW=M(require("@fastify/compress")),BW=M(require("@fastify/static")),HW=M(Bb()),kW=M(require("path")),FW=M(mt()),GW=M(_s()),qW=M(ae()),$W=M(Sn()),VW=M(Xu());Pr();var Ka=M(HS());Ji();Va.default.initSync();var mge=6e4,pge=1024*1024*1024,Ege="TRUE",{CONFIG_PARAMS:em}=$,Cd;KW.exports={hdbServer:LW,start:LW};async function LW(e){try{Hi.default.debug("In Fastify server"+process.cwd()),Hi.default.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Hi.default.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=MW.default.isMaster,await gge();let t=e.securePort>0;Cd=Sge(t),await Cd.ready(),e||(e={}),e.isOperationsServer=!0;try{Ke.http(Cd.server,e),Cd.server.closeIdleConnections||await Cd.listen({port:0,host:"::"})}catch(r){throw Cd.close(),Hi.default.error(r),Hi.default.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Hi.default.fatal(t),process.exit(1)}}a(LW,"operationsServer");async function gge(){Hi.default.trace("Configuring HarperDB process."),GW.default.setSchemaDataToGlobal(),await $W.default.setUsersWithRolesCache(),await VW.default.getLicense()}a(gge,"setUp");function Sge(e){Hi.default.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Tge(e),r=(0,vW.default)(t);r.server.headersTimeout=Rge(),r.setErrorHandler(Ka.serverErrorHandler);let n=Age();n&&r.register(UW.default,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,u){r.server.emit("unhandled",l.raw,u.raw)}),c()}),r.register(HW.default),r.register(xW.default),r.register(BW.default,{root:kW.default.join(FW.PACKAGE_ROOT,"studio/build-local")}),bf(r);let s=Va.default.get(cA.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!qW.default.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Ka.reqBodyValidationHandler,Ka.authHandler],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),(0,Ka.handlePostRequest)(i,o)}),r.get("/health",()=>"HarperDB is running."),Hi.default.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Sge,"buildServer");function Tge(e){let t=Va.default.get(em.OPERATIONSAPI_NETWORK_TIMEOUT),r=Va.default.get(em.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:pge,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Tge,"getServerOptions");function Age(){let e=Va.default.get(em.OPERATIONSAPI_NETWORK_CORS),t=Va.default.get(em.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Ege)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(Age,"getCORSOpts");function Rge(){return Va.default.get(em.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??mge}a(Rge,"getHeaderTimeoutConfig")});var ST={};Ue(ST,{disableNATS:()=>bge,publishToStream:()=>gT,setNATSReplicator:()=>uC,setPublishToStream:()=>Oge,setSubscription:()=>hC,start:()=>yge});function yge(){tm.default.get(U.CLUSTERING_ENABLED)&&wge()}function bge(e=!0){JW=e}function Oge(e,t){gT=e,hC=t}function wge(){if(JW||process.env._DISABLE_NATS)return;let e=Je(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];uC(s,r,i)}}Zc((r,n)=>{uC(r.tableName,r.databaseName,r),n&&ZW(r)}),!WW&&(WW=!0)}function uC(e,t,r){if(t==="system"&&Ige.includes(e))return;if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Vr{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this.getId(),record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this.getId()})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this.getId(),record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this.getId(),record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this.getId()})}static defineSchema(i){ZW(i)}static subscribe(){let i=new Un;return hC(t,e,i),i}static subscribeOnThisThread(i){return i<(tm.default.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Nge)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new pT(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=XW;return i}a(n,"getNATSTransaction")}function ZW(e){let t=tm.default.get(U.CLUSTERING_NODENAME);gT(`${fC.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,_C.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var zW,fC,_C,jW,QW,tm,ET,JW,gT,hC,Nge,XW,WW,Ige,pT,dC,mC=be(()=>{ve();Zo();zW=M(rr()),fC=M(wt()),_C=M(oo());Kl();jW=M(Jb()),QW=M(un()),tm=M(le());k();ET=M(j());a(yge,"start");a(bge,"disableNATS");gT=zW.publishToStream,hC=jW.setSubscription;a(Oge,"setPublishToStream");Nge=2;a(wge,"assignReplicationSource");Ige=["hdb_job","hdb_analytics","hdb_raw_analytics","hdb_info","hdb_license"];a(uC,"setNATSReplicator");a(ZW,"publishSchema");pT=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=tm.default.get(U.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],l,u;for(let f of i){let d=f.table,_=f.operation=="put"?"upsert":f.operation;l||(ET.trace(`Sending transaction event ${_}`),u=l={operation:_,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,_!=="delete"&&_!=="invalidate"&&(l.records=o)),l.table===d&&l.operation===_?(o.push(f.record),c.push(f.id)):u=u.next={operation:_,table:d,id:f.id,record:f.record},f.expiresAt&&(u.expiresAt=f.expiresAt)}l&&n.push(gT(`${fC.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,_C.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(f=>{throw ET.error("An error has occurred trying to replicate transaction",l,f),f.statusCode=504,f}))}return Promise.all(n)}},dC=class extends pT{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,QW.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};XW=new dC});async function sz({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await pC.get(e,{returnNonexistent:!0});i=new SC(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await pC.get(e);o&&o.delete()}i=new AT(e,t)}return n&&(n.id=e,n.user={username:t?.username},rm.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function EC(){return TT++,TT>65500&&(TT=1),TT}function gC(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=ls.getMatch(n,"mqtt");if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ot(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var tz,Ya,rz,nz,ez,pC,rm,TT,AT,SC,iz=be(()=>{ve();Jl();tz=M(un()),Ya=M(j());cc();rz=M(rt()),nz=M(nC());Pr();ez=100,pC=dt({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),rm=dt({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,rz.getWorkerIndex)()===0&&(async()=>{await nz.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of rm.search({})){let t=e.data,r={...e};r.user?.username&&(r.user=await Ke.getUser(r.user.username));try{await gC(r,t,r)}catch{(0,Ya.warn)("Failed to publish will",t)}rm.delete(e.id)}})();a(sz,"getSession");TT=1;a(EC,"getNextMessageId");AT=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),l,u;if(c>-1?(l=s.slice(c),u=s.slice(0,c)):u=s,!u)throw new Error("No topic provided");if(u.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let f=this.subscriptions.find(R=>R.topic===s),d;f?(d=i>0,f.end(),this.subscriptions.splice(this.subscriptions.indexOf(f),1)):d=i===2;let _={search:l,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Ya.trace)("Resuming subscription from",s,"from",o);let h=ls.getMatch(u,"mqtt");if(!h){let R=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw R.statusCode=404,R}if(_.url=h.relativeURL,_.url.indexOf("+")>-1||_.url.indexOf("#")>-1){let R=_.url.slice(1);if(R.indexOf("#")>-1&&R.indexOf("#")!==R.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(_.isCollection=!0,R.indexOf("+")===R.length-1)_.onlyChildren=!0,_.url="/"+R.slice(0,R.length-1);else{let E=R.split("/"),T;for(let H=0;H<E.length;H++)if(E[H].indexOf("+")>-1)if(E[H]==="+")T=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&T)throw new Error("Filters can not be combined");let w=!0;E[E.length-1]==="#"&&(E.length--,w=!1),T&&(n=a(H=>{let q=H.id;if(!Array.isArray(q))if(q?.indexOf?.("/")>-1)q=q.split("/");else return!1;if(w&&q.length!==E.length)return!1;for(let W=0;W<E.length;W++)if(E[W]!=="+"&&E[W]!==q[W])return!1;return!0},"filter"));let v=E.indexOf("+");_.url="/"+(v>-1?E.slice(0,v):E).concat("").join("/")}}else _.isCollection=!1;let m=h.path,S=h.Resource,g=await Ot(_,async()=>{let R=this.createContext();R.topic=s,R.retainHandling=i,R.isCollection=_.isCollection;let E=await S.subscribe(_,R);if(!E)return;if(!E[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);let T=(async()=>{for await(let w of E)try{let v;if(w.type&&w.type!=="put"&&w.type!=="delete"&&w.type!=="message"&&w.type!=="patch"||n&&!n(w))continue;r?(w.topic=s,v=this.needsAcknowledge(w)):(w.acknowledge?.(),v=EC());let H=w.id;if(Array.isArray(H)&&(H=Ql(H)),H==null&&(H=""),await this.listener(m+"/"+H,w.value,v,t)===!1)break;this.awaitingAcks?.size>ez?await new Promise(W=>setTimeout(W,this.awaitingAcks.size-ez)):await new Promise(setImmediate)}catch(v){(0,Ya.warn)(v)}})();return E});if(g)return g.topic=s,g.qos=t.qos,this.subscriptions.push(g),g}resume(){}needsAcknowledge(t){let r=EC();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,{acknowledge:t.acknowledge})),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r.acknowledge())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return gC(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Ot(r,async()=>{try{if(!t){let n=await rm.get(this.sessionId);n?.doesExist()&&await gC(n,n.data,r)}}finally{await rm.delete(this.sessionId)}}).catch(n=>{(0,Ya.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(gC,"publish");SC=class extends AT{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.localTime):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=EC(),n={topic:t.topic,timestamp:t.localTime};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks?.get(t);if(!r)return;this.awaitingAcks?.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Ya.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,tz.getNextMonotonicTime)()),(0,Ya.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),pC.put(this.sessionRecord)}}});var AC={};Ue(AC,{bypassAuth:()=>Cge,start:()=>Pge});function Cge(){uz=!0}function Pge({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new lz.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((u,f,d,_)=>{if(f.headers.get("sec-websocket-protocol")!=="mqtt")return _(u,f,d);o.events.emit("connection",u),fr.debug?.("Received WebSocket connection for MQTT from",u._socket.remoteAddress);let{onMessage:h,onClose:m}=az(u,S=>{u.send(S)},f,Promise.resolve(d).then(()=>f?.user),o);u.on("message",h),u.on("close",m),u.on("error",S=>{fr.info?.("WebSocket error",S)})},{...n})),(t||s)&&c.push(e.socket(async u=>{let f;if(o.events.emit("connection",u),fr.debug?.(`Received ${u.getCertificate?"SSL":"TCP"} connection for MQTT from ${u.remoteAddress}`),l){if(u.authorized)try{let h=l.user;if(h!==null){(h===void 0||h==="Common Name"||h==="CN")&&(h=u.getPeerCertificate().subject.CN);try{f=await e.getUser(h,null,null),(0,Pd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&yT.notify?.({username:f?.username,status:Ms.SUCCESS,type:Vo.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:u.remoteAddress})}catch(m){throw(0,Pd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&yT.error?.({username:h,status:Ms.FAILURE,type:Vo.AUTHENTICATION,auth_strategy:"mqtt",remote_address:u.remoteAddress}),m}}else fr.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",u.remoteAddress)}catch(h){o.events.emit("error",h,u),fr.error?.(h)}else if(l.required)return fr.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${u.authorizationError}`),u.end()}!f&&uz&&u.remoteAddress.includes("127.0.0.1")&&(f=await(0,cz.getSuperUser)(),fr.debug?.("Auto-authorizing local connection",f?.username));let{onMessage:d,onClose:_}=az(u,h=>u.write(h),null,f,o);u.on("data",d),u.on("close",_),u.on("error",h=>{fr.info?.("Socket error",h)})},{port:t,securePort:s,mtls:l})),c}function az(e,t,r,n,s){oz||(oz=!0,g_(d=>{RT>0&&d.push({metric:"mqtt-connections",connections:RT,byThread:!0})}));let i;RT++;let o,c={protocolVersion:4},l=(0,bT.parser)({protocolVersion:5});function u(d){l.parse(d)}a(u,"onMessage");function f(){RT--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Yn(!1,"connection","mqtt","disconnect"),fr.debug?.("MQTT connection was closed",e.remoteAddress))}return a(f,"onClose"),l.on("packet",async d=>{n?.then&&(n=await n);let _=d.cmd;if(o)o.then&&await o;else if(_!=="connect"){fr.info?.("Received packet before connection was established, closing connection"),e?.destroy?e.destroy():e?.terminate();return}let h=d.topic,m=h?.indexOf("/",1),S=m>0?h.slice(0,m):h;tr(d.length,"bytes-received",S,R(d),"mqtt");try{switch(o?.receivedPacket?.(),_){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await Ke.getUser(d.username,d.password.toString(),r),(0,Pd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&yT.notify?.({username:n?.username,status:Ms.SUCCESS,type:Vo.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(se){return(0,Pd.get)(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&yT.error?.({username:d.username,status:Ms.FAILURE,type:Vo.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,se),Yn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Yn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let se=e.deserialize||(e.deserialize=eo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?se(d.will.payload):void 0,delete d.will.payload}o=sz({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(se){return fr.error?.(se),s.events.emit("auth-failed",d,e,se),Yn(!1,"connection","mqtt","connect"),g({cmd:"connack",reasonCode:se.code||5,returnCode:se.code||128})}s.events.emit("connected",o,e),Yn(!0,"connection","mqtt","connect"),g({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0});let T=a(async(se,Y,ne,ue)=>{try{if(i)throw new Error("Session disconnected while trying to send message to",se);let oe=se.indexOf("/",1),pe=oe>0?se.slice(0,oe):se;g({cmd:"publish",topic:se,payload:await E(Y),messageId:ne||Math.floor(Math.random()*1e8),qos:ue.qos},pe);let Te=e._socket??e;return Te.writableNeedDrain?new Promise(ye=>Te.once("drain",ye)):!Te.closed}catch(oe){return fr.error?.(oe),o?.disconnect(),s.sessions.delete(o),!1}},"listener");o.setListener(T),o.sessionWasPresent&&await o.resume();break;case"subscribe":let w=[];for(let se of d.subscriptions){let Y;try{let ne=await o.addSubscription(se,se.qos>=1);Y=ne?ne.qos||0:c.protocolVersion<5?128:143}catch(ne){s.events.emit("error",ne,e,se,o),ne.statusCode?ne.statusCode===500?fr.warn?.(ne):fr.info?.(ne):fr.error?.(ne),Y=c.protocolVersion<5?128:ne.statusCode===403?135:ne.statusCode===404?143:128}w.push(Y)}await o.committed,g({cmd:"suback",granted:w,messageId:d.messageId});break;case"unsubscribe":{let se=[];for(let Y of d.unsubscriptions)se.push(o.removeSubscription(Y)?0:17);g({cmd:"unsuback",granted:se,messageId:d.messageId});break}case"pubrel":g({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let v=d.qos===2?"pubrec":"puback",H=e.deserialize||(e.deserialize=eo(r?.headers.get?.("content-type"))),W=(d.payload?.length||0)>0?H(d.payload):void 0,te;try{te=await o.publish(d,W)}catch(se){s.events.emit("error",se,e,d,o),fr.warn?.(se),d.qos>0&&g({cmd:v,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&g({cmd:v,messageId:d.messageId,reasonCode:te===!1?144:0},d.topic);break;case"pubrec":g({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":g({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Yn(!0,"connection","mqtt","disconnect"),fr.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(T){s.events.emit("error",T,e,d,o),fr.error?.(T),g({cmd:"disconnect"})}function g(T,w){let v=(0,bT.generate)(T,c);t(v),tr(v.length,"bytes-sent",w,R(T),"mqtt")}a(g,"sendPacket");function R(T){return T.qos>0?T.cmd+",qos="+T.qos:T.cmd}a(R,"packetMethodName");function E(T){return ra(T,r)}a(E,"serialize")}),l.on("error",d=>{fr.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:u,onClose:f}}var bT,cz,Pd,TC,lz,yT,fr,uz,oz,RT,dz=be(()=>{bT=require("mqtt-packet");iz();cz=M(Sn());Ji();Oi();Pr();Pd=M(le());k();TC=M(_i()),lz=require("events"),yT=(0,TC.loggerWithTag)("auth-event"),fr=(0,TC.loggerWithTag)("mqtt"),uz=(0,Pd.get)(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Cge,"bypassAuth");a(Pge,"start");RT=0;a(az,"onSocket")});var Rh={};Ue(Rh,{component_errors:()=>Ld,getComponentName:()=>Uge,loadComponent:()=>wT,loadComponentDirectories:()=>pz,setErrorReporter:()=>vge});function pz(e,t){t&&(yC=t),e&&(NC=e);let r=[];if((0,ct.existsSync)(RC)){let s=(0,ct.readdirSync)(RC,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,gt.join)(RC,o);r.push(wT(c,yC,sA,!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(wT(n,yC,n,!1,null,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{mz=!0})}function vge(e){nm=e}function xge(e,t){return new Promise((r,n)=>{let s=Je().system.hdb_info;if(!s)return r();let i=setTimeout(()=>{s.primaryStore.unlock(e,0),n(new Error("symlinking harperdb module timed out"))},1e4);if(s.primaryStore.attemptLock(e,0,()=>{clearTimeout(i),r()}))try{(0,ct.rmSync)(t,{recursive:!0,force:!0}),(0,ct.existsSync)((0,gt.join)(e,"node_modules"))||(0,ct.mkdirSync)((0,gt.join)(e,"node_modules")),(0,ct.symlinkSync)(CC.PACKAGE_ROOT,t,"dir"),r()}finally{s.primaryStore.unlock(e,0)}})}async function wT(e,t,r,n,s,i){let o=(0,ct.realpathSync)(e);if(OT.has(o))return OT.get(o);OT.set(o,!0),s&&(NC=s);try{let c;n&&(Ld=new Map);let l=(0,gt.join)(e,"harperdb-config.yaml");(0,ct.existsSync)(l)?c=n?(0,IT.getConfigObj)():(0,bC.parseDocument)((0,ct.readFileSync)(l,"utf8")).toJSON():!n&&(0,ct.existsSync)(l=(0,gt.join)(e,"config.yaml"))?c=(0,bC.parseDocument)((0,ct.readFileSync)(l,"utf8")).toJSON():c=wC;try{let d=(0,gt.join)(e,"node_modules","harperdb");(n||((0,ct.existsSync)(d)||!e.startsWith((0,OC.getHdbBasePath)()))&&(!(0,ct.existsSync)(d)||(0,ct.realpathSync)(CC.PACKAGE_ROOT)!==(0,ct.realpathSync)(d)))&&await xge(e,d)}catch(d){Il.default.error("Error symlinking harperdb module",d),d.code=="EPERM"&&process.platform==="win32"&&Il.default.error('You may need to enable developer mode in "Settings" / "System" (or "Update & Security") / "For developers", in order to enable symlinks so components can use `import from "harperdb"`')}let u=NT,f=n;for(let d in c){NT=d;let _=c[d];if(Ld.set(n?d:(0,gt.basename)(e),!1),!_)continue;let h,m=_.package;try{if(m){let T=e,w;for(;!(0,ct.existsSync)(w=(0,gt.join)(T,"node_modules",d));)if(T=(0,gt.dirname)(T),T.length<(0,OC.getHdbBasePath)().length){w=null;break}if(w)h=await wT(w,t,r,!1),f=!0;else throw new Error(`Unable to find package ${d}:${m}`)}else h=Mge[d];if(!h)continue;let S=a(T=>(T.origin=r,dt(T)),"ensureTable"),g=_.network||(_.port||_.securePort)&&_,R=g?.securePort||g?.https&&g.port,E=!g?.https&&g?.port;if(Dd.isMainThread&&(h=await h.startOnMainThread?.({server:Ke,ensureTable:S,port:E,securePort:R,resources:t,..._})||h,n&&g))for(let T of[E,R])try{if(+T&&!fz.includes(T)){let w=IC.get(U.HTTP_SESSIONAFFINITY);w&&Il.default.warn("Session affinity is not recommended and may cause memory leaks"),(w||!yE)&&(fz.push(T),cC(T,w))}}catch(w){console.error("Error listening on socket",T,w,d)}if(t.isWorker&&(h=await h.start?.({server:Ke,ensureTable:S,port:E,securePort:R,resources:t,..._})||h),NC.set(h,!0),(h.handleFile||h.handleDirectory||h.setupFile||h.setupDirectory)&&_.files!=null){if(_.files.includes(".."))throw(0,hz.handleHDBError)("Can not reference parent directories");let T=(0,gt.join)(e,_.files).replace(/\\/g,"/"),w=T.indexOf("/*");if(w>-1&&_.files!==wC[d]?.files&&!(0,ct.existsSync)(T.slice(0,w)))throw new Error(`The path '${T.slice(0,w)}' does not exist and cannot be used as the base of the resolved 'files' path value '${_.files}'`);let v=(0,gt.basename)(e),H=_.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+v+H.slice(2):H==="."?"/"+v:"/"+v+"/"+H;let q,W,te;if(_.root){let Y=_.root;Y.startsWith("/")&&(Y=Y.slice(1)),Y.endsWith("/")&&(Y=Y.slice(0,-1)),Y+="/",W=(0,gt.join)(e,Y)}else(te=T.indexOf("/*"))>-1?(W=T.slice(0,te+1),q=(0,gt.relative)(e,W)):_.files.indexOf("/")>-1&&(W=T.slice(0,T.lastIndexOf("/")+1),q=(0,gt.relative)(e,W));let se=!1;if(Dd.isMainThread&&h.setupDirectory&&(se=await h.setupDirectory?.(H,W,t)),t.isWorker&&h.handleDirectory&&(se=await h.handleDirectory?.(H,W,t)),se){f=!0;continue}for(let Y of await(0,_z.default)(T,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:ue}=Y;f=!0;let oe=(0,gt.relative)(e,ne).replace(/\\/g,"/");if(q)if(oe.startsWith(q))oe=oe.slice(q.length+1);else throw new Error(`The root path '${_.root}' does not reference a valid part of the file path '${oe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let pe=H+(H.endsWith("/")?"":"/")+oe;try{if(ue.isFile()){let Te=await Lge(ne);Dd.isMainThread&&await h.setupFile?.(Te,pe,ne,t),t.isWorker&&await h.handleFile?.(Te,pe,ne,t)}else Dd.isMainThread&&await h.setupDirectory?.(pe,ne,t),t.isWorker&&await h.handleDirectory?.(pe,ne,t)}catch(Te){let ye=`Could not load ${ue.isFile()?"file":"directory"} '${ne}'${_.module?` using '${_.module}'`:""} for application '${e}' due to:
132
- `;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,nm?.(Te),Il.default.error(Te),t.set(_.path||"/",new ea(Te)),Ld.set(n?d:(0,gt.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,gt.basename)(e)}' due to: ${S.message}`,nm?.(S),((0,sm.getWorkerIndex)()===0?console:Il.default).error(S),t.set(_.path||"/",new ea(S),null,!0),Ld.set(n?d:(0,gt.basename)(e),S.message)}}if(NT=u,Dd.isMainThread&&!mz&&i&&(0,sm.watchDir)(e,async()=>pz()),c.extensionModule){let d=await gE((0,gt.join)(e,c.extensionModule));return OT.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;nm?.(new Error(d)),((0,sm.getWorkerIndex)()===0?console:Il.default).error(d),Ld.set((0,gt.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,nm?.(c),t.set("",new ea(c))}}var ct,gt,Dd,bC,IC,CC,_z,sm,Il,hz,OC,Dge,IT,Lge,RC,NC,mz,yC,Ld,Mge,wC,fz,OT,nm,NT,Uge,yh=be(()=>{ct=require("fs"),gt=require("path"),Dd=require("worker_threads"),bC=require("yaml"),IC=M(le()),CC=M(mt());k();oL();qL();Xx();rB();nB();GB();RK();IK();PK();_z=M(require("fast-glob")),sm=M(rt()),Il=M(j());Sb();Pr();hz=M(me());ve();WI();OC=M(le()),Dge=M(YW());tS();mC();hs();dz();IT=M(bt());bE();FA();({readFile:Lge}=ct.promises),RC=(0,IT.resolvePath)(IC.get(U.COMPONENTSROOT)),NC=new Map,Ld=new Map;a(pz,"loadComponentDirectories");Mge={REST:NE,rest:NE,graphql:sR,graphqlSchema:$A,roles:gb,jsResource:Ab,fastifyRoutes:lI,login:yb,static:uI,operationsApi:Dge,customFunctions:{},http:{},clustering:ST,replication:Ea,authentication:mh,mqtt:AC,loadEnv:dI},wC={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(wC,"static",{value:{files:"web/**"}});fz=[],OT=new Map;a(vge,"setErrorReporter");Uge=a(()=>NT,"getComponentName");a(xge,"symlinkHarperModule");a(wT,"loadComponent")});var dT=P((qMe,gz)=>{var{isMainThread:Ez}=require("worker_threads"),{getTables:Bge,getDatabases:FMe,table:GMe}=(ve(),D(it)),{loadComponentDirectories:Hge,loadComponent:kge}=(yh(),D(Rh)),{resetResources:Fge}=(Jl(),D(nL)),Gge=lw(),qge=bt(),{dirname:$ge}=require("path"),{getConnection:Vge}=rr(),Kge=le(),{CONFIG_PARAMS:Yge}=(k(),D($)),{loadCertificates:Wge}=Qs(),PC=new Map;async function zge(e=!1){!Ez&&Kge.get(Yge.CLUSTERING_ENABLED)&&Vge();try{Ez&&await Gge()}catch(n){console.error(n)}let t=Fge();Bge(),t.isWorker=e,await Wge(),await kge($ge(qge.getConfigFilePath()),t,"hdb",!0,PC),await Hge(PC,t);let r=[];for(let[n]of PC)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(zge,"loadRootComponents");gz.exports.loadRootComponents=zge});var rt=P((VMe,oi)=>{"use strict";ym();var{Worker:jge,MessageChannel:Qge,parentPort:ki,isMainThread:UC,threadId:Jge,workerData:Fi}=require("worker_threads"),{PACKAGE_ROOT:Xge}=mt(),{join:Rz,isAbsolute:Zge,extname:eSe}=require("path"),{server:yz}=(Pr(),D(ql)),{watch:tSe,readdir:rSe}=require("fs/promises"),{totalmem:Sz}=require("os"),Md=(k(),D($)),bz=le(),ii=j(),{randomBytes:nSe}=require("crypto"),{_assignPackageExport:sSe}=ai(),Tz=1024*1024,Wa=[],Cs=[],iSe=50,xC=1e4,oSe="restart",Oz="request_thread_info",Nz="resource_report",wz="thread_info",Iz="added-port",aSe="ack",DC;sSe("threads",Cs);oi.exports={startWorker:LC,restartWorkers:HC,shutdownWorkers:fSe,workers:Wa,setMonitorListener:TSe,onMessageFromWorkers:_Se,onMessageByType:Uz,broadcast:mSe,broadcastWithAcknowledgement:ESe,setChildListenerByType:dSe,getWorkerIndex:Cz,getWorkerCount:Pz,getTicketKeys:Lz,setMainIsWorker:lSe,setTerminateTimeout:cSe,restartNumber:Fi?.restartNumber||1};Cs.onMessageByType=Uz;Cs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Cs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};oi.exports.whenThreadsStarted=new Promise(e=>{oi.exports.threadsHaveStarted=e});var BC;function cSe(e){xC=e}a(cSe,"setTerminateTimeout");function Cz(){return Fi?Fi.workerIndex:BC?0:void 0}a(Cz,"getWorkerIndex");function Pz(){return Fi?Fi.workerCount:BC?1:void 0}a(Pz,"getWorkerCount");function lSe(e){BC=e,oi.exports.threadsHaveStarted()}a(lSe,"setMainIsWorker");var Dz=1,CT;function Lz(){return CT||(CT=UC?nSe(48):Fi.ticketKeys,CT)}a(Lz,"getTicketKeys");Object.defineProperty(yz,"workerIndex",{get(){return Cz()}});Object.defineProperty(yz,"workerCount",{get(){return Pz()}});var Mz={[Oz](e,t){gSe(t)},[Nz](e,t){SSe(t,e)}};function LC(e,t={}){let r=process.constrainedMemory?.()||Sz();r=Math.min(r,Sz(),2e4*Tz);let n=bz.get(Md.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Tz/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Cs){let u=new Qge;u.existingPort=l,i.push(u),o.push(u.port2)}eSe(e)||(e+=".js");let c=new jge(Zge(e)?e:Rz(Xge,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Dz=t.threadCount,name:t.name,restartNumber:oi.exports.restartNumber,ticketKeys:Lz()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:Iz,port:l,threadId:c.threadId},[l]);return DT(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>LC(e,t),c.on("error",l=>{ii.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Wa.splice(Wa.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<iSe?(t.unexpectedRestarts=c.unexpectedRestarts+1,LC(e,t)):ii.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{Mz[l.type]?.(l,c)}),Wa.push(c),RSe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(LC,"startWorker");var uSe=[Md.THREAD_TYPES.HTTP];async function HC(e=null,t=Math.max(Dz>3,1),r=!0){if(UC){try{process.chdir(process.cwd())}catch(o){ii.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=dT();await o()}oi.exports.restartNumber++,t<1&&(t=t*Wa.length);let n=[],s=[];for(let o of Wa.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ii.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:oi.exports.restartNumber,type:Md.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=uSe.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{ii.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},xC*2).unref();o.on("exit",()=>{clearTimeout(f),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),u()})});if(n.push(l),c&&r){let u=o.startCopy(),f=new Promise(d=>{let _=a(h=>{h.type===Md.ITC_EVENT_TYPES.CHILD_STARTED&&(ii.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");ii.trace("Waiting for worker to start",u.threadId),u.on("message",_)});s.push(f),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=id();r&&(e==="http"||!e)&&bz.get(Md.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ki.postMessage({type:oSe,workerType:e})}a(HC,"restartWorkers");function dSe(e,t){Mz[e]=t}a(dSe,"setChildListenerByType");function fSe(e){return HC(e,1/0,!1)}a(fSe,"shutdownWorkers");var vz=[];function _Se(e){vz.push(e)}a(_Se,"onMessageFromWorkers");var MC=new Map;function Uz(e,t){let r=MC.get(e);r||MC.set(e,r=[]),r.push(t)}a(Uz,"onMessageByType");var hSe=10;async function mSe(e,t){let r=0;for(let n of Cs)try{n.postMessage(e),r++>hSe&&(r=0,await new Promise(setImmediate))}catch(s){ii.error("Unable to send message to worker",s)}t&&Bz(e,null)}a(mSe,"broadcast");var PT=new Map,pSe=1;function ESe(e){return new Promise(t=>{let r=0;for(let n of Cs)try{let s=pSe++,i=a(()=>{PT.delete(s),--r===0&&t(),n!==ki&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,PT.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of PT)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ii.error("Unable to send message to worker",s)}r===0&&t()})}a(ESe,"broadcastWithAcknowledgement");function gSe(e){e.postMessage({type:wz,workers:xz()})}a(gSe,"sendThreadInfo");function xz(){let e=Date.now();return Wa.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(xz,"getChildWorkerInfo");function SSe(e,t){e.resources=t,e.resources.updated=Date.now()}a(SSe,"recordResourceReport");var vC;function TSe(e){vC=e}a(TSe,"setMonitorListener");var ASe=1e3,Az=!1;function RSe(){Az||(Az=!0,setInterval(()=>{for(let e of Wa){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}vC&&vC()},ASe).unref())}a(RSe,"startMonitoring");var ySe=1e3;if(ki&&Fi?.addPorts){DT(ki);for(let e=0,t=Fi.addPorts.length;e<t;e++){let r=Fi.addPorts[e];r.threadId=Fi.addThreadIds[e],DT(r)}setInterval(()=>{let e=process.memoryUsage();ki.postMessage({type:Nz,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},ySe).unref(),DC=a(()=>new Promise((e,t)=>{ki.on("message",r),ki.postMessage({type:Oz});function r(n){n.type===wz&&(ki.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else DC=xz;oi.exports.getThreadInfo=DC;function DT(e,t){Cs.push(e),e.on("message",r=>{if(r.type===Iz)r.port.threadId=r.threadId,DT(r.port);else if(r.type===aSe){let n=PT.get(r.id);n&&n()}else Bz(r,e)}).on("close",()=>{Cs.splice(Cs.indexOf(e),1)}).on("exit",()=>{Cs.splice(Cs.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(DT,"addPort");function Bz(e,t){for(let n of vz)n(e,t);let r=MC.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){ii.error(s)}}a(Bz,"notifyMessageListeners");if(UC){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await rSe(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Rz(s,o.name));try{for await(let{filename:o}of tSe(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await HC(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");oi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else ki.on("message",async e=>{let{type:t}=e;t===Md.ITC_EVENT_TYPES.SHUTDOWN&&(oi.exports.restartNumber=e.restartNumber,ki.unref(),setTimeout(()=>{ii.warn("Thread did not voluntarily terminate",Jge),process.exit(0)},xC).unref())})});var Ex={};Ue(Ex,{ACTION_32_BIT:()=>Ap,ACTION_64_BIT:()=>NSe,AUDIT_STORE_OPTIONS:()=>uh,Decoder:()=>Xc,HAS_BLOBS:()=>pn,HAS_CURRENT_RESIDENCY_ID:()=>Tc,HAS_EXPIRATION_EXTENDED_TYPE:()=>Df,HAS_ORIGINATING_OPERATION:()=>Pf,HAS_PREVIOUS_RESIDENCY_ID:()=>Ac,REMOTE_SEQUENCE_UPDATE:()=>ig,createAuditEntry:()=>ru,getLastRemoved:()=>vO,openAuditStore:()=>vT,readAuditEntry:()=>Nt,removeAuditEntry:()=>UT,setAuditRetention:()=>OSe,transactionKeyEncoder:()=>Yz});function vT(e){let t=e.auditStore=e.openDB(kC.AUDIT_STORE_NAME,{create:!1,...uh});t||(t=e.auditStore=e.openDB(kC.AUDIT_STORE_NAME,uh),kz(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,f){return r[l]=f,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,o=GC;zh(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(o=l),clearTimeout(n);let u=new Promise(f=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let d=0,_,h;try{for(let{key:m,value:S}of t.getRange({start:1,snapshot:!1,end:Date.now()-FC/(1+i*i)})){try{_=UT(t,m,S)}catch(g){vd.warn("Error removing audit entry",g)}if(h=m,await new Promise(setImmediate),++d>=bSe){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,FC/10):(kz(t,h),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,om.getWorkerIndex)()===(0,om.getWorkerCount)()-1&&c(),(0,om.getWorkerIndex)()===0&&!Hz)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(Hz=!0,vd.error("The current time is before the last recorded entry in the audit log. Time reversal can undermine the integrity of data tracking and certificate validation and the time must be corrected."));return t}function UT(e,t,r){let n=wSe(r),s;if(n&pn){s=Nt(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&hc(()=>ta(s.getValue(i)),i.rootStore)}if((n&15)===qC){s=s||Nt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId).version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function kz(e,t){$C[0]=t,e.put(Symbol.for("last-removed"),Wz)}function vO(e){let t=e.get(Symbol.for("last-removed"));if(t)return Wz.set(t),$C[0]}function OSe(e,t=GC){FC=e,GC=t}function ru(e,t,r,n,s,i,o,c,l,u,f,d,_){let h=zz[o];if(!h)throw new Error(`Invalid audit entry type ${o}`);let m=1;if(n&&(n>1?za.setFloat64(0,n):Ps.set(hR),m=9),l){if(l&255)throw new Error("Illegal extended type");m+=3}R(s),R(t),g(r),za.setFloat64(m,e),m+=8,l&Tc&&R(u),l&Ac&&R(f),l&Df&&(za.setFloat64(m,d),m+=8),l&Pf&&R(jz[_]),i?g(i):Ps[m++]=0,l?za.setUint32(n?8:0,h|l|3221225472):Ps[n?8:0]=h;let S=Ps.subarray(0,m);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=m;m+=1,m=(0,Cl.writeKey)(E,Ps,m);let w=m-T-1;w>127?w>16383?(vd.error("Key or username was too large for audit entry",E),m=T+1,Ps[T]=0):(Ps.copyWithin(T+2,T+1,m),za.setUint16(T,w|32768),m++):Ps[T]=w}function R(E){E<128?Ps[m++]=E:E<16384?(za.setUint16(m,E|32768),m+=2):E<1056964608?(za.setUint32(m,E|3221225472),m+=4):(Ps[m]=255,za.setUint32(m+1,E),m+=5)}}function wSe(e){let t=0;e[0]==66&&(t=8);let r=e[t];if(r<128)return r;let n=e.dataView||(e.dataView=new Xc(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Xc(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),o=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,f=n.position+=l,d=n.readFloat64(),_,h,m,S;if(i&Tc&&(_=n.readInt()),i&Ac&&(h=n.readInt()),i&Df&&(m=n.readFloat64()),i&Pf){let T=n.readInt();S=jz[T]}l=n.readInt();let g=n.position,R=n.position+=l,E;return{type:zz[i&7],tableId:c,nodeId:o,get recordId(){return(0,Cl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return R>g?(0,Cl.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&LT||i&im&&!w)return E||(E=hc(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&im&&v)return nb(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(LT|im)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:h,expiresAt:m,originatingOperation:S}}catch(n){return vd.error("Reading audit entry error",n,e),{}}}var Cl,MT,kC,om,Kz,vd,Ps,za,Yz,uh,FC,bSe,$C,Wz,GC,Hz,LT,im,Fz,qC,Gz,qz,$z,Vz,Ap,NSe,ig,Tc,Ac,Pf,Df,pn,zz,jz,Xc,to=be(()=>{Cl=require("ordered-binary"),MT=M(le()),kC=M(vt());k();om=M(rt()),Kz=M(ae());nu();vd=M(j());iE();us();nT();(0,MT.initSync)();Ps=Buffer.alloc(2816),za=new DataView(Ps.buffer,Ps.byteOffset,2816),Yz={writeKey(e,t,r){return e===Cf?(t.set(Cf,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Cl.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Cl.readKey)(e,t,r)}},uh={encoding:"binary",keyEncoder:Yz},FC=(0,Kz.convertToMS)((0,MT.get)(U.LOGGING_AUDITRETENTION))||86400*3,bSe=1e3,$C=new Float64Array(1),Wz=new Uint8Array($C.buffer),GC=1e4,Hz=!1;a(vT,"openAuditStore");a(UT,"removeAuditEntry");a(kz,"updateLastRemoved");a(vO,"getLastRemoved");a(OSe,"setAuditRetention");LT=16,im=32,Fz=1,qC=2,Gz=3,qz=4,$z=5,Vz=6,Ap=14,NSe=15,ig=11,Tc=512,Ac=1024,Pf=2048,Df=4096,pn=8192,zz={put:Fz|LT,[Fz]:"put",delete:qC,[qC]:"delete",message:Gz|LT,[Gz]:"message",invalidate:qz|im,[qz]:"invalidate",patch:$z|im,[$z]:"patch",relocate:Vz,[Vz]:"relocate"},jz={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(ru,"createAuditEntry");a(wSe,"readAction");a(Nt,"readAuditEntry");Xc=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t;return t=this.getUint8(this.position++),t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch(t){throw t.message=`Error reading float64: ${t.message} at position ${this.position}`,t}}}});function YC(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=Jz,ISe(e.primaryStore,e.auditStore)):(c=Qz,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{Xz(Qz[i])})));let l=c[i]||(c[i]=[]);if(l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now()),s?.scope==="full-database")return;let u=l[o];u||(u=l[o]=new Map,u.envs=l,u.tableId=o,u.store=e.primaryStore),t=Ql(t);let f=new KC(r);f.startTime=n;let d=u.get(t);return d?d.push(f):(u.set(t,d=[f]),d.tables=u,d.key=t),f.subscriptions=d,f}function Xz(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),Zz(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Nt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Ql(c),u=0;do{let f=o.get(l);if(f){for(let _ of f)if(!(u>0&&!(_.includeDescendants&&!(_.onlyChildren&&u>1)))){if(_.startTime>=n){(0,VC.info)("omitting",c,_.startTime,n);continue}try{let h;_.supportsTransactions&&_.txnInProgress!==i.version&&(h=!0,_.txnInProgress||(r?r.push(_):r=[_]),_.txnInProgress=i.version),_.listener(c,i,n,h)}catch(h){console.error(h),(0,VC.info)(h)}}}if(l==null)break;let d=l.lastIndexOf?.("/",l.length-2);d!==l.length-1&&u++,d>-1?l=l.slice(0,d+1):l=null}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function ISe(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let l=Jz[s];if(!l)return;let u=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{Xz(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function Zz(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function qk(e){return e.nextTransaction||(YC({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),Zz(e)),e.nextTransaction}var VC,Qz,Jz,KC,UO=be(()=>{VC=M(j());Kl();Jl();to();Qz=Object.create(null),Jz=Object.create(null);a(YC,"addSubscription");KC=class extends Un{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables;if(t){let r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(Xz,"notifyFromTransactionData");a(ISe,"listenToCommits");a(Zz,"nextTransaction");a(qk,"whenNextTransaction")});var Kw={};Ue(Kw,{EVICTED:()=>Xo,INVALIDATED:()=>_n,coerceType:()=>HT,makeTable:()=>FT,setServerUtilities:()=>xSe});function FT(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:f,sealed:d,splitSegments:_,replicate:h}=e,{expirationMS:m,evictionMS:S,audit:g,trackDeletes:R}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=ER(i,n,l),w,v,H={},q=Promise.resolve(),W,te,se;for(let K of E)(K.assignCreatedTime||K.name==="__createdtime__")&&(W=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(te=K),K.expiresAt&&(se=K),K.isPrimaryKey&&(H=K);let Y,ne=[],ue=[],oe=1,pe=2,Te={},ye={},jt=864e5,lt=0,Rr,is,Dn,vl=!1,Ul,jT=new Map,QT=new Map,Lt,kd,pm=Dl.get(U.REPLICATION_DATABASES);if(Array.isArray(pm)){for(let K of pm)if(K.name===c&&K.replicateTo>=0){kd=K.replicateTo;break}}let Em=i.getRange({start:!1,end:!1}).constructor,Fd=10,gm=6;g&&Vd(),zh(i.env.path,K=>{if(v)return $i(K)});class Ce extends Vr{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=E;static replicate=h;static sealed=d;static splitSegments=_??!0;static createdTimeProperty=W;static updatedTimeProperty=te;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return m}static dbisDB=f;static schemaDefined=u;static sourcedFrom(p,O){if(O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource)p.intermediateSource=!0,this.sources.unshift(p);else{if(this.sources.some(I=>!I.intermediateSource)){if(this.sources.some(I=>I.name===p.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(p)}v=v||p.get&&(!p.get.reliesOnPrototype||p.prototype.get),w=w||p.load;let A=a(I=>{let L=this.sources;if(L=L.filter(B=>B.intermediateSource&&B[I]&&(!B[I].reliesOnPrototype||B.prototype[I])),L.length>0)if(L.length===1){let B=L[0];return(N,x,G)=>{if(N?.source!==B)return B[I](x,G,N)}}else return(B,N,x)=>{let G=[];for(let z of L){if(B?.source===z)break;G.push(z[I](N,x,B))}return Promise.all(G)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1];y.intermediateSource&&(y={});let b=a(I=>{if(y[I]&&(!y[I].reliesOnPrototype||y.prototype[I]))return(L,B,N)=>{if(!L?.source)return y[I](B,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,B=a(async(N,x)=>{let G=N.value,z=N.table?Ve[c][N.table]:Ce;if(c===Wd&&(N.table===Fl.ROLE_TABLE_NAME||N.table===Fl.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[z.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=p;let ie={residencyId:Za(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await z.getResource(N.id,x,ie);switch(N.finished&&await N.finished,N.type){case"put":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!0,ie);case"patch":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!1,ie);case"delete":return F._writeDelete(ie);case"publish":case"message":return F._writePublish(G,ie);case"invalidate":return F._writeInvalidate(G,ie);case"relocate":return F._writeRelocate(ie);default:xe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=p.subscribe;N&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Pl.getWorkerIndex)(),x):(0,Pl.getWorkerIndex)()===0,z=N&&G&&await p.subscribe?.(x);if(z){let ie;for await(let F of z)try{if(!(F.type==="transaction"?F.writes[0]:F)){xe.default.error?.("Bad subscription event",F);continue}if(F.source=p,F.type==="end_txn"){if(ie?.resolve(),F.localTime&&L!==F.localTime){if(F.remoteNodeIds?.length>0){let ce=[Symbol.for("seq"),F.remoteNodeIds[0]],ee=f.get(ce),Q=ee?.nodes;Q||(Q=[]);for(let fe of F.remoteNodeIds.slice(1)){let Ae=Q.find(De=>De.id===fe);Q=Q.filter(De=>De.id!==fe||De===Ae),Ae||(Ae={id:fe,seqId:0},Q.push(Ae)),Ae.seqId=Math.max(ee?.seqId??1,F.localTime),fe===ie?.nodeId&&(Ae.lastTxnTime=F.timestamp)}let _e=Math.max(ee?.seqId??1,F.localTime);xe.default.trace?.("Received txn",c,new Date(_e),new Date(F.localTime),F.remoteNodeIds),f.put(ce,{seqId:_e,nodes:Q})}L=F.localTime}F.onCommit&&ie?.committed.then(F.onCommit);continue}if(ie)if(F.beginTxn)ie.resolve();else{ie.write_promises.push(B(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=Ot(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(B(ee,F))}catch(Q){throw Q.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(F),Q}return Promise.all(ce)}else if(F.type==="define_schema"){let ce=this.attributes.slice(0),ee;for(let Q of F.attributes)ce.find(_e=>_e.name===Q.name)||(ce.push(Q),ee=!0);ee&&(dt({table:s,database:c,attributes:ce,origin:"cluster"}),cm.signalSchemaChange(new lm.SchemaEventMsg(process.pid,Gt.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[B(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):B(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>cm.signalUserChange(new lm.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(qe){xe.default.error?.("error in subscription handler",qe)}}}catch(N){xe.default.error?.(N)}})(),this}static get isCaching(){return v}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(p,O,A){let y=super.getResource(p,O,A);if(p!=null){wr(p);try{if(y.getRecord?.())return y;if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let b=!A?.async||i.cache?.get?.(p),C=Gr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return xl(p,O,{transaction:I,ensureLoaded:A?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Nr.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let B=Bl(p,L,O,y);if(B)return C?.disregardReadTxn(),y.#i=!0,zC(B,N=>(Ce._updateResource(y,N),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(p)),b}}return y}static _updateResource(p,O){p.#r=O,p.#e=O?.value??null,p.#n=O?.version}ensureLoaded(){let p=Bl(this.getId(),this.#r,this.getContext());if(p)return this.#i=!0,zC(p,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let p=H?.type;if(p==="String"||p==="ID")return super.getNewId();if(!Lt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!HSe(i)||C.pid===process.pid)){let L=C.start,B=C.end;I=L;for(let N of i.getKeys({start:B,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;Lt=new BigInt64Array([BigInt(I)+1n]),Lt=new BigInt64Array(i.getUserSharedBuffer("id",Lt.buffer)),Lt.maxSafeId=C.end}let O=Number(Atomics.add(Lt,0,1n)),A=p==="Int"?512:1048576;if(O+A>=Lt.maxSafeId){let b=a(C=>{Lt.maxSafeId=O+(p==="Int"?1023:4194303);let I=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=C?void 0:i.useReadTransaction(),B=Number(Lt[0]);for(let G of i.getKeys({start:B+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Lt.maxSafeId<I){if(N.end>Lt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,Lt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:Lt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Lt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(Lt,0,BigInt(G.start+1)),Lt.maxSafeId=G.end}},"updateEnd");O+A===Lt.maxSafeId?setImmediate(b):O+100>=Lt.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${p=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return O;function y(b){let C=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,I=C/4,L,B,N=!1,x,G;do{x=Math.floor(Math.random()*C),G={start:x,end:x+(p==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let z of i.getKeys({start:x,limit:1,reverse:!0}))L=z;B=C;for(let z of i.getKeys({start:x+1,end:C,limit:1}))B=z;I*=.875,I<1e3&&!N&&(N=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${p==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,B,I))}while(!(I<B-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let z=i.getEntry(Symbol.for("id_allocation"));return(z?.version??null)==b?(xe.default.info?.("Allocated new id range",G),i.put(Symbol.for("id_allocation"),G,Date.now()),G):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...z.value})})}}static setTTLExpiration(p){if(typeof p=="number")m=p*1e3,S||(S=0);else if(p&&typeof p=="object")m=p.expiration*1e3,S=(p.eviction||0)*1e3,jt=p.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(m<0)throw new Error("Expiration can not be negative");jt=jt||(m+S)/4,$i()}static getResidencyRecord(p){return f.get([Symbol.for("residency_by_id"),p])}static setResidency(p){Ce.getResidency=p&&((O,A)=>{try{return p(O,A)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(p){Ce.getResidencyById=p&&(O=>{try{return p(O)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(p,O){if(Ce.getResidencyById)return Ce.getResidencyById(p[t]);let A=kd;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(A=O.replicateTo)}if(A>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,A));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+A));let I=C+A-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(p=!0){g=p,p&&Vd(),Ce.audit=p}static coerceId(p){return p===""?null:HT(p,H)}static async dropTable(){delete Ve[c][s];for(let p of i.getRange({versions:!0,snapshot:!1,lazy:!0}))p.metadataFlags&pn&&p.value&&ta(p.value);if(c===o){for(let p of E)f.remove(Ce.tableName+"/"+p.name),r[p.name]?.drop();f.remove(Ce.tableName+"/"),i.drop(),await f.committed}else console.log("legacy dropTable"),await i.close(),await BT.default.remove(data_path),await BT.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));cm.signalSchemaChange(new lm.SchemaEventMsg(process.pid,Gt.DROP_TABLE,c,s))}get(p){if(typeof p=="string")return this.getProperty(p);if(this.isCollection)return this.search(p);if(this.getId()===null){if(p?.conditions||p?.size>0)return this.search(p);let O={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:E};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(A=>(O.recordCount=A.recordCount,O.estimatedRecordRange=A.estimatedRange,O)):O}if(p?.property)return this.getProperty(p.property);if(this.doesExist()||p?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(p,O){let A=Fr(p);if(A?.read){if(A.isSuperUser)return!0;let y=A.attribute_permissions,b=O?.select;if(y?.length>0||vl&&b){if(O||(O={}),b){let C=y?.length>0&&WC(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let B=Dn[L]?.definition?.tableClass;if(B){if(I.name||(I={name:I}),!B.prototype.allowRead.call(null,p,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else O.select=y.filter(C=>C.read&&!Dn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(p,O){let A=Fr(p);if(A?.update){let y=A.attribute_permissions;if(y?.length>0){let b=WC(y,"update");for(let C in O)if(!b[C])return!1;for(let C of y){let I=C.attribute_name;!C.update&&!(I in O)&&(O[I]=this.getProperty(I))}}return kl(this.getContext())}}allowCreate(p,O){if(this.isCollection){let A=Fr(p);if(A?.insert){let y=A.attribute_permissions;if(y?.length>0){let b=WC(y,"insert");for(let C in O)if(!b[C])return!1;return kl(this.getContext())}else return kl(this.getContext())}}else return this.allowUpdate(p,{})}allowDelete(p){return Fr(p)?.delete&&kl(this.getContext())}update(p,O){if(!Gr(this.getContext()))throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let y;return typeof p=="object"&&p&&(O?(Object.isFrozen(p)&&(p={...p}),this.#e={},this.#t=p):(y=this.#t,y&&(p=Object.assign(y,p)),this.#t=p)),this._writeUpdate(this.#t,O),this}addTo(p,O){if(typeof O=="number"||typeof O=="bigint")this.#s===tj?this.set(p,(+this.getProperty(p)||0)+O):(this.#s||this.update(),this.set(p,new cE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(p,O){if(typeof O=="number")return this.addTo(p,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(p){this.#t=p}setRecord(p){this.#e=p}invalidate(){this._writeInvalidate()}_writeInvalidate(p,O){let A=this.getContext(),y=this.getId();wr(y),Gr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,A,y),beforeIntermediate:ye.invalidate?.bind(this,A,y),commit:a((C,I)=>{if(!(qi(C,I,O?.nodeId)<=0)){p??=null;for(let L in r)p||(p={}),p[L]===void 0&&(p[L]=this.getProperty(L));xe.default.trace?.(`Invalidating entry id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,p,this.#r,C,_n,g,{user:A?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(p){let O=this.getContext(),A=this.getId();wr(A),Gr(this.getContext()).addWrite({key:A,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,A),beforeIntermediate:ye.relocate?.bind(this,O,A),commit:a((b,C)=>{if(qi(b,C,p?.nodeId)<=0)return;let I=Ce.getResidencyRecord(p.residencyId),L=0,B=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)B||(B={}),B[x]=N(x);L=_n}else B=N;xe.default.trace?.(`Relocating entry id: ${A}, timestamp: ${new Date(b).toISOString()}`),T(A,B,this.#r,b,L,g,{user:O.user,residencyId:p.residencyId,nodeId:p.nodeId,expiresAt:p.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(p,O){let A={previousResidency:this.getResidencyRecord(p.residencyId),isRelocation:!0},y=Vi(this.getResidency(O.value,A)),b;if(y){if(!y.includes(server.hostname))return!1;b=Za(y)}let I=T(p.key,O.value,p,p.version,0,!0,{residencyId:b,expiresAt:O.expiresAt},"relocate",!1,null);return!0}static evict(p,O,A){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(p),!b||!O)||b.version!==A))){if(v){if(i.hasLock(p,b.version))return;let C;for(let I in r)C||(C={}),C[I]=O[I];if(C)return T(p,C,b,A,Xo,null,null,null,!0)}if(i.ifVersion(p,A,()=>{on(p,O,null)}),g)return T(p,null,b,A,Xo,null,null,null,!0);Sc(i,b??i.getEntry(p),A)}}lock(){throw new Error("Not yet implemented")}static operation(p,O){return p.table||=s,p.schema||=c,lj.operation(p,O)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,O,A){let y=this.getContext(),b=Gr(y),C=this.getId();wr(C);let I=this.#r;this.#s=O?tj:MSe;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(B=>{p||(p=this.#t),O||p&&oE(this.#t===p?this:p)?y?.source||(b.checkOverloaded(),this.validate(p,!O),te&&(p[te.name]=te.type==="Date"?new Date(B):te.type==="String"?new Date(B).toISOString():B),O&&(t&&p[t]!==C&&(p[t]=C),W&&(I?.value?p[W.name]=I?.value[W.name]:p[W.name]=W.type==="Date"?new Date(B):W.type==="String"?new Date(B).toISOString():B),p=xc(p))):b.removeWrite(L)},"validate"),before:O?Te.put?()=>Te.put(y,C,p):null:Te.patch?()=>Te.patch(y,C,p):Te.put?()=>Te.put(y,C,xc(this)):null,beforeIntermediate:O?ye.put?()=>ye.put(y,C,p):null:ye.patch?()=>ye.patch(y,C,p):ye.put?()=>ye.put(y,C,xc(this)):null,commit:a((B,N,x)=>{if(x){if(y&&N?.version>(y.lastModified||0)&&(y.lastModified=N.version),this.#r=N,N?.value&&N.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");O||(this.#e=N?.value??null)}this.#t=void 0,this.#n=B;let G=N?.value,z=p;this.#s=0;let ie=!1,F=qi(B,N,A?.nodeId),qe;if(F<=0)if(g){let _e=N.localTime,fe=N.version;xe.default.trace?.("Applying CRDT update to record with id: ",C,"applying later update:",fe);let Ae=[];for(;_e>B||fe>=B&&_e>0;){let De=l.get(_e);if(!De)break;let we=Nt(De);if(fe=we.version,fe>=B){if(fe===B){if(F=qi(B,{version:fe,localTime:_e},A?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),qe=p;else if(we.type==="put"||we.type==="delete")return}_e=we.previousLocalTime}Ae.sort((De,we)=>De.version-we.version);for(let De of Ae){let we=De.getValue(i);if(z=sE(z,we,O),xe.default.debug?.("Rebuilding update with future patch:",z),!z)return}}else{if(O)return;z=sE(z,G,O),xe.default.debug?.("Rebuilding update without audit:",z)}let Z;if(O?Z=z:(this.#e=G,Z=xc(this,z)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(A?.residencyId!=null)ce=A.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=Vi(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(qe??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=qe[fe]}ce=Za(_e)}O||(qe=p);let ee=y?.expiresAt??(m?m+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(B).toISOString()}${ee?", expires at: "+new Date(ee).toISOString():""}${N?", replaces entry from: "+new Date(N.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(Z).slice(0,100)}catch{return""}})()),on(C,G,Z);let Q=O?"put":"patch";T(C,Z,N,B,ie?_n:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:A?.nodeId,originatingOperation:y?.originatingOperation},Q,!1,qe),y.expiresAt&&$i()},"commit")};b.addWrite(L)}async delete(p){if(typeof p=="string")return this.deleteProperty(p);if(this.isCollection){for await(let O of this.search(p))(await Ce.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(p);return}return this.#e?this._writeDelete(p):!1}_writeDelete(p){let O=Gr(this.getContext()),A=this.getId();wr(A);let y=this.getContext();return O.addWrite({key:A,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,A),beforeIntermediate:ye.delete?.bind(this,y,A),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!(qi(b,C,p?.nodeId)<=0)&&(on(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${A}, txn timestamp: ${new Date(b).toISOString()}`),g||R?(T(A,null,this.#r,b,0,g,{user:y?.user,nodeId:p?.nodeId},"delete"),g||$i()):Sc(i,C))},"commit")}),!0}search(p){let O=this.getContext(),A=Gr(O);if(!p)throw new Error("No query provided");let y=p.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this.getId()&&(y=[{attribute:null,comparator:Array.isArray(this.getId())?"prefix":"starts_with",value:this.getId()}].concat(y));let b,C={};function I(Q,_e){let fe;switch(_e){case"and":case void 0:if(Q.length<1)throw new Error('An "and" operator requires at least one condition');fe=!0;break;case"or":if(Q.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+_e)}for(let Ae of Q){if(Ae.conditions){Ae.conditions=I(Ae.conditions,Ae.operator);continue}let De=Ae[0]??Ae.attribute,we=De==null?H:fi(E,De);if(we)(we.type||UA[Ae.comparator])&&(Ae[1]===void 0?Ae.value=B(Ae.value,we):Ae[1]=B(Ae[1],we));else if(De!=null)throw(0,Nr.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let _r=Ae.chainedConditions[0],Ir,Ls;if(_r.comparator==="gt"||_r.comparator==="greater_than"||_r.comparator==="ge"||_r.comparator==="greater_than_equal"?(Ir=Ae,Ls=_r):(Ir=_r,Ls=Ae),Ir.comparator!=="lt"&&Ir.comparator!=="less_than"&&Ir.comparator!=="le"&&Ir.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ls.comparator==="ge"||Ls.comparator==="greater_than_equal",Rt=Ir.comparator==="le"||Ir.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(Rt?"le":"lt"),Ae.value=[Ls.value,Ir.value]}else throw new Error("Multiple chained conditions are not currently supported")}return Q}a(I,"prepareConditions");function L(Q,_e){if(p.enforceExecutionOrder)return Q;for(let fe of Q)fe.conditions&&(fe.conditions=L(fe.conditions,fe.operator));return Q.length>1&&_e!=="or"?(0,aj.sortBy)(Q,Qm(Ce)):Q}a(L,"orderConditions");function B(Q,_e){return Array.isArray(Q)?Q.map(fe=>HT(fe,_e)):HT(Q,_e)}a(B,"coerceTypedValues");let N=p.operator;(y.length>0||N)&&(y=I(y,N));let x=typeof p.sort=="object"&&p.sort,G;if(x&&N!=="or"){let Q=x.attribute;if(Q==null)throw new Nr.ClientError("Sort requires an attribute");if(b=y.find(_e=>jl(_e.attribute)===jl(Q)),!b){let _e=fi(E,Q);if(!_e)throw(0,Nr.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not a defined attribute`,404);if(_e.indexed)b={attribute:Q,comparator:"sort"},y.push(b);else if(y.length===0&&!p.allowFullScan)throw(0,Nr.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!x.descending)}y=L(y,N),x&&(b&&y[0]===b?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(b&&y.splice(y.indexOf(b),1),G=x));let z=p.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!z};let ie=A.useReadTxn(),F=xA(y,N,Ce,ie,p,O,(Q,_e)=>qd(Q,z,O,ie,_e),C),qe=p.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(z,O,ie,C,qe,!0),ce=Ce.transformToOrderedSelect(F,z,G,ie,O,Z);function ee(Q){return p.offset||p.limit!==void 0?Q.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0):Q}return a(ee,"applyOffset"),G&&(ce=ee(ce)),ce.onDone=()=>{ce.onDone=null,A.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(z){let Q=[];for(let _e of z)_e==="*"?Q.push(...E.map(fe=>fe.name)):Q.push(_e.name||_e);return Q}return E.filter(Q=>!Q.computed&&!Q.relationship).map(Q=>Q.name)},ce}static transformToOrderedSelect(p,O,A,y,b,C){let I=new Em;if(A){p=qd(p,O,y,b,null);let L;I.iterate=function(){let N,x=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),G,z=A.dbOrderedAttribute,ie,F,qe=!0;function Z(ee){let Q=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=Hl(fe,ee.attribute,y),we=Hl(Ae,ee.attribute,y),_r=_e?(0,Ll.compareKeys)(we,De):(0,Ll.compareKeys)(De,we);return _r===0?Q?.(fe,Ae)||0:_r}}a(Z,"createComparator");let ce=Z(A);return{async next(){let ee;if(N)if(ee=N.next(),ee.done){if(G)return I.onDone&&I.onDone(),ee}else return{value:await C.call(this,ee.value)};L=[],ie&&L.push(ie);do if(ee=await x.next(),ee.done){if(G=!0,L.length)break;return I.onDone&&I.onDone(),ee}else{let Q=ee.value;if(Q?.then&&(Q=await Q),z){let _e=Hl(Q,z,y);if(qe)qe=!1,F=_e;else if(_e!==F){F=_e,ie=Q;break}}L.push(Q)}while(!0);return A.isGrouped,L.sort(ce),N=L[Symbol.iterator](),ee=N.next(),ee.done?(I.onDone&&I.onDone(),ee):{value:await C.call(this,ee.value)}},return(){I.onDone&&I.onDone(),x.return()},throw(){I.onDone&&I.onDone(),x.throw()}}};let B=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],z;if(G.name===N.attribute[0]){for(z=G.sort||(G.sort={});z.next;)z=z.next;z.attribute=N.attribute.slice(1),z.descending=N.descending}else G===N.attribute[0]&&(O[x]=z={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&B(N.next)},"applySortingOnSelect");B(A)}else I.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),I=I.map(function(L){try{let B=C.call(this,L);return typeof B?.catch=="function"?B.catch(N=>{throw N.partialObject={[t]:L.key},N}):B}catch(B){throw B.partialObject={[t]:L.key},B}});return I}static transformEntryForSelect(p,O,A,y,b,C){if(p&&(p===t||p?.length===1&&p[0]===t&&Array.isArray(p))){let N=a(x=>(O?.transaction?.stale&&(O.transaction.stale=!1),x?.key??x),"transform");return p===t?N:p.asArray?x=>[N(x)]:x=>({[t]:N(x)})}let I;b&&v&&!(typeof p=="string"?[p]:p)?.every(N=>{let x;return typeof N=="object"?x=N.name:x=N,r[x]||x===t})&&(I=!0);let L,B=a(function(N){let x;if(O?.transaction?.stale&&(O.transaction.stale=!1),N!=null){if(x=N.value||N.deref?.()?.value,!x&&(N.key===void 0||N.deref)||N.metadataFlags&_n){if(N.metadataFlags&_n&&O.replicateFrom===!1&&C&&N.residencyId)return Qa.SKIP;if(N=xl(N.key??N,O,{transaction:A,lazy:p?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(B.bind(this));x=N?.value}if(I&&N?.metadataFlags&(_n|Xo)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=Bl(N.key??N,N,O);if(G?.then)return G.then(B)}}if(x==null)return C?Qa.SKIP:x;if(p&&!(p[0]==="*"&&p.length===1)){let G,z=a((F,qe)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Dn?.[Z],ee;if(ce){let Q=y?.[Z];if(Q)if(Q.hasMappings){let fe=ce.from?x[ce.from]:jl(N.key);ee=Q.get(fe),ee||(ee=[])}else ee=Q.fromRecord?.(x);else ee=ce(x,O,N);let _e=a(fe=>{if(fe&&typeof fe=="object"){let Ae=ce.definition?.tableClass||Ce;L||(L={});let De=L[Z]||(L[Z]=Ae.transformEntryForSelect(Z===F?null:F.select||(Array.isArray(F)?F:null),O,A,Q,b));if(Array.isArray(fe)){let we=[],_r=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,A,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ir=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Ir);we.push(Re.value),Re=_r.next()}qe(we,Z)},"nextValue"),Ls=Ir(_r.next());Ls&&(G||(G=[]),G.push(Ls));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>qe(we,Z)));return}}qe(fe,Z)},"handleResolvedValue");ee?.then?(G||(G=[]),G.push(ee.then(_e))):_e(ee);return}else ee=x[Z],ee&&typeof ee=="object"&&Z!==F&&(ee=Ce.transformEntryForSelect(F.select||F,O,A,null)({value:ee}));qe(ee,Z)},"selectAttribute"),ie;if(typeof p=="string")z(p,F=>{ie=F});else if(Array.isArray(p))if(p.asArray)ie=[],p.forEach((F,qe)=>{F==="*"?p[qe]=x:z(F,Z=>ie[qe]=Z)});else{ie={};let F=p.forceNulls;for(let qe of p)if(qe==="*")for(let Z in x)ie[Z]=x[Z];else z(qe,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new Nr.ClientError("Invalid select"+p);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return B}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||dt({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),p||(p={});let O=!p.rawEvents,A=[],y=this,b=YC(Ce,this.getId()??null,function(I,L,B,N){try{let x=L.getValue?.(i,O),G=L.type;if(!x&&G==="patch"&&O){let ie=i.getEntry(I);ie?.version===L.version?x=ie.value:x=L.getValue?.(i,!0,B),G="put"}let z={id:I,localTime:B,value:x,version:L.version,type:G,beginTxn:N};A?A.push(z):this.send(z)}catch(x){xe.default.error?.(x)}},p.startTime||0,p),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,p.onlyChildren&&(b.onlyChildren=!0)),p.supportsTransactions&&(b.supportsTransactions=!0);let I=this.getId(),L=p.previousCount;L>1e3&&(L=1e3);let B=p.startTime;if(this.isCollection){if(B){if(L)throw new Nr.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:B,exclusiveStart:!0,snapshot:!1})){let G=Nt(x);if(G.tableId!==n)continue;let z=G.recordId;if(I==null||ij(I,z)){let ie=G.getValue(i,O,N);if(b.send({id:z,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>nj&&await b.waitForDrain()===!1)return}b.startTime=N}}else if(L){let N=[];for(let{key:x,value:G}of l.getRange({start:"z",end:!1,reverse:!0}))try{let z=Nt(G);if(z.tableId!==n)continue;let ie=z.recordId;if(I==null||ij(I,ie)){let F=z.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:z.version,type:z.type}),--L<=0)break}}catch(z){xe.default.error("Error getting history entry",x,z)}for(let x=N.length;x>0;)b.send(N[--x]);N[0]&&(b.startTime=N[0].localTime)}else if(!p.omitCurrent){for(let{key:N,value:x,version:G,localTime:z}of i.getRange({start:I??!1,end:I==null?void 0:[I,Ll.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:z,value:x,version:G,type:"put"}),b.queue?.length>nj&&await b.waitForDrain()===!1))return}}else{L&&!B&&(B=0);let N=this.#r?.localTime;if(N===pR&&(i.cache?.delete(I),this.#r=i.getEntry(I),xe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),xe.default.trace?.("Subscription from",B,"from",I,N),B<N){let x=[],G=N;do{let z=l.get(G);if(z){p.omitCurrent=!0;let ie=Nt(z),F=ie.getValue(i,O,G);O&&(ie.type="put"),x.push({id:I,value:F,localTime:G,...ie}),G=ie.previousLocalTime}else break;L&&L--}while(G>B&&L!==0);for(let z=x.length;z>0;)b.send(x[--z]);b.startTime=N}!p.omitCurrent&&this.doesExist()&&b.send({id:I,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of A)b.send(N);A=null})();return p.listener&&b.on("data",p.listener),b}static subscribeOnThisThread(p,O){return p===0||O?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(p,O){this._writePublish(p,O)}_writePublish(p,O){let A=Gr(this.getContext()),y=this.getId()||null;y!=null&&wr(y);let b=this.getContext();A.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(A.checkOverloaded(),this.validate(p))},"validate"),before:Te.publish?.bind(this,b,y,p),beforeIntermediate:ye.publish?.bind(this,b,y,p),commit:a((C,I,L)=>{I===void 0&&R&&!g&&$i(),xe.default.trace?.(`Publishing message to id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,I?.value??null,I,I?.version||C,0,!0,{user:b?.user,residencyId:O?.residencyId,expiresAt:b?.expiresAt,nodeId:O?.nodeId},"message",!1,p)},"commit")})}validate(p,O){let A,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let B=0,N=L.length;B<N;B++){let x=L[B],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let B in b)L.find(N=>N.name===B)||(A||(A=[])).push(`Property ${B} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof hi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,B=b.length;L<B;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=E.length;b<C;b++){let I=E[b];if(!(I.relationship||I.computed)&&(!O||I.name in p)){let L=y(p[I.name],I,I.name);L&&(p[I.name]=L)}}if(d)for(let b in p)E.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new Nr.ClientError(A.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(p){let O=E.slice(0);for(let A of p){if(!A.name)throw new Nr.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new Nr.ClientError("Attribute names cannot include backticks or forward slashes");(0,cj.validateAttribute)(A.name),O.push(A)}return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(p){let O=E.filter(A=>!p.includes(A.name));return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static getSize(){let p=i.getStats();return(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getAuditSize(){let p=l?.getStats();return p&&(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getStorageStats(){let p=i.env.path,O=BT.default.statfsSync?.(p)??{};return{available:O.bavail*O.bsize,free:O.bfree*O.bsize,size:O.blocks*O.bsize}}static async getRecordCount(p){let O=i.getStats().entryCount,A=1e3/2,y=performance.now(),b=Math.floor(O/2),C=p?.exactCount,I=0,L=0,B;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await ja(),!C&&L<b&&performance.now()-y>A){B=L;break}if(B){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:B,snapshot:!1}))ee!=null&&I++,await ja();let x=B*2,G=(I+N)/x,z=Math.pow((I-N+1)/B/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(z)*O,1),F=Math.round(G*O),qe=Math.max(F-1.96*ie,I+N),Z=Math.min(F+1.96*ie,O),ce=Math.pow(10,Math.round(Math.log10(ie)));return ce>F&&(ce=ce/10),I=Math.round(F/ce)*ce,{recordCount:I,estimatedRange:[Math.round(qe),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Dn=this.propertyResolvers={$id:a((p,O,A)=>({value:A.key}),"$id"),$updatedtime:a((p,O,A)=>A.version,"$updatedtime"),$record:a((p,O,A)=>A?{value:p}:p,"$record")};for(let p of this.attributes){p.isPrimaryKey&&(H=p),p.resolve=null;let O=p.relationship,A=p.computed;if(O)if(p.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),A&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),vl=!0,O.to)p.elements?.definition?(Dn[p.name]=p.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=p.elements.definition.tableClass;return C?zl({attribute:O.to,value:I},Gr(b).getReadTxn(),!1,L,!1).asArray:L.search([{attribute:O.to,value:I}],b).asArray},p.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},p.resolve.definition=p.elements.definition,O.from&&(p.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${p.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let y=p.definition||p.elements?.definition;y?(Dn[p.name]=p.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(p.elements){let B,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(B=!0),G});return O.filterMissing?B?Promise.all(N).then(x=>x.filter(oj)):N.filter(oj):B?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(L,C)}},p.set=(b,C)=>{if(Array.isArray(C)){let I=C.map(L=>L.getId?.()||L[y.tableClass.primaryKey]);b[O.from]=I}else{let I=C.getId?.()||C[y.tableClass.primaryKey];b[O.from]=I}},p.resolve.definition=p.definition||p.elements?.definition,p.resolve.from=O.from):console.error(`The relationship property "${p.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${p.name}" in table "${s}" must use either "from" or "to" arguments`);else A&&(typeof A.from=="function"&&this.setComputedAttribute(p.name,A.from),Dn[p.name]=p.resolve=(y,b,C)=>{let I=typeof A.from=="string"?y[A.from]:y,L=this.userResolvers[p.name];if(L)return L(I,b,C);xe.default.warn(`Computed attribute "${p.name}" does not have a function assigned to it. Please use setComputedAttribute('${p.name}', resolver) to assign a resolver function.`),this.userResolvers[p.name]=()=>{}})}lE(this,this)}static setComputedAttribute(p,O){let A=fi(E,p);if(!A){console.error(`The attribute "${p}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${p}" is not defined as computed in the table "${s}"`);return}this.userResolvers[p]=O}static async deleteHistory(p=0,O=!1){let A;for(let{key:y,value:b}of l.getRange({start:0,end:p}))await ja(),Nt(b).tableId===n&&(A=UT(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await ja(),C===null&&I<p&&(A=Sc(i,y))}await A}static async*getHistory(p=0,O=1/0){for(let{key:A,value:y}of l.getRange({start:p||1,end:O})){await ja();let b=Nt(y);b.tableId===n&&(yield{id:b.recordId,localTime:A,version:b.version,type:b.type,value:b.getValue(i,!0,A),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(p){let O=[];if(p==null)throw new Error("An id is required");let A=i.getEntry(p);if(!A)return O;let y=A.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await ja();let C=l.get(y);if(C){let I=Nt(C);O.push({id:I.recordId,localTime:y,version:I.version,type:I.type,value:I.getValue(i,!0,y),user:I.user}),y=I.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){Y?.remove()}}Ce.updatedAttributes();let Gd=Ce.prototype;return m&&Ce.setTTLExpiration(m/1e3),se&&Sm(),Ce;function on(K,p,O){let A;for(let y in r){let b=r[y],C=b.isIndexing,I=Dn[y],L=O&&(I?I(O):O[y]),B=p&&(I?I(p):p[y]);if(L===B&&!C)continue;A=!0;let N=b.indexNulls,x=(0,am.getIndexedValues)(L,N),G=(0,am.getIndexedValues)(B,N);if(G?.length>0){let z=new Set(G);if(x=x?x.filter(ie=>{if(z.has(ie))z.delete(ie);else return!0}):[],G=Array.from(z),(G.length>0||x.length>0)&&ej){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,sj)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&ej&&b.prefetch(x.map(z=>({key:z,value:K})),sj);if(x)for(let z=0,ie=x.length;z<ie;z++)b.put(x[z],K)}return A}a(on,"updateIndices");function wr(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>rj)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Ll.writeKey)(K,vSe,0)>rj)throw new Error("Primary key size is too large: "+K.length);return!0}a(wr,"checkValidId");function xl(K,p,O,A,y){if(Ce.getResidencyById&&O.ensureLoaded&&p?.replicateFrom!==!1){let C=Vi(Ce.getResidencyById(K));if(C&&!C.includes(server.hostname)&&w)return w({key:K,residency:C}).then(y)}let b=a(()=>{if(p?.transaction?.stale&&(p.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let C=i.getEntry(K,O);return C?.residencyId&&C.metadataFlags&_n&&w&&O.ensureLoaded&&p?.replicateFrom!==!1?w(C).then(I=>y(I,K),I=>(xe.default.error?.("Error loading remote record",K,C,O,I),y(null,K))):(C&&p&&(C?.version>(p.lastModified||0)&&(p.lastModified=C.version),C?.localTime&&!p.lastRefreshed&&(p.lastRefreshed=C.localTime)),y(C,K))},"whenPrefetched");return A?b():oe>0?(oe--,b()):new Promise((C,I)=>{oe===0?(oe--,i.prefetch([K],()=>{L(),B()})):(ne.push(K),ue.push(B),ne.length>gm&&(oe--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{oe===-1?L():oe++;for(let x of N)x()}),ne=[],ue=[],pe>2&&pe--}else oe=pe,pe<Fd&&pe++}a(L,"prefetch");function B(){try{C(b())}catch(N){I(N)}}a(B,"load")})}a(xl,"loadLocalRecord");function Fr(K){if(!K?.role)return;let p=K.role.permission;if(p.super_user)return USe;let O=p[c],A,y=O?.tables;if(y)return y[s];if(c==="data"&&(A=p[s])&&!A.tables)return A}a(Fr,"getTablePermissions");function Bl(K,p,O,A){if(v){let y=!1;if(O.noCache?y=!0:(p?(!p.value||p.metadataFlags&(_n|Xo)||p.expiresAt!=null&&p.expiresAt<Date.now())&&(y=!0):y=!0,Yn(!y,"cache-hit",s)),y){let b=$d(K,p,O).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),O&&(C?.version>(O.lastModified||0)&&(O.lastModified=C.version),O.lastRefreshed=Date.now()),C));if(O?.onlyIfCached||p?.value&&A?.allowStaleWhileRevalidate?.(p,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!A.doesExist())throw new Nr.ServerError("Entry is not cached",504);return}else return b}}else if(p?.value&&p.expiresAt!=null&&p.expiresAt<Date.now())return Ce.evict(p.key,p.value,p.version),p.value=null,{then(y){return y(p)}}}a(Bl,"ensureLoadedFromSource");function Gr(K){let p=K?.transaction;if(p){if(!p.lmdbDb)return p.lmdbDb=i,p;do{if(p.lmdbDb?.path===i.path)return p;let O=p.next;if(!O)return p=p.next=new ac,p.lmdbDb=i,p;p=O}while(!0)}else return new Wm}a(Gr,"txnForContext");function Hl(K,p,O){if(!K)return;let A=K.value||i.getEntry(K.key)?.value;if(typeof p=="object"){let b=Dn,C=A;for(let I=0,L=p.length;I<L;I++){let B=p[I],N=b?.[B];C=N&&C?N(C,O,!0)?.value:C?.[B],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Dn[p];return y?y(A,O):A[p]}a(Hl,"getAttributeValue");function qd(K,p,O,A,y){let b=y?.length,C={transaction:A,lazy:b>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},I;function L(B,N){let x=B?.value;if(!x)return Qa.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,B))return Qa.SKIP;return N!==void 0&&(B.key=N),B}if(a(L,"processEntry"),b>0||!K.hasEntries){let B=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Qa.SKIP;for(let x=0;x<b;x++){let z=y[x].idFilter;if(z){if(!z(N))return Qa.SKIP;I||(I=[]),I.push(x)}}return xl(N,O,C,!1,L)});return Array.isArray(K)&&(B=B.filter(N=>N!==Qa.SKIP)),B.hasEntries=!0,B}return K}a(qd,"transformToEntries");function qi(K,p,O=server.replication?.getThisNodeId(l)){if(K<=p?.version){if(p?.version===K&&O!==void 0){let A=server.replication?.exportIdMapping(l),y=p.localTime,b=y&&l.get(y);if(b){let C,I,L=Nt(b);for(let B in A)A[B]===O&&(C=B),A[B]===L.nodeId&&(I=B);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a(qi,"precedesExistingVersion");async function $d(K,p,O){let A=p?.metadataFlags,y=p?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(_n|Xo)?b($d(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},LSe)});let I=p?.value,L={requestContext:O,replacingRecord:I,replacingEntry:p,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},B=O?.responseHeaders;return new Promise((N,x)=>{let G;zC(Ot(L,async z=>{let ie=performance.now(),F,qe,Z;try{for(let _e of Ce.sources)if(_e.get&&(!_e.get.reliesOnPrototype||_e.prototype.get)){if(_e.available?.(p)===!1)continue;if(L.source=_e,F=await _e.get(K,L),F)break}Z=A&_n;let ee=L.lastModified||Z&&y;qe=Z||ee>y||!I,ee||(ee=(0,am.getNextMonotonicTime)());let Q=performance.now()-ie;if(tr(Q,"cache-resolution",s,null,"success"),B&&RE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),z.timestamp=ee,m&&L.expiresAt==null&&(L.expiresAt=Date.now()+m),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=I,ee=y;else throw new Nr.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}G=!0,N({key:K,version:ee,value:F})}catch(ee){ee.message+=` while resolving record ${K} for ${s}`,I&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(N({key:K,version:y,value:I}),xe.default.trace?.(ee.message,"(returned stale record)")):x(ee);let Q=performance.now()-ie;tr(Q,"cache-resolution",s,null,"fail"),B&&RE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Gr(L).addWrite({key:K,store:i,entry:p,nodeName:"source",commit:a((ee,Q)=>{if(Q?.version!==y)return;let _e=on(K,I,F);if(F){ye.put?.(L,K,F),Q&&(O.previousResidency=Ce.getResidencyRecord(Q.residencyId));let fe,Ae=!1,De,we=Vi(Ce.getResidency(F,O));if(we){if(!we.includes(server.hostname))if(fe=F,Ae=!0,Ce.getResidencyById)F=void 0;else{F=null;for(let _r in r)F||(F={}),F[_r]=fe[_r]}De=Za(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,Q,ee,Ae?_n:0,g&&(qe||Ae)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:De},"put",!!Z,fe)}else Q&&(ye.delete?.(L,K),xe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),g||R?T(K,null,Q,ee,0,g&&qe||null,{user:L?.user},"delete",!!Z):Sc(i,Q,y))},"commit")})}),()=>{i.unlock(K,y)},z=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",z)})})}a($d,"getFromSource");function kl(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new Nr.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new Nr.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(kl,"checkContextPermissions");function $i(K){let p=!1;if(K&&(K-lt>1&&(p=!0),lt=K),!(jt===Rr&&!p)&&(Rr=jt,(0,Pl.getWorkerIndex)()===(0,Pl.getWorkerCount)()-1))return is&&clearTimeout(is),jt?new Promise(O=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let y=jt/(1+lt),b=p?Date.now():Math.ceil((Date.now()-A.getTime())/y)*y+A.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),is=setTimeout(()=>q=q.then(async()=>{if(C(Math.max(I+jt,Date.now())),i.rootStore.status!=="open"){clearTimeout(is);return}let L=50,B=new Array(L),N=0,x=Math.pow(lt,8)*(Dl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(lt,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function z(ie,F,qe,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(lt){let ee=i.lastSize;return qe&pn&&Zl(Z,Q=>{Q.size&&(ee+=Q.size)}),xe.default.trace?.(`shouldEvict adjusted ${ce} ${ee}, ${ce*(ie-F)/ee} < ${x}`),ce*(ie-F)/ee<x}return!1}a(z,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:qe,value:Z,version:ce,expiresAt:ee,metadataFlags:Q}=F,_e;Z===null&&!g&&ce+DSe<Date.now()?_e=Sc(i,F,ce):ee!=null&&z(ee,ce,Q,Z)&&(_e=Ce.evict(qe,Z,ce),ie++),_e&&(await B[N],B[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await ja()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${ie} entries`)}catch(ie){xe.default.warn?.(`Error in cleanup scan for ${s}:`,ie)}O(void 0),lt=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a($i,"scheduleCleanup");function Vd(){Y=l?.addDeleteRemovalCallback(n,i,(K,p)=>{i.remove(K,p)})}a(Vd,"addDeleteRemoval");function Sm(){(0,Pl.getWorkerIndex)()===0&&setInterval(async()=>{if(!Ul){Ul=!0;try{let K=se.name,p=r[K];if(!p)throw new Error(`expiresAt attribute ${se} must be indexed`);for(let O of p.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of p.getValues(O)){let y=i.getEntry(A);y?.value?y.value[K]<Date.now()&&Ce.evict(A,y.value,y.version):i.ifVersion(A,y?.version,()=>p.remove(O,A))}await ja()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{Ul=!1}}},PSe).unref()}a(Sm,"runRecordExpirationEviction");function Vi(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let p=server.shards?.get?.(K);if(p)return xe.default.trace?.(`Shard ${K} mapped to ${p.map(O=>O.name).join(", ")}`),p.map(O=>O.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(Vi,"residencyFromFunction");function Za(K){if(K){let p=K.join(","),O=f.get([Symbol.for("residency_by_set"),p]);return O||(f.put([Symbol.for("residency_by_set"),p],O=Math.floor(Math.random()*2147418112)+65535),f.put([Symbol.for("residency_by_id"),O],K),O)}}a(Za,"getResidencyId")}function WC(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function sj(){}function xSe(e){lj=e}function HT(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return xT(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return xT(+e);case"Float":return e==="null"?null:xT(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;BSe.test(e)||(e+="Z");let n=new Date(e);return xT(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,kT.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function xT(e){if(isNaN(e))throw new SyntaxError;return e}function ij(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function zC(e,t,r){return e?.then?e.then(t,r):t(e)}function oj(e){return e!=null}function Ds(e){try{return JSON.stringify(e)}catch{return e}}function HSe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Qa,am,aj,cj,Dl,Nr,cm,lm,xe,Ll,Pl,kT,BT,CSe,lj,PSe,DSe,ej,LSe,tj,MSe,_n,Xo,vSe,rj,nj,USe,Ave,BSe,ja,pf=be(()=>{k();Qa=require("lmdb"),am=M(un()),aj=require("lodash"),cj=M(uf());Zo();zm();Dl=M(le());UO();Nr=M(me()),cm=M(lo()),lm=M(qs());ve();mf();xe=M(_i());ob();cc();Ll=require("ordered-binary"),Pl=M(rt());to();kT=M(ae());nu();Oi();iE();T_();BT=M(require("node:fs"));us();nT();CSe=new Uint8Array(9);CSe[8]=192;PSe=6e4,DSe=864e5;Dl.initSync();ej=Dl.get(U.STORAGE_PREFETCHWRITES),LSe=1e4,tj=1,MSe=2,_n=1,Xo=8,vSe=Buffer.allocUnsafeSlow(8192),rj=1978,nj=100,USe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},Ave=(0,kT.convertToMS)(Dl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(FT,"makeTable");a(WC,"attributesAsObject");a(sj,"noop");a(xSe,"setServerUtilities");BSe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(HT,"coerceType");a(xT,"rejectNaN");a(ij,"isDescendantId");ja=a(()=>new Promise(setImmediate),"rest");a(zC,"when");a(oj,"exists");a(Ds,"stringify");a(HSe,"hasOtherProcesses")});var it={};Ue(it,{database:()=>pu,database_envs:()=>qo,databases:()=>Ve,dropDatabase:()=>db,dropTableMeta:()=>$Se,getDatabases:()=>Je,getDefaultCompression:()=>Qg,getTables:()=>kSe,onRemovedDB:()=>G_,onUpdatedTable:()=>Zc,readMetaDb:()=>um,resetDatabases:()=>nd,table:()=>dt,tables:()=>Kn});function kSe(){return VT||Je(),Kn||{}}function Je(){if(VT)return Ve;VT=!0,Bd=new Map;let e=(0,zt.getHdbBasePath)()&&(0,Pt.join)((0,zt.getHdbBasePath)(),rc),t=(0,zt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,zt.get)(U.STORAGE_PATH)||e&&((0,ns.existsSync)(e)?e:(0,Pt.join)((0,zt.getHdbBasePath)(),Nm)),!e)return;if((0,ns.existsSync)(e))for(let n of(0,ns.readdirSync)(e,{withFileTypes:!0})){let s=(0,Pt.basename)(n.name,".mdb");n.isFile()&&(0,Pt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&um((0,Pt.join)(e,n.name),null,s)}if((0,ns.existsSync)((0,xd.getBaseSchemaPath)())){for(let n of(0,ns.readdirSync)((0,xd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Pt.join)((0,xd.getBaseSchemaPath)(),n.name),i=(0,Pt.join)((0,xd.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,ns.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Pt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Pt.join)(i,o.name);um((0,Pt.join)(s,o.name),(0,Pt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,ns.existsSync)(i))for(let c of(0,ns.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Pt.extname)(c.name).toLowerCase()===".mdb"&&um((0,Pt.join)(i,c.name),(0,Pt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Pt.join)(l.path,(0,Pt.basename)(c+".mdb"));(0,ns.existsSync)(u)&&um(u,c,n,null,!0)}}for(let n in Ve){let s=Bd.get(n);if(s){let i=Ve[n];n.includes("delete")&&Dt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Dt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Kn)delete Kn[i];delete Kn[KT]}}let r=["hdb_temp","hdb_certificate","hdb_analytics","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if(Ve.system)for(let n of r)Ve.system[n]&&(Ve.system[n].replicate=!1);return Bd=null,Ve}function nd(){VT=!1;for(let[,e]of qo)e.needsDeletion=!0;Je();for(let[e,t]of qo)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),qo.delete(e),delete Ve[t.databaseName],fm.forEach(r=>r(t.databaseName)));return Ve}function um(e,t,r=JC,n,s){let i=new jC.default(e,!1);try{let o=qo.get(e);o?o.needsDeletion=!1:(o=(0,Hd.open)(i),qo.set(e,o));let c=new Ml.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(GT.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,ns.existsSync)(n)&&(i.path=n,u=(0,Hd.open)(i),u.isLegacy=!0):u=vT(o));let f=_j(r),d=f[KT],_=new Map;for(let{key:h,value:m}of l.getRange({start:!1})){let[S,g]=h.toString().split("/");g===""?g=m.name:g||(g=S,S=t,m.name||(m.name=g,m.indexed=!m.is_hash_attribute)),d?.add(S);let R=_.get(S);R||_.set(S,R={attributes:[]}),(g==null||m.is_hash_attribute)&&(R.primary=m),g!=null&&R.attributes.push(m),Object.defineProperty(m,"key",{value:h,configurable:!0})}for(let[h,m]of _){let{attributes:S,primary:g}=m;if(!g){for(let oe of S)if(oe.is_hash_attribute||oe.isPrimaryKey){g=oe;break}if(!g){Dt.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(S)}`);continue}}let R=f[h],E={},T=[],w,v,H=typeof g.audit=="boolean"?g.audit:(0,zt.get)(U.LOGGING_AUDITLOG),q=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(R)E=R.indices,T=R.attributes,R.schemaVersion++;else{w=g.tableId,w?w>=(l.get(Ud)||0)&&(l.putSync(Ud,w+1),Dt.info(`Updating next table id (it was out of sync) to ${w+1} for ${h}`)):(g.tableId=w=l.get(Ud),w||(w=1),Dt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(Ud,w+1),l.putSync(g.key,g));let oe=new Ml.default(!g.is_hash_attribute,g.is_hash_attribute);if(oe.compression=g.compression,oe.compression){let pe=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||fj;oe.compression.threshold=pe}v=yp(o.openDB(g.key,oe),o),o.databaseName=r,v.tableId=w}let ue;for(let oe of S){oe.attribute=oe.name;try{if(!oe.is_hash_attribute&&(oe.indexed||oe.attribute&&!oe.name)){if(!E[oe.name]){let Te=new Ml.default(!oe.is_hash_attribute,oe.is_hash_attribute);E[oe.name]=o.openDB(oe.key,Te),E[oe.name].indexNulls=oe.indexNulls}let pe=T.find(Te=>Te.name===oe.name);pe?T.splice(T.indexOf(pe),1,oe):T.push(oe),ue=!0}}catch(pe){Dt.error("Error trying to update attribute",oe,T,E,pe)}}for(let oe of T)if(!S.find(Te=>Te.name===oe.name)){if(oe.is_hash_attribute){Dt.error("Unable to remove existing primary key attribute",oe);continue}oe.indexed&&(T.splice(T.indexOf(oe),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=hj(f,h,FT({primaryStore:v,auditStore:u,audit:H,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:q,tableName:h,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let oe of dm)oe(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function _j(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Kn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),Bd&&!Bd.has(e)){let r=new Set;t[KT]=r,Bd.set(e,r)}return t}function hj(e,t,r){return e[t]=r,r}function pu({database:e,table:t}){e||(e=JC),Je();let r=_j(e),n=(0,Pt.join)((0,zt.getHdbBasePath)(),rc),s=(0,zt.get)(U.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,zt.get)(U.STORAGE_PATH)||((0,ns.existsSync)(n)?n:(0,Pt.join)((0,zt.getHdbBasePath)(),Nm));let o=(0,Pt.join)(n,(i?t:e)+".mdb"),c=qo.get(o);if(!c||c.status==="closed"){let l=new jC.default(o,!1);c=(0,Hd.open)(l),qo.set(o,c)}return c.auditStore||(c.auditStore=vT(c)),c}async function db(e){if(!Ve[e])throw new Error("Schema does not exist");let t=Ve[e],r;for(let n in t)r=t[n].primaryStore.rootStore,qo.delete(r.path),r.status==="open"&&(await r.close(),await _m.remove(r.path));if(r||(r=pu({database:e,table:null}),r.status==="open"&&(await r.close(),await _m.remove(r.path))),e==="data"){for(let n in Kn)delete Kn[n];delete Kn[KT]}delete Ve[e],fm.forEach(n=>n(e)),await QA(r)}function dt(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,schemaDefined:_,origin:h}=e;r||(r=JC);let m=pu({database:r,table:t}),S=Ve[r];Dt.trace(`Defining ${t} in ${r}`);let g=S?.[t];if(m.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,E,T;_==null&&(_=!0);let w=new Ml.default(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let v,H;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...o)}else{let Y=m.auditStore;E=o.find(pe=>pe.isPrimaryKey)||{},R=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=Qg(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,zt.get)(U.LOGGING_AUDITLOG),n&&(E.expiration=n),s&&(E.eviction=s),u??=!1,E.splitSegments=u,typeof l=="boolean"&&(E.sealed=l),typeof f=="boolean"&&(E.replicate=f),h&&(E.origins?E.origins.includes(h)||E.origins.push(h):E.origins=[h]),Dt.trace(`${t} table loading, opening primary store`);let ne=new Ml.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=m.dbisDb=m.openDB(GT.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return H&&H(),nd(),dt(e);let oe=yp(m.openDB(ue,ne),m);m.databaseName=r,oe.tableId=T.get(Ud),Dt.trace(`Assigning new table id ${oe.tableId} for ${t}`),oe.tableId||(oe.tableId=1),T.put(Ud,oe.tableId+1),E.tableId=oe.tableId,g=hj(S,t,FT({primaryStore:oe,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:oe.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let q=g.indices;T=T||(m.dbisDb=m.openDB(GT.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,oe]=Y.toString().split("/");if(oe===""&&(oe=ne.name),oe){if(ue!==t)continue}else continue;let pe=o.find(ye=>ye.name===oe),Te=!pe?.indexed&&ne.indexed&&!ne.isPrimaryKey;if((!pe||Te)&&(se(),v=!0,pe||T.remove(Y),Te)){let ye=g.indices[ue];ye&&W.push(ye)}}let te=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(v=!0,Y.relationship))continue;let ne=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ne,configurable:!0});let ue=T.get(ne);if(Y.isPrimaryKey){if(ue=ue||T.get(ne=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||f!==void 0&&f!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||Y.type!==ue.type){let pe={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),pe.audit=c),n&&(pe.expiration=+n),s&&(pe.eviction=+s),l!==void 0&&(pe.sealed=l),f!==void 0&&(pe.replicate=f),Y.type&&(pe.type=Y.type),v=!0,se(),T.put(ne,pe)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let oe=!ue||ue.type!==Y.type||ue.indexed!==Y.indexed||ue.nullable!==Y.nullable||ue.version!==Y.version||JSON.stringify(ue.properties)!==JSON.stringify(Y.properties)||JSON.stringify(ue.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let pe=new Ml.default(!0,!1),Te=m.openDB(ne,pe);(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<hm.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<hm.workerData?.restartNumber)&&(v=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=ue?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Te}),te.push(Y))),T.put(ne,Y)),ue?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Te.indexNulls=Y.indexNulls,q[Y.name]=Te}else oe&&(v=!0,se(),T.put(ne,Y))}}finally{H&&H()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Dt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=qSe(g,te,W):v&&qT.signalSchemaChange(new $T.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,v)for(let Y of dm)Y(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Dt.trace(`${t} table loaded`),g;function se(){H||m.transactionSync(()=>({then(Y){H=Y}}))}a(se,"startTxn")}async function qSe(e,t,r){try{Dt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await qT.signalSchemaChange(new $T.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let d of t)(0,Hd.compareKeys)(d.lastIndexedKey,u)<0&&(u=d.lastIndexedKey),d.lastIndexedKey==null&&d.dbi.clearAsync();let f=0;for(let{key:d,value:_,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(_){if(f++,s=e.primaryStore.ifVersion(d,h,()=>{for(let m=0;m<l;m++){let S=t[m],g=S.name;try{let R=S.resolve,E=_&&(R?R(_):_[g]),T=(0,uj.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(R){o[g]||(o[g]=!0,Dt.error(`Error indexing attribute ${g}`,R))}}}),s.then(()=>f--,m=>{f--,Dt.error(m)}),hm.workerData&&hm.workerData.restartNumber!==dj.restartNumber&&(i=!0),++c%100===0||i){for(let m of t)m.lastIndexedKey=d,e.dbisDB.put(m.key,m);if(i)return}f>FSe?await s:f>GSe&&await new Promise(m=>setImmediate(m))}for(let d of t)delete d.lastIndexedKey,delete d.indexingPID,d.dbi.isIndexing=!1,s=e.dbisDB.put(d.key,d)}await s,await qT.signalSchemaChange(new $T.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Dt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Dt.error("Error in indexing",n)}}function $Se({table:e,database:t}){let r=pu({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function Zc(e){return dm.push(e),{remove(){let t=dm.indexOf(e);t>-1&&dm.splice(t,1)}}}function G_(e){return fm.push(e),{remove(){let t=fm.indexOf(e);t>-1&&fm.splice(t,1)}}}function Qg(){let e=(0,zt.get)(U.STORAGE_COMPRESSION),t=(0,zt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||fj,n={startingOffset:32};return t&&(n.dictionary=_m.readFileSync(t)),r&&(n.threshold=r),e&&n}var zt,GT,Hd,Pt,ns,xd,Ml,jC,_m,QC,uj,qT,$T,hm,Dt,dj,JC,KT,fj,Kn,Ve,Ud,dm,fm,VT,qo,Bd,FSe,GSe,ve=be(()=>{zt=M(le()),GT=M(vt()),Hd=require("lmdb"),Pt=require("path"),ns=require("fs"),xd=M(pt());pf();Ml=M(Lf()),jC=M(Mf());k();_m=M(require("fs-extra")),QC=M(ai()),uj=M(un()),qT=M(lo()),$T=M(qs()),hm=require("worker_threads"),Dt=M(j()),dj=M(rt());to();nu();us();JC="data",KT=Symbol("defined-tables"),fj=((0,zt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,zt.initSync)();Kn=Object.create(null),Ve=Object.create(null);(0,QC._assignPackageExport)("databases",Ve);(0,QC._assignPackageExport)("tables",Kn);Ud=Symbol.for("next-table-id"),dm=[],fm=[],qo=new Map;a(kSe,"getTables");a(Je,"getDatabases");a(nd,"resetDatabases");a(um,"readMetaDb");a(_j,"ensureDB");a(hj,"setTable");a(pu,"database");a(db,"dropDatabase");a(dt,"table");FSe=1e3,GSe=10;a(qSe,"runIndexing");a($Se,"dropTableMeta");a(Zc,"onUpdatedTable");a(G_,"onRemovedDB");a(Qg,"getDefaultCompression")});var ae=P((Lve,Ij)=>{"use strict";var Ja=require("path"),Sj=require("fs-extra"),Pn=j(),mj=require("fs-extra"),YT=require("os"),VSe=require("net"),KSe=require("recursive-iterator"),Ar=(k(),D($)),{PACKAGE_ROOT:YSe}=mt(),WSe=gA(),pj=require("papaparse"),WT=require("moment"),{inspect:zSe}=require("util"),Ej=require("is-number"),Dve=require("lodash"),jSe=require("minimist"),QSe=require("https"),JSe=require("http"),{hdb_errors:zT}=me(),XSe=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Tj=require("util").promisify(setTimeout),ZSe=100,eTe=5,tTe="",rTe=4,gj={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Ij.exports={isEmpty:ss,isEmptyOrZeroLength:Gi,arrayHasEmptyValues:iTe,arrayHasEmptyOrZeroLengthValues:oTe,buildFolderPath:aTe,isBoolean:Aj,errorizeMessage:nTe,stripFileExtension:lTe,autoCast:uTe,autoCastJSON:Rj,autoCastJSONDeep:ZC,removeDir:dTe,compareVersions:fTe,isCompatibleDataVersion:_Te,escapeRawValue:hTe,unescapeValue:mTe,stringifyProps:pTe,timeoutPromise:gTe,isClusterOperation:TTe,getClusterUser:RTe,checkGlobalSchemaTable:ATe,getHomeDir:bj,getPropsFilePath:ETe,promisifyPapaParse:yTe,removeBOM:Oj,createEventPromise:bTe,checkProcessRunning:OTe,checkSchemaTableExist:NTe,checkSchemaExists:Nj,checkTableExists:wj,getStartOfTomorrowInSeconds:wTe,getLimitKey:ITe,isObject:cTe,isNotEmptyAndHasValue:sTe,autoCasterIsNumberCheck:yj,backtickASTSchemaItems:CTe,isPortTaken:STe,createForkArgs:PTe,autoCastBoolean:DTe,async_set_timeout:Tj,getTableHashAttribute:LTe,doesSchemaExist:MTe,doesTableExist:vTe,stringifyObj:UTe,ms_to_time:xTe,changeExtension:BTe,getEnvCliRootPath:eP,noBootFile:HTe,httpRequest:kTe,transformReq:FTe,convertToMS:GTe,PACKAGE_ROOT:YSe};function nTe(e){return e instanceof Error?e:new Error(e)}a(nTe,"errorizeMessage");function ss(e){return e==null}a(ss,"isEmpty");function sTe(e){return!ss(e)&&(e||e===0||e===""||Aj(e))}a(sTe,"isNotEmptyAndHasValue");function Gi(e){return ss(e)||e.length===0||e.size===0}a(Gi,"isEmptyOrZeroLength");function iTe(e){if(ss(e))return!0;for(let t=0;t<e.length;t++)if(ss(e[t]))return!0;return!1}a(iTe,"arrayHasEmptyValues");function oTe(e){if(Gi(e))return!0;for(let t=0;t<e.length;t++)if(Gi(e[t]))return!0;return!1}a(oTe,"arrayHasEmptyOrZeroLengthValues");function aTe(...e){try{return e.join(Ja.sep)}catch{console.error(e)}}a(aTe,"buildFolderPath");function Aj(e){return ss(e)?!1:e===!0||e===!1}a(Aj,"isBoolean");function cTe(e){return ss(e)?!1:typeof e=="object"}a(cTe,"isObject");function lTe(e){return Gi(e)?tTe:e.slice(0,-rTe)}a(lTe,"stripFileExtension");function uTe(e){return ss(e)||e===""||typeof e!="string"?e:gj[e]!==void 0?gj[e]:yj(e)===!0?Number(e):XSe.test(e)?new Date(e):e}a(uTe,"autoCast");function Rj(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Rj,"autoCastJSON");function ZC(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=ZC(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=ZC(r);n!==r&&(e[t]=n)}return e}else return Rj(e)}a(ZC,"autoCastJSONDeep");function yj(e){if(e.startsWith("0.")&&Ej(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Ej(e))}a(yj,"autoCasterIsNumberCheck");async function dTe(e){if(Gi(e))throw new Error(`Directory path: ${e} does not exist`);try{await mj.emptyDir(e),await mj.remove(e)}catch(t){throw Pn.error(`Error removing files in ${e} -- ${t}`),t}}a(dTe,"removeDir");function fTe(e,t){if(Gi(e)){Pn.info("Invalid current version sent as parameter.");return}if(Gi(t)){Pn.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(fTe,"compareVersions");function _Te(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(_Te,"isCompatibleDataVersion");function hTe(e){if(ss(e))return e;let t=String(e);return t==="."?Ar.UNICODE_PERIOD:t===".."?Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD:t.replace(Ar.FORWARD_SLASH_REGEX,Ar.UNICODE_FORWARD_SLASH)}a(hTe,"escapeRawValue");function mTe(e){if(ss(e))return e;let t=String(e);return t===Ar.UNICODE_PERIOD?".":t===Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD?"..":String(e).replace(Ar.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(mTe,"unescapeValue");function pTe(e,t){if(ss(e))return Pn.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+YT.EOL}!Gi(n)&&n[0]===";"?r+=" "+n+s+YT.EOL:Gi(n)||(r+=n+"="+s+YT.EOL)}catch{Pn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(pTe,"stringifyProps");function bj(){let e;try{e=YT.homedir()}catch{e=process.env.HOME}return e}a(bj,"getHomeDir");function ETe(){let e=Ja.join(bj(),Ar.HDB_HOME_DIR_NAME,Ar.BOOT_PROPS_FILE_NAME);return Sj.existsSync(e)||(e=Ja.join(__dirname,"../","hdb_boot_properties.file")),e}a(ETe,"getPropsFilePath");function gTe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(gTe,"timeoutPromise");async function STe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=VSe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(STe,"isPortTaken");function TTe(e){try{return Ar.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Pn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(TTe,"isClusterOperation");function ATe(e,t){let r=(ve(),D(it)).getDatabases();if(!r[e])return zT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return zT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(ATe,"checkGlobalSchemaTable");function RTe(e,t){if(ss(t)){Pn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ss(e)||Gi(e)){Pn.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Pn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Pn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(RTe,"getClusterUser");function yTe(){pj.parsePromise=function(e,t,r){return new Promise(function(n,s){pj.parse(e,{header:!0,transformHeader:Oj,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(yTe,"promisifyPapaParse");function Oj(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Oj,"removeBOM");function bTe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Pn.info(`Got cluster status event response: ${zSe(s)}`);try{i.cancel()}catch{Pn.error("Error trying to cancel timeout.")}n(s)})})}a(bTe,"createEventPromise");async function OTe(e){let t=!0,r=0;do await Tj(ZSe*r++),(await WSe.findPs(e)).length>0&&(t=!1);while(t&&r<eTe);if(t)throw new Error(`process ${e} was not started`)}a(OTe,"checkProcessRunning");function NTe(e,t){let r=Nj(e);if(r)return r;let n=wj(e,t);if(n)return n}a(NTe,"checkSchemaTableExist");function Nj(e){let{getDatabases:t}=(ve(),D(it));if(!t()[e])return zT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Nj,"checkSchemaExists");function wj(e,t){let{getDatabases:r}=(ve(),D(it));if(!r()[e][t])return zT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(wj,"checkTableExists");function wTe(){let e=WT().utc().add(1,"d").startOf("d").unix(),t=WT().utc().unix();return e-t}a(wTe,"getStartOfTomorrowInSeconds");function ITe(){return WT().utc().format("DD-MM-YYYY")}a(ITe,"getLimitKey");function CTe(e){try{let t=new KSe(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){Pn.error("Got an error back ticking items."),Pn.error(t)}}a(CTe,"backtickASTSchemaItems");function PTe(e){return[e]}a(PTe,"createForkArgs");function DTe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(DTe,"autoCastBoolean");function LTe(e,t){let{getDatabases:r}=(ve(),D(it)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(LTe,"getTableHashAttribute");function MTe(e){let{getDatabases:t}=(ve(),D(it));return t()[e]!==void 0}a(MTe,"doesSchemaExist");function vTe(e,t){let{getDatabases:r}=(ve(),D(it));return r()[e]?.[t]!==void 0}a(vTe,"doesTableExist");function UTe(e){try{return JSON.stringify(e)}catch{return e}}a(UTe,"stringifyObj");function xTe(e){let t=WT.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(xTe,"ms_to_time");function BTe(e,t){let r=Ja.basename(e,Ja.extname(e));return Ja.join(Ja.dirname(e),r+t)}a(BTe,"changeExtension");function eP(){if(process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=jSe(process.argv);if(e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(eP,"getEnvCliRootPath");var XC;function HTe(){if(XC)return XC;let e=eP();if(eP()&&Sj.pathExistsSync(Ja.join(e,Ar.HDB_CONFIG_FILE)))return XC=!0,!0}a(HTe,"noBootFile");function kTe(e,t){let r;return e.protocol==="http:"?r=JSe:r=QSe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(kTe,"httpRequest");function FTe(e){if(!e.schema&&!e.database){e.schema=Ar.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(FTe,"transformReq");function GTe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(GTe,"convertToMS")});ym();var tP=(k(),D($)),Cj=ae(),mm=j(),qTe=_s(),$Te=Sn(),VTe=aS(),{start:KTe}=(mC(),D(ST)),{closeConnection:YTe}=rr(),Pj=require("moment"),Dj=CS(),{cloneDeep:WTe}=require("lodash"),zTe=process.env[tP.PROCESS_NAME_ENV_PROP],Xa=zTe.substring(4);a(async function(){let t={id:Xa,request:void 0},r=0;try{mm.notify("Starting job:",Xa),KTe(),qTe.setSchemaDataToGlobal(),await $Te.setUsersWithRolesCache();let n=await Dj.getJobById(Xa);if(Cj.isEmptyOrZeroLength(n))throw new Error(`Unable to find a record in hdb_job for job: ${Xa}`);let{request:s}=n[0];if(Cj.isEmptyOrZeroLength(s))throw new Error("Did not find job request in hdb_job table, unable to proceed");s=WTe(s);let i=VTe.getOperationFunction(s);mm.trace("Running operation:",s.operation,"for job",Xa);let o=await i.job_operation_function(s);mm.trace("Result from job:",Xa,o),t.status=tP.JOB_STATUS_ENUM.COMPLETE,typeof o=="string"?t.message=o:(t.result=o,t.message="Successfully completed job: "+Xa),t.end_datetime=Pj().valueOf(),mm.notify("Successfully completed job:",Xa)}catch(n){r=1,mm.error(n),t.status=tP.JOB_STATUS_ENUM.ERROR,t.message=n.message?n.message:n,t.end_datetime=Pj().valueOf()}finally{await Dj.updateJob(t),await YTe(),setTimeout(()=>{process.exit(r)},3e3).unref()}},"job")();
132
+ `;Te.message=`${ye}${Te.message}`,Te.stack=`${ye}${Te.stack}`,nm?.(Te),Il.default.error(Te),t.set(_.path||"/",new ea(Te)),Ld.set(n?d:(0,gt.basename)(e),Te.message)}}}}catch(S){S.message=`Could not load component '${d}' for application '${(0,gt.basename)(e)}' due to: ${S.message}`,nm?.(S),((0,sm.getWorkerIndex)()===0?console:Il.default).error(S),t.set(_.path||"/",new ea(S),null,!0),Ld.set(n?d:(0,gt.basename)(e),S.message)}}if(NT=u,Dd.isMainThread&&!mz&&i&&(0,sm.watchDir)(e,async()=>pz()),c.extensionModule){let d=await gE((0,gt.join)(e,c.extensionModule));return OT.set(o,d),d}if(!f&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;nm?.(new Error(d)),((0,sm.getWorkerIndex)()===0?console:Il.default).error(d),Ld.set((0,gt.basename)(e),d)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,nm?.(c),t.set("",new ea(c))}}var ct,gt,Dd,bC,IC,CC,_z,sm,Il,hz,OC,Dge,IT,Lge,RC,NC,mz,yC,Ld,Mge,wC,fz,OT,nm,NT,Uge,yh=be(()=>{ct=require("fs"),gt=require("path"),Dd=require("worker_threads"),bC=require("yaml"),IC=M(le()),CC=M(mt());k();oL();qL();Xx();rB();nB();GB();RK();IK();PK();_z=M(require("fast-glob")),sm=M(rt()),Il=M(j());Sb();Pr();hz=M(me());ve();WI();OC=M(le()),Dge=M(YW());tS();mC();hs();dz();IT=M(bt());bE();FA();({readFile:Lge}=ct.promises),RC=(0,IT.resolvePath)(IC.get(U.COMPONENTSROOT)),NC=new Map,Ld=new Map;a(pz,"loadComponentDirectories");Mge={REST:NE,rest:NE,graphql:sR,graphqlSchema:$A,roles:gb,jsResource:Ab,fastifyRoutes:lI,login:yb,static:uI,operationsApi:Dge,customFunctions:{},http:{},clustering:ST,replication:Ea,authentication:mh,mqtt:AC,loadEnv:dI},wC={rest:!0,graphqlSchema:{files:"*.graphql"},roles:{files:"roles.yaml"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(wC,"static",{value:{files:"web/**"}});fz=[],OT=new Map;a(vge,"setErrorReporter");Uge=a(()=>NT,"getComponentName");a(xge,"symlinkHarperModule");a(wT,"loadComponent")});var dT=P((qMe,gz)=>{var{isMainThread:Ez}=require("worker_threads"),{getTables:Bge,getDatabases:FMe,table:GMe}=(ve(),D(it)),{loadComponentDirectories:Hge,loadComponent:kge}=(yh(),D(Rh)),{resetResources:Fge}=(Jl(),D(nL)),Gge=lw(),qge=bt(),{dirname:$ge}=require("path"),{getConnection:Vge}=rr(),Kge=le(),{CONFIG_PARAMS:Yge}=(k(),D($)),{loadCertificates:Wge}=Qs(),PC=new Map;async function zge(e=!1){!Ez&&Kge.get(Yge.CLUSTERING_ENABLED)&&Vge();try{Ez&&await Gge()}catch(n){console.error(n)}let t=Fge();Bge(),t.isWorker=e,await Wge(),await kge($ge(qge.getConfigFilePath()),t,"hdb",!0,PC),await Hge(PC,t);let r=[];for(let[n]of PC)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(zge,"loadRootComponents");gz.exports.loadRootComponents=zge});var rt=P((VMe,oi)=>{"use strict";ym();var{Worker:jge,MessageChannel:Qge,parentPort:ki,isMainThread:UC,threadId:Jge,workerData:Fi}=require("worker_threads"),{PACKAGE_ROOT:Xge}=mt(),{join:Rz,isAbsolute:Zge,extname:eSe}=require("path"),{server:yz}=(Pr(),D(ql)),{watch:tSe,readdir:rSe}=require("fs/promises"),{totalmem:Sz}=require("os"),Md=(k(),D($)),bz=le(),ii=j(),{randomBytes:nSe}=require("crypto"),{_assignPackageExport:sSe}=ai(),Tz=1024*1024,Wa=[],Cs=[],iSe=50,xC=1e4,oSe="restart",Oz="request_thread_info",Nz="resource_report",wz="thread_info",Iz="added-port",aSe="ack",DC;sSe("threads",Cs);oi.exports={startWorker:LC,restartWorkers:HC,shutdownWorkers:fSe,workers:Wa,setMonitorListener:TSe,onMessageFromWorkers:_Se,onMessageByType:Uz,broadcast:mSe,broadcastWithAcknowledgement:ESe,setChildListenerByType:dSe,getWorkerIndex:Cz,getWorkerCount:Pz,getTicketKeys:Lz,setMainIsWorker:lSe,setTerminateTimeout:cSe,restartNumber:Fi?.restartNumber||1};Cs.onMessageByType=Uz;Cs.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Cs.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};oi.exports.whenThreadsStarted=new Promise(e=>{oi.exports.threadsHaveStarted=e});var BC;function cSe(e){xC=e}a(cSe,"setTerminateTimeout");function Cz(){return Fi?Fi.workerIndex:BC?0:void 0}a(Cz,"getWorkerIndex");function Pz(){return Fi?Fi.workerCount:BC?1:void 0}a(Pz,"getWorkerCount");function lSe(e){BC=e,oi.exports.threadsHaveStarted()}a(lSe,"setMainIsWorker");var Dz=1,CT;function Lz(){return CT||(CT=UC?nSe(48):Fi.ticketKeys,CT)}a(Lz,"getTicketKeys");Object.defineProperty(yz,"workerIndex",{get(){return Cz()}});Object.defineProperty(yz,"workerCount",{get(){return Pz()}});var Mz={[Oz](e,t){gSe(t)},[Nz](e,t){SSe(t,e)}};function LC(e,t={}){let r=process.constrainedMemory?.()||Sz();r=Math.min(r,Sz(),2e4*Tz);let n=bz.get(Md.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Tz/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Cs){let u=new Qge;u.existingPort=l,i.push(u),o.push(u.port2)}eSe(e)||(e+=".js");let c=new jge(Zge(e)?e:Rz(Xge,e),{resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps","--expose-internals"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Dz=t.threadCount,name:t.name,restartNumber:oi.exports.restartNumber,ticketKeys:Lz()},transferList:o,...t});for(let{port1:l,existingPort:u}of i)u.postMessage({type:Iz,port:l,threadId:c.threadId},[l]);return DT(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>LC(e,t),c.on("error",l=>{ii.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Wa.splice(Wa.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<iSe?(t.unexpectedRestarts=c.unexpectedRestarts+1,LC(e,t)):ii.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{Mz[l.type]?.(l,c)}),Wa.push(c),RSe(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(LC,"startWorker");var uSe=[Md.THREAD_TYPES.HTTP];async function HC(e=null,t=Math.max(Dz>3,1),r=!0){if(UC){try{process.chdir(process.cwd())}catch(o){ii.error("Unable to reestablish current working directory",o)}if(r){let{loadRootComponents:o}=dT();await o()}oi.exports.restartNumber++,t<1&&(t=t*Wa.length);let n=[],s=[];for(let o of Wa.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ii.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:oi.exports.restartNumber,type:Md.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=uSe.indexOf(o.name)>-1,l=new Promise(u=>{let f=setTimeout(()=>{ii.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},xC*2).unref();o.on("exit",()=>{clearTimeout(f),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),u()})});if(n.push(l),c&&r){let u=o.startCopy(),f=new Promise(d=>{let _=a(h=>{h.type===Md.ITC_EVENT_TYPES.CHILD_STARTED&&(ii.trace("Worker has started",u.threadId),d(),s.splice(s.indexOf(f)),u.off("message",_))},"startListener");ii.trace("Waiting for worker to start",u.threadId),u.on("message",_)});s.push(f),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=id();r&&(e==="http"||!e)&&bz.get(Md.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ki.postMessage({type:oSe,workerType:e})}a(HC,"restartWorkers");function dSe(e,t){Mz[e]=t}a(dSe,"setChildListenerByType");function fSe(e){return HC(e,1/0,!1)}a(fSe,"shutdownWorkers");var vz=[];function _Se(e){vz.push(e)}a(_Se,"onMessageFromWorkers");var MC=new Map;function Uz(e,t){let r=MC.get(e);r||MC.set(e,r=[]),r.push(t)}a(Uz,"onMessageByType");var hSe=10;async function mSe(e,t){let r=0;for(let n of Cs)try{n.postMessage(e),r++>hSe&&(r=0,await new Promise(setImmediate))}catch(s){ii.error("Unable to send message to worker",s)}t&&Bz(e,null)}a(mSe,"broadcast");var PT=new Map,pSe=1;function ESe(e){return new Promise(t=>{let r=0;for(let n of Cs)try{let s=pSe++,i=a(()=>{PT.delete(s),--r===0&&t(),n!==ki&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,PT.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of PT)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ii.error("Unable to send message to worker",s)}r===0&&t()})}a(ESe,"broadcastWithAcknowledgement");function gSe(e){e.postMessage({type:wz,workers:xz()})}a(gSe,"sendThreadInfo");function xz(){let e=Date.now();return Wa.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(xz,"getChildWorkerInfo");function SSe(e,t){e.resources=t,e.resources.updated=Date.now()}a(SSe,"recordResourceReport");var vC;function TSe(e){vC=e}a(TSe,"setMonitorListener");var ASe=1e3,Az=!1;function RSe(){Az||(Az=!0,setInterval(()=>{for(let e of Wa){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}vC&&vC()},ASe).unref())}a(RSe,"startMonitoring");var ySe=1e3;if(ki&&Fi?.addPorts){DT(ki);for(let e=0,t=Fi.addPorts.length;e<t;e++){let r=Fi.addPorts[e];r.threadId=Fi.addThreadIds[e],DT(r)}setInterval(()=>{let e=process.memoryUsage();ki.postMessage({type:Nz,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},ySe).unref(),DC=a(()=>new Promise((e,t)=>{ki.on("message",r),ki.postMessage({type:Oz});function r(n){n.type===wz&&(ki.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else DC=xz;oi.exports.getThreadInfo=DC;function DT(e,t){Cs.push(e),e.on("message",r=>{if(r.type===Iz)r.port.threadId=r.threadId,DT(r.port);else if(r.type===aSe){let n=PT.get(r.id);n&&n()}else Bz(r,e)}).on("close",()=>{Cs.splice(Cs.indexOf(e),1)}).on("exit",()=>{Cs.splice(Cs.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(DT,"addPort");function Bz(e,t){for(let n of vz)n(e,t);let r=MC.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){ii.error(s)}}a(Bz,"notifyMessageListeners");if(UC){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await rSe(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Rz(s,o.name));try{for await(let{filename:o}of tSe(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await HC(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");oi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else ki.on("message",async e=>{let{type:t}=e;t===Md.ITC_EVENT_TYPES.SHUTDOWN&&(oi.exports.restartNumber=e.restartNumber,ki.unref(),setTimeout(()=>{ii.warn("Thread did not voluntarily terminate",Jge),process.exit(0)},xC).unref())})});var Ex={};Ue(Ex,{ACTION_32_BIT:()=>Ap,ACTION_64_BIT:()=>NSe,AUDIT_STORE_OPTIONS:()=>uh,Decoder:()=>Xc,HAS_BLOBS:()=>pn,HAS_CURRENT_RESIDENCY_ID:()=>Tc,HAS_EXPIRATION_EXTENDED_TYPE:()=>Df,HAS_ORIGINATING_OPERATION:()=>Pf,HAS_PREVIOUS_RESIDENCY_ID:()=>Ac,REMOTE_SEQUENCE_UPDATE:()=>ig,createAuditEntry:()=>ru,getLastRemoved:()=>vO,openAuditStore:()=>vT,readAuditEntry:()=>Nt,removeAuditEntry:()=>UT,setAuditRetention:()=>OSe,transactionKeyEncoder:()=>Yz});function vT(e){let t=e.auditStore=e.openDB(kC.AUDIT_STORE_NAME,{create:!1,...uh});t||(t=e.auditStore=e.openDB(kC.AUDIT_STORE_NAME,uh),kz(t,1)),t.rootStore=e,t.tableStores=[];let r=[];t.addDeleteRemovalCallback=function(l,u,f){return r[l]=f,t.tableStores[l]=u,t.deleteCallbacks=r,{remove(){delete r[l]}}};let n=null,s,i=0,o=GC;zh(t.env.path,l=>{if(i=l,l)return c(100)});function c(l){l&&(o=l),clearTimeout(n);let u=new Promise(f=>{n=setTimeout(async()=>{if(await s,s=u,t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let d=0,_,h;try{for(let{key:m,value:S}of t.getRange({start:1,snapshot:!1,end:Date.now()-FC/(1+i*i)})){try{_=UT(t,m,S)}catch(g){vd.warn("Error removing audit entry",g)}if(h=m,await new Promise(setImmediate),++d>=bSe){o=10;break}}await _}finally{d===0?o=Math.min(o<<1,FC/10):(kz(t,h),o>100&&(o=o>>1)),f(void 0),c()}},o).unref()});return u}if(a(c,"scheduleAuditCleanup"),t.scheduleAuditCleanup=c,(0,om.getWorkerIndex)()===(0,om.getWorkerCount)()-1&&c(),(0,om.getWorkerIndex)()===0&&!Hz)for(let l of t.getKeys({reverse:!0,limit:1}))l>Date.now()&&(Hz=!0,vd.error("The current time is before the last recorded entry in the audit log. Time reversal can undermine the integrity of data tracking and certificate validation and the time must be corrected."));return t}function UT(e,t,r){let n=wSe(r),s;if(n&pn){s=Nt(r);let i=e.tableStores[s.tableId],o=i?.getEntry(s.recordId);(!o||o.version!==s.version||!o.value)&&hc(()=>ta(s.getValue(i)),i.rootStore)}if((n&15)===qC){s=s||Nt(r);let i=s.tableId;e.tableStores[s.tableId]?.getEntry(s.recordId)?.version===s.version&&e.deleteCallbacks?.[i]?.(s.recordId,s.version)}return e.remove(t)}function kz(e,t){$C[0]=t,e.put(Symbol.for("last-removed"),Wz)}function vO(e){let t=e.get(Symbol.for("last-removed"));if(t)return Wz.set(t),$C[0]}function OSe(e,t=GC){FC=e,GC=t}function ru(e,t,r,n,s,i,o,c,l,u,f,d,_){let h=zz[o];if(!h)throw new Error(`Invalid audit entry type ${o}`);let m=1;if(n&&(n>1?za.setFloat64(0,n):Ps.set(hR),m=9),l){if(l&255)throw new Error("Illegal extended type");m+=3}R(s),R(t),g(r),za.setFloat64(m,e),m+=8,l&Tc&&R(u),l&Ac&&R(f),l&Df&&(za.setFloat64(m,d),m+=8),l&Pf&&R(jz[_]),i?g(i):Ps[m++]=0,l?za.setUint32(n?8:0,h|l|3221225472):Ps[n?8:0]=h;let S=Ps.subarray(0,m);if(c)return Buffer.concat([S,c]);return S;function g(E){let T=m;m+=1,m=(0,Cl.writeKey)(E,Ps,m);let w=m-T-1;w>127?w>16383?(vd.error("Key or username was too large for audit entry",E),m=T+1,Ps[T]=0):(Ps.copyWithin(T+2,T+1,m),za.setUint16(T,w|32768),m++):Ps[T]=w}function R(E){E<128?Ps[m++]=E:E<16384?(za.setUint16(m,E|32768),m+=2):E<1056964608?(za.setUint32(m,E|3221225472),m+=4):(Ps[m]=255,za.setUint32(m+1,E),m+=5)}}function wSe(e){let t=0;e[0]==66&&(t=8);let r=e[t];if(r<128)return r;let n=e.dataView||(e.dataView=new Xc(e.buffer,e.byteOffset,e.byteLength));return n.position=t,n.readInt()}function Nt(e,t=0,r=void 0){try{let n=e.dataView||(e.dataView=new Xc(e.buffer,e.byteOffset,e.byteLength));n.position=t;let s;e[n.position]==66&&(s=n.readFloat64());let i=n.readInt(),o=n.readInt(),c=n.readInt(),l=n.readInt(),u=n.position,f=n.position+=l,d=n.readFloat64(),_,h,m,S;if(i&Tc&&(_=n.readInt()),i&Ac&&(h=n.readInt()),i&Df&&(m=n.readFloat64()),i&Pf){let T=n.readInt();S=jz[T]}l=n.readInt();let g=n.position,R=n.position+=l,E;return{type:zz[i&7],tableId:c,nodeId:o,get recordId(){return(0,Cl.readKey)(e,u,f)},getBinaryRecordId(){return e.subarray(u,f)},version:d,previousLocalTime:s,get user(){return R>g?(0,Cl.readKey)(e,g,R):void 0},get encoded(){return t?e.subarray(t,r):e},getValue(T,w,v){if(i&LT||i&im&&!w)return E||(E=hc(()=>T.decoder.decode(e.subarray(n.position,r)),T.rootStore)),E;if(i&im&&v)return nb(T.getEntry(this.recordId),v,T)},getBinaryValue(){return i&(LT|im)?e.subarray(n.position,r):void 0},extendedType:i,residencyId:_,previousResidencyId:h,expiresAt:m,originatingOperation:S}}catch(n){return vd.error("Reading audit entry error",n,e),{}}}var Cl,MT,kC,om,Kz,vd,Ps,za,Yz,uh,FC,bSe,$C,Wz,GC,Hz,LT,im,Fz,qC,Gz,qz,$z,Vz,Ap,NSe,ig,Tc,Ac,Pf,Df,pn,zz,jz,Xc,to=be(()=>{Cl=require("ordered-binary"),MT=M(le()),kC=M(vt());k();om=M(rt()),Kz=M(ae());nu();vd=M(j());iE();us();nT();(0,MT.initSync)();Ps=Buffer.alloc(2816),za=new DataView(Ps.buffer,Ps.byteOffset,2816),Yz={writeKey(e,t,r){return e===Cf?(t.set(Cf,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Cl.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Cl.readKey)(e,t,r)}},uh={encoding:"binary",keyEncoder:Yz},FC=(0,Kz.convertToMS)((0,MT.get)(U.LOGGING_AUDITRETENTION))||86400*3,bSe=1e3,$C=new Float64Array(1),Wz=new Uint8Array($C.buffer),GC=1e4,Hz=!1;a(vT,"openAuditStore");a(UT,"removeAuditEntry");a(kz,"updateLastRemoved");a(vO,"getLastRemoved");a(OSe,"setAuditRetention");LT=16,im=32,Fz=1,qC=2,Gz=3,qz=4,$z=5,Vz=6,Ap=14,NSe=15,ig=11,Tc=512,Ac=1024,Pf=2048,Df=4096,pn=8192,zz={put:Fz|LT,[Fz]:"put",delete:qC,[qC]:"delete",message:Gz|LT,[Gz]:"message",invalidate:qz|im,[qz]:"invalidate",patch:$z|im,[$z]:"patch",relocate:Vz,[Vz]:"relocate"},jz={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(ru,"createAuditEntry");a(wSe,"readAction");a(Nt,"readAuditEntry");Xc=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t;return t=this.getUint8(this.position++),t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch(t){throw t.message=`Error reading float64: ${t.message} at position ${this.position}`,t}}}});function YC(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=Jz,ISe(e.primaryStore,e.auditStore)):(c=Qz,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{Xz(Qz[i])})));let l=c[i]||(c[i]=[]);if(l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now()),s?.scope==="full-database")return;let u=l[o];u||(u=l[o]=new Map,u.envs=l,u.tableId=o,u.store=e.primaryStore),t=Ql(t);let f=new KC(r);f.startTime=n;let d=u.get(t);return d?d.push(f):(u.set(t,d=[f]),d.tables=u,d.key=t),f.subscriptions=d,f}function Xz(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),Zz(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Nt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=Ql(c),u=0;do{let f=o.get(l);if(f){for(let _ of f)if(!(u>0&&!(_.includeDescendants&&!(_.onlyChildren&&u>1)))){if(_.startTime>=n){(0,VC.info)("omitting",c,_.startTime,n);continue}try{let h;_.supportsTransactions&&_.txnInProgress!==i.version&&(h=!0,_.txnInProgress||(r?r.push(_):r=[_]),_.txnInProgress=i.version),_.listener(c,i,n,h)}catch(h){console.error(h),(0,VC.info)(h)}}}if(l==null)break;let d=l.lastIndexOf?.("/",l.length-2);d!==l.length-1&&u++,d>-1?l=l.slice(0,d+1):l=null}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function ISe(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let l=Jz[s];if(!l)return;let u=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{Xz(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",u)&&u()})}}function Zz(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function qk(e){return e.nextTransaction||(YC({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),Zz(e)),e.nextTransaction}var VC,Qz,Jz,KC,UO=be(()=>{VC=M(j());Kl();Jl();to();Qz=Object.create(null),Jz=Object.create(null);a(YC,"addSubscription");KC=class extends Un{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables;if(t){let r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(Xz,"notifyFromTransactionData");a(ISe,"listenToCommits");a(Zz,"nextTransaction");a(qk,"whenNextTransaction")});var Kw={};Ue(Kw,{EVICTED:()=>Xo,INVALIDATED:()=>_n,coerceType:()=>HT,makeTable:()=>FT,setServerUtilities:()=>xSe});function FT(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:f,sealed:d,splitSegments:_,replicate:h}=e,{expirationMS:m,evictionMS:S,audit:g,trackDeletes:R}=e;S??=0;let{attributes:E}=e;E||(E=[]);let T=ER(i,n,l),w,v,H={},q=Promise.resolve(),W,te,se;for(let K of E)(K.assignCreatedTime||K.name==="__createdtime__")&&(W=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(te=K),K.expiresAt&&(se=K),K.isPrimaryKey&&(H=K);let Y,ne=[],ue=[],oe=1,pe=2,Te={},ye={},jt=864e5,lt=0,Rr,is,Dn,vl=!1,Ul,jT=new Map,QT=new Map,Lt,kd,pm=Dl.get(U.REPLICATION_DATABASES);if(Array.isArray(pm)){for(let K of pm)if(K.name===c&&K.replicateTo>=0){kd=K.replicateTo;break}}let Em=i.getRange({start:!1,end:!1}).constructor,Fd=10,gm=6;g&&Vd(),zh(i.env.path,K=>{if(v)return $i(K)});class Ce extends Vr{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=g;static databasePath=o;static databaseName=c;static attributes=E;static replicate=h;static sealed=d;static splitSegments=_??!0;static createdTimeProperty=W;static updatedTimeProperty=te;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return m}static dbisDB=f;static schemaDefined=u;static sourcedFrom(p,O){if(O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource)p.intermediateSource=!0,this.sources.unshift(p);else{if(this.sources.some(I=>!I.intermediateSource)){if(this.sources.some(I=>I.name===p.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(p)}v=v||p.get&&(!p.get.reliesOnPrototype||p.prototype.get),w=w||p.load;let A=a(I=>{let L=this.sources;if(L=L.filter(B=>B.intermediateSource&&B[I]&&(!B[I].reliesOnPrototype||B.prototype[I])),L.length>0)if(L.length===1){let B=L[0];return(N,x,G)=>{if(N?.source!==B)return B[I](x,G,N)}}else return(B,N,x)=>{let G=[];for(let z of L){if(B?.source===z)break;G.push(z[I](N,x,B))}return Promise.all(G)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1];y.intermediateSource&&(y={});let b=a(I=>{if(y[I]&&(!y[I].reliesOnPrototype||y.prototype[I]))return(L,B,N)=>{if(!L?.source)return y[I](B,N,L)}},"getApplyToCanonicalSource");Te={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ye={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let C=y.shouldRevalidateEvents;return(async()=>{let I=!1,L,B=a(async(N,x)=>{let G=N.value,z=N.table?Ve[c][N.table]:Ce;if(c===Wd&&(N.table===Fl.ROLE_TABLE_NAME||N.table===Fl.USER_TABLE_NAME)&&(I=!0),N.id===void 0&&(N.id=G[z.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=p;let ie={residencyId:Za(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId},F=await z.getResource(N.id,x,ie);switch(N.finished&&await N.finished,N.type){case"put":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!0,ie);case"patch":return C?F._writeInvalidate(G,ie):F._writeUpdate(G,!1,ie);case"delete":return F._writeDelete(ie);case"publish":case"message":return F._writePublish(G,ie);case"invalidate":return F._writeInvalidate(G,ie);case"relocate":return F._writeRelocate(ie);default:xe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=p.subscribe;N&&R==null&&(R=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},G=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Pl.getWorkerIndex)(),x):(0,Pl.getWorkerIndex)()===0,z=N&&G&&await p.subscribe?.(x);if(z){let ie;for await(let F of z)try{if(!(F.type==="transaction"?F.writes[0]:F)){xe.default.error?.("Bad subscription event",F);continue}if(F.source=p,F.type==="end_txn"){if(ie?.resolve(),F.localTime&&L!==F.localTime){if(F.remoteNodeIds?.length>0){let ce=[Symbol.for("seq"),F.remoteNodeIds[0]],ee=f.get(ce),Q=ee?.nodes;Q||(Q=[]);for(let fe of F.remoteNodeIds.slice(1)){let Ae=Q.find(De=>De.id===fe);Q=Q.filter(De=>De.id!==fe||De===Ae),Ae||(Ae={id:fe,seqId:0},Q.push(Ae)),Ae.seqId=Math.max(ee?.seqId??1,F.localTime),fe===ie?.nodeId&&(Ae.lastTxnTime=F.timestamp)}let _e=Math.max(ee?.seqId??1,F.localTime);xe.default.trace?.("Received txn",c,new Date(_e),new Date(F.localTime),F.remoteNodeIds),f.put(ce,{seqId:_e,nodes:Q})}L=F.localTime}F.onCommit&&ie?.committed.then(F.onCommit);continue}if(ie)if(F.beginTxn)ie.resolve();else{ie.write_promises.push(B(F,ie));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let Z=Ot(F,()=>{if(F.type==="transaction"){let ce=[];for(let ee of F.writes)try{ce.push(B(ee,F))}catch(Q){throw Q.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(F),Q}return Promise.all(ce)}else if(F.type==="define_schema"){let ce=this.attributes.slice(0),ee;for(let Q of F.attributes)ce.find(_e=>_e.name===Q.name)||(ce.push(Q),ee=!0);ee&&(dt({table:s,database:c,attributes:ce,origin:"cluster"}),cm.signalSchemaChange(new lm.SchemaEventMsg(process.pid,Gt.CREATE_TABLE,c,s)))}else return F.beginTxn?(ie=F,ie.write_promises=[B(F,F)],new Promise(ce=>{ie.resolve=()=>ce(Promise.all(ie.write_promises))})):B(F,F)});ie&&(ie.committed=Z),I&&Z&&!Z?.waitingForUserChange&&(Z.then(()=>cm.signalUserChange(new lm.UserEventMsg(process.pid))),Z.waitingForUserChange=!0),F.onCommit&&(Z?Z.then(F.onCommit):F.onCommit())}catch(qe){xe.default.error?.("error in subscription handler",qe)}}}catch(N){xe.default.error?.(N)}})(),this}static get isCaching(){return v}static get shouldRevalidateEvents(){return this.prototype.get!==Ce.prototype.get}static getResource(p,O,A){let y=super.getResource(p,O,A);if(p!=null){wr(p);try{if(y.getRecord?.())return y;if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let b=!A?.async||i.cache?.get?.(p),C=Gr(O),I=C.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return xl(p,O,{transaction:I,ensureLoaded:A?.ensureLoaded},b,L=>{if(L?Ce._updateResource(y,L):y.#e=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Nr.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let B=Bl(p,L,O,y);if(B)return C?.disregardReadTxn(),y.#i=!0,zC(B,N=>(Ce._updateResource(y,N),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(p)),b}}return y}static _updateResource(p,O){p.#r=O,p.#e=O?.value??null,p.#n=O?.version}ensureLoaded(){let p=Bl(this.getId(),this.#r,this.getContext());if(p)return this.#i=!0,zC(p,O=>{this.#r=O,this.#e=O.value,this.#n=O.version})}static getNewId(){let p=H?.type;if(p==="String"||p==="ID")return super.getNewId();if(!Lt){let b=i.getEntry(Symbol.for("id_allocation")),C=b?.value,I;if(C&&C.nodeName===server.hostname&&(!HSe(i)||C.pid===process.pid)){let L=C.start,B=C.end;I=L;for(let N of i.getKeys({start:B,end:L,limit:1,reverse:!0}))I=N}else C=y(b?.version??null),I=C.start;Lt=new BigInt64Array([BigInt(I)+1n]),Lt=new BigInt64Array(i.getUserSharedBuffer("id",Lt.buffer)),Lt.maxSafeId=C.end}let O=Number(Atomics.add(Lt,0,1n)),A=p==="Int"?512:1048576;if(O+A>=Lt.maxSafeId){let b=a(C=>{Lt.maxSafeId=O+(p==="Int"?1023:4194303);let I=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=C?void 0:i.useReadTransaction(),B=Number(Lt[0]);for(let G of i.getKeys({start:B+1,end:I,limit:1,transaction:L}))I=G;L?.done();let{value:N,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Lt.maxSafeId<I){if(N.end>Lt.maxSafeId-100)return;xe.default.info?.("New id allocation",O,Lt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:N.start,end:Lt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{xe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Lt.maxSafeId}, but id of ${I} detected`);let G=y(x);G.alreadyUpdated||Atomics.store(Lt,0,BigInt(G.start+1)),Lt.maxSafeId=G.end}},"updateEnd");O+A===Lt.maxSafeId?setImmediate(b):O+100>=Lt.maxSafeId&&(xe.default.warn?.(`Synchronous id allocation required on table ${s}${p=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>b(!0)))}return O;function y(b){let C=(p==="Int"?Math.pow(2,31):Math.pow(2,49))-1,I=C/4,L,B,N=!1,x,G;do{x=Math.floor(Math.random()*C),G={start:x,end:x+(p==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},L=0;for(let z of i.getKeys({start:x,limit:1,reverse:!0}))L=z;B=C;for(let z of i.getKeys({start:x+1,end:C,limit:1}))B=z;I*=.875,I<1e3&&!N&&(N=!0,xe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${p==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,L,B,I))}while(!(I<B-x&&(I<x-L||L===0)));return i.transactionSync(()=>{let z=i.getEntry(Symbol.for("id_allocation"));return(z?.version??null)==b?(xe.default.info?.("Allocated new id range",G),i.put(Symbol.for("id_allocation"),G,Date.now()),G):(xe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...z.value})})}}static setTTLExpiration(p){if(typeof p=="number")m=p*1e3,S||(S=0);else if(p&&typeof p=="object")m=p.expiration*1e3,S=(p.eviction||0)*1e3,jt=p.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(m<0)throw new Error("Expiration can not be negative");jt=jt||(m+S)/4,$i()}static getResidencyRecord(p){return f.get([Symbol.for("residency_by_id"),p])}static setResidency(p){Ce.getResidency=p&&((O,A)=>{try{return p(O,A)}catch(y){throw y.message+=` in residency function for table ${s}`,y}})}static setResidencyById(p){Ce.getResidencyById=p&&(O=>{try{return p(O)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(p,O){if(Ce.getResidencyById)return Ce.getResidencyById(p[t]);let A=kd;if(O.replicateTo!=null){if(Array.isArray(O.replicateTo))return O.replicateTo.includes(server.hostname)?O.replicateTo:[server.hostname,...O.replicateTo];O.replicateTo>=0&&(A=O.replicateTo)}if(A>=0&&server.nodes){let y=[server.hostname];if(O.previousResidency)y.push(...O.previousResidency.slice(0,A));else{let b=server.nodes.map(L=>L.name),C=Math.floor(b.length*Math.random());y.push(...b.slice(C,C+A));let I=C+A-b.length;I>0&&y.push(...b.slice(0,I))}return y}}static enableAuditing(p=!0){g=p,p&&Vd(),Ce.audit=p}static coerceId(p){return p===""?null:HT(p,H)}static async dropTable(){delete Ve[c][s];for(let p of i.getRange({versions:!0,snapshot:!1,lazy:!0}))p.metadataFlags&pn&&p.value&&ta(p.value);if(c===o){for(let p of E)f.remove(Ce.tableName+"/"+p.name),r[p.name]?.drop();f.remove(Ce.tableName+"/"),i.drop(),await f.committed}else console.log("legacy dropTable"),await i.close(),await BT.default.remove(data_path),await BT.default.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));cm.signalSchemaChange(new lm.SchemaEventMsg(process.pid,Gt.DROP_TABLE,c,s))}get(p){if(typeof p=="string")return this.getProperty(p);if(this.isCollection)return this.search(p);if(this.getId()===null){if(p?.conditions||p?.size>0)return this.search(p);let O={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:E};return this.getContext()?.includeExpensiveRecordCountEstimates?Ce.getRecordCount().then(A=>(O.recordCount=A.recordCount,O.estimatedRecordRange=A.estimatedRange,O)):O}if(p?.property)return this.getProperty(p.property);if(this.doesExist()||p?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(p,O){let A=Fr(p);if(A?.read){if(A.isSuperUser)return!0;let y=A.attribute_permissions,b=O?.select;if(y?.length>0||vl&&b){if(O||(O={}),b){let C=y?.length>0&&WC(y,"read");O.select=b.map(I=>{let L=I.name||I;if(!C||C[L]){let B=Dn[L]?.definition?.tableClass;if(B){if(I.name||(I={name:I}),!B.prototype.allowRead.call(null,p,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else O.select=y.filter(C=>C.read&&!Dn[C.attribute_name]).map(C=>C.attribute_name);return O}else return!0}}allowUpdate(p,O){let A=Fr(p);if(A?.update){let y=A.attribute_permissions;if(y?.length>0){let b=WC(y,"update");for(let C in O)if(!b[C])return!1;for(let C of y){let I=C.attribute_name;!C.update&&!(I in O)&&(O[I]=this.getProperty(I))}}return kl(this.getContext())}}allowCreate(p,O){if(this.isCollection){let A=Fr(p);if(A?.insert){let y=A.attribute_permissions;if(y?.length>0){let b=WC(y,"insert");for(let C in O)if(!b[C])return!1;return kl(this.getContext())}else return kl(this.getContext())}}else return this.allowUpdate(p,{})}allowDelete(p){return Fr(p)?.delete&&kl(this.getContext())}update(p,O){if(!Gr(this.getContext()))throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let y;return typeof p=="object"&&p&&(O?(Object.isFrozen(p)&&(p={...p}),this.#e={},this.#t=p):(y=this.#t,y&&(p=Object.assign(y,p)),this.#t=p)),this._writeUpdate(this.#t,O),this}addTo(p,O){if(typeof O=="number"||typeof O=="bigint")this.#s===tj?this.set(p,(+this.getProperty(p)||0)+O):(this.#s||this.update(),this.set(p,new cE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(p,O){if(typeof O=="number")return this.addTo(p,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(p){this.#t=p}setRecord(p){this.#e=p}invalidate(){this._writeInvalidate()}_writeInvalidate(p,O){let A=this.getContext(),y=this.getId();wr(y),Gr(this.getContext()).addWrite({key:y,store:i,invalidated:!0,entry:this.#r,before:Te.invalidate?.bind(this,A,y),beforeIntermediate:ye.invalidate?.bind(this,A,y),commit:a((C,I)=>{if(!(qi(C,I,O?.nodeId)<=0)){p??=null;for(let L in r)p||(p={}),p[L]===void 0&&(p[L]=this.getProperty(L));xe.default.trace?.(`Invalidating entry id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,p,this.#r,C,_n,g,{user:A?.user,residencyId:O?.residencyId,nodeId:O?.nodeId},"invalidate")}},"commit")})}_writeRelocate(p){let O=this.getContext(),A=this.getId();wr(A),Gr(this.getContext()).addWrite({key:A,store:i,invalidated:!0,entry:this.#r,before:Te.relocate?.bind(this,O,A),beforeIntermediate:ye.relocate?.bind(this,O,A),commit:a((b,C)=>{if(qi(b,C,p?.nodeId)<=0)return;let I=Ce.getResidencyRecord(p.residencyId),L=0,B=null,N=C?.value;if(I&&!I.includes(server.hostname)){for(let x in r)B||(B={}),B[x]=N(x);L=_n}else B=N;xe.default.trace?.(`Relocating entry id: ${A}, timestamp: ${new Date(b).toISOString()}`),T(A,B,this.#r,b,L,g,{user:O.user,residencyId:p.residencyId,nodeId:p.nodeId,expiresAt:p.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(p,O){let A={previousResidency:this.getResidencyRecord(p.residencyId),isRelocation:!0},y=Vi(this.getResidency(O.value,A)),b;if(y){if(!y.includes(server.hostname))return!1;b=Za(y)}let I=T(p.key,O.value,p,p.version,0,!0,{residencyId:b,expiresAt:O.expiresAt},"relocate",!1,null);return!0}static evict(p,O,A){let y=this.Source,b;if(!((v||g)&&(!O||(b=i.getEntry(p),!b||!O)||b.version!==A))){if(v){if(i.hasLock(p,b.version))return;let C;for(let I in r)C||(C={}),C[I]=O[I];if(C)return T(p,C,b,A,Xo,null,null,null,!0)}if(i.ifVersion(p,A,()=>{on(p,O,null)}),g)return T(p,null,b,A,Xo,null,null,null,!0);Sc(i,b??i.getEntry(p),A)}}lock(){throw new Error("Not yet implemented")}static operation(p,O){return p.table||=s,p.schema||=c,lj.operation(p,O)}put(p){this.update(p,!0)}patch(p){this.update(p,!1)}_writeUpdate(p,O,A){let y=this.getContext(),b=Gr(y),C=this.getId();wr(C);let I=this.#r;this.#s=O?tj:MSe;let L={key:C,store:i,entry:I,nodeName:y?.nodeName,validate:a(B=>{p||(p=this.#t),O||p&&oE(this.#t===p?this:p)?y?.source||(b.checkOverloaded(),this.validate(p,!O),te&&(p[te.name]=te.type==="Date"?new Date(B):te.type==="String"?new Date(B).toISOString():B),O&&(t&&p[t]!==C&&(p[t]=C),W&&(I?.value?p[W.name]=I?.value[W.name]:p[W.name]=W.type==="Date"?new Date(B):W.type==="String"?new Date(B).toISOString():B),p=xc(p))):b.removeWrite(L)},"validate"),before:O?Te.put?()=>Te.put(y,C,p):null:Te.patch?()=>Te.patch(y,C,p):Te.put?()=>Te.put(y,C,xc(this)):null,beforeIntermediate:O?ye.put?()=>ye.put(y,C,p):null:ye.patch?()=>ye.patch(y,C,p):ye.put?()=>ye.put(y,C,xc(this)):null,commit:a((B,N,x)=>{if(x){if(y&&N?.version>(y.lastModified||0)&&(y.lastModified=N.version),this.#r=N,N?.value&&N.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");O||(this.#e=N?.value??null)}this.#t=void 0,this.#n=B;let G=N?.value,z=p;this.#s=0;let ie=!1,F=qi(B,N,A?.nodeId),qe;if(F<=0)if(g){let _e=N.localTime,fe=N.version;xe.default.trace?.("Applying CRDT update to record with id: ",C,"applying later update:",fe);let Ae=[];for(;_e>B||fe>=B&&_e>0;){let De=l.get(_e);if(!De)break;let we=Nt(De);if(fe=we.version,fe>=B){if(fe===B){if(F=qi(B,{version:fe,localTime:_e},A?.nodeId),F===0)return;if(F>0)continue}if(we.type==="patch")Ae.push(we),qe=p;else if(we.type==="put"||we.type==="delete")return}_e=we.previousLocalTime}Ae.sort((De,we)=>De.version-we.version);for(let De of Ae){let we=De.getValue(i);if(z=sE(z,we,O),xe.default.debug?.("Rebuilding update with future patch:",z),!z)return}}else{if(O)return;z=sE(z,G,O),xe.default.debug?.("Rebuilding update without audit:",z)}let Z;if(O?Z=z:(this.#e=G,Z=xc(this,z)),this.#e=Z,Z&&Z.getRecord)throw new Error("Can not assign a record to a record, check for circular references");let ce;if(A?.residencyId!=null)ce=A.residencyId;else{I?.residencyId&&(y.previousResidency=Ce.getResidencyRecord(I.residencyId));let _e=Vi(Ce.getResidency(Z,y));if(_e&&!_e.includes(server.hostname))if(qe??=Z,ie=!0,Ce.getResidencyById)Z=void 0;else{Z=null;for(let fe in r)Z||(Z={}),Z[fe]=qe[fe]}ce=Za(_e)}O||(qe=p);let ee=y?.expiresAt??(m?m+Date.now():-1);xe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(B).toISOString()}${ee?", expires at: "+new Date(ee).toISOString():""}${N?", replaces entry from: "+new Date(N.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(Z).slice(0,100)}catch{return""}})()),on(C,G,Z);let Q=O?"put":"patch";T(C,Z,N,B,ie?_n:0,g,{omitLocalRecord:ie,user:y?.user,residencyId:ce,expiresAt:ee,nodeId:A?.nodeId,originatingOperation:y?.originatingOperation},Q,!1,qe),y.expiresAt&&$i()},"commit")};b.addWrite(L)}async delete(p){if(typeof p=="string")return this.deleteProperty(p);if(this.isCollection){for await(let O of this.search(p))(await Ce.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(p);return}return this.#e?this._writeDelete(p):!1}_writeDelete(p){let O=Gr(this.getContext()),A=this.getId();wr(A);let y=this.getContext();return O.addWrite({key:A,store:i,entry:this.#r,nodeName:y?.nodeName,before:Te.delete?.bind(this,y,A),beforeIntermediate:ye.delete?.bind(this,y,A),commit:a((b,C,I)=>{let L=C?.value;I&&(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),Ce._updateResource(this,C)),!(qi(b,C,p?.nodeId)<=0)&&(on(this.getId(),L),xe.default.trace?.(`Deleting record with id: ${A}, txn timestamp: ${new Date(b).toISOString()}`),g||R?(T(A,null,this.#r,b,0,g,{user:y?.user,nodeId:p?.nodeId},"delete"),g||$i()):Sc(i,C))},"commit")}),!0}search(p){let O=this.getContext(),A=Gr(O);if(!p)throw new Error("No query provided");let y=p.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this.getId()&&(y=[{attribute:null,comparator:Array.isArray(this.getId())?"prefix":"starts_with",value:this.getId()}].concat(y));let b,C={};function I(Q,_e){let fe;switch(_e){case"and":case void 0:if(Q.length<1)throw new Error('An "and" operator requires at least one condition');fe=!0;break;case"or":if(Q.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+_e)}for(let Ae of Q){if(Ae.conditions){Ae.conditions=I(Ae.conditions,Ae.operator);continue}let De=Ae[0]??Ae.attribute,we=De==null?H:fi(E,De);if(we)(we.type||UA[Ae.comparator])&&(Ae[1]===void 0?Ae.value=B(Ae.value,we):Ae[1]=B(Ae[1],we));else if(De!=null)throw(0,Nr.handleHDBError)(new Error,`${De} is not a defined attribute`,404);if(Ae.chainedConditions)if(Ae.chainedConditions.length===1&&(!Ae.operator||Ae.operator=="and")){let _r=Ae.chainedConditions[0],Ir,Ls;if(_r.comparator==="gt"||_r.comparator==="greater_than"||_r.comparator==="ge"||_r.comparator==="greater_than_equal"?(Ir=Ae,Ls=_r):(Ir=_r,Ls=Ae),Ir.comparator!=="lt"&&Ir.comparator!=="less_than"&&Ir.comparator!=="le"&&Ir.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Re=Ls.comparator==="ge"||Ls.comparator==="greater_than_equal",Rt=Ir.comparator==="le"||Ir.comparator==="less_than_equal";Ae.comparator=(Re?"ge":"gt")+(Rt?"le":"lt"),Ae.value=[Ls.value,Ir.value]}else throw new Error("Multiple chained conditions are not currently supported")}return Q}a(I,"prepareConditions");function L(Q,_e){if(p.enforceExecutionOrder)return Q;for(let fe of Q)fe.conditions&&(fe.conditions=L(fe.conditions,fe.operator));return Q.length>1&&_e!=="or"?(0,aj.sortBy)(Q,Qm(Ce)):Q}a(L,"orderConditions");function B(Q,_e){return Array.isArray(Q)?Q.map(fe=>HT(fe,_e)):HT(Q,_e)}a(B,"coerceTypedValues");let N=p.operator;(y.length>0||N)&&(y=I(y,N));let x=typeof p.sort=="object"&&p.sort,G;if(x&&N!=="or"){let Q=x.attribute;if(Q==null)throw new Nr.ClientError("Sort requires an attribute");if(b=y.find(_e=>jl(_e.attribute)===jl(Q)),!b){let _e=fi(E,Q);if(!_e)throw(0,Nr.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not a defined attribute`,404);if(_e.indexed)b={attribute:Q,comparator:"sort"},y.push(b);else if(y.length===0&&!p.allowFullScan)throw(0,Nr.handleHDBError)(new Error,`${Array.isArray(Q)?Q.join("."):Q} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!x.descending)}y=L(y,N),x&&(b&&y[0]===b?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(b&&y.splice(y.indexOf(b),1),G=x));let z=p.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),p.explain)return{conditions:y,operator:N,postOrdering:G,selectApplied:!!z};let ie=A.useReadTxn(),F=xA(y,N,Ce,ie,p,O,(Q,_e)=>qd(Q,z,O,ie,_e),C),qe=p.ensureLoaded!==!1;G||(F=ee(F));let Z=Ce.transformEntryForSelect(z,O,ie,C,qe,!0),ce=Ce.transformToOrderedSelect(F,z,G,ie,O,Z);function ee(Q){return p.offset||p.limit!==void 0?Q.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0):Q}return a(ee,"applyOffset"),G&&(ce=ee(ce)),ce.onDone=()=>{ce.onDone=null,A.doneReadTxn()},ce.selectApplied=!0,ce.getColumns=()=>{if(z){let Q=[];for(let _e of z)_e==="*"?Q.push(...E.map(fe=>fe.name)):Q.push(_e.name||_e);return Q}return E.filter(Q=>!Q.computed&&!Q.relationship).map(Q=>Q.name)},ce}static transformToOrderedSelect(p,O,A,y,b,C){let I=new Em;if(A){p=qd(p,O,y,b,null);let L;I.iterate=function(){let N,x=p[Symbol.asyncIterator]?p[Symbol.asyncIterator]():p[Symbol.iterator](),G,z=A.dbOrderedAttribute,ie,F,qe=!0;function Z(ee){let Q=ee.next&&Z(ee.next),_e=ee.descending;return(fe,Ae)=>{let De=Hl(fe,ee.attribute,y),we=Hl(Ae,ee.attribute,y),_r=_e?(0,Ll.compareKeys)(we,De):(0,Ll.compareKeys)(De,we);return _r===0?Q?.(fe,Ae)||0:_r}}a(Z,"createComparator");let ce=Z(A);return{async next(){let ee;if(N)if(ee=N.next(),ee.done){if(G)return I.onDone&&I.onDone(),ee}else return{value:await C.call(this,ee.value)};L=[],ie&&L.push(ie);do if(ee=await x.next(),ee.done){if(G=!0,L.length)break;return I.onDone&&I.onDone(),ee}else{let Q=ee.value;if(Q?.then&&(Q=await Q),z){let _e=Hl(Q,z,y);if(qe)qe=!1,F=_e;else if(_e!==F){F=_e,ie=Q;break}}L.push(Q)}while(!0);return A.isGrouped,L.sort(ce),N=L[Symbol.iterator](),ee=N.next(),ee.done?(I.onDone&&I.onDone(),ee):{value:await C.call(this,ee.value)}},return(){I.onDone&&I.onDone(),x.return()},throw(){I.onDone&&I.onDone(),x.throw()}}};let B=a(N=>{if(typeof O=="object"&&Array.isArray(N.attribute))for(let x=0;x<O.length;x++){let G=O[x],z;if(G.name===N.attribute[0]){for(z=G.sort||(G.sort={});z.next;)z=z.next;z.attribute=N.attribute.slice(1),z.descending=N.descending}else G===N.attribute[0]&&(O[x]=z={name:G,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&B(N.next)},"applySortingOnSelect");B(A)}else I.iterate=(p[Symbol.asyncIterator]||p[Symbol.iterator]).bind(p),I=I.map(function(L){try{let B=C.call(this,L);return typeof B?.catch=="function"?B.catch(N=>{throw N.partialObject={[t]:L.key},N}):B}catch(B){throw B.partialObject={[t]:L.key},B}});return I}static transformEntryForSelect(p,O,A,y,b,C){if(p&&(p===t||p?.length===1&&p[0]===t&&Array.isArray(p))){let N=a(x=>(O?.transaction?.stale&&(O.transaction.stale=!1),x?.key??x),"transform");return p===t?N:p.asArray?x=>[N(x)]:x=>({[t]:N(x)})}let I;b&&v&&!(typeof p=="string"?[p]:p)?.every(N=>{let x;return typeof N=="object"?x=N.name:x=N,r[x]||x===t})&&(I=!0);let L,B=a(function(N){let x;if(O?.transaction?.stale&&(O.transaction.stale=!1),N!=null){if(x=N.value||N.deref?.()?.value,!x&&(N.key===void 0||N.deref)||N.metadataFlags&_n){if(N.metadataFlags&_n&&O.replicateFrom===!1&&C&&N.residencyId)return Qa.SKIP;if(N=xl(N.key??N,O,{transaction:A,lazy:p?.length<4,ensureLoaded:b},this?.isSync,G=>G),N?.then)return N.then(B.bind(this));x=N?.value}if(I&&N?.metadataFlags&(_n|Xo)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(O.onlyIfCached&&O.noCacheStore)return{[t]:N.key,message:"This entry has expired"};let G=Bl(N.key??N,N,O);if(G?.then)return G.then(B)}}if(x==null)return C?Qa.SKIP:x;if(p&&!(p[0]==="*"&&p.length===1)){let G,z=a((F,qe)=>{let Z;typeof F=="object"?Z=F.name:Z=F;let ce=Dn?.[Z],ee;if(ce){let Q=y?.[Z];if(Q)if(Q.hasMappings){let fe=ce.from?x[ce.from]:jl(N.key);ee=Q.get(fe),ee||(ee=[])}else ee=Q.fromRecord?.(x);else ee=ce(x,O,N);let _e=a(fe=>{if(fe&&typeof fe=="object"){let Ae=ce.definition?.tableClass||Ce;L||(L={});let De=L[Z]||(L[Z]=Ae.transformEntryForSelect(Z===F?null:F.select||(Array.isArray(F)?F:null),O,A,Q,b));if(Array.isArray(fe)){let we=[],_r=Ae.transformToOrderedSelect(fe,F.select,typeof F.sort=="object"&&F.sort,O,A,De)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ir=a(Re=>{for(;!Re.done;){if(Re?.then)return Re.then(Ir);we.push(Re.value),Re=_r.next()}qe(we,Z)},"nextValue"),Ls=Ir(_r.next());Ls&&(G||(G=[]),G.push(Ls));return}else if(fe=De.call(this,fe),fe?.then){G||(G=[]),G.push(fe.then(we=>qe(we,Z)));return}}qe(fe,Z)},"handleResolvedValue");ee?.then?(G||(G=[]),G.push(ee.then(_e))):_e(ee);return}else ee=x[Z],ee&&typeof ee=="object"&&Z!==F&&(ee=Ce.transformEntryForSelect(F.select||F,O,A,null)({value:ee}));qe(ee,Z)},"selectAttribute"),ie;if(typeof p=="string")z(p,F=>{ie=F});else if(Array.isArray(p))if(p.asArray)ie=[],p.forEach((F,qe)=>{F==="*"?p[qe]=x:z(F,Z=>ie[qe]=Z)});else{ie={};let F=p.forceNulls;for(let qe of p)if(qe==="*")for(let Z in x)ie[Z]=x[Z];else z(qe,(Z,ce)=>{Z===void 0&&F&&(Z=null),ie[ce]=Z})}else throw new Nr.ClientError("Invalid select"+p);return G?Promise.all(G).then(()=>ie):ie}return x},"transform");return B}async subscribe(p){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||dt({table:s,database:c,schemaDefined:u,attributes:E,audit:!0}),p||(p={});let O=!p.rawEvents,A=[],y=this,b=YC(Ce,this.getId()??null,function(I,L,B,N){try{let x=L.getValue?.(i,O),G=L.type;if(!x&&G==="patch"&&O){let ie=i.getEntry(I);ie?.version===L.version?x=ie.value:x=L.getValue?.(i,!0,B),G="put"}let z={id:I,localTime:B,value:x,version:L.version,type:G,beginTxn:N};A?A.push(z):this.send(z)}catch(x){xe.default.error?.(x)}},p.startTime||0,p),C=(async()=>{this.isCollection&&(b.includeDescendants=!0,p.onlyChildren&&(b.onlyChildren=!0)),p.supportsTransactions&&(b.supportsTransactions=!0);let I=this.getId(),L=p.previousCount;L>1e3&&(L=1e3);let B=p.startTime;if(this.isCollection){if(B){if(L)throw new Nr.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:x}of l.getRange({start:B,exclusiveStart:!0,snapshot:!1})){let G=Nt(x);if(G.tableId!==n)continue;let z=G.recordId;if(I==null||ij(I,z)){let ie=G.getValue(i,O,N);if(b.send({id:z,localTime:N,value:ie,version:G.version,type:G.type}),b.queue?.length>nj&&await b.waitForDrain()===!1)return}b.startTime=N}}else if(L){let N=[];for(let{key:x,value:G}of l.getRange({start:"z",end:!1,reverse:!0}))try{let z=Nt(G);if(z.tableId!==n)continue;let ie=z.recordId;if(I==null||ij(I,ie)){let F=z.getValue(i,O,x);if(N.push({id:ie,localTime:x,value:F,version:z.version,type:z.type}),--L<=0)break}}catch(z){xe.default.error("Error getting history entry",x,z)}for(let x=N.length;x>0;)b.send(N[--x]);N[0]&&(b.startTime=N[0].localTime)}else if(!p.omitCurrent){for(let{key:N,value:x,version:G,localTime:z}of i.getRange({start:I??!1,end:I==null?void 0:[I,Ll.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(b.send({id:N,localTime:z,value:x,version:G,type:"put"}),b.queue?.length>nj&&await b.waitForDrain()===!1))return}}else{L&&!B&&(B=0);let N=this.#r?.localTime;if(N===pR&&(i.cache?.delete(I),this.#r=i.getEntry(I),xe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),xe.default.trace?.("Subscription from",B,"from",I,N),B<N){let x=[],G=N;do{let z=l.get(G);if(z){p.omitCurrent=!0;let ie=Nt(z),F=ie.getValue(i,O,G);O&&(ie.type="put"),x.push({id:I,value:F,localTime:G,...ie}),G=ie.previousLocalTime}else break;L&&L--}while(G>B&&L!==0);for(let z=x.length;z>0;)b.send(x[--z]);b.startTime=N}!p.omitCurrent&&this.doesExist()&&b.send({id:I,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of A)b.send(N);A=null})();return p.listener&&b.on("data",p.listener),b}static subscribeOnThisThread(p,O){return p===0||O?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(p,O){this._writePublish(p,O)}_writePublish(p,O){let A=Gr(this.getContext()),y=this.getId()||null;y!=null&&wr(y);let b=this.getContext();A.addWrite({key:y,store:i,entry:this.#r,nodeName:b?.nodeName,validate:a(()=>{b?.source||(A.checkOverloaded(),this.validate(p))},"validate"),before:Te.publish?.bind(this,b,y,p),beforeIntermediate:ye.publish?.bind(this,b,y,p),commit:a((C,I,L)=>{I===void 0&&R&&!g&&$i(),xe.default.trace?.(`Publishing message to id: ${y}, timestamp: ${new Date(C).toISOString()}`),T(y,I?.value??null,I,I?.version||C,0,!0,{user:b?.user,residencyId:O?.residencyId,expiresAt:b?.expiresAt,nodeId:O?.nodeId},"message",!1,p)},"commit")})}validate(p,O){let A,y=a((b,C,I)=>{if(C.type&&b!=null)if(O&&b.__op__&&(b=b.value),C.properties){typeof b!="object"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an object${C.type?" ("+C.type+")":""}`);let L=C.properties;for(let B=0,N=L.length;B<N;B++){let x=L[B],G=y(b[x.name],x,I+"."+x.name);G&&(b[x.name]=G)}if(C.sealed&&b!=null&&typeof b=="object")for(let B in b)L.find(N=>N.name===B)||(A||(A=[])).push(`Property ${B} is not allowed within object in property ${I}`)}else switch(C.type){case"Int":(typeof b!="number"||b>>0!==b)&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(L=>typeof L=="string")||(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a string`);break;case"Boolean":typeof b!="boolean"&&(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a bigint`)}break;case"Bytes":if(!(b instanceof Uint8Array)){if(typeof b=="string")return Buffer.from(b);(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(b instanceof hi)){if(typeof b=="string"&&(b=Buffer.from(b)),b instanceof Buffer)return createBlob(b,{type:"text/plain"});(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be a Blob`)}break;case"array":if(Array.isArray(b)){if(C.elements)for(let L=0,B=b.length;L<B;L++){let N=b[L],x=y(N,C.elements,I+"[*]");x&&(b[L]=x)}}else(A||(A=[])).push(`Value ${Ds(b)} in property ${I} must be an Array`);break}C.nullable===!1&&b==null&&(A||(A=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let b=0,C=E.length;b<C;b++){let I=E[b];if(!(I.relationship||I.computed)&&(!O||I.name in p)){let L=y(p[I.name],I,I.name);L&&(p[I.name]=L)}}if(d)for(let b in p)E.find(C=>C.name===b)||(A||(A=[])).push(`Property ${b} is not allowed`);if(A)throw new Nr.ClientError(A.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return v?!!this.#i:void 0}static async addAttributes(p){let O=E.slice(0);for(let A of p){if(!A.name)throw new Nr.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new Nr.ClientError("Attribute names cannot include backticks or forward slashes");(0,cj.validateAttribute)(A.name),O.push(A)}return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static async removeAttributes(p){let O=E.filter(A=>!p.includes(A.name));return dt({table:s,database:c,schemaDefined:u,attributes:O}),Ce.indexingOperation}static getSize(){let p=i.getStats();return(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getAuditSize(){let p=l?.getStats();return p&&(p.treeBranchPageCount+p.treeLeafPageCount+p.overflowPages)*p.pageSize}static getStorageStats(){let p=i.env.path,O=BT.default.statfsSync?.(p)??{};return{available:O.bavail*O.bsize,free:O.bfree*O.bsize,size:O.blocks*O.bsize}}static async getRecordCount(p){let O=i.getStats().entryCount,A=1e3/2,y=performance.now(),b=Math.floor(O/2),C=p?.exactCount,I=0,L=0,B;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&I++,L++,await ja(),!C&&L<b&&performance.now()-y>A){B=L;break}if(B){let N=I;I=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:B,snapshot:!1}))ee!=null&&I++,await ja();let x=B*2,G=(I+N)/x,z=Math.pow((I-N+1)/B/2,2)+G*(1-G)/x,ie=Math.max(Math.sqrt(z)*O,1),F=Math.round(G*O),qe=Math.max(F-1.96*ie,I+N),Z=Math.min(F+1.96*ie,O),ce=Math.pow(10,Math.round(Math.log10(ie)));return ce>F&&(ce=ce/10),I=Math.round(F/ce)*ce,{recordCount:I,estimatedRange:[Math.round(qe),Math.round(Z)]}}return{recordCount:I}}static updatedAttributes(){Dn=this.propertyResolvers={$id:a((p,O,A)=>({value:A.key}),"$id"),$updatedtime:a((p,O,A)=>A.version,"$updatedtime"),$record:a((p,O,A)=>A?{value:p}:p,"$record")};for(let p of this.attributes){p.isPrimaryKey&&(H=p),p.resolve=null;let O=p.relationship,A=p.computed;if(O)if(p.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),A&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),vl=!0,O.to)p.elements?.definition?(Dn[p.name]=p.resolve=(y,b,C)=>{let I=y[O.from?O.from:t],L=p.elements.definition.tableClass;return C?zl({attribute:O.to,value:I},Gr(b).getReadTxn(),!1,L,!1).asArray:L.search([{attribute:O.to,value:I}],b).asArray},p.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},p.resolve.definition=p.elements.definition,O.from&&(p.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${p.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let y=p.definition||p.elements?.definition;y?(Dn[p.name]=p.resolve=(b,C,I)=>{let L=b[O.from];if(L!==void 0){if(p.elements){let B,N=L?.map(x=>{let G=I?y.tableClass.primaryStore.getEntry(x,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(x,C);return G?.then&&(B=!0),G});return O.filterMissing?B?Promise.all(N).then(x=>x.filter(oj)):N.filter(oj):B?Promise.all(N):N}return I?y.tableClass.primaryStore.getEntry(L,{transaction:Gr(C).getReadTxn()}):y.tableClass.get(L,C)}},p.set=(b,C)=>{if(Array.isArray(C)){let I=C.map(L=>L.getId?.()||L[y.tableClass.primaryKey]);b[O.from]=I}else{let I=C.getId?.()||C[y.tableClass.primaryKey];b[O.from]=I}},p.resolve.definition=p.definition||p.elements?.definition,p.resolve.from=O.from):console.error(`The relationship property "${p.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${p.name}" in table "${s}" must use either "from" or "to" arguments`);else A&&(typeof A.from=="function"&&this.setComputedAttribute(p.name,A.from),Dn[p.name]=p.resolve=(y,b,C)=>{let I=typeof A.from=="string"?y[A.from]:y,L=this.userResolvers[p.name];if(L)return L(I,b,C);xe.default.warn(`Computed attribute "${p.name}" does not have a function assigned to it. Please use setComputedAttribute('${p.name}', resolver) to assign a resolver function.`),this.userResolvers[p.name]=()=>{}})}lE(this,this)}static setComputedAttribute(p,O){let A=fi(E,p);if(!A){console.error(`The attribute "${p}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${p}" is not defined as computed in the table "${s}"`);return}this.userResolvers[p]=O}static async deleteHistory(p=0,O=!1){let A;for(let{key:y,value:b}of l.getRange({start:0,end:p}))await ja(),Nt(b).tableId===n&&(A=UT(l,y,b));if(O)for(let y of i.getRange({start:0,versions:!0})){let{key:b,value:C,localTime:I}=y;await ja(),C===null&&I<p&&(A=Sc(i,y))}await A}static async*getHistory(p=0,O=1/0){for(let{key:A,value:y}of l.getRange({start:p||1,end:O})){await ja();let b=Nt(y);b.tableId===n&&(yield{id:b.recordId,localTime:A,version:b.version,type:b.type,value:b.getValue(i,!0,A),user:b.user,operation:b.originatingOperation})}}static async getHistoryOfRecord(p){let O=[];if(p==null)throw new Error("An id is required");let A=i.getEntry(p);if(!A)return O;let y=A.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await ja();let C=l.get(y);if(C){let I=Nt(C);O.push({id:I.recordId,localTime:y,version:I.version,type:I.type,value:I.getValue(i,!0,y),user:I.user}),y=I.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){Y?.remove()}}Ce.updatedAttributes();let Gd=Ce.prototype;return m&&Ce.setTTLExpiration(m/1e3),se&&Sm(),Ce;function on(K,p,O){let A;for(let y in r){let b=r[y],C=b.isIndexing,I=Dn[y],L=O&&(I?I(O):O[y]),B=p&&(I?I(p):p[y]);if(L===B&&!C)continue;A=!0;let N=b.indexNulls,x=(0,am.getIndexedValues)(L,N),G=(0,am.getIndexedValues)(B,N);if(G?.length>0){let z=new Set(G);if(x=x?x.filter(ie=>{if(z.has(ie))z.delete(ie);else return!0}):[],G=Array.from(z),(G.length>0||x.length>0)&&ej){let ie=G.concat(x).map(F=>({key:F,value:K}));b.prefetch(ie,sj)}for(let ie=0,F=G.length;ie<F;ie++)b.remove(G[ie],K)}else x?.length>0&&ej&&b.prefetch(x.map(z=>({key:z,value:K})),sj);if(x)for(let z=0,ie=x.length;z<ie;z++)b.put(x[z],K)}return A}a(on,"updateIndices");function wr(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>rj)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Ll.writeKey)(K,vSe,0)>rj)throw new Error("Primary key size is too large: "+K.length);return!0}a(wr,"checkValidId");function xl(K,p,O,A,y){if(Ce.getResidencyById&&O.ensureLoaded&&p?.replicateFrom!==!1){let C=Vi(Ce.getResidencyById(K));if(C&&!C.includes(server.hostname)&&w)return w({key:K,residency:C}).then(y)}let b=a(()=>{if(p?.transaction?.stale&&(p.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let C=i.getEntry(K,O);return C?.residencyId&&C.metadataFlags&_n&&w&&O.ensureLoaded&&p?.replicateFrom!==!1?w(C).then(I=>y(I,K),I=>(xe.default.error?.("Error loading remote record",K,C,O,I),y(null,K))):(C&&p&&(C?.version>(p.lastModified||0)&&(p.lastModified=C.version),C?.localTime&&!p.lastRefreshed&&(p.lastRefreshed=C.localTime)),y(C,K))},"whenPrefetched");return A?b():oe>0?(oe--,b()):new Promise((C,I)=>{oe===0?(oe--,i.prefetch([K],()=>{L(),B()})):(ne.push(K),ue.push(B),ne.length>gm&&(oe--,L()));function L(){if(ne.length>0){let N=ue;i.prefetch(ne,()=>{oe===-1?L():oe++;for(let x of N)x()}),ne=[],ue=[],pe>2&&pe--}else oe=pe,pe<Fd&&pe++}a(L,"prefetch");function B(){try{C(b())}catch(N){I(N)}}a(B,"load")})}a(xl,"loadLocalRecord");function Fr(K){if(!K?.role)return;let p=K.role.permission;if(p.super_user)return USe;let O=p[c],A,y=O?.tables;if(y)return y[s];if(c==="data"&&(A=p[s])&&!A.tables)return A}a(Fr,"getTablePermissions");function Bl(K,p,O,A){if(v){let y=!1;if(O.noCache?y=!0:(p?(!p.value||p.metadataFlags&(_n|Xo)||p.expiresAt!=null&&p.expiresAt<Date.now())&&(y=!0):y=!0,Yn(!y,"cache-hit",s)),y){let b=$d(K,p,O).then(C=>(C?.value&&C?.value.getRecord?.()&&xe.default.error?.("Can not assign a record that is already a resource"),O&&(C?.version>(O.lastModified||0)&&(O.lastModified=C.version),O.lastRefreshed=Date.now()),C));if(O?.onlyIfCached||p?.value&&A?.allowStaleWhileRevalidate?.(p,K)){if(b.catch(C=>xe.default.warn?.(C)),O?.onlyIfCached&&!A.doesExist())throw new Nr.ServerError("Entry is not cached",504);return}else return b}}else if(p?.value&&p.expiresAt!=null&&p.expiresAt<Date.now())return Ce.evict(p.key,p.value,p.version),p.value=null,{then(y){return y(p)}}}a(Bl,"ensureLoadedFromSource");function Gr(K){let p=K?.transaction;if(p){if(!p.lmdbDb)return p.lmdbDb=i,p;do{if(p.lmdbDb?.path===i.path)return p;let O=p.next;if(!O)return p=p.next=new ac,p.lmdbDb=i,p;p=O}while(!0)}else return new Wm}a(Gr,"txnForContext");function Hl(K,p,O){if(!K)return;let A=K.value||i.getEntry(K.key)?.value;if(typeof p=="object"){let b=Dn,C=A;for(let I=0,L=p.length;I<L;I++){let B=p[I],N=b?.[B];C=N&&C?N(C,O,!0)?.value:C?.[B],b=N?.definition?.tableClass?.propertyResolvers}return C}let y=Dn[p];return y?y(A,O):A[p]}a(Hl,"getAttributeValue");function qd(K,p,O,A,y){let b=y?.length,C={transaction:A,lazy:b>0||typeof p=="string"||p?.length<4,alwaysPrefetch:!0},I;function L(B,N){let x=B?.value;if(!x)return Qa.SKIP;for(let G=0;G<b;G++)if(!I?.includes(G)&&!y[G](x,B))return Qa.SKIP;return N!==void 0&&(B.key=N),B}if(a(L,"processEntry"),b>0||!K.hasEntries){let B=K.map(N=>{if(I=null,typeof N=="object"&&N?.key!==void 0)return b>0?L(N):N;if(N==null)return Qa.SKIP;for(let x=0;x<b;x++){let z=y[x].idFilter;if(z){if(!z(N))return Qa.SKIP;I||(I=[]),I.push(x)}}return xl(N,O,C,!1,L)});return Array.isArray(K)&&(B=B.filter(N=>N!==Qa.SKIP)),B.hasEntries=!0,B}return K}a(qd,"transformToEntries");function qi(K,p,O=server.replication?.getThisNodeId(l)){if(K<=p?.version){if(p?.version===K&&O!==void 0){let A=server.replication?.exportIdMapping(l),y=p.localTime,b=y&&l.get(y);if(b){let C,I,L=Nt(b);for(let B in A)A[B]===O&&(C=B),A[B]===L.nodeId&&(I=B);if(C>I)return 1;if(C===I)return 0}}return-1}return 1}a(qi,"precedesExistingVersion");async function $d(K,p,O){let A=p?.metadataFlags,y=p?.version,b,C;if(!i.attemptLock(K,y,()=>{clearTimeout(C);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(_n|Xo)?b($d(K,i.getEntry(K),O)):b(N)}))return new Promise(N=>{b=N,C=setTimeout(()=>{i.unlock(K,y)},LSe)});let I=p?.value,L={requestContext:O,replacingRecord:I,replacingEntry:p,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:O?.resourceCache},B=O?.responseHeaders;return new Promise((N,x)=>{let G;zC(Ot(L,async z=>{let ie=performance.now(),F,qe,Z;try{for(let _e of Ce.sources)if(_e.get&&(!_e.get.reliesOnPrototype||_e.prototype.get)){if(_e.available?.(p)===!1)continue;if(L.source=_e,F=await _e.get(K,L),F)break}Z=A&_n;let ee=L.lastModified||Z&&y;qe=Z||ee>y||!I,ee||(ee=(0,am.getNextMonotonicTime)());let Q=performance.now()-ie;if(tr(Q,"cache-resolution",s,null,"success"),B&&RE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),z.timestamp=ee,m&&L.expiresAt==null&&(L.expiresAt=Date.now()+m),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=I,ee=y;else throw new Nr.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}G=!0,N({key:K,version:ee,value:F})}catch(ee){ee.message+=` while resolving record ${K} for ${s}`,I&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(N({key:K,version:y,value:I}),xe.default.trace?.(ee.message,"(returned stale record)")):x(ee);let Q=performance.now()-ie;tr(Q,"cache-resolution",s,null,"fail"),B&&RE(B,"Server-Timing",`cache-resolve;dur=${Q.toFixed(2)}`,!0),L.transaction.abort();return}if(O?.noCacheStore||L.noCacheStore){L.transaction.abort();return}Gr(L).addWrite({key:K,store:i,entry:p,nodeName:"source",commit:a((ee,Q)=>{if(Q?.version!==y)return;let _e=on(K,I,F);if(F){ye.put?.(L,K,F),Q&&(O.previousResidency=Ce.getResidencyRecord(Q.residencyId));let fe,Ae=!1,De,we=Vi(Ce.getResidency(F,O));if(we){if(!we.includes(server.hostname))if(fe=F,Ae=!0,Ce.getResidencyById)F=void 0;else{F=null;for(let _r in r)F||(F={}),F[_r]=fe[_r]}De=Za(we)}xe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),T(K,F,Q,ee,Ae?_n:0,g&&(qe||Ae)||null,{user:L?.user,expiresAt:L.expiresAt,residencyId:De},"put",!!Z,fe)}else Q&&(ye.delete?.(L,K),xe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(ee).toISOString()}`),g||R?T(K,null,Q,ee,0,g&&qe||null,{user:L?.user},"delete",!!Z):Sc(i,Q,y))},"commit")})}),()=>{i.unlock(K,y)},z=>{i.unlock(K,y),G&&xe.default.error?.("Error committing cache update",z)})})}a($d,"getFromSource");function kl(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new Nr.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new Nr.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(kl,"checkContextPermissions");function $i(K){let p=!1;if(K&&(K-lt>1&&(p=!0),lt=K),!(jt===Rr&&!p)&&(Rr=jt,(0,Pl.getWorkerIndex)()===(0,Pl.getWorkerCount)()-1))return is&&clearTimeout(is),jt?new Promise(O=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let y=jt/(1+lt),b=p?Date.now():Math.ceil((Date.now()-A.getTime())/y)*y+A.getTime(),C=a(I=>{xe.default.trace?.(`Scheduled next cleanup scan at ${new Date(I)}`),is=setTimeout(()=>q=q.then(async()=>{if(C(Math.max(I+jt,Date.now())),i.rootStore.status!=="open"){clearTimeout(is);return}let L=50,B=new Array(L),N=0,x=Math.pow(lt,8)*(Dl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),G=S/Math.pow(Math.max(lt,1),4);xe.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${G}ms`);function z(ie,F,qe,Z){let ce=ie+G-Date.now();if(ce<0)return!0;if(lt){let ee=i.lastSize;return qe&pn&&Zl(Z,Q=>{Q.size&&(ee+=Q.size)}),xe.default.trace?.(`shouldEvict adjusted ${ce} ${ee}, ${ce*(ie-F)/ee} < ${x}`),ce*(ie-F)/ee<x}return!1}a(z,"shouldEvict");try{let ie=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:qe,value:Z,version:ce,expiresAt:ee,metadataFlags:Q}=F,_e;Z===null&&!g&&ce+DSe<Date.now()?_e=Sc(i,F,ce):ee!=null&&z(ee,ce,Q,Z)&&(_e=Ce.evict(qe,Z,ce),ie++),_e&&(await B[N],B[N]=_e.catch(fe=>{xe.default.error?.("Cleanup error",fe)}),++N>=L&&(N=0)),await ja()}xe.default.info?.(`Finished cleanup scan for ${s}, evicted ${ie} entries`)}catch(ie){xe.default.warn?.(`Error in cleanup scan for ${s}:`,ie)}O(void 0),lt=0}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");C(b)}):void 0}a($i,"scheduleCleanup");function Vd(){Y=l?.addDeleteRemovalCallback(n,i,(K,p)=>{i.remove(K,p)})}a(Vd,"addDeleteRemoval");function Sm(){(0,Pl.getWorkerIndex)()===0&&setInterval(async()=>{if(!Ul){Ul=!0;try{let K=se.name,p=r[K];if(!p)throw new Error(`expiresAt attribute ${se} must be indexed`);for(let O of p.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of p.getValues(O)){let y=i.getEntry(A);y?.value?y.value[K]<Date.now()&&Ce.evict(A,y.value,y.version):i.ifVersion(A,y?.version,()=>p.remove(O,A))}await ja()}}catch(K){xe.default.error?.("Error in evicting old records",K)}finally{Ul=!1}}},PSe).unref()}a(Sm,"runRecordExpirationEviction");function Vi(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let p=server.shards?.get?.(K);if(p)return xe.default.trace?.(`Shard ${K} mapped to ${p.map(O=>O.name).join(", ")}`),p.map(O=>O.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a(Vi,"residencyFromFunction");function Za(K){if(K){let p=K.join(","),O=f.get([Symbol.for("residency_by_set"),p]);return O||(f.put([Symbol.for("residency_by_set"),p],O=Math.floor(Math.random()*2147418112)+65535),f.put([Symbol.for("residency_by_id"),O],K),O)}}a(Za,"getResidencyId")}function WC(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function sj(){}function xSe(e){lj=e}function HT(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return xT(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return xT(+e);case"Float":return e==="null"?null:xT(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;BSe.test(e)||(e+="Z");let n=new Date(e);return xT(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,kT.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function xT(e){if(isNaN(e))throw new SyntaxError;return e}function ij(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function zC(e,t,r){return e?.then?e.then(t,r):t(e)}function oj(e){return e!=null}function Ds(e){try{return JSON.stringify(e)}catch{return e}}function HSe(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Qa,am,aj,cj,Dl,Nr,cm,lm,xe,Ll,Pl,kT,BT,CSe,lj,PSe,DSe,ej,LSe,tj,MSe,_n,Xo,vSe,rj,nj,USe,Ave,BSe,ja,pf=be(()=>{k();Qa=require("lmdb"),am=M(un()),aj=require("lodash"),cj=M(uf());Zo();zm();Dl=M(le());UO();Nr=M(me()),cm=M(lo()),lm=M(qs());ve();mf();xe=M(_i());ob();cc();Ll=require("ordered-binary"),Pl=M(rt());to();kT=M(ae());nu();Oi();iE();T_();BT=M(require("node:fs"));us();nT();CSe=new Uint8Array(9);CSe[8]=192;PSe=6e4,DSe=864e5;Dl.initSync();ej=Dl.get(U.STORAGE_PREFETCHWRITES),LSe=1e4,tj=1,MSe=2,_n=1,Xo=8,vSe=Buffer.allocUnsafeSlow(8192),rj=1978,nj=100,USe={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},Ave=(0,kT.convertToMS)(Dl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(FT,"makeTable");a(WC,"attributesAsObject");a(sj,"noop");a(xSe,"setServerUtilities");BSe=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(HT,"coerceType");a(xT,"rejectNaN");a(ij,"isDescendantId");ja=a(()=>new Promise(setImmediate),"rest");a(zC,"when");a(oj,"exists");a(Ds,"stringify");a(HSe,"hasOtherProcesses")});var it={};Ue(it,{database:()=>pu,database_envs:()=>qo,databases:()=>Ve,dropDatabase:()=>db,dropTableMeta:()=>$Se,getDatabases:()=>Je,getDefaultCompression:()=>Qg,getTables:()=>kSe,onRemovedDB:()=>G_,onUpdatedTable:()=>Zc,readMetaDb:()=>um,resetDatabases:()=>nd,table:()=>dt,tables:()=>Kn});function kSe(){return VT||Je(),Kn||{}}function Je(){if(VT)return Ve;VT=!0,Bd=new Map;let e=(0,zt.getHdbBasePath)()&&(0,Pt.join)((0,zt.getHdbBasePath)(),rc),t=(0,zt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,zt.get)(U.STORAGE_PATH)||e&&((0,ns.existsSync)(e)?e:(0,Pt.join)((0,zt.getHdbBasePath)(),Nm)),!e)return;if((0,ns.existsSync)(e))for(let n of(0,ns.readdirSync)(e,{withFileTypes:!0})){let s=(0,Pt.basename)(n.name,".mdb");n.isFile()&&(0,Pt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&um((0,Pt.join)(e,n.name),null,s)}if((0,ns.existsSync)((0,xd.getBaseSchemaPath)())){for(let n of(0,ns.readdirSync)((0,xd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Pt.join)((0,xd.getBaseSchemaPath)(),n.name),i=(0,Pt.join)((0,xd.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,ns.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,Pt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,Pt.join)(i,o.name);um((0,Pt.join)(s,o.name),(0,Pt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,ns.existsSync)(i))for(let c of(0,ns.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Pt.extname)(c.name).toLowerCase()===".mdb"&&um((0,Pt.join)(i,c.name),(0,Pt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],u=(0,Pt.join)(l.path,(0,Pt.basename)(c+".mdb"));(0,ns.existsSync)(u)&&um(u,c,n,null,!0)}}for(let n in Ve){let s=Bd.get(n);if(s){let i=Ve[n];n.includes("delete")&&Dt.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(Dt.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in Kn)delete Kn[i];delete Kn[KT]}}let r=["hdb_temp","hdb_certificate","hdb_analytics","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if(Ve.system)for(let n of r)Ve.system[n]&&(Ve.system[n].replicate=!1);return Bd=null,Ve}function nd(){VT=!1;for(let[,e]of qo)e.needsDeletion=!0;Je();for(let[e,t]of qo)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),qo.delete(e),delete Ve[t.databaseName],fm.forEach(r=>r(t.databaseName)));return Ve}function um(e,t,r=JC,n,s){let i=new jC.default(e,!1);try{let o=qo.get(e);o?o.needsDeletion=!1:(o=(0,Hd.open)(i),qo.set(e,o));let c=new Ml.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(GT.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,ns.existsSync)(n)&&(i.path=n,u=(0,Hd.open)(i),u.isLegacy=!0):u=vT(o));let f=_j(r),d=f[KT],_=new Map;for(let{key:h,value:m}of l.getRange({start:!1})){let[S,g]=h.toString().split("/");g===""?g=m.name:g||(g=S,S=t,m.name||(m.name=g,m.indexed=!m.is_hash_attribute)),d?.add(S);let R=_.get(S);R||_.set(S,R={attributes:[]}),(g==null||m.is_hash_attribute)&&(R.primary=m),g!=null&&R.attributes.push(m),Object.defineProperty(m,"key",{value:h,configurable:!0})}for(let[h,m]of _){let{attributes:S,primary:g}=m;if(!g){for(let oe of S)if(oe.is_hash_attribute||oe.isPrimaryKey){g=oe;break}if(!g){Dt.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(S)}`);continue}}let R=f[h],E={},T=[],w,v,H=typeof g.audit=="boolean"?g.audit:(0,zt.get)(U.LOGGING_AUDITLOG),q=g.trackDeletes,W=g.expiration,te=g.eviction,se=g.sealed,Y=g.splitSegments,ne=g.replicate;if(R)E=R.indices,T=R.attributes,R.schemaVersion++;else{w=g.tableId,w?w>=(l.get(Ud)||0)&&(l.putSync(Ud,w+1),Dt.info(`Updating next table id (it was out of sync) to ${w+1} for ${h}`)):(g.tableId=w=l.get(Ud),w||(w=1),Dt.debug("Table {table_name} missing an id, assigning {table_id}"),l.putSync(Ud,w+1),l.putSync(g.key,g));let oe=new Ml.default(!g.is_hash_attribute,g.is_hash_attribute);if(oe.compression=g.compression,oe.compression){let pe=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||fj;oe.compression.threshold=pe}v=yp(o.openDB(g.key,oe),o),o.databaseName=r,v.tableId=w}let ue;for(let oe of S){oe.attribute=oe.name;try{if(!oe.is_hash_attribute&&(oe.indexed||oe.attribute&&!oe.name)){if(!E[oe.name]){let Te=new Ml.default(!oe.is_hash_attribute,oe.is_hash_attribute);E[oe.name]=o.openDB(oe.key,Te),E[oe.name].indexNulls=oe.indexNulls}let pe=T.find(Te=>Te.name===oe.name);pe?T.splice(T.indexOf(pe),1,oe):T.push(oe),ue=!0}}catch(pe){Dt.error("Error trying to update attribute",oe,T,E,pe)}}for(let oe of T)if(!S.find(Te=>Te.name===oe.name)){if(oe.is_hash_attribute){Dt.error("Unable to remove existing primary key attribute",oe);continue}oe.indexed&&(T.splice(T.indexOf(oe),1),ue=!0)}if(R)ue&&(R.schemaVersion++,R.updatedAttributes());else{R=hj(f,h,FT({primaryStore:v,auditStore:u,audit:H,sealed:se,splitSegments:Y,replicate:ne,expirationMS:W&&W*1e3,evictionMS:te&&te*1e3,trackDeletes:q,tableName:h,tableId:w,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:E,attributes:S,schemaDefined:g.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let oe of dm)oe(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function _j(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=Kn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),Bd&&!Bd.has(e)){let r=new Set;t[KT]=r,Bd.set(e,r)}return t}function hj(e,t,r){return e[t]=r,r}function pu({database:e,table:t}){e||(e=JC),Je();let r=_j(e),n=(0,Pt.join)((0,zt.getHdbBasePath)(),rc),s=(0,zt.get)(U.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,zt.get)(U.STORAGE_PATH)||((0,ns.existsSync)(n)?n:(0,Pt.join)((0,zt.getHdbBasePath)(),Nm));let o=(0,Pt.join)(n,(i?t:e)+".mdb"),c=qo.get(o);if(!c||c.status==="closed"){let l=new jC.default(o,!1);c=(0,Hd.open)(l),qo.set(o,c)}return c.auditStore||(c.auditStore=vT(c)),c}async function db(e){if(!Ve[e])throw new Error("Schema does not exist");let t=Ve[e],r;for(let n in t)r=t[n].primaryStore.rootStore,qo.delete(r.path),r.status==="open"&&(await r.close(),await _m.remove(r.path));if(r||(r=pu({database:e,table:null}),r.status==="open"&&(await r.close(),await _m.remove(r.path))),e==="data"){for(let n in Kn)delete Kn[n];delete Kn[KT]}delete Ve[e],fm.forEach(n=>n(e)),await QA(r)}function dt(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,schemaDefined:_,origin:h}=e;r||(r=JC);let m=pu({database:r,table:t}),S=Ve[r];Dt.trace(`Defining ${t} in ${r}`);let g=S?.[t];if(m.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,E,T;_==null&&(_=!0);let w=new Ml.default(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let v,H;if(g){if(R=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...o)}else{let Y=m.auditStore;E=o.find(pe=>pe.isPrimaryKey)||{},R=E.name,E.is_hash_attribute=E.isPrimaryKey=!0,E.schemaDefined=_,E.compression=Qg(),d&&(E.trackDeletes=!0),c=E.audit=typeof c=="boolean"?c:(0,zt.get)(U.LOGGING_AUDITLOG),n&&(E.expiration=n),s&&(E.eviction=s),u??=!1,E.splitSegments=u,typeof l=="boolean"&&(E.sealed=l),typeof f=="boolean"&&(E.replicate=f),h&&(E.origins?E.origins.includes(h)||E.origins.push(h):E.origins=[h]),Dt.trace(`${t} table loading, opening primary store`);let ne=new Ml.default(!1,!0);ne.compression=E.compression;let ue=t+"/";if(T=m.dbisDb=m.openDB(GT.INTERNAL_DBIS_NAME,w),se(),T.get(ue))return H&&H(),nd(),dt(e);let oe=yp(m.openDB(ue,ne),m);m.databaseName=r,oe.tableId=T.get(Ud),Dt.trace(`Assigning new table id ${oe.tableId} for ${t}`),oe.tableId||(oe.tableId=1),T.put(Ud,oe.tableId+1),E.tableId=oe.tableId,g=hj(S,t,FT({primaryStore:oe,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:f,trackDeletes:d,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:oe.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:_,dbisDB:T})),g.schemaVersion=1,v=!0,T.put(ue,E)}let q=g.indices;T=T||(m.dbisDb=m.openDB(GT.INTERNAL_DBIS_NAME,w)),g.dbisDB=T;let W=[];for(let{key:Y,value:ne}of T.getRange({start:!0})){let[ue,oe]=Y.toString().split("/");if(oe===""&&(oe=ne.name),oe){if(ue!==t)continue}else continue;let pe=o.find(ye=>ye.name===oe),Te=!pe?.indexed&&ne.indexed&&!ne.isPrimaryKey;if((!pe||Te)&&(se(),v=!0,pe||T.remove(Y),Te)){let ye=g.indices[ue];ye&&W.push(ye)}}let te=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(v=!0,Y.relationship))continue;let ne=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ne,configurable:!0});let ue=T.get(ne);if(Y.isPrimaryKey){if(ue=ue||T.get(ne=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||f!==void 0&&f!==g.replicate||(+n||void 0)!==(+ue.expiration||void 0)||(+s||void 0)!==(+ue.eviction||void 0)||Y.type!==ue.type){let pe={...ue};typeof c=="boolean"&&(c&&g.enableAuditing(c),pe.audit=c),n&&(pe.expiration=+n),s&&(pe.eviction=+s),l!==void 0&&(pe.sealed=l),f!==void 0&&(pe.replicate=f),Y.type&&(pe.type=Y.type),v=!0,se(),T.put(ne,pe)}continue}ue?.attribute&&!ue.name&&(ue.indexed=!0);let oe=!ue||ue.type!==Y.type||ue.indexed!==Y.indexed||ue.nullable!==Y.nullable||ue.version!==Y.version||JSON.stringify(ue.properties)!==JSON.stringify(Y.properties)||JSON.stringify(ue.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let pe=new Ml.default(!0,!1),Te=m.openDB(ne,pe);(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<hm.workerData?.restartNumber)&&(v=!0,se(),ue=T.get(ne),(oe||ue.indexingPID&&ue.indexingPID!==process.pid||ue.restartNumber<hm.workerData?.restartNumber)&&(v=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=ue?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Te}),te.push(Y))),T.put(ne,Y)),ue?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Te.indexNulls=Y.indexNulls,q[Y.name]=Te}else oe&&(v=!0,se(),T.put(ne,Y))}}finally{H&&H()}if(v&&(g.schemaVersion++,g.updatedAttributes()),Dt.trace(`${t} table loading, running index`),te.length>0||W.length>0?g.indexingOperation=qSe(g,te,W):v&&qT.signalSchemaChange(new $T.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,v)for(let Y of dm)Y(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Dt.trace(`${t} table loaded`),g;function se(){H||m.transactionSync(()=>({then(Y){H=Y}}))}a(se,"startTxn")}async function qSe(e,t,r){try{Dt.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await qT.signalSchemaChange(new $T.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let d of t)(0,Hd.compareKeys)(d.lastIndexedKey,u)<0&&(u=d.lastIndexedKey),d.lastIndexedKey==null&&d.dbi.clearAsync();let f=0;for(let{key:d,value:_,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(_){if(f++,s=e.primaryStore.ifVersion(d,h,()=>{for(let m=0;m<l;m++){let S=t[m],g=S.name;try{let R=S.resolve,E=_&&(R?R(_):_[g]),T=(0,uj.getIndexedValues)(E);if(T)for(let w=0,v=T.length;w<v;w++)S.dbi.put(T[w],d)}catch(R){o[g]||(o[g]=!0,Dt.error(`Error indexing attribute ${g}`,R))}}}),s.then(()=>f--,m=>{f--,Dt.error(m)}),hm.workerData&&hm.workerData.restartNumber!==dj.restartNumber&&(i=!0),++c%100===0||i){for(let m of t)m.lastIndexedKey=d,e.dbisDB.put(m.key,m);if(i)return}f>FSe?await s:f>GSe&&await new Promise(m=>setImmediate(m))}for(let d of t)delete d.lastIndexedKey,delete d.indexingPID,d.dbi.isIndexing=!1,s=e.dbisDB.put(d.key,d)}await s,await qT.signalSchemaChange(new $T.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Dt.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Dt.error("Error in indexing",n)}}function $Se({table:e,database:t}){let r=pu({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function Zc(e){return dm.push(e),{remove(){let t=dm.indexOf(e);t>-1&&dm.splice(t,1)}}}function G_(e){return fm.push(e),{remove(){let t=fm.indexOf(e);t>-1&&fm.splice(t,1)}}}function Qg(){let e=(0,zt.get)(U.STORAGE_COMPRESSION),t=(0,zt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,zt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||fj,n={startingOffset:32};return t&&(n.dictionary=_m.readFileSync(t)),r&&(n.threshold=r),e&&n}var zt,GT,Hd,Pt,ns,xd,Ml,jC,_m,QC,uj,qT,$T,hm,Dt,dj,JC,KT,fj,Kn,Ve,Ud,dm,fm,VT,qo,Bd,FSe,GSe,ve=be(()=>{zt=M(le()),GT=M(vt()),Hd=require("lmdb"),Pt=require("path"),ns=require("fs"),xd=M(pt());pf();Ml=M(Lf()),jC=M(Mf());k();_m=M(require("fs-extra")),QC=M(ai()),uj=M(un()),qT=M(lo()),$T=M(qs()),hm=require("worker_threads"),Dt=M(j()),dj=M(rt());to();nu();us();JC="data",KT=Symbol("defined-tables"),fj=((0,zt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,zt.initSync)();Kn=Object.create(null),Ve=Object.create(null);(0,QC._assignPackageExport)("databases",Ve);(0,QC._assignPackageExport)("tables",Kn);Ud=Symbol.for("next-table-id"),dm=[],fm=[],qo=new Map;a(kSe,"getTables");a(Je,"getDatabases");a(nd,"resetDatabases");a(um,"readMetaDb");a(_j,"ensureDB");a(hj,"setTable");a(pu,"database");a(db,"dropDatabase");a(dt,"table");FSe=1e3,GSe=10;a(qSe,"runIndexing");a($Se,"dropTableMeta");a(Zc,"onUpdatedTable");a(G_,"onRemovedDB");a(Qg,"getDefaultCompression")});var ae=P((Lve,Ij)=>{"use strict";var Ja=require("path"),Sj=require("fs-extra"),Pn=j(),mj=require("fs-extra"),YT=require("os"),VSe=require("net"),KSe=require("recursive-iterator"),Ar=(k(),D($)),{PACKAGE_ROOT:YSe}=mt(),WSe=gA(),pj=require("papaparse"),WT=require("moment"),{inspect:zSe}=require("util"),Ej=require("is-number"),Dve=require("lodash"),jSe=require("minimist"),QSe=require("https"),JSe=require("http"),{hdb_errors:zT}=me(),XSe=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Tj=require("util").promisify(setTimeout),ZSe=100,eTe=5,tTe="",rTe=4,gj={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Ij.exports={isEmpty:ss,isEmptyOrZeroLength:Gi,arrayHasEmptyValues:iTe,arrayHasEmptyOrZeroLengthValues:oTe,buildFolderPath:aTe,isBoolean:Aj,errorizeMessage:nTe,stripFileExtension:lTe,autoCast:uTe,autoCastJSON:Rj,autoCastJSONDeep:ZC,removeDir:dTe,compareVersions:fTe,isCompatibleDataVersion:_Te,escapeRawValue:hTe,unescapeValue:mTe,stringifyProps:pTe,timeoutPromise:gTe,isClusterOperation:TTe,getClusterUser:RTe,checkGlobalSchemaTable:ATe,getHomeDir:bj,getPropsFilePath:ETe,promisifyPapaParse:yTe,removeBOM:Oj,createEventPromise:bTe,checkProcessRunning:OTe,checkSchemaTableExist:NTe,checkSchemaExists:Nj,checkTableExists:wj,getStartOfTomorrowInSeconds:wTe,getLimitKey:ITe,isObject:cTe,isNotEmptyAndHasValue:sTe,autoCasterIsNumberCheck:yj,backtickASTSchemaItems:CTe,isPortTaken:STe,createForkArgs:PTe,autoCastBoolean:DTe,async_set_timeout:Tj,getTableHashAttribute:LTe,doesSchemaExist:MTe,doesTableExist:vTe,stringifyObj:UTe,ms_to_time:xTe,changeExtension:BTe,getEnvCliRootPath:eP,noBootFile:HTe,httpRequest:kTe,transformReq:FTe,convertToMS:GTe,PACKAGE_ROOT:YSe};function nTe(e){return e instanceof Error?e:new Error(e)}a(nTe,"errorizeMessage");function ss(e){return e==null}a(ss,"isEmpty");function sTe(e){return!ss(e)&&(e||e===0||e===""||Aj(e))}a(sTe,"isNotEmptyAndHasValue");function Gi(e){return ss(e)||e.length===0||e.size===0}a(Gi,"isEmptyOrZeroLength");function iTe(e){if(ss(e))return!0;for(let t=0;t<e.length;t++)if(ss(e[t]))return!0;return!1}a(iTe,"arrayHasEmptyValues");function oTe(e){if(Gi(e))return!0;for(let t=0;t<e.length;t++)if(Gi(e[t]))return!0;return!1}a(oTe,"arrayHasEmptyOrZeroLengthValues");function aTe(...e){try{return e.join(Ja.sep)}catch{console.error(e)}}a(aTe,"buildFolderPath");function Aj(e){return ss(e)?!1:e===!0||e===!1}a(Aj,"isBoolean");function cTe(e){return ss(e)?!1:typeof e=="object"}a(cTe,"isObject");function lTe(e){return Gi(e)?tTe:e.slice(0,-rTe)}a(lTe,"stripFileExtension");function uTe(e){return ss(e)||e===""||typeof e!="string"?e:gj[e]!==void 0?gj[e]:yj(e)===!0?Number(e):XSe.test(e)?new Date(e):e}a(uTe,"autoCast");function Rj(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Rj,"autoCastJSON");function ZC(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=ZC(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=ZC(r);n!==r&&(e[t]=n)}return e}else return Rj(e)}a(ZC,"autoCastJSONDeep");function yj(e){if(e.startsWith("0.")&&Ej(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Ej(e))}a(yj,"autoCasterIsNumberCheck");async function dTe(e){if(Gi(e))throw new Error(`Directory path: ${e} does not exist`);try{await mj.emptyDir(e),await mj.remove(e)}catch(t){throw Pn.error(`Error removing files in ${e} -- ${t}`),t}}a(dTe,"removeDir");function fTe(e,t){if(Gi(e)){Pn.info("Invalid current version sent as parameter.");return}if(Gi(t)){Pn.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),l=Math.min(o.length,c.length);for(let u=0;u<l;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(fTe,"compareVersions");function _Te(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(_Te,"isCompatibleDataVersion");function hTe(e){if(ss(e))return e;let t=String(e);return t==="."?Ar.UNICODE_PERIOD:t===".."?Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD:t.replace(Ar.FORWARD_SLASH_REGEX,Ar.UNICODE_FORWARD_SLASH)}a(hTe,"escapeRawValue");function mTe(e){if(ss(e))return e;let t=String(e);return t===Ar.UNICODE_PERIOD?".":t===Ar.UNICODE_PERIOD+Ar.UNICODE_PERIOD?"..":String(e).replace(Ar.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(mTe,"unescapeValue");function pTe(e,t){if(ss(e))return Pn.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+YT.EOL}!Gi(n)&&n[0]===";"?r+=" "+n+s+YT.EOL:Gi(n)||(r+=n+"="+s+YT.EOL)}catch{Pn.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(pTe,"stringifyProps");function bj(){let e;try{e=YT.homedir()}catch{e=process.env.HOME}return e}a(bj,"getHomeDir");function ETe(){let e=Ja.join(bj(),Ar.HDB_HOME_DIR_NAME,Ar.BOOT_PROPS_FILE_NAME);return Sj.existsSync(e)||(e=Ja.join(__dirname,"../","hdb_boot_properties.file")),e}a(ETe,"getPropsFilePath");function gTe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:a(function(){clearTimeout(r)},"cancel")}}a(gTe,"timeoutPromise");async function STe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=VSe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(STe,"isPortTaken");function TTe(e){try{return Ar.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Pn.error(`Error checking operation against cluster ops ${t}`)}return!1}a(TTe,"isClusterOperation");function ATe(e,t){let r=(ve(),D(it)).getDatabases();if(!r[e])return zT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return zT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(ATe,"checkGlobalSchemaTable");function RTe(e,t){if(ss(t)){Pn.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ss(e)||Gi(e)){Pn.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Pn.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Pn.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(RTe,"getClusterUser");function yTe(){pj.parsePromise=function(e,t,r){return new Promise(function(n,s){pj.parse(e,{header:!0,transformHeader:Oj,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(yTe,"promisifyPapaParse");function Oj(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Oj,"removeBOM");function bTe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Pn.info(`Got cluster status event response: ${zSe(s)}`);try{i.cancel()}catch{Pn.error("Error trying to cancel timeout.")}n(s)})})}a(bTe,"createEventPromise");async function OTe(e){let t=!0,r=0;do await Tj(ZSe*r++),(await WSe.findPs(e)).length>0&&(t=!1);while(t&&r<eTe);if(t)throw new Error(`process ${e} was not started`)}a(OTe,"checkProcessRunning");function NTe(e,t){let r=Nj(e);if(r)return r;let n=wj(e,t);if(n)return n}a(NTe,"checkSchemaTableExist");function Nj(e){let{getDatabases:t}=(ve(),D(it));if(!t()[e])return zT.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Nj,"checkSchemaExists");function wj(e,t){let{getDatabases:r}=(ve(),D(it));if(!r()[e][t])return zT.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(wj,"checkTableExists");function wTe(){let e=WT().utc().add(1,"d").startOf("d").unix(),t=WT().utc().unix();return e-t}a(wTe,"getStartOfTomorrowInSeconds");function ITe(){return WT().utc().format("DD-MM-YYYY")}a(ITe,"getLimitKey");function CTe(e){try{let t=new KSe(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){Pn.error("Got an error back ticking items."),Pn.error(t)}}a(CTe,"backtickASTSchemaItems");function PTe(e){return[e]}a(PTe,"createForkArgs");function DTe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(DTe,"autoCastBoolean");function LTe(e,t){let{getDatabases:r}=(ve(),D(it)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(LTe,"getTableHashAttribute");function MTe(e){let{getDatabases:t}=(ve(),D(it));return t()[e]!==void 0}a(MTe,"doesSchemaExist");function vTe(e,t){let{getDatabases:r}=(ve(),D(it));return r()[e]?.[t]!==void 0}a(vTe,"doesTableExist");function UTe(e){try{return JSON.stringify(e)}catch{return e}}a(UTe,"stringifyObj");function xTe(e){let t=WT.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(xTe,"ms_to_time");function BTe(e,t){let r=Ja.basename(e,Ja.extname(e));return Ja.join(Ja.dirname(e),r+t)}a(BTe,"changeExtension");function eP(){if(process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=jSe(process.argv);if(e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ar.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(eP,"getEnvCliRootPath");var XC;function HTe(){if(XC)return XC;let e=eP();if(eP()&&Sj.pathExistsSync(Ja.join(e,Ar.HDB_CONFIG_FILE)))return XC=!0,!0}a(HTe,"noBootFile");function kTe(e,t){let r;return e.protocol==="http:"?r=JSe:r=QSe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8"),o.body="",o.on("data",c=>{o.body+=c}),o.on("end",()=>{n(o)})});i.on("error",o=>{s(o)}),i.write(t instanceof Buffer?t:JSON.stringify(t)),i.end()})}a(kTe,"httpRequest");function FTe(e){if(!e.schema&&!e.database){e.schema=Ar.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(FTe,"transformReq");function GTe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(GTe,"convertToMS")});ym();var tP=(k(),D($)),Cj=ae(),mm=j(),qTe=_s(),$Te=Sn(),VTe=aS(),{start:KTe}=(mC(),D(ST)),{closeConnection:YTe}=rr(),Pj=require("moment"),Dj=CS(),{cloneDeep:WTe}=require("lodash"),zTe=process.env[tP.PROCESS_NAME_ENV_PROP],Xa=zTe.substring(4);a(async function(){let t={id:Xa,request:void 0},r=0;try{mm.notify("Starting job:",Xa),KTe(),qTe.setSchemaDataToGlobal(),await $Te.setUsersWithRolesCache();let n=await Dj.getJobById(Xa);if(Cj.isEmptyOrZeroLength(n))throw new Error(`Unable to find a record in hdb_job for job: ${Xa}`);let{request:s}=n[0];if(Cj.isEmptyOrZeroLength(s))throw new Error("Did not find job request in hdb_job table, unable to proceed");s=WTe(s);let i=VTe.getOperationFunction(s);mm.trace("Running operation:",s.operation,"for job",Xa);let o=await i.job_operation_function(s);mm.trace("Result from job:",Xa,o),t.status=tP.JOB_STATUS_ENUM.COMPLETE,typeof o=="string"?t.message=o:(t.result=o,t.message="Successfully completed job: "+Xa),t.end_datetime=Pj().valueOf(),mm.notify("Successfully completed job:",Xa)}catch(n){r=1,mm.error(n),t.status=tP.JOB_STATUS_ENUM.ERROR,t.message=n.message?n.message:n,t.end_datetime=Pj().valueOf()}finally{await Dj.updateJob(t),await YTe(),setTimeout(()=>{process.exit(r)},3e3).unref()}},"job")();