@cybearl/cypack 1.10.6 → 1.10.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/backend.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/main/json.ts","../src/backend/logger.ts","../src/main/formats.ts","../src/backend/bench.ts","../src/backend/cgas/status.ts","../src/backend/crypto.ts","../src/backend/cybuffer.ts","../src/backend/host.ts","../src/main/errors.ts","../src/backend/next/nextApiWrapper.ts","../src/backend/next/nextAuthApiWrapper.ts"],"names":["stringify","object","indent","_","value","defaultParameters","parameters","formatMessage","log","colors","native","foreign","acc","key","strLevel","effect","color","formattedDate","dateFormat","masks","formattedLevel","formattedForeign","line","index","finalLog","stream","pretty","__","logger","pino","level","showLevel","showTimestamp","foreignObjectStartAtNewLine","padding","alignForeignObject","newParameters","logger_default","slugifyLib","formatUnit","num","unit","timeUnit","addSpaceBeforeUnit","strUnit","spaceOrNot","formatHRTime","hrtime","formatPercentage","percentage","Bench","benchmarkDuration","fn","name","initialTime","operationsPerSecond","avgExecutionTime","operations","totalTime","t0","t1","internalBenchmarkDuration","i","category","clear","benchCategory","longestFnName","functions","b","result","fastestFn","formattedFnName","formattedAvgExecutionTime","formattedOperationsPerSecond","formattedPercentage","indicatorPadding","generateCGASStatus","status","marker","version","message","markerOnly","aes256GcmEncrypt","data","keyBuffer","iv","randomBytes","cipher","createCipheriv","ciphertext","tag","payload","aes256GcmDecrypt","decipher","createDecipheriv","plaintext","aes256GcmDecryptPayload","parts","crypto","formatCyBufferError","CyBuffer","_CyBuffer","length","options","tmpUint8Array","tmpUint16View","endianness","offset","fillWith","buffer","byteLength","encoding","array","msbFirst","start","end","target","prop","parsedValue","highNibble","lowNibble","bitOffset","check","orientedOffset","verifyAlignment","bitLength","arrayOffset","orderedBitOffset","bits","prefix","hexString","hexPrefix","randomFillSync","wordLength","calculatedLength","offsetIndex","j","temp","dividedLength","endOffsetIndex","first","last","shift","getHostname","execSync","prettyName","hostname","BaseErrors","NextApiWrapper","req","res","methods","error","response","method","methodInput","NextAuthApiWrapper","user","role","roles","session","authOptions"],"mappings":"sPAeO,SAASA,CAAAA,CAAUC,CAAAA,CAAiBC,CAAAA,CAAS,CAAA,CAAW,CAC3D,OAAO,IAAA,CAAK,SAAA,CACRD,CAAAA,CACA,CAACE,CAAAA,CAAGC,CAAAA,GACI,OAAOA,CAAAA,EAAU,UAAA,EACjB,OAAOA,CAAAA,EAAU,QAAA,CAAiBA,CAAAA,CAAM,QAAA,EAAS,CAE9CA,CAAAA,CAEXF,CACJ,CACJ,CCJA,IAAMG,CAAAA,CAAgC,CAClC,KAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,EAAa,OAAA,CAChC,SAAA,CAAW,IAAA,CACX,aAAA,CAAe,IAAA,CACf,2BAAA,CAA6B,KAAA,CAC7B,oBAAA,CAAsB,CAAA,CACtB,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,KACxB,CAAA,CAKMC,CAAAA,CAAyB,CAAE,GAAGD,CAAkB,CAAA,CAOtD,SAASE,CAAAA,CAAcC,CAAAA,CAAoBC,CAAAA,CAA2B,CAClE,IAAMC,CAAAA,CAAS,CACX,KAAA,CAAOF,CAAAA,CAAI,KAAA,CACX,IAAA,CAAMA,CAAAA,CAAI,IAAA,CACV,GAAA,CAAKA,CAAAA,CAAI,GAAA,CACT,QAAA,CAAUA,CAAAA,CAAI,QAAA,CACd,GAAA,CAAKA,CAAAA,CAAI,GACb,CAAA,CAGMG,CAAAA,CAAU,MAAA,CAAO,OAAA,CAAQH,CAAG,CAAA,CAAE,MAAA,CAAO,CAACI,CAAAA,CAAiC,CAACC,CAAAA,CAAKT,CAAK,CAAA,IAC/E,MAAA,CAAO,IAAA,CAAKM,CAAM,CAAA,CAAE,QAAA,CAASG,CAAG,CAAA,GAAGD,CAAAA,CAAIC,CAAG,CAAA,CAAIT,CAAAA,CAAAA,CAC5CQ,CAAAA,CAAAA,CACR,E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ACD,GAAI,IAAA,CAAK,MAAA,CAAQ,OAAO,MAAM,IAAA,CAAK,cAAA,CAAe,IAAA,CAAK,MAAA,CAAQA,CAAW,CAAA,CAC1E,MACJ,KAAK,OAAA,CACD,GAAI,IAAA,CAAK,OAAA,CAAS,OAAO,MAAM,IAAA,CAAK,cAAA,CAAe,IAAA,CAAK,OAAA,CAASA,CAAW,CAAA,CAC5E,MACJ,KAAK,MACD,GAAI,IAAA,CAAK,QAAA,CAAU,OAAO,MAAM,IAAA,CAAK,cAAA,CAAe,IAAA,CAAK,SAAUA,CAAW,CAAA,CAC9E,MACJ,KAAK,QAAA,CACD,GAAI,IAAA,CAAK,OAAA,CAAS,OAAO,MAAM,IAAA,CAAK,cAAA,CAAe,IAAA,CAAK,OAAA,CAASA,CAAW,CAAA,CAC5E,MACJ,QACI,OAAO,IAAA,CAAK,aAAA,CAAcR,CAAAA,CAAW,kBAAkB,CAC/D,CACJ,CAAA,MAASK,EAAO,CACZ,OAAO,IAAA,CAAK,aAAA,CAAcL,CAAAA,CAAW,qBAAA,CAAuBK,CAAK,CACrE,CACJ,CACJ","file":"backend.js","sourcesContent":["/**\n * Format a JSON object with indentation.\n * @param str The JSON string to format.\n * @returns The formatted JSON string.\n */\nexport function formatJson(str: string): string {\n return JSON.stringify(JSON.parse(str), null, 4)\n}\n\n/**\n * Stringify a JSON object with support for BigInt and functions.\n * @param object The object to stringify.\n * @param indent The number of spaces to indent (optional, defaults to 4)\n * @returns The stringified JSON object.\n */\nexport function stringify(object: unknown, indent = 4): string {\n return JSON.stringify(\n object,\n (_, value) => {\n if (typeof value === \"function\") return value.toString()\n if (typeof value === \"bigint\") return value.toString()\n\n return value\n },\n indent,\n )\n}\n","import type { Color, Colorette } from \"colorette\"\nimport dateFormat, { masks } from \"dateformat\"\nimport pino, { type LogDescriptor } from \"pino\"\nimport pretty from \"pino-pretty\"\nimport { stringify } from \"@/main/json\"\n\n/**\n * The type of the parameters object.\n */\ntype Parameters = {\n level: pino.LevelWithSilentOrString\n showLevel: boolean\n showTimestamp: boolean\n foreignObjectStartAtNewLine: boolean\n foreignObjectPadding: number | \"after-timestamp\" | \"after-level\"\n foreignObjectIndent: number\n alignForeignObject?: boolean\n}\n\n/**\n * The default parameters for the logger instance.\n */\nconst defaultParameters: Parameters = {\n level: process.env.LOG_LEVEL || \"trace\",\n showLevel: true,\n showTimestamp: true,\n foreignObjectStartAtNewLine: false,\n foreignObjectPadding: 0,\n foreignObjectIndent: 4,\n alignForeignObject: false,\n}\n\n/**\n * Temporary parameters for the current logger instance.\n */\nconst parameters: Parameters = { ...defaultParameters }\n\n/**\n * Modify the format of the message depending on the log level.\n * @param log The log descriptor.\n * @returns The formatted message.\n */\nfunction formatMessage(log: LogDescriptor, colors: Colorette): string {\n const native = {\n level: log.level,\n time: log.time,\n pid: log.pid,\n hostname: log.hostname,\n msg: log.msg,\n }\n\n // Generate an object with foreign keys and their values\n const foreign = Object.entries(log).reduce((acc: { [key: string]: unknown }, [key, value]) => {\n if (!Object.keys(native).includes(key)) acc[key] = value\n return acc\n }, {})\n\n let strLevel = \"N/A\"\n let effect: Color | undefined\n let color: Color\n\n switch (log.level as number | string) {\n case 10:\n case \"trace\":\n strLevel = \"TRACE\"\n color = colors.black\n break\n case 20:\n case \"debug\":\n strLevel = \"DEBUG\"\n color = colors.blue\n break\n case 30:\n case \"info\":\n strLevel = \"INFO\"\n color = colors.green\n break\n case 40:\n case \"warn\":\n strLevel = \"WARN\"\n color = colors.yellow\n break\n case 50:\n case \"error\":\n strLevel = \"ERROR\"\n color = colors.redBright\n break\n case 60:\n case \"fatal\":\n strLevel = \"FATAL\"\n effect = colors.bold\n color = colors.redBright\n break\n default:\n strLevel = \"N/A\"\n color = colors.white\n break\n }\n\n let formattedDate = \"\"\n if (parameters.showTimestamp) formattedDate = `[${dateFormat(new Date(log.time), masks.isoDateTime)}] `\n\n let formattedLevel = \"\"\n if (parameters.showLevel) {\n formattedLevel = parameters.alignForeignObject ? `[${strLevel}] `.padEnd(8, \" \") : `[${strLevel}] `\n }\n\n let formattedForeign = \"\"\n if (Object.keys(foreign).length > 0) {\n if (parameters.foreignObjectPadding === \"after-timestamp\") {\n parameters.foreignObjectPadding = formattedDate.length\n } else if (parameters.foreignObjectPadding === \"after-level\") {\n parameters.foreignObjectPadding = formattedDate.length + formattedLevel.length\n }\n\n formattedForeign =\n `${parameters.foreignObjectStartAtNewLine ? \"\\n\" : \" \"}${stringify(foreign, parameters.foreignObjectIndent)}`\n .split(\"\\n\")\n .map((line, index) => {\n if (index === 0) return line\n return line.padStart(line.length + (parameters.foreignObjectPadding as number), \" \")\n })\n .join(\"\\n\")\n }\n\n let finalLog = color(`${formattedDate}${formattedLevel}${log.msg}${formattedForeign}`)\n if (effect) finalLog = effect(finalLog)\n\n console.log(finalLog)\n return \"\"\n}\n\n/**\n * The pretty logger stream, note that no keys are included by defaults, everything goes through\n * the message format function via the `log` object.\n */\nconst stream = pretty({\n crlf: false,\n colorize: true,\n sync: true,\n include: \"\",\n messageFormat: (log, _, __, { colors }) => formatMessage(log, colors),\n})\n\n/**\n * A custom logger instance compatible with both front and back-end, allowing to log messages\n * with different levels and colors.\n *\n * The available levels are:\n * - `fatal`\n * - `error`\n * - `warn`\n * - `info`\n * - `debug`\n * - `trace`\n *\n * The available parameters are:\n * - `setLevel`: Set the logger level (defaults to `\"trace\"`).\n * - `setShowLevel`: Set the logger level display (defaults to `true`).\n * - `setShowTimestamp`: Set the logger timestamp display (defaults to `true`).\n * - `setForeignObjectStartAtNewLine`: Set the logger foreign object new line display (defaults to `false`).\n * - `setForeignObjectPadding`: Set the padding for foreign objects (defaults to `0`).\n * - `setForeignObjectIndent`: Set the indent for foreign objects (defaults to `4`).\n * - `setAlignForeignObject`: Align any foreign object to the same column (defaults to `false`).\n * - `setParameters`: Set all the parameters at once.\n * - `resetParameters`: Reset all the parameters to their default values.\n */\nconst logger = pino({ level: parameters.level }, stream) as pino.Logger & {\n /**\n * Set the logger level, available levels are:\n * - `fatal`\n * - `error`\n * - `warn`\n * - `info`\n * - `debug`\n * - `trace`\n *\n * The logging level is a **minimum** level. For instance if `logger.level` is `\"info\"` then all\n * `\"fatal\"`, `\"error\"`, `\"warn\"` and `\"info\"` logs will be enabled.\n * @param level The new logger level.\n */\n setLevel: (level: Parameters[\"level\"]) => void\n\n /**\n * Set the logger level display.\n * @param showLevel Whether to show the level or not.\n */\n setShowLevel: (showLevel: Parameters[\"showLevel\"]) => void\n\n /**\n * Set the logger timestamp display.\n * @param showTimestamp Whether to show the timestamp or not.\n */\n setShowTimestamp: (showTimestamp: Parameters[\"showTimestamp\"]) => void\n\n /**\n * Set the logger foreign object new line display (wether to start the foreign object on a new line or not).\n * @param foreignObjectStartAtNewLine Whether to start the foreign object on a new line or not.\n */\n setForeignObjectStartAtNewLine: (foreignObjectStartAtNewLine: Parameters[\"foreignObjectStartAtNewLine\"]) => void\n\n /**\n * Set the padding for foreign objects, it also accepts `\"after-timestamp\"` and\n * `\"after-level\"` to automatically calculate the padding to match the beginning of the\n * specified element.\n * @param padding The padding for foreign objects.\n */\n setForeignObjectPadding: (padding: Parameters[\"foreignObjectPadding\"]) => void\n\n /**\n * Set the indent for foreign objects.\n * @param indent The indent for foreign objects.\n */\n setForeignObjectIndent: (indent: Parameters[\"foreignObjectIndent\"]) => void\n\n /**\n * Set whether to align any foreign object to the same column.\n * @param alignForeignObject Whether to align any foreign object to the same column.\n */\n setAlignForeignObject: (alignForeignObject: Parameters[\"alignForeignObject\"]) => void\n\n /**\n * Set all the parameters at once.\n * @param parameters The new parameters.\n */\n setParameters: (parameters: Parameters) => void\n\n /**\n * Reset all the parameters to their default values.\n */\n resetParameters: () => void\n}\n\n// Inject the getters and setters\n\nlogger.setLevel = (level: Parameters[\"level\"]) => {\n parameters.level = level\n logger.level = level\n}\n\nlogger.setShowLevel = (showLevel: Parameters[\"showLevel\"]) => {\n parameters.showLevel = showLevel\n}\n\nlogger.setShowTimestamp = (showTimestamp: Parameters[\"showTimestamp\"]) => {\n parameters.showTimestamp = showTimestamp\n}\n\nlogger.setForeignObjectStartAtNewLine = (foreignObjectStartAtNewLine: Parameters[\"foreignObjectStartAtNewLine\"]) => {\n parameters.foreignObjectStartAtNewLine = foreignObjectStartAtNewLine\n}\n\nlogger.setForeignObjectPadding = (padding: Parameters[\"foreignObjectPadding\"]) => {\n parameters.foreignObjectPadding = padding\n}\n\nlogger.setForeignObjectIndent = (indent: Parameters[\"foreignObjectIndent\"]) => {\n parameters.foreignObjectIndent = indent\n}\n\nlogger.setAlignForeignObject = (alignForeignObject: Parameters[\"alignForeignObject\"] = false) => {\n parameters.alignForeignObject = alignForeignObject\n}\n\nlogger.setParameters = (newParameters: Parameters) => {\n Object.assign(parameters, newParameters)\n}\n\nlogger.resetParameters = () => {\n Object.assign(parameters, defaultParameters)\n}\n\nexport default logger\n","import slugifyLib from \"slugify\"\nimport CyCONSTANTS from \"@/main/constants\"\n\n/**\n * The slugify function from the slugify library.\n */\nconst slugify = (slugifyLib as any).default || slugifyLib\n\n/**\n * Validate a direct ID parameter (as integer for SQL DBs etc..).\n * @param id The ID to validate.\n * @returns True if the ID is valid, false otherwise.\n */\nexport function isValidIntId(id: string): boolean {\n return typeof id === \"string\" && id.length > 0 && Number.isInteger(Number(id)) && Number(id) >= 0\n}\n\n/**\n * Validates a slug.\n * @param slug The slug to validate.\n * @returns True if the slug is valid, false otherwise.\n */\nexport function isValidSlug(slug: string): boolean {\n return typeof slug === \"string\" && slug.length > 0 && CyCONSTANTS.SLUG_REGEX.test(slug)\n}\n\n/**\n * Format a number with an attached unit + an optional time unit.\n *\n * **Note:** The time unit can be set to null to only display the unit.\n * @param num The number to format.\n * @param unit The unit to use (optional, defaults to \"Op\").\n * @param timeUnit The time unit to use (optional, defaults to \"s\").\n * @param padding The padding to use (optional, defaults to 12).\n * @param addSpaceBeforeUnit Whether to add a space before the unit (optional, defaults to `true`).\n * @returns The formatted string.\n */\nexport function formatUnit(\n num: number,\n unit: string | null = \"Op\",\n timeUnit: string | null = \"s\",\n padding = 12,\n addSpaceBeforeUnit = true,\n): string {\n let strUnit: string\n\n if (typeof unit === \"string\" && typeof timeUnit === \"string\") {\n strUnit = `${unit}/${timeUnit}`\n } else if (typeof unit === \"string\") {\n strUnit = unit\n } else {\n strUnit = \"\"\n }\n\n // Add a space before the unit if needed\n const spaceOrNot = addSpaceBeforeUnit ? \" \" : \"\"\n\n // Y = yotta\n if (num >= 10 ** 24) {\n return `${(num / 10 ** 24).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}Y${strUnit}`.padStart(padding, \" \")\n }\n\n // E = exa\n if (num >= 10 ** 18) {\n return `${(num / 10 ** 18).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}E${strUnit}`.padStart(padding, \" \")\n }\n\n // P = peta\n if (num >= 10 ** 15) {\n return `${(num / 10 ** 15).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}P${strUnit}`.padStart(padding, \" \")\n }\n\n // T = tera\n if (num >= 10 ** 12) {\n return `${(num / 10 ** 12).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}T${strUnit}`.padStart(padding, \" \")\n }\n\n // G = giga\n if (num >= 10 ** 9) {\n return `${(num / 10 ** 9).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}G${strUnit}`.padStart(padding, \" \")\n }\n\n // M = mega\n if (num >= 10 ** 6) {\n return `${(num / 10 ** 6).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}M${strUnit}`.padStart(padding, \" \")\n }\n\n // k = kilo\n if (num >= 10 ** 3) {\n return `${(num / 10 ** 3).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}k${strUnit}`.padStart(padding, \" \")\n }\n\n return `${num.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}${strUnit}`.padStart(padding, \" \")\n}\n\n/**\n * Format a high-resolution time, into a responsive string with the en-US locale format.\n * @param hrtime The hrtime in nanoseconds.\n * @param padding The padding to use (optional, defaults to 8).\n * @returns The formatted string.\n */\nexport function formatHRTime(hrtime: bigint | number, padding = 8): string {\n // Hours\n if (hrtime >= 3600000000000000n) {\n return `${(Number(hrtime) / 3600000000000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}h`.padStart(padding, \" \")\n }\n\n // Minutes\n if (hrtime >= 60000000000n) {\n return `${(Number(hrtime) / 60000000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}m`.padStart(padding, \" \")\n }\n\n // Seconds\n if (hrtime >= 1000000000n) {\n return `${(Number(hrtime) / 1000000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}s`.padStart(padding, \" \")\n }\n\n // Milliseconds\n if (hrtime >= 1000000n) {\n return `${(Number(hrtime) / 1000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}ms`.padStart(padding, \" \")\n }\n\n // Microseconds\n if (hrtime >= 1000n) {\n return `${(Number(hrtime) / 1000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}µs`.padStart(padding, \" \")\n }\n\n // Nanoseconds\n return `${hrtime.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}ns`.padStart(padding, \" \")\n}\n\n/**\n * Format a time in milliseconds into a responsive string with the en-US locale format.\n * @param time The time in milliseconds.\n * @param padding The padding to use (optional, defaults to 10).\n * @returns The formatted string.\n */\nexport function formatTime(time: number, padding = 10): string {\n // Hours\n if (time >= 3600000) {\n return `${(time / 3600000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}h`.padStart(padding, \" \")\n }\n\n // Minutes\n if (time >= 60000) {\n return `${(time / 60000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}m`.padStart(padding, \" \")\n }\n\n // Seconds\n if (time >= 1000) {\n return `${(time / 1000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}s`.padStart(padding, \" \")\n }\n\n // Milliseconds\n return `${time.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}ms`.padStart(padding, \" \")\n}\n\n/**\n * Format a percentage with the en-US locale format.\n * @param percentage The percentage to format.\n * @param padding The padding to use (optional, defaults to 7).\n * @returns The formatted string.\n */\nexport function formatPercentage(percentage: number, padding = 7): string {\n return `${percentage.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}%`.padStart(padding, \" \")\n}\n\n/**\n * Truncate a string to a certain length.\n * @param str The string to truncate.\n * @param len The maximum length of the string.\n * @returns The truncated string.\n */\nexport function truncateString(str: string, len: number) {\n if (str.length <= len) return str\n return `${str.slice(0, len)}...`\n}\n\n/**\n * Parse a query containing either a number or numbers separated by commas and returns an array of numbers.\n * @param query The query string to parse.\n * @returns An array of numbers extracted from the query.\n */\nexport function parseQueryNumberArray(query: string | Array<string>): number[] {\n const result: number[] = []\n const items = Array.isArray(query) ? query : query.split(\",\").map(item => item.trim())\n\n for (const item of items) {\n const num = Number.parseInt(item, 10)\n if (!Number.isNaN(num)) result.push(num)\n }\n\n return result\n}\n\n/**\n * Parse a query containing either a string or strings separated by commas and returns an array of strings.\n * @param query The query string to parse.\n * @returns An array of strings extracted from the query.\n */\nexport function parseQueryStringArray(query: string | Array<string>): string[] {\n const result: string[] = []\n const items = Array.isArray(query) ? query : query.split(\",\").map(item => item.trim())\n\n for (const item of items) {\n if (item.length > 0) result.push(item)\n }\n\n return result\n}\n\n/**\n * The options for the `slugify` function.\n */\nconst slugifyOptions = {\n lower: true,\n strict: true,\n}\n\n/**\n * Slugify a given name with support for automatic number incrementing.\n * @param name The name to slugify.\n * @param previousSlug An optional previous slug to compare against,\n * the previous slug should ends with `-<number>`, this slug will automatically\n * increment the number if the slug already exists.\n * @returns The slugified version of the name.\n */\nexport function slugifyName(name: string, previousSlug?: string): string {\n if (previousSlug) {\n // If the previous slug ends with a number, we increment it\n const match = previousSlug.match(/-(\\d+)$/)\n\n if (match) {\n const number = Number.parseInt(match[1], 10)\n const baseSlug = previousSlug.slice(0, -match[0].length)\n return slugify(`${baseSlug}-${number + 1}`, slugifyOptions)\n }\n }\n\n return slugify(name, slugifyOptions)\n}\n","import logger from \"@/backend/logger\"\nimport { formatHRTime, formatPercentage, formatUnit } from \"@/main/formats\"\n\n/**\n * The type of the benchmark function result.\n */\nexport type BenchmarkResult = {\n operationsPerSecond: number\n avgExecutionTime: number\n operations: number\n}\n\n/**\n * An object containing multiple benchmark results, ordered by functions.\n */\nexport type BenchmarkResults = {\n [fn: string]: BenchmarkResult\n}\n\n/**\n * A class that provides a simple way to benchmark functions.\n */\nexport default class Bench {\n /**\n * The duration of the benchmark in milliseconds.\n */\n benchmarkDuration: number\n\n /**\n * Stores the results of the benchmark.\n */\n results: BenchmarkResults = {}\n\n /**\n * Creates a new benchmarking instance.\n * @param benchmarkDuration The duration of the benchmark in milliseconds (optional, defaults to 256ms).\n */\n constructor(benchmarkDuration = 256) {\n this.benchmarkDuration = benchmarkDuration\n }\n\n /**\n * The main headless benchmarking function.\n *\n * Does not print anything to the console but returns the number of iterations per second\n * and the logs themselves for further formatting, such as console coloring depending on the results.\n * @param fn The function to run.\n * @param name The name of the function to run.\n * @returns The benchmark result (operations per second, average execution time, and total operations).\n */\n benchmark = (fn: () => unknown, name: string): void => {\n let res: unknown\n\n const initialTime = process.hrtime.bigint()\n\n let operationsPerSecond = 0\n let avgExecutionTime = 0\n let operations = 0\n let totalTime = 0n\n let t0 = 0n\n let t1 = 0n\n\n // Convert the milliseconds benchmark duration to nanoseconds (matching HRTime resolution)\n const internalBenchmarkDuration = BigInt(this.benchmarkDuration) * 1_000_000n\n\n for (let i = 0; i < Number.POSITIVE_INFINITY; i++) {\n t0 = process.hrtime.bigint()\n res = fn()\n t1 = process.hrtime.bigint()\n totalTime += t1 - t0\n\n if (t1 - initialTime >= internalBenchmarkDuration) {\n avgExecutionTime = Number(totalTime) / i\n operationsPerSecond = 1_000_000_000 / avgExecutionTime\n\n // Estimate the number of operations realized\n // Instead of measuring \"i\" because of the other operations in the loop\n operations = Number(t1 - initialTime) / avgExecutionTime\n\n // Access res to prevent the function from being optimized out\n // It slows down the benchmark but is necessary for the result to be far more accurate\n res = `${res}`\n\n // Break after one report\n break\n }\n }\n\n this.results[name] = {\n operationsPerSecond,\n avgExecutionTime: avgExecutionTime,\n operations: operations,\n }\n }\n\n /**\n * Formats and prints multiple benchmark results.\n * @param category The category of the benchmark results (optional, defaults to `RESULTS`).\n * @param clear Whether to clear the results object for the next benchmark (optional, defaults to `true`).\n */\n print = (category?: string, clear = true) => {\n const benchCategory = category || \"RESULTS\"\n\n logger.info(`\\n${benchCategory.toUpperCase()}:`)\n logger.info(\"=\".repeat(benchCategory.length + 1))\n\n // Measure the longest function name for padding\n let longestFnName = 0\n for (const fn of Object.keys(this.results)) {\n if (fn.length > longestFnName) longestFnName = fn.length\n }\n\n // Sort the functions by their operations per second\n const functions = Object.entries(this.results).sort(\n (a, b) => b[1].operationsPerSecond - a[1].operationsPerSecond,\n )\n\n for (const [fn, result] of functions) {\n // Add a percentage for each function\n // based on the fastest function's operations per second\n const fastestFn = functions[0][1].operationsPerSecond\n const percentage = (result.operationsPerSecond / fastestFn) * 100\n\n const formattedFnName = `>> ${fn} `.padEnd(longestFnName + 4, \"═\")\n const formattedAvgExecutionTime = `AVG TIME: ${formatHRTime(result.avgExecutionTime)}`\n const formattedOperationsPerSecond = `OPS: ${formatUnit(result.operationsPerSecond)}`\n const formattedPercentage = `PERCENTAGE: ${formatPercentage(percentage)}`\n\n const log = `${formattedFnName}═> ${formattedAvgExecutionTime} | ${formattedOperationsPerSecond} | ${formattedPercentage}`\n\n const indicatorPadding = 10\n if (percentage >= 90) logger.debug(log + \"(fastest)\".padStart(indicatorPadding, \" \"))\n else if (percentage >= 60) logger.info(log + \"(fast)\".padStart(indicatorPadding, \" \"))\n else if (percentage >= 30) logger.warn(log + \"(medium)\".padStart(indicatorPadding, \" \"))\n else if (percentage >= 10) logger.error(log + \"(slow)\".padStart(indicatorPadding, \" \"))\n else logger.error(log + \"(slowest)\".padStart(indicatorPadding, \" \"))\n }\n\n // Clear the results object for the next benchmark\n if (clear) this.results = {}\n }\n}\n","import type { CGASStatus, CGASStatusString } from \"@/main/types/cgas\"\n\n/**\n * Returns the formatted status of the application based on the different parameters.\n * This function should be executed within the CGAS API endpoint to return the status.\n * @param status The status of the application.\n * @param marker The marker of the application.\n * @param version The version of the application (optional).\n * @param message The message to display (optional).\n * @param markerOnly Whether to only return the marker (optional, defaults to false).\n * @returns The formatted status of the application.\n */\nexport function generateCGASStatus(\n status: CGASStatusString,\n marker: string,\n version: string | undefined,\n message?: string,\n markerOnly?: boolean,\n): CGASStatus | string {\n if (markerOnly) return marker\n\n return {\n status,\n marker,\n timestamp: new Date().toISOString(),\n version: {\n raw: version ?? \"unavailable\",\n formatted: version ? `v${version}` : \"unavailable\",\n },\n message: message ?? \"The application is running smoothly.\",\n }\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\"\n\n/**\n * The return type of the `encrypt` function.\n * - `iv`: Base64-encoded initialization vector used for encryption (no need to store it securely).\n * - `ciphertext`: Base64-encoded ciphertext resulting from the encryption process.\n * - `tag`: Authentication tag as a Buffer, used for verifying the integrity of the ciphertext.\n * - `payload`: Full payload combining iv, ciphertext, and tag, formatted as \"iv.ciphertext.tag\".\n */\nexport type CryptoAes256GcmEncryptResult = {\n iv: string\n ciphertext: string\n tag: Buffer\n payload: string\n}\n\n/**\n * Encrypts data using AES-256-GCM symmetric encryption.\n * @param key The base64-encoded key to use for encryption. Must be 32 bytes when decoded.\n * @param data The plaintext data to encrypt.\n * @returns An object containing the initialization vector (iv), ciphertext, and authentication tag.\n * @throws If any error occurs during encryption.\n */\nfunction aes256GcmEncrypt(key: string, data: string): CryptoAes256GcmEncryptResult {\n const keyBuffer = Buffer.from(key, \"base64\")\n if (keyBuffer.length !== 32) {\n throw new Error(`Invalid key length: expected 32 bytes, got ${keyBuffer.length}`)\n }\n\n const iv = randomBytes(12).toString(\"base64\")\n const cipher = createCipheriv(\"aes-256-gcm\", keyBuffer, Buffer.from(iv, \"base64\"))\n\n let ciphertext = cipher.update(data, \"utf8\", \"base64\")\n ciphertext += cipher.final(\"base64\")\n const tag = cipher.getAuthTag()\n\n const payload = `${iv}.${ciphertext}.${tag.toString(\"base64\")}`\n return { iv, ciphertext, tag, payload }\n}\n\n/**\n * Decrypts data using AES-256-GCM symmetric encryption.\n * @param key The base64-encoded key to use for decryption. Must be 32 bytes when decoded.\n * @param iv The base64-encoded initialization vector used during encryption.\n * @param ciphertext The base64-encoded ciphertext to decrypt.\n * @param tag The base64-encoded authentication tag used during encryption.\n * @returns The decrypted plaintext data or null if decryption fails.\n */\nfunction aes256GcmDecrypt(key: string, iv: string, ciphertext: string, tag: string) {\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", Buffer.from(key, \"base64\"), Buffer.from(iv, \"base64\"))\n decipher.setAuthTag(Buffer.from(tag, \"base64\"))\n\n let plaintext = decipher.update(ciphertext, \"base64\", \"utf8\")\n plaintext += decipher.final(\"utf8\")\n\n return plaintext\n } catch (_) {\n // No information is provided about the error to avoid leaking sensitive data\n return null\n }\n}\n\n/**\n * Decrypts a payload that contains the initialization vector, ciphertext, and authentication tag.\n * @param key The base64-encoded key to use for decryption. Must be 32 bytes when decoded.\n * @param payload The payload string containing iv, ciphertext, and tag separated by dots.\n * @returns The decrypted plaintext data or null if decryption fails.\n */\nfunction aes256GcmDecryptPayload(key: string, payload: string) {\n const parts = payload.split(\".\")\n if (parts.length !== 3) {\n throw new Error(\"Invalid payload format\")\n }\n\n const [iv, ciphertext, tag] = parts\n return aes256GcmDecrypt(key, iv, ciphertext, tag)\n}\n\n/**\n * Contains utility functions for encryption and decryption.\n */\nexport const crypto = {\n aes256Gcm: {\n encrypt: aes256GcmEncrypt,\n decrypt: aes256GcmDecrypt,\n decryptPayload: aes256GcmDecryptPayload,\n },\n}\n","import { randomFillSync } from \"node:crypto\"\n\n/**\n * Format an error message for the CyBuffer class.\n * @param name The name of the module.\n * @param message The error message.\n * @returns The formatted error message.\n */\nfunction formatCyBufferError(name: string, message: string): string {\n return `[CyBuffer - ${name}] ${message}`\n}\n\n/**\n * A type for a single bit (`0` or `1`).\n */\nexport type Bit = 0 | 1\n\n/**\n * A type for the endianness of a buffer.\n */\nexport type Endianness = \"LE\" | \"BE\"\n\n/**\n * A type for the encoding of a string.\n */\nexport type StringEncoding = \"utf8\" | \"hex\"\n\n/**\n * `CyBuffer` is a helper class that indirectly extends the Uint8Array class with additional methods\n * similar to the Buffer class in Node.js, while also providing multiple utility methods\n * linked to advanced cryptography and binary data manipulation.\n */\nexport default class CyBuffer {\n /**\n * The platform's endianness which all related methods will use by default,\n * in order to normalize the endianness parameter.\n */\n readonly platformEndianness: Endianness\n\n /**\n * The ArrayBuffer instance referenced by the buffer.\n */\n readonly arrayBuffer: ArrayBuffer\n\n /**\n * The Uint8Array instance that acts as a bridge between the buffer and the array buffer.\n */\n readonly array: Uint8Array\n\n /**\n * The offset in bytes of the buffer.\n */\n readonly offset: number\n\n /**\n * The length in bytes of the buffer.\n */\n readonly length: number\n\n /**\n * Creates a new `CyBuffer` instance based on a length or an input.\n * @param length The length of the buffer to create.\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param options The options to use (optional).\n * - `arrayBuffer`: The array buffer to use.\n * - `offset`: The offset in bytes to start reading from (optional, defaults to 0).\n * - `length`: The length in bytes to read (optional, defaults to the input length).\n */\n constructor(\n length: number,\n options?: {\n arrayBuffer: ArrayBuffer\n offset?: number\n length?: number\n },\n ) {\n if (length < 0) throw new RangeError(formatCyBufferError(\"constructor\", `Invalid buffer length: '${length}'.`))\n if (!Number.isInteger(length))\n throw new TypeError(formatCyBufferError(\"constructor\", `Invalid buffer length: '${length}'.`))\n\n this.platformEndianness = this.getPlatformEndianness()\n\n if (options) {\n this.arrayBuffer = options.arrayBuffer\n this.offset = options.offset ?? 0\n this.length = options.length ?? length\n this.array = new Uint8Array(this.arrayBuffer, this.offset, this.length)\n } else {\n this.arrayBuffer = new ArrayBuffer(length)\n this.offset = 0\n this.length = length\n this.array = new Uint8Array(this.arrayBuffer)\n }\n\n // Applying proxy\n // biome-ignore lint/correctness/noConstructorReturn: Used to apply the proxy\n return this._proxy\n }\n\n /**\n * ============\n * SIGNATURES\n * ============\n */\n\n /**\n * Signature for the `[]` operator.\n */\n [index: number]: number\n\n /**\n * ==================\n * INTERNAL METHODS\n * ==================\n */\n\n /**\n * Get the platform endianness.\n * @returns The platform endianness.\n */\n getPlatformEndianness = (): Endianness => {\n const tmpUint8Array = new Uint8Array(4)\n const tmpUint16View = new Uint32Array(tmpUint8Array.buffer)\n\n tmpUint16View[0] = 0xff00\n return tmpUint8Array[0] === 0xff ? \"BE\" : \"LE\"\n }\n\n /**\n * Normalizes the endianness parameter.\n *\n * By default, the extended Uint8Array is written for Little Endian, to keep it consistent,\n * if the platform is big endian the endianness parameter is reversed.\n *\n * - Little endian platform:\n * - `LE` read from left to right.\n * - `BE` read from right to left.\n * - Big endian platform:\n * - `LE` read from right to left.\n * - `BE` read from left to right.\n */\n normalizeEndianness = (endianness: Endianness): Endianness => {\n if (this.platformEndianness === \"BE\") {\n if (endianness === \"LE\") return \"BE\"\n return \"LE\"\n }\n\n return endianness\n }\n\n /**\n * Checks the offset and length for validity.\n *\n * **Note:** This method is used internally by the read/write methods.\n * @param offset The offset to check.\n * @param length The length to check.\n * @throws If the offset or length are invalid.\n * @returns The current buffer instance.\n */\n check = (offset: number, length: number): this => {\n if (Number.isNaN(offset) || Number.isNaN(length)) {\n throw new TypeError(formatCyBufferError(\"check\", `Invalid offset: '${offset}' or length: '${length}'.`))\n }\n\n if (offset < 0 || offset >= this.length) {\n throw new RangeError(\n formatCyBufferError(\"check\", `Invalid offset: '${offset}', it must be >= 0 & < ${this.length}.`),\n )\n }\n\n if (length < 1 || length > this.length) {\n throw new RangeError(\n formatCyBufferError(\"check\", `Invalid length: '${length}', it must be > 0 & <= ${this.length}.`),\n )\n }\n\n if (offset + length > this.length) {\n throw new RangeError(\n formatCyBufferError(\n \"check\",\n `Invalid offset (${offset}) + length (${length}): '${offset + length}', it must be <= ${this.length}.`,\n ),\n )\n }\n\n if (offset % 1 !== 0)\n throw new RangeError(formatCyBufferError(\"check\", `Invalid offset alignment: '${offset}'.`))\n if (length % 1 !== 0)\n throw new RangeError(formatCyBufferError(\"check\", `Invalid length alignment: '${length}'.`))\n\n return this\n }\n\n /**\n * ================\n * STATIC METHODS\n * ================\n */\n\n /**\n * Creates a new `CyBuffer` instance of the specified length, initially filled with zeros.\n * @param length The length of the buffer.\n * @param fillWith The value to initially fill the buffer with (optional).\n * @returns A new `CyBuffer` instance.\n */\n static alloc = (length: number, fillWith?: number): CyBuffer => {\n const buffer = new CyBuffer(length)\n if (fillWith !== undefined) buffer.fill(fillWith)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from an hexadecimal string (supports `0x` prefix).\n *\n * **Note:** There is no `endianness` parameter here as there is no concept of word size,\n * the order will simply follow the string.\n * @param value The hexadecimal string to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromHexString = (value: string): CyBuffer => {\n // Remove any `0x` prefix before writing\n if (value.startsWith(\"0x\")) value = value.slice(2)\n\n const byteLength = Math.ceil(value.length / 2)\n const buffer = new CyBuffer(byteLength)\n buffer.writeHexString(value, 0, byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from an UTF-8 string.\n * @param value The UTF-8 string to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUtf8String = (value: string): CyBuffer => {\n const buffer = new CyBuffer(value.length)\n buffer.writeUtf8String(value, 0, value.length)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a string using a specific encoding.\n * @param value The string to create the buffer from.\n * @param encoding The encoding to use (optional, defaults to \"utf8\").\n * @returns A new `CyBuffer` instance.\n */\n static fromString = (value: string, encoding: StringEncoding = \"utf8\"): CyBuffer => {\n const buffer = new CyBuffer(value.length)\n buffer.writeString(value, encoding, 0, value.length)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from an array of bits.\n * @param array The array of bits to create the buffer from.\n * @param msbFirst Whether to write the bits from the most significant bit (optional, defaults to `true`).\n * @returns A new `CyBuffer` instance.\n */\n static fromBits = (array: Bit[], msbFirst = true): CyBuffer => {\n const buffer = new CyBuffer(Math.ceil(array.length / 8))\n buffer.writeBits(array, 0, array.length, msbFirst)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a Uint8Array.\n * @param array The Uint8Array to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUint8Array = (array: Uint8Array): CyBuffer => {\n const buffer = new CyBuffer(array.byteLength)\n buffer.writeUint8Array(array, 0, array.byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a Uint16Array.\n * @param array The Uint16Array to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUint16Array = (array: Uint16Array): CyBuffer => {\n const buffer = new CyBuffer(array.byteLength)\n buffer.writeUint16Array(array, 0, array.byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a Uint32Array.\n * @param array The Uint32Array to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUint32Array = (array: Uint32Array): CyBuffer => {\n const buffer = new CyBuffer(array.byteLength)\n buffer.writeUint32Array(array, 0, array.byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a big integer.\n * @param value The big integer to create the buffer from.\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns A new `CyBuffer` instance.\n */\n static fromBigInt = (value: bigint, endianness?: Endianness): CyBuffer => {\n if (value < 0n) throw new RangeError(formatCyBufferError(\"fromBigInt\", `Invalid big integer: '${value}'.`))\n\n const byteLength = Math.ceil(value.toString(16).length / 2)\n const buffer = new CyBuffer(byteLength)\n buffer.writeBigInt(value, 0, byteLength, endianness)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a range of numbers between 0 and 255.\n * @param start The start of the range, inclusive.\n * @param end The end of the range, exclusive.\n * @returns A new `CyBuffer` instance.\n */\n static fromRange = (start: number, end: number): CyBuffer => {\n const buffer = new CyBuffer(end - start)\n buffer.writeRange(start, end)\n return buffer\n }\n\n /**\n * ===========\n * ACCESSORS\n * ===========\n */\n\n /**\n * The proxy that allows to access/assign values via the [] operator.\n * Note that both the getter and setter are safe and never throw.\n * @returns The proxy returned by the constructor.\n */\n private get _proxy(): CyBuffer {\n return new Proxy(this, {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !Number.isNaN(Number(prop))) {\n this.check(Number(prop), 1)\n\n return target.array[Number(prop)] ?? undefined\n }\n\n return target[prop as keyof this]\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\" && !Number.isNaN(Number(prop))) {\n const parsedValue = Number(value)\n\n if (Number.isNaN(parsedValue)) {\n throw new TypeError(formatCyBufferError(\"proxy\", `Invalid value: '${value}'.`))\n }\n\n if (parsedValue < 0 || parsedValue > 255) {\n throw new RangeError(formatCyBufferError(\"proxy\", `Value is out of bounds: '${value}'.`))\n }\n\n this.check(Number(prop), 1)\n\n target.array[Number(prop)] = value\n return true\n }\n\n target[prop as keyof this] = value\n return true\n },\n })\n }\n\n /**\n * The symbol iterator of the buffer, allowing to iterate over the buffer\n * using `for..of` loops and returning bytes.\n * @returns A new generator yielding the bytes of the buffer.\n */\n *[Symbol.iterator](): Generator<number> {\n let i = 0\n while (i < this.length) yield this.array[i++]\n }\n\n /**\n * Iterates over the buffer and yields the index and value of each byte as an array.\n * @returns The generator yielding the index and value of each byte.\n */\n *entries(): Generator<[number, number]> {\n for (let i = 0; i < this.length; i++) {\n yield [i, this.array[i]]\n }\n }\n\n /**\n * ===============\n * WRITE METHODS\n * ===============\n */\n\n /**\n * Writes an hexadecimal string to the buffer (supports `0x` prefix).\n *\n * **Note:** There is no `endianness` parameter here as there is no concept of word size,\n * the order will simply follow the string.\n * @param value The hexadecimal string to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the value length).\n * @returns The current buffer instance.\n */\n writeHexString = (value: string, offset = 0, length = value.length / 2): this => {\n if (length === 0) {\n throw new RangeError(\n formatCyBufferError(\"writeHexString\", `Invalid hexadecimal string length: '${length}'.`),\n )\n }\n\n if (length % 1 !== 0) {\n throw new RangeError(\n formatCyBufferError(\"writeHexString\", `Invalid hexadecimal string length: '${length}'.`),\n )\n }\n\n if (value.length % 2 !== 0) {\n throw new RangeError(\n formatCyBufferError(\"writeHexString\", `Invalid hexadecimal string length: '${value.length}'.`),\n )\n }\n\n // Remove any `0x` prefix before writing\n if (value.startsWith(\"0x\")) {\n // Detects if the length is equal to the default value,\n // if it is, edit the length by removing the prefix\n if (length === value.length / 2) length = (value.length - 2) / 2\n value = value.slice(2)\n }\n\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n const highNibble = value.charCodeAt(i * 2) | 0x20 // Convert to lowercase for A-F\n const lowNibble = value.charCodeAt(i * 2 + 1) | 0x20 // Convert to lowercase for A-F\n\n // Converts the pair of hexadecimal characters to a byte\n this.array[offset + i] =\n ((highNibble - (highNibble > 57 ? 87 : 48)) << 4) | (lowNibble - (lowNibble > 57 ? 87 : 48))\n }\n\n return this\n }\n\n /**\n * Writes an UTF-8 string to the buffer.\n * @param value The UTF-8 string to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the value length).\n * @returns The current buffer instance.\n */\n writeUtf8String = (value: string, offset = 0, length = value.length): this => {\n if (length === 0) {\n throw new RangeError(formatCyBufferError(\"writeUtf8String\", `Invalid UTF-8 string length: '${length}'.`))\n }\n\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) this.array[offset + i] = value.charCodeAt(i)\n return this\n }\n\n /**\n * Writes a string to the buffer using a specific encoding.\n *\n * **Notes:**\n * - The `hex` encoding supports `0x` prefix but there's no `endianness` parameter here,\n * it follows the order of the string.\n * @param value The string to write to the buffer.\n * @param encoding The encoding to use (optional, defaults to \"utf8\").\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the value length).\n * @returns The current buffer instance.\n */\n writeString = (value: string, encoding: StringEncoding = \"utf8\", offset = 0, length = value.length): this => {\n if (encoding === \"utf8\") {\n this.writeUtf8String(value, offset, length)\n return this\n }\n\n if (encoding === \"hex\") {\n this.writeHexString(value, offset, Math.ceil(length / 2))\n return this\n }\n\n throw new TypeError(formatCyBufferError(\"writeString\", `Invalid encoding: '${encoding}'.`))\n }\n\n /**\n * Writes a single bit to the buffer.\n * @param value The value to write (`0` or `1`).\n * @param bitOffset The offset to read from **as a number of bits** (optional, defaults to 0).\n * @param msbFirst Whether to write the bit to the most significant bit (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeBit = (value: Bit, bitOffset = 0, msbFirst = true, check = true): this => {\n if (value < 0 || value > 1)\n throw new RangeError(formatCyBufferError(\"writeBit\", `Value is out of bounds: '${value}'.`))\n\n const offset = Math.floor(bitOffset / 8)\n if (check) this.check(offset, 1)\n\n const orientedOffset = msbFirst ? 7 - (bitOffset % 8) : bitOffset % 8\n if (value === 1) this.array[offset] |= 1 << orientedOffset\n else this.array[offset] &= ~(1 << orientedOffset)\n\n return this\n }\n\n /**\n * Writes a single byte to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint8 = (value: number, offset = 0, check = true): this => {\n if (value < 0 || value > 255) {\n throw new RangeError(formatCyBufferError(\"writeUint8\", `Value is out of bounds: '${value}'.`))\n }\n\n if (check) this.check(offset, 1)\n\n value >>>= 0\n this.array[offset] = value\n\n return this\n }\n\n /**\n * **[LITTLE ENDIAN]** Writes a single 16-bit value to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16LE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffff) {\n throw new RangeError(formatCyBufferError(\"writeUint16LE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint16LE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n\n value >>>= 0\n this.array[offset] = value & 0xff\n this.array[offset + 1] = (value >> 8) & 0xff\n\n return this\n }\n\n /**\n * **[BIG ENDIAN]** Writes a single 16-bit value to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16BE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffff) {\n throw new RangeError(formatCyBufferError(\"writeUint16BE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint16BE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n\n value >>>= 0\n this.array[offset] = (value >> 8) & 0xff\n this.array[offset + 1] = value & 0xff\n\n return this\n }\n\n /**\n * Writes a single 16-bit value to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16 = (\n value: number,\n offset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n check = true,\n ): this => {\n if (this.normalizeEndianness(endianness) === \"LE\") {\n this.writeUint16LE(value, offset, verifyAlignment, check)\n return this\n }\n\n this.writeUint16BE(value, offset, verifyAlignment, check)\n return this\n }\n\n /**\n * **[LITTLE ENDIAN]** Writes a single 32-bit word to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32LE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffffffff) {\n throw new RangeError(formatCyBufferError(\"writeUint32LE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint32LE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n value >>>= 0\n this.array[offset] = value & 0xff\n this.array[offset + 1] = (value >> 8) & 0xff\n this.array[offset + 2] = (value >> 16) & 0xff\n this.array[offset + 3] = (value >> 24) & 0xff\n\n return this\n }\n\n /**\n * **[BIG ENDIAN]** Writes a single 32-bit word to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32BE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffffffff) {\n throw new RangeError(formatCyBufferError(\"writeUint32BE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint32BE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n value >>>= 0\n this.array[offset] = (value >> 24) & 0xff\n this.array[offset + 1] = (value >> 16) & 0xff\n this.array[offset + 2] = (value >> 8) & 0xff\n this.array[offset + 3] = value & 0xff\n\n return this\n }\n\n /**\n * Writes a single 32-bit word to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32 = (\n value: number,\n offset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n check = true,\n ): this => {\n if (this.normalizeEndianness(endianness) === \"LE\") {\n this.writeUint32LE(value, offset, verifyAlignment, check)\n return this\n }\n\n this.writeUint32BE(value, offset, verifyAlignment, check)\n return this\n }\n\n /**\n * Writes an array of bits to the buffer.\n * @param array The array of bits to write to the buffer.\n * @param bitOffset The offset to start writing at **as a number of bits** (optional, defaults to 0).\n * @param bitLength The length to write **as a number of bits** (optional, defaults to the array length).\n * @param msbFirst Whether to write the bits from the most significant bit (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeBits = (array: Bit[], bitOffset = 0, bitLength = array.length, msbFirst = true): this => {\n if (!array || !Array.isArray(array)) {\n throw new TypeError(formatCyBufferError(\"writeBits\", `Invalid array of bits: '${array}'.`))\n }\n\n const offset = Math.floor(bitOffset / 8)\n const length = Math.ceil(bitLength / 8)\n this.check(offset, length)\n\n for (let i = 0; i < bitLength; i++) this.writeBit(array[i], bitOffset + i, msbFirst, false)\n\n return this\n }\n\n /**\n * Writes a Uint8Array to the buffer.\n * @param array The Uint8Array to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param arrayOffset The offset to start reading from in the array (optional, defaults to 0).\n * @returns The current buffer instance.\n */\n writeUint8Array = (array: Uint8Array, offset = 0, length = array.byteLength, arrayOffset = 0): this => {\n if (!array || !(array instanceof Uint8Array)) {\n throw new TypeError(formatCyBufferError(\"writeUint8Array\", `Invalid Uint8Array: '${array}'.`))\n }\n\n this.check(offset, length)\n\n for (let i = arrayOffset; i < length; i++) this.array[offset - arrayOffset + i] = array[i]\n\n return this\n }\n\n /**\n * Writes a Uint16Array to the buffer.\n * @param array The Uint16Array to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param arrayOffset The offset to start reading from in the array (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16Array = (\n array: Uint16Array,\n offset = 0,\n length = array.byteLength,\n arrayOffset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n ): this => {\n if (!array || !(array instanceof Uint16Array)) {\n throw new TypeError(formatCyBufferError(\"writeUint16Array\", `Invalid Uint16Array: '${array}'.`))\n }\n\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint16Array\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n this.check(offset, length)\n\n if (this.normalizeEndianness(endianness) === \"LE\") {\n for (let i = arrayOffset; i < length; i += 2) {\n this.writeUint16LE(array[i / 2], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n for (let i = arrayOffset; i < length; i += 2) {\n this.writeUint16BE(array[i / 2], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n /**\n * Writes a Uint32Array to the buffer.\n * @param array The Uint16Array to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param arrayOffset The offset to start reading from in the array (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32Array = (\n array: Uint32Array,\n offset = 0,\n length = array.byteLength,\n arrayOffset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n ): this => {\n if (!array || !(array instanceof Uint32Array)) {\n throw new TypeError(formatCyBufferError(\"writeUint32Array\", `Invalid Uint32Array: '${array}'.`))\n }\n\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint32Array\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n this.check(offset, length)\n\n if (this.normalizeEndianness(endianness) === \"LE\") {\n for (let i = arrayOffset; i < length; i += 4) {\n this.writeUint32LE(array[i / 4], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n for (let i = arrayOffset; i < length; i += 4) {\n this.writeUint32BE(array[i / 4], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n /**\n * **[LITTLE ENDIAN]** Writes a big integer of any size to the buffer.\n *\n * **No alignment is required, the length is automatically calculated.**\n * @param value The big integer to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @returns The current buffer instance.\n */\n writeBigIntLE = (value: bigint, offset = 0, length = Math.ceil(Number(value).toString(16).length / 2)): this => {\n if (value < 0n)\n throw new RangeError(formatCyBufferError(\"writeBigIntLE\", `Invalid big integer value: '${value}'.`))\n\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n this.array[offset + i] = Number(value & BigInt(0xff))\n value >>= BigInt(8)\n }\n\n return this\n }\n\n /**\n * **[BIG ENDIAN]** Writes a big integer of any size to the buffer.\n *\n * **No alignment is required, the length is automatically calculated.**\n * @param value The big integer to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @returns The current buffer instance.\n */\n writeBigIntBE = (value: bigint, offset = 0, length = Math.ceil(Number(value).toString(16).length / 2)): this => {\n if (value < 0n)\n throw new RangeError(formatCyBufferError(\"writeBigIntBE\", `Invalid big integer value: '${value}'.`))\n\n this.check(offset, length)\n\n for (let i = length - 1; i >= 0; i--) {\n this.array[offset + i] = Number(value & BigInt(0xff))\n value >>= BigInt(8)\n }\n\n return this\n }\n\n /**\n * Writes a big integer of any size to the buffer.\n *\n * **No alignment is required, the length is automatically calculated.**\n * @param value The big integer to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns The current buffer instance.\n */\n writeBigInt = (\n value: bigint,\n offset = 0,\n length = Math.ceil(Number(value).toString(16).length / 2),\n endianness = this.platformEndianness,\n ): this => {\n if (this.normalizeEndianness(endianness) === \"LE\") {\n this.writeBigIntLE(value, offset, length)\n return this\n }\n\n this.writeBigIntBE(value, offset, length)\n return this\n }\n\n /**\n * Writes a range of numbers between 0 and 255 to the buffer.\n * @param start The start of the range, inclusive.\n * @param end The end of the range, exclusive.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @returns The current buffer instance.\n */\n writeRange = (start: number, end: number, offset = 0): this => {\n if (start < 0 || start > 255) {\n throw new RangeError(formatCyBufferError(\"writeRange\", `Invalid start value: '${start}'.`))\n }\n\n if (end < 0 || end > 255) {\n throw new RangeError(formatCyBufferError(\"writeRange\", `Invalid end value: '${end}'.`))\n }\n\n const length = end - start\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n this.array[offset + i] = start + i\n }\n\n return this\n }\n\n /**\n * ==============\n * READ METHODS\n * ==============\n *\n * Notes:\n * - All read methods have the capability to disable the overall check.\n * - All of the \"endianness sensitive\" methods are wrapped within a single\n * method with an optional endianness parameter.\n */\n\n /**\n * **[LITTLE ENDIAN]** Reads a part of the buffer and returns it as an hexadecimal string (always uppercase).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The hexadecimal string.\n */\n readHexStringLE = (offset = 0, length = this.length - offset, check = true): string => {\n if (check) this.check(offset, length)\n return Buffer.from(this.arrayBuffer, offset, length).toString(\"hex\").toUpperCase()\n }\n\n /**\n * **[BIG ENDIAN]** Reads a part of the buffer and returns it as an hexadecimal string (always uppercase).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The hexadecimal string.\n */\n readHexStringBE = (offset = 0, length = this.length - offset, check = true): string => {\n if (check) this.check(offset, length)\n const hexString = Buffer.from(this.arrayBuffer, offset, length).toString(\"hex\").toUpperCase()\n return hexString.match(/.{2}/g)!.reverse().join(\"\")\n }\n\n /**\n * Reads a part of the buffer and returns it as an hexadecimal string (always uppercase).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).'\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The hexadecimal string.\n */\n readHexString = (\n offset = 0,\n length = this.length - offset,\n endianness = this.platformEndianness,\n check = true,\n ): string => {\n if (check) this.check(offset, length)\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readHexStringLE(offset, length, false)\n return this.readHexStringBE(offset, length, false)\n }\n\n /**\n * Reads a part of the buffer and returns it as an UTF-8 string.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The UTF-8 string.\n */\n readUtf8String = (offset = 0, length = this.length - offset, check = true): string => {\n if (check) this.check(offset, length)\n return Buffer.from(this.arrayBuffer, offset, length).toString(\"utf8\")\n }\n\n /**\n * Read a single bit from the buffer.\n *\n * **Note:** The offset is in bits, not bytes in contrast to the other methods.\n * @param bitOffset The offset to read from **as a number of bits** (optional, defaults to 0).\n * @param msbFirst Whether to read the bit from the most significant bit (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The bit as 0 or 1.\n */\n readBit = (bitOffset = 0, msbFirst = true, check = true): Bit => {\n const offset = Math.floor(bitOffset / 8)\n if (check) this.check(offset, 1)\n\n const orderedBitOffset = msbFirst ? 7 - (bitOffset % 8) : bitOffset % 8\n return (this.array[offset] & (1 << orderedBitOffset)) !== 0 ? 1 : 0\n }\n\n /**\n * Reads a single byte from the buffer.\n *\n * Equivalent to using the index signature (square bracket notation).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The byte as number.\n */\n readUint8 = (offset = 0, check = true): number => {\n if (check) this.check(offset, 1)\n return this.array[offset]\n }\n\n /**\n * **[LITTLE ENDIAN]** Reads a single 16-bit value from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The 16-bit value.\n */\n readUint16LE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint16LE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n\n return (this.array[offset] | (this.array[offset + 1] << 8)) >>> 0\n }\n\n /**\n * **[BIG ENDIAN]** Reads a single 16-bit value from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The 16-bit value.\n */\n readUint16BE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint16BE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n return ((this.array[offset] << 8) | this.array[offset + 1]) >>> 0\n }\n\n /**\n * Reads a single 16-bit value from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param endianness Whether to read the value in Little Endian (optional, defaults to `false`).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The 16-bit value.\n */\n readUint16 = (offset = 0, endianness = this.platformEndianness, verifyAlignment = true, check = true): number => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readUint16LE(offset, verifyAlignment, check)\n return this.readUint16BE(offset, verifyAlignment, check)\n }\n\n /**\n * **[LITTLE ENDIAN]** Reads a single 32-bit word from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n */\n readUint32LE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint32LE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n return (\n (this.array[offset] |\n (this.array[offset + 1] << 8) |\n (this.array[offset + 2] << 16) |\n (this.array[offset + 3] << 24)) >>>\n 0\n )\n }\n\n /**\n * **[BIG ENDIAN]** Reads a single 32-bit word from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n */\n readUint32BE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint32BE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n return (\n ((this.array[offset] << 24) |\n (this.array[offset + 1] << 16) |\n (this.array[offset + 2] << 8) |\n this.array[offset + 3]) >>>\n 0\n )\n }\n\n /**\n * Reads a single 32-bit word from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param endianness Whether to read the value in Little Endian (optional, defaults to `false`).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n */\n readUint32 = (offset = 0, endianness = this.platformEndianness, verifyAlignment = true, check = true): number => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readUint32LE(offset, verifyAlignment, check)\n return this.readUint32BE(offset, verifyAlignment, check)\n }\n\n /**\n * Reads a part of the buffer and return it as a bit array.\n *\n * **Note:** The offset is in bits, not bytes in contrast to the other methods.\n * @param bitOffset The offset to read from **as a number of bits** (optional, defaults to 0).\n * @param bitLength The length to read **as a number of bits** (optional, defaults to the buffer length - offset).\n * @param msbFirst Whether to read the bits from the most significant bit (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The bit array.\n */\n readBits = (offset = 0, length = this.length * 8 - offset * 8, msbFirst = true, check = true): Bit[] => {\n const bits: Bit[] = []\n\n for (let i = 0; i < length; i++) bits.push(this.readBit(offset + i, msbFirst, check))\n\n return bits\n }\n\n /**\n * Reads a part of the buffer and return it as a Uint8Array.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The Uint8Array.\n */\n readUint8Array = (offset = 0, length = this.length - offset, check = true): Uint8Array => {\n if (check) this.check(offset, length)\n return new Uint8Array(this.arrayBuffer, offset ?? this.offset, length ?? this.length)\n }\n\n /**\n * Reads a part of the buffer and return it as a Uint16Array.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The Uint16Array.\n */\n readUint16Array = (offset = 0, length = this.length - offset, check = true): Uint16Array => {\n if (check) this.check(offset, length)\n return new Uint16Array(this.arrayBuffer, offset ?? this.offset, length ? length / 2 : this.length / 2)\n }\n\n /**\n * Reads a part of the buffer and return it as a Uint32Array.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The Uint32Array.\n */\n readUint32Array = (offset = 0, length = this.length - offset, check = true): Uint32Array => {\n if (check) this.check(offset, length)\n return new Uint32Array(this.arrayBuffer, offset ?? this.offset, length ? length / 4 : this.length / 4)\n }\n\n /**\n * **[LITTLE ENDIAN]** Reads a certain amount of bytes from the buffer and converts it into a big integer.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The big integer.\n */\n readBigIntLE = (offset = 0, length = this.length - offset, check = true): bigint => {\n if (check) this.check(offset, length)\n\n let result = 0n\n for (let i = length - 1; i >= 0; i--) {\n result = (result << 8n) | BigInt(this.array[offset + i])\n }\n\n return result\n }\n\n /**\n * **[BIG ENDIAN]** Reads a certain amount of bytes from the buffer and converts it into a big integer.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The big integer.\n */\n readBigIntBE = (offset = 0, length = this.length - offset, check = true): bigint => {\n if (check) this.check(offset, length)\n\n let result = 0n\n for (let i = 0; i < length; i++) {\n result = (result << 8n) | BigInt(this.array[offset + i])\n }\n\n return result\n }\n\n /**\n * Reads a certain amount of bytes from the buffer and converts it into a big integer.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param endianness Whether to read the value in Little Endian (optional, defaults to `false`).\n * @returns The big integer.\n */\n readBigInt = (\n offset = 0,\n length = this.length - offset,\n endianness = this.platformEndianness,\n check = true,\n ): bigint => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readBigIntLE(offset, length, check)\n return this.readBigIntBE(offset, length, check)\n }\n\n /**\n * ====================\n * CONVERSION METHODS\n * ====================\n */\n\n /**\n * Converts the buffer into an hexadecimal string (always uppercase).\n * @param prefix Whether to prefix the hexadecimal string with `0x` (optional, defaults to `false`).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns The hexadecimal string.\n */\n toHexString = (prefix = false, endianness = this.platformEndianness): string => {\n let hexString = Buffer.from(this.arrayBuffer).toString(\"hex\").toUpperCase()\n\n if (this.normalizeEndianness(endianness) === \"BE\") {\n hexString = hexString.match(/.{2}/g)?.reverse().join(\"\") ?? \"\"\n }\n\n if (prefix) return `0x${hexString}`\n return hexString\n }\n\n /**\n * Converts the buffer into an UTF-8 string.\n * @returns The UTF-8 string.\n */\n toUtf8String = (): string => Buffer.from(this.arrayBuffer).toString(\"utf8\")\n\n /**\n * Converts the buffer into a string representation (hex string is always uppercase).\n * @param encoding The encoding to use (optional, defaults to \"hex\").\n * @param hexPrefix Whether to prefix the hexadecimal string with `0x` (optional, defaults to `false`).\n * @returns The string representation of the buffer.\n */\n toString = (encoding: \"utf8\" | \"hex\" = \"hex\", hexPrefix = false): string => {\n if (encoding === \"utf8\") return this.toUtf8String()\n return this.toHexString(hexPrefix)\n }\n\n /**\n * Converts the buffer into a bit array.\n * @param msbFirst Whether to read the bits from the most significant bit (optional, defaults to `true`).\n * @returns The bit array.\n */\n toBits = (msbFirst = true): Bit[] => {\n const length = this.length * 8\n const bits: Bit[] = new Array(length)\n for (let i = 0; i < length; i++) bits[i] = this.readBit(i, msbFirst)\n return bits\n }\n\n /**\n * Converts the buffer into a Uint8Array.\n * @returns The Uint8Array.\n */\n toUint8Array = (): Uint8Array => new Uint8Array(this.arrayBuffer, this.offset, this.length)\n\n /**\n * Converts the buffer into a Uint16Array.\n * @returns The Uint16Array.\n */\n toUint16Array = (): Uint16Array => new Uint16Array(this.arrayBuffer, this.offset, this.length / 2)\n\n /**\n * Converts the buffer into a Uint32Array.\n * @returns The Uint32Array.\n */\n toUint32Array = (): Uint32Array => new Uint32Array(this.arrayBuffer, this.offset, this.length / 4)\n\n /**\n * Converts the buffer into a big integer.\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns The big integer.\n */\n toBigInt = (endianness = this.platformEndianness): bigint => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readBigIntLE()\n return this.readBigIntBE()\n }\n\n /**\n * ===============\n * CHECK METHODS\n * ===============\n */\n\n /**\n * Checks if the current buffer is equal to the specified buffer.\n * @param buffer The buffer to compare to.\n * @returns Whether the buffers are equal.\n */\n equals = (buffer: CyBuffer): boolean => {\n if (this.length !== buffer.length) {\n return false\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.array[i] !== buffer[i]) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Check if the buffer is empty.\n * @returns Whether the buffer is empty.\n */\n isEmpty = (): boolean => {\n for (let i = 0; i < this.length; i++) {\n if (this.array[i] !== 0) return false\n }\n\n return true\n }\n\n /**\n * Check if the buffer is full.\n * @returns Whether the buffer is full.\n */\n isFull = (): boolean => {\n for (let i = 0; i < this.length; i++) {\n if (this.array[i] !== 255) return false\n }\n\n return true\n }\n\n /**\n * ====================\n * RANDOMNESS METHODS\n * ====================\n */\n\n /**\n * Randomly fills the buffer with bytes.\n *\n * **WARNING:** This method is not safe for cryptographic contexts, use the `safeRandomFill` method\n * when security is a concern.\n * @param offset The offset to start filling at (optional, defaults to 0).\n * @param length The length to fill (optional, defaults to the buffer length - offset).\n */\n randomFill = (offset = 0, length = this.length - offset) => {\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n this.array[offset + i] = Math.floor(Math.random() * 256)\n }\n }\n\n /**\n * Randomly fills the buffer with bytes.\n *\n * **WARNING:** This method is safe for cryptographic contexts, but is far slower than the `randomFill` method,\n * use this method when security is a concern. Uses the Node.js `crypto.randomFillSync` method.\n * @param offset The offset to start filling at (optional, defaults to 0).\n * @param length The length to fill (optional, defaults to the buffer length - offset).\n */\n safeRandomFill = (offset = 0, length = this.length) => randomFillSync(this.array, offset, length)\n\n /**\n * =================\n * UTILITY METHODS\n * =================\n */\n\n /**\n * Copies the buffer into a new buffer.\n * @param offset The offset to start copying at (optional, defaults to 0).\n * @param length The length to copy (optional, defaults to the buffer length).\n * @returns A new buffer containing the copied data.\n */\n copy = (offset = 0, length = this.length): CyBuffer => {\n this.check(offset, length)\n const buffer = new CyBuffer(length)\n for (let i = 0; i < length; i++) buffer[i] = this.array[i + offset]\n return buffer\n }\n\n /**\n * Returns a new buffer that references the same memory as the original buffer,\n * A lot more efficient than copying it (~ 4 times faster than the `copy` method).\n * @param offset The start offset (optional, defaults to 0).\n * @param end The end offset (optional, defaults to the buffer length).\n * @returns The subarray pointing to the same memory.\n */\n subarray = (offset = 0, length = this.length): CyBuffer => {\n this.check(offset, length)\n\n return new CyBuffer(length, {\n arrayBuffer: this.arrayBuffer,\n offset: offset,\n length: length,\n })\n }\n\n /**\n * Swaps the order of the buffer.\n * @param offset The offset to start swapping at (optional, defaults to 0).\n * @param length The length to swap (optional, defaults to the buffer length).\n * @param wordLength The length per word (optional, defaults to 4).\n * @returns The current buffer instance.\n */\n swap = (offset = 0, length = this.length, wordLength = 4): this => {\n if (wordLength < 2) throw new RangeError(formatCyBufferError(\"swap\", `Invalid word length: '${wordLength}'.`))\n\n if (wordLength % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"swap\", `Invalid word length alignment: '${wordLength}'.`))\n }\n\n this.check(offset, length)\n\n const calculatedLength = offset + length\n for (let i = 0; i < calculatedLength; i += wordLength) {\n const offsetIndex = i + offset\n\n for (let j = 0; j < wordLength / 2; j++) {\n const temp = this.array[offsetIndex + j]\n this.array[offsetIndex + j] = this.array[offsetIndex + wordLength - j - 1]\n this.array[offsetIndex + wordLength - j - 1] = temp\n }\n }\n\n return this\n }\n\n /**\n * Reverses a part of the buffer.\n * @param offset The offset to start reversing at (optional, defaults to 0).\n * @param length The length to reverse (optional, defaults to the buffer length).\n * @returns The current buffer instance.\n */\n partialReverse = (offset = 0, length = this.length): this => {\n this.check(offset, length)\n\n const dividedLength = Math.floor(length / 2)\n const calculatedLength = offset + length\n\n for (let i = 0; i < dividedLength; i++) {\n const offsetIndex = i + offset\n const endOffsetIndex = calculatedLength - i - 1\n const temp = this.array[offsetIndex]\n this.array[offsetIndex] = this.array[endOffsetIndex]\n this.array[endOffsetIndex] = temp\n }\n\n return this\n }\n\n /**\n * Reverses the entire buffer.\n * @returns The current buffer instance.\n */\n reverse = (): this => {\n this.array.reverse()\n return this\n }\n\n /**\n * Rotates the buffer to the left.\n * @returns The current buffer instance.\n */\n rotateLeft = (): this => {\n const first = this.array[0]\n\n for (let i = 0; i < this.length - 1; i++) this.array[i] = this.array[i + 1]\n this.array[this.length - 1] = first\n\n return this\n }\n\n /**\n * Rotates the buffer to the right.\n * @returns The current buffer instance.\n */\n rotateRight = (): this => {\n const last = this.array[this.length - 1]\n\n for (let i = this.length - 1; i > 0; i--) this.array[i] = this.array[i - 1]\n this.array[0] = last\n\n return this\n }\n\n /**\n * Shifts the buffer to the left, filling the empty space with zeros.\n * @param offset The offset to start shifting at (optional, defaults to 0).\n * @param length The length to shift (optional, defaults to the buffer length).\n * @param shift The number of bytes to shift (optional, defaults to 1).\n * @returns The current buffer instance.\n */\n shiftLeft = (offset = 0, length = this.length, shift = 1): this => {\n this.check(offset, length)\n\n for (let i = 0; i < this.length - 1; i++) this.array[i] = this.array[i + shift]\n for (let i = 0; i < shift; i++) this.array[this.length - i - 1] = 0\n\n return this\n }\n\n /**\n * Shifts the buffer to the right, filling the empty spaces with zeros.\n * @param offset The offset to start shifting at (optional, defaults to 0).\n * @param length The length to shift (optional, defaults to the buffer length).\n * @param shift The number of bytes to shift (optional, defaults to 1).\n * @returns The current buffer instance.\n */\n shiftRight = (offset = 0, length = this.length, shift = 1): this => {\n this.check(offset, length)\n\n for (let i = this.length - 1; i > 0; i--) this.array[i] = this.array[i - shift]\n for (let i = 0; i < shift; i++) this.array[i] = 0\n\n return this\n }\n\n /**\n * Fills the buffer with a specified value.\n * @param value The value to fill the buffer with.\n * @param offset The offset to start filling at (optional, defaults to 0).\n * @param length The length to fill (optional, defaults to the buffer length).\n * @returns The current buffer instance.\n */\n fill = (value: number, offset = 0, length = this.length): this => {\n if (value < 0 || value > 255) throw new RangeError(formatCyBufferError(\"fill\", `Invalid value: '${value}'.`))\n\n this.check(offset, length)\n this.array.fill(value, offset, offset + length)\n return this\n }\n\n /**\n * Clears the buffer by filling it with zeros.\n * @param offset The offset to start clearing at (optional, defaults to 0).\n * @param length The length to clear (optional, defaults to the buffer length).\n * @returns The current buffer instance.\n */\n clear = (offset = 0, length = this.length): this => {\n this.check(offset, length)\n this.array.fill(0, offset, offset + length)\n return this\n }\n}\n","import { execSync } from \"node:child_process\"\nimport { hostname } from \"node:os\"\n\n/**\n * Get the name of the host on which the application is running.\n * @returns The name of the host.\n */\nexport function getHostname() {\n switch (process.platform) {\n case \"win32\":\n return process.env.COMPUTERNAME\n case \"darwin\":\n return execSync(\"scutil --get ComputerName\").toString().trim()\n case \"linux\": {\n const prettyName = execSync(\"hostnamectl --pretty\").toString().trim()\n return prettyName === \"\" ? hostname() : prettyName\n }\n default:\n return hostname()\n }\n}\n","import { stringify } from \"@/main/json\"\nimport type { ErrorObj, FailedRequest } from \"@/main/types/requests\"\n\n/**\n * Formats an `ErrorObj` into a standard error sent back by an API endpoint.\n */\nexport function formatErrorResponse(error: ErrorObj, customMessage?: string, additionalData?: unknown) {\n let err: ErrorObj\n if (additionalData) err = { ...error, data: additionalData }\n else err = error\n\n return {\n success: false,\n message: customMessage || error.message,\n error: err,\n }\n}\n\n/**\n * Formats an `ErrorObj` and stringifies it for it to be supported by the `Error` class.\n * @param error The `ErrorObj` object to format.\n * @param message Replaces the standard error message with a custom one (optional).\n * @param additionalData Additional data to include in the error (optional).\n * @returns The formatted error string.\n */\nexport function stringifyError(error: ErrorObj, message?: string, additionalData?: unknown): string {\n if (message) error.message = message\n\n let err: ErrorObj\n if (additionalData) err = { ...error, data: additionalData }\n else err = error\n\n // Allow special keys in the JSON stringification\n const allowSpecialKeys = (_: string, value: unknown) => {\n if (typeof value === \"function\") return value.toString()\n if (typeof value === \"bigint\") return value.toString()\n\n return value\n }\n\n return JSON.stringify(err, allowSpecialKeys, 4)\n}\n\n/**\n * Parse the error of a CRUD call and return a standardized error.\n * @param error The error to parse.\n * @returns The standardized error object.\n */\nexport function parseCRUDError(error: unknown): FailedRequest {\n let errorString = \"\"\n\n try {\n try {\n errorString = (error as any).toString()\n } catch (_) {\n errorString = stringify(error)\n }\n } catch (_) {\n errorString = \"Unknown error\"\n }\n\n return {\n success: false,\n message: \"An error occurred while performing a CRUD operation.\",\n error: {\n status: 500,\n name: \"CRUD_ERROR\",\n message: \"CRUD operation failed.\",\n data: {\n rawError: error,\n error: errorString,\n },\n },\n }\n}\n\n/**\n * Formats a message and an error object into a JSON string that follows the `FailedRequest` standard,\n * the goal is to not end up with special characters such as newlines in the message, so it can be parsed\n * back into an object without issues.\n * @param message The message to format.\n * @param error The error object to format.\n * @returns The formatted JSON string.\n */\nexport function formatMessageAsStringifiedError(message: string, error?: unknown): string {\n let errorObj: ErrorObj = {\n status: 500,\n name: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred.\",\n data: null,\n }\n\n if (error) {\n try {\n // Testing with JSON.stringify to see if it's a valid JSON object\n stringify(error, 4)\n\n errorObj = error as ErrorObj\n } catch {\n // Convert the error to a basic non-escaped string\n errorObj = {\n ...errorObj,\n data: {\n rawError: `${error}`,\n },\n }\n }\n }\n\n const res = stringify({\n success: false,\n message,\n error: errorObj,\n })\n\n // Ensure that no \"Error: \" or line break ends up in the message\n return res.replaceAll(\"Error: \", \"\").replaceAll(\"\\n\", \" \")\n}\n\n/**\n * Contains all the standard available errors for the application, it serves as a base\n * to extend with your custom errors.\n *\n * The recommended way is to create an `AppErrors` object that extends this one, preferably\n * at a place similar to `lib/utils/errors.ts`:\n * ```typescript\n * import { BaseErrors } from \"...\"\n *\n * export const AppErrors = {\n * ...BaseErrors,\n * //=====//\n *\t // 401 //\n *\t //=====//\n * BLAH_BLAH: {\n * status: 401,\n * name: \"BlahBlah\",\n * message: \"Blah blah blah.\",\n * data: null,\n * },\n * }\n * ```\n */\nexport const BaseErrors = {\n //=====//\n // 400 //\n //=====//\n BAD_REQUEST: {\n status: 400,\n name: \"BadRequest\",\n message: \"Bad request.\",\n data: null,\n },\n //=====//\n // 401 //\n //=====//\n UNAUTHORIZED: {\n status: 401,\n name: \"Unauthorized\",\n message: \"Unauthorized.\",\n data: null,\n },\n //=====//\n // 402 //\n //=====//\n PAYMENT_REQUIRED: {\n status: 402,\n name: \"PaymentRequired\",\n message: \"Payment required.\",\n data: null,\n },\n //=====//\n // 403 //\n //=====//\n FORBIDDEN: {\n status: 403,\n name: \"Forbidden\",\n message: \"Forbidden.\",\n data: null,\n },\n //=====//\n // 404 //\n //=====//\n NOT_FOUND: {\n status: 404,\n name: \"NotFound\",\n message: \"Not found.\",\n data: null,\n },\n //=====//\n // 405 //\n //=====//\n METHOD_NOT_ALLOWED: {\n status: 405,\n name: \"MethodNotAllowed\",\n message: \"Method not allowed.\",\n data: null,\n },\n //=====//\n // 408 //\n //=====//\n REQUEST_TIMEOUT: {\n status: 408,\n name: \"RequestTimeout\",\n message: \"Request timed out.\",\n data: null,\n },\n //=====//\n // 409 //\n //=====//\n CONFLICT: {\n status: 409,\n name: \"Conflict\",\n message: \"Conflict.\",\n data: null,\n },\n //=====//\n // 500 //\n //=====//\n INTERNAL_SERVER_ERROR: {\n status: 500,\n name: \"InternalServerError\",\n message: \"Internal server error.\",\n data: null,\n },\n BACKEND_FUNCTION_RUNNING_ON_CLIENT: {\n status: 500,\n name: \"BackendFunctionRunningOnClient\",\n message: \"A function reserved for the backend is running on the client.\",\n data: null,\n },\n //=====//\n // 501 //\n //=====//\n NOT_IMPLEMENTED: {\n status: 501,\n name: \"NotImplemented\",\n message: \"Not implemented.\",\n data: null,\n },\n //=====//\n // 509 //\n //=====//\n BANDWIDTH_LIMIT_EXCEEDED: {\n status: 509,\n name: \"BandwidthLimitExceeded\",\n message: \"Bandwidth limit exceeded.\",\n data: null,\n },\n} as const satisfies Record<string, ErrorObj>\n","import type { NextApiRequest, NextApiResponse } from \"next\"\nimport { BaseErrors } from \"@/main/errors\"\nimport type { ErrorObj, FailedRequest } from \"@/main/types/requests\"\n\n/**\n * The type for the overall wrapper options.\n */\n// biome-ignore lint/complexity/noBannedTypes: Unused for now\ntype WrapperOptions = {}\n\n/**\n * The type for a Next API wrapped method input.\n */\nexport type NextApiMethodInput = {\n req: NextApiRequest\n res: NextApiResponse\n wrapper: NextApiWrapper\n}\n\n/**\n * The type for a Next API wrapped method.\n */\ntype NextApiMethod = ({ req, res, wrapper }: NextApiMethodInput) => Promise<void> | void\n\n/**\n * The type for a Next API wrapped method, extended with specific options.\n */\ntype NextApiMethodWithOptions = {\n method: NextApiMethod\n}\n\n/**\n * An object containing all methods for the API route.\n */\ntype NextApiMethods = {\n read?: NextApiMethod | NextApiMethodWithOptions\n write?: NextApiMethod | NextApiMethodWithOptions\n update?: NextApiMethod | NextApiMethodWithOptions\n replace?: NextApiMethod | NextApiMethodWithOptions\n remove?: NextApiMethod | NextApiMethodWithOptions\n}\n\n/**\n * A class that wraps the Next.js API routes.\n */\nexport default class NextApiWrapper {\n private _req!: NextApiRequest\n private _res!: NextApiResponse\n\n // Methods\n private _read: NextApiMethod | NextApiMethodWithOptions | undefined\n private _write: NextApiMethod | NextApiMethodWithOptions | undefined\n private _update: NextApiMethod | NextApiMethodWithOptions | undefined\n private _replace: NextApiMethod | NextApiMethodWithOptions | undefined\n private _remove: NextApiMethod | NextApiMethodWithOptions | undefined\n\n // Options\n private _options!: WrapperOptions\n\n /**\n * The constructor for the `NextApiWrapper` class.\n * @param req The `NextApiRequest` object.\n * @param res The `NextApiResponse` object.\n * @param methods The methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n * @param options The options for the wrapper:\n * - (Currently none)\n */\n constructor(req: NextApiRequest, res: NextApiResponse, methods?: NextApiMethods, options?: WrapperOptions) {\n this.setRequestResponse(req, res)\n this.setMethods(methods || {})\n this.setOptions(options || {})\n }\n\n /**\n * Set request and response objects.\n * @param req The new `NextApiRequest` object.\n * @param res The new `NextApiResponse` object.\n */\n setRequestResponse(req: NextApiRequest, res: NextApiResponse) {\n this._req = req\n this._res = res\n }\n\n /**\n * Set methods for the API route.\n * @param methods The new methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n */\n setMethods(methods: NextApiMethods) {\n this._read = methods?.read\n this._write = methods?.write\n this._update = methods?.update\n this._replace = methods?.replace\n this._remove = methods?.remove\n }\n\n /**\n * Set options for the API route.\n * @param options The new options for the wrapper:\n * - (Currently none)\n */\n setOptions(options: Partial<WrapperOptions>) {\n this._options = { ...this._options, ...options }\n }\n\n /**\n * A private method to check data validity.\n * @param data The data to be checked.\n * @returns Whether the data is valid.\n */\n private _checkDataValidity(data: unknown) {\n if (data === undefined || data === null) return false\n return true\n }\n\n /**\n * Returns a properly formatted success response.\n * @param status Status code to be sent in the response.\n * @param data Data to be sent in the response (optional, defaults to `null`).\n */\n successResponse(status: number, data?: unknown) {\n return this._res.status(status).send({\n success: true,\n data: this._checkDataValidity(data) ? data : null,\n })\n }\n\n /**\n * Returns a properly formatted error response, based on error constants.\n * @param error Error code constant to be sent in the response.\n * @param data Additional data to be sent in the response (optional).\n * @param message Error message to be sent in the response (optional, defaults to the internal error message).\n */\n errorResponse(error: ErrorObj, data?: unknown, message?: string) {\n const response: FailedRequest = {\n success: false,\n message: message || error.message,\n error: this._checkDataValidity(data) ? { ...error, data } : error,\n }\n\n return this._res.status(error.status).send(response)\n }\n\n /**\n * Check if a method is a direct method or a method with options and execute it.\n * @param method The method to be checked.\n * @param methodInput The method input object.\n * @returns Whether the method was executed successfully.\n */\n private async _executeMethod(method: NextApiMethod | NextApiMethodWithOptions, methodInput: NextApiMethodInput) {\n if (typeof method === \"function\") {\n await method(methodInput)\n return true\n }\n\n await method.method(methodInput)\n return true\n }\n\n /**\n * Run and route the request to the appropriate method.\n * @returns The response from the method.\n */\n async run() {\n const methodInput: NextApiMethodInput = {\n req: this._req,\n res: this._res,\n wrapper: this,\n }\n\n try {\n switch (this._req.method) {\n case \"GET\":\n if (this._read) return await this._executeMethod(this._read, methodInput)\n break\n case \"POST\":\n if (this._write) return await this._executeMethod(this._write, methodInput)\n break\n case \"PATCH\":\n if (this._update) return await this._executeMethod(this._update, methodInput)\n break\n case \"PUT\":\n if (this._replace) return await this._executeMethod(this._replace, methodInput)\n break\n case \"DELETE\":\n if (this._remove) return await this._executeMethod(this._remove, methodInput)\n break\n default:\n return this.errorResponse(BaseErrors.METHOD_NOT_ALLOWED)\n }\n } catch (error) {\n return this.errorResponse(BaseErrors.INTERNAL_SERVER_ERROR, error)\n }\n }\n}\n","import type { NextApiRequest, NextApiResponse } from \"next\"\nimport type { Session } from \"next-auth\"\nimport { BaseErrors } from \"@/main/errors\"\nimport type { ErrorObj, FailedRequest } from \"@/main/types/requests\"\n\n/**\n * A session with a user extended with optional roles.\n */\nexport type ExtendedSession = Session & {\n user: Session[\"user\"] & {\n roles: string[] | undefined\n }\n}\n\n/**\n * The type for the authentication options.\n */\nexport type AuthOptions = {\n requireAuth?: boolean\n hasRole?: string\n hasSomeRoles?: string[]\n hasAllRoles?: string[]\n}\n\n/**\n * The type for the overall wrapper options.\n */\ntype WrapperOptions = {\n authFunction?: (req: NextApiRequest, res: NextApiResponse) => Promise<ExtendedSession | null>\n roles?: string[]\n} & AuthOptions\n\n/**\n * The type for a Next API wrapped method input.\n */\nexport type NextAuthApiMethodInput = {\n req: NextApiRequest\n res: NextApiResponse\n session: ExtendedSession | null\n wrapper: NextAuthApiWrapper\n}\n\n/**\n * The type for a Next API wrapped method.\n */\ntype NextApiMethod = ({ req, res, session, wrapper }: NextAuthApiMethodInput) => Promise<void> | void\n\n/**\n * The type for a Next API wrapped method, extended with specific auth options.\n */\ntype NextAuthApiMethodWithAuthOptions = {\n method: NextApiMethod\n authOptions?: AuthOptions\n}\n\n/**\n * An object containing all methods for the API route.\n */\ntype NextApiMethods = {\n read?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n write?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n update?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n replace?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n remove?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n}\n\n/**\n * A class that wraps the Next.js API routes.\n */\nexport default class NextAuthApiWrapper {\n private _req!: NextApiRequest\n private _res!: NextApiResponse\n\n // Methods\n private _read: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _write: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _update: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _replace: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _remove: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n\n // Options\n private _options!: WrapperOptions\n\n /**\n * The constructor for the `NextAuthApiWrapper` class.\n * @param req The `NextApiRequest` object.\n * @param res The `NextApiResponse` object.\n * @param methods The methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n * @param options The options for the wrapper:\n * - `authFunction`: The function to be used for authentication.\n * - `roles`: The roles to be used for the wrapper.\n * - `requireAuth`: Whether to require authentication (defaults to `false`).\n * - `hasRole`: The user needs to have the role.\n * - `hasSomeRoles`: The user needs to have at least one of the roles.\n * - `hasAllRoles`: The user needs to have all of the roles.\n */\n constructor(req: NextApiRequest, res: NextApiResponse, methods?: NextApiMethods, options?: WrapperOptions) {\n this.setRequestResponse(req, res)\n this.setMethods(methods || {})\n this.setOptions(options || {})\n }\n\n /**\n * Set request and response objects.\n * @param req The new `NextApiRequest` object.\n * @param res The new `NextApiResponse` object.\n */\n setRequestResponse(req: NextApiRequest, res: NextApiResponse) {\n this._req = req\n this._res = res\n }\n\n /**\n * Set methods for the API route.\n * @param methods The new methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n */\n setMethods(methods: NextApiMethods) {\n this._read = methods?.read\n this._write = methods?.write\n this._update = methods?.update\n this._replace = methods?.replace\n this._remove = methods?.remove\n }\n\n /**\n * Set options for the API route.\n * @param options The new options for the wrapper:\n * - `authFunction`: The function to be used for authentication.\n * - `roles`: The roles to be used for the wrapper.\n * - `requireAuth`: Whether to require authentication (defaults to `false`).\n * - `hasRole`: The user needs to have the role.\n * - `hasSomeRoles`: The user needs to have at least one of the roles.\n * - `hasAllRoles`: The user needs to have all of the roles.\n */\n setOptions(options: Partial<WrapperOptions>) {\n this._options = { ...this._options, ...options }\n }\n\n /**\n * A private method to check data validity.\n * @param data The data to be checked.\n * @returns Whether the data is valid.\n */\n private _checkDataValidity(data: unknown) {\n if (data === undefined || data === null) return false\n return true\n }\n\n /**\n * Returns a properly formatted success response.\n * @param status Status code to be sent in the response.\n * @param data Data to be sent in the response (optional, defaults to `null`).\n */\n successResponse(status: number, data?: unknown) {\n return this._res.status(status).send({\n success: true,\n data: this._checkDataValidity(data) ? data : null,\n })\n }\n\n /**\n * Returns a properly formatted error response, based on error constants.\n * @param error Error code constant to be sent in the response.\n * @param data Additional data to be sent in the response (optional).\n * @param message Error message to be sent in the response (optional, defaults to the internal error message).\n */\n errorResponse(error: ErrorObj, data?: unknown, message?: string) {\n const response: FailedRequest = {\n success: false,\n message: message || error.message,\n error: this._checkDataValidity(data) ? { ...error, data } : error,\n }\n\n return this._res.status(error.status).send(response)\n }\n\n /**\n * Verify if the user has a specific role.\n * @param user The user object.\n * @param role The role to be checked.\n * @returns Whether the user has the role.\n */\n hasRole(user: ExtendedSession[\"user\"], role: string) {\n return user.roles?.includes(role)\n }\n\n /**\n * Verify if the user has at least one of the roles.\n * @param user The user object.\n * @param roles The roles to be checked.\n * @returns Whether the user has at least one of the roles.\n */\n hasSomeRoles(user: ExtendedSession[\"user\"], roles: string[]) {\n return roles.some(role => user.roles?.includes(role))\n }\n\n /**\n * Verify if the user has all of the roles.\n * @param user The user object.\n * @param roles The roles to be checked.\n * @returns Whether the user has all of the roles.\n */\n hasAllRoles(user: ExtendedSession[\"user\"], roles: string[]) {\n return roles.every(role => user.roles?.includes(role))\n }\n\n /**\n * Check the authentication and roles of the user based on the auth options.\n * @param session The session object.\n * @param authOptions The authentication options.\n * @returns Whether the user has the required authentication and roles.\n */\n checkAuthOptions(session: ExtendedSession | null, authOptions: AuthOptions) {\n if (authOptions.requireAuth) {\n if (!session) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n if (authOptions.hasRole) {\n if (!session || !this.hasRole(session.user, authOptions.hasRole)) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n if (authOptions.hasSomeRoles) {\n if (!session || !this.hasSomeRoles(session.user, authOptions.hasSomeRoles)) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n if (authOptions.hasAllRoles) {\n if (!session || !this.hasAllRoles(session.user, authOptions.hasAllRoles)) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n return true\n }\n\n /**\n * Check if a method is a direct method or a method with auth options and execute it.\n * @param method The method to be checked.\n * @param methodInput The method input object.\n * @returns Whether the method was executed successfully.\n */\n private async _executeMethod(\n method: NextApiMethod | NextAuthApiMethodWithAuthOptions,\n methodInput: NextAuthApiMethodInput,\n ) {\n if (typeof method === \"function\") {\n await method(methodInput)\n return true\n }\n\n if (method.authOptions) {\n const authCheckRes = this.checkAuthOptions(methodInput.session, method.authOptions)\n if (!authCheckRes) return false\n }\n\n await method.method(methodInput)\n return true\n }\n\n /**\n * Run and route the request to the appropriate method.\n * @returns The response from the method.\n */\n async run() {\n const session = this._options.authFunction ? await this._options.authFunction(this._req, this._res) : null\n const authCheckRes = this.checkAuthOptions(session, this._options)\n if (!authCheckRes) return\n\n const methodInput: NextAuthApiMethodInput = {\n req: this._req,\n res: this._res,\n session,\n wrapper: this,\n }\n\n try {\n switch (this._req.method) {\n case \"GET\":\n if (this._read) return await this._executeMethod(this._read, methodInput)\n break\n case \"POST\":\n if (this._write) return await this._executeMethod(this._write, methodInput)\n break\n case \"PATCH\":\n if (this._update) return await this._executeMethod(this._update, methodInput)\n break\n case \"PUT\":\n if (this._replace) return await this._executeMethod(this._replace, methodInput)\n break\n case \"DELETE\":\n if (this._remove) return await this._executeMethod(this._remove, methodInput)\n break\n default:\n return this.errorResponse(BaseErrors.METHOD_NOT_ALLOWED)\n }\n } catch (error) {\n return this.errorResponse(BaseErrors.INTERNAL_SERVER_ERROR, error)\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/main/json.ts","../src/backend/logger.ts","../src/main/formats.ts","../src/backend/bench.ts","../src/backend/cgas/status.ts","../src/backend/crypto.ts","../src/backend/cybuffer.ts","../src/backend/host.ts","../src/main/errors.ts","../src/backend/next/nextApiWrapper.ts","../src/backend/next/nextAuthApiWrapper.ts"],"names":["stringify","object","indent","_","value","defaultParameters","parameters","formatMessage","log","colors","native","foreign","acc","key","strLevel","effect","color","formattedDate","dateFormat","masks","formattedLevel","formattedForeign","line","index","finalLog","stream","pretty","__","logger","pino","level","showLevel","showTimestamp","foreignObjectStartAtNewLine","padding","alignForeignObject","newParameters","logger_default","slugifyLib","formatUnit","num","unit","timeUnit","addSpaceBeforeUnit","strUnit","spaceOrNot","formatHRTime","hrtime","formatPercentage","percentage","Bench","benchmarkDuration","fn","name","initialTime","operationsPerSecond","avgExecutionTime","operations","totalTime","t0","t1","internalBenchmarkDuration","i","category","clear","benchCategory","longestFnName","functions","b","result","fastestFn","formattedFnName","formattedAvgExecutionTime","formattedOperationsPerSecond","formattedPercentage","indicatorPadding","generateCGASStatus","status","marker","version","message","markerOnly","aes256GcmEncrypt","data","keyBuffer","iv","randomBytes","cipher","createCipheriv","ciphertext","tag","payload","aes256GcmDecrypt","decipher","createDecipheriv","plaintext","aes256GcmDecryptPayload","parts","crypto","formatCyBufferError","CyBuffer","_CyBuffer","length","options","tmpUint8Array","tmpUint16View","endianness","offset","fillWith","buffer","byteLength","encoding","array","msbFirst","start","end","target","prop","parsedValue","highNibble","lowNibble","bitOffset","check","orientedOffset","verifyAlignment","bitLength","arrayOffset","orderedBitOffset","bits","prefix","hexString","hexPrefix","randomFillSync","wordLength","calculatedLength","offsetIndex","j","temp","dividedLength","endOffsetIndex","first","last","shift","getHostname","execSync","prettyName","hostname","BaseErrors","NextApiWrapper","req","res","methods","error","response","method","methodInput","NextAuthApiWrapper","user","role","roles","session","authOptions"],"mappings":"sPAeO,SAASA,CAAAA,CAAUC,CAAAA,CAAiBC,CAAAA,CAAS,CAAA,CAAW,CAC3D,OAAO,IAAA,CAAK,SAAA,CACRD,CAAAA,CACA,CAACE,CAAAA,CAAGC,CAAAA,GACI,OAAOA,CAAAA,EAAU,UAAA,EACjB,OAAOA,CAAAA,EAAU,QAAA,CAAiBA,CAAAA,CAAM,QAAA,EAAS,CAE9CA,CAAAA,CAEXF,CACJ,CACJ,CCJA,IAAMG,CAAAA,CAAgC,CAClC,KAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,EAAa,OAAA,CAChC,SAAA,CAAW,IAAA,CACX,aAAA,CAAe,IAAA,CACf,2BAAA,CAA6B,KAAA,CAC7B,oBAAA,CAAsB,CAAA,CACtB,mBAAA,CAAqB,CAAA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AASK,EAAO,CACZ,OAAO,IAAA,CAAK,aAAA,CAAcL,CAAAA,CAAW,qBAAA,CAAuBK,CAAK,CACrE,CACJ,CACJ","file":"backend.js","sourcesContent":["/**\n * Format a JSON object with indentation.\n * @param str The JSON string to format.\n * @returns The formatted JSON string.\n */\nexport function formatJson(str: string): string {\n return JSON.stringify(JSON.parse(str), null, 4)\n}\n\n/**\n * Stringify a JSON object with support for BigInt and functions.\n * @param object The object to stringify.\n * @param indent The number of spaces to indent (optional, defaults to 4)\n * @returns The stringified JSON object.\n */\nexport function stringify(object: unknown, indent = 4): string {\n return JSON.stringify(\n object,\n (_, value) => {\n if (typeof value === \"function\") return value.toString()\n if (typeof value === \"bigint\") return value.toString()\n\n return value\n },\n indent,\n )\n}\n","import type { Color, Colorette } from \"colorette\"\nimport dateFormat, { masks } from \"dateformat\"\nimport pino, { type LogDescriptor } from \"pino\"\nimport pretty from \"pino-pretty\"\nimport { stringify } from \"@/main/json\"\n\n/**\n * The type of the parameters object.\n */\ntype Parameters = {\n level: pino.LevelWithSilentOrString\n showLevel: boolean\n showTimestamp: boolean\n foreignObjectStartAtNewLine: boolean\n foreignObjectPadding: number | \"after-timestamp\" | \"after-level\"\n foreignObjectIndent: number\n alignForeignObject?: boolean\n}\n\n/**\n * The default parameters for the logger instance.\n */\nconst defaultParameters: Parameters = {\n level: process.env.LOG_LEVEL || \"trace\",\n showLevel: true,\n showTimestamp: true,\n foreignObjectStartAtNewLine: false,\n foreignObjectPadding: 0,\n foreignObjectIndent: 4,\n alignForeignObject: false,\n}\n\n/**\n * Temporary parameters for the current logger instance.\n */\nconst parameters: Parameters = { ...defaultParameters }\n\n/**\n * Modify the format of the message depending on the log level.\n * @param log The log descriptor.\n * @returns The formatted message.\n */\nfunction formatMessage(log: LogDescriptor, colors: Colorette): string {\n const native = {\n level: log.level,\n time: log.time,\n pid: log.pid,\n hostname: log.hostname,\n msg: log.msg,\n }\n\n // Generate an object with foreign keys and their values\n const foreign = Object.entries(log).reduce((acc: { [key: string]: unknown }, [key, value]) => {\n if (!Object.keys(native).includes(key)) acc[key] = value\n return acc\n }, {})\n\n let strLevel = \"N/A\"\n let effect: Color | undefined\n let color: Color\n\n switch (log.level as number | string) {\n case 10:\n case \"trace\":\n strLevel = \"TRACE\"\n color = colors.black\n break\n case 20:\n case \"debug\":\n strLevel = \"DEBUG\"\n color = colors.blue\n break\n case 30:\n case \"info\":\n strLevel = \"INFO\"\n color = colors.green\n break\n case 40:\n case \"warn\":\n strLevel = \"WARN\"\n color = colors.yellow\n break\n case 50:\n case \"error\":\n strLevel = \"ERROR\"\n color = colors.redBright\n break\n case 60:\n case \"fatal\":\n strLevel = \"FATAL\"\n effect = colors.bold\n color = colors.redBright\n break\n default:\n strLevel = \"N/A\"\n color = colors.white\n break\n }\n\n let formattedDate = \"\"\n if (parameters.showTimestamp) formattedDate = `[${dateFormat(new Date(log.time), masks.isoDateTime)}] `\n\n let formattedLevel = \"\"\n if (parameters.showLevel) {\n formattedLevel = parameters.alignForeignObject ? `[${strLevel}] `.padEnd(8, \" \") : `[${strLevel}] `\n }\n\n let formattedForeign = \"\"\n if (Object.keys(foreign).length > 0) {\n if (parameters.foreignObjectPadding === \"after-timestamp\") {\n parameters.foreignObjectPadding = formattedDate.length\n } else if (parameters.foreignObjectPadding === \"after-level\") {\n parameters.foreignObjectPadding = formattedDate.length + formattedLevel.length\n }\n\n formattedForeign =\n `${parameters.foreignObjectStartAtNewLine ? \"\\n\" : \" \"}${stringify(foreign, parameters.foreignObjectIndent)}`\n .split(\"\\n\")\n .map((line, index) => {\n if (index === 0) return line\n return line.padStart(line.length + (parameters.foreignObjectPadding as number), \" \")\n })\n .join(\"\\n\")\n }\n\n let finalLog = color(`${formattedDate}${formattedLevel}${log.msg}${formattedForeign}`)\n if (effect) finalLog = effect(finalLog)\n\n console.log(finalLog)\n return \"\"\n}\n\n/**\n * The pretty logger stream, note that no keys are included by defaults, everything goes through\n * the message format function via the `log` object.\n */\nconst stream = pretty({\n crlf: false,\n colorize: true,\n sync: true,\n include: \"\",\n messageFormat: (log, _, __, { colors }) => formatMessage(log, colors),\n})\n\n/**\n * A custom logger instance compatible with both front and back-end, allowing to log messages\n * with different levels and colors.\n *\n * The available levels are:\n * - `fatal`\n * - `error`\n * - `warn`\n * - `info`\n * - `debug`\n * - `trace`\n *\n * The available parameters are:\n * - `setLevel`: Set the logger level (defaults to `\"trace\"`).\n * - `setShowLevel`: Set the logger level display (defaults to `true`).\n * - `setShowTimestamp`: Set the logger timestamp display (defaults to `true`).\n * - `setForeignObjectStartAtNewLine`: Set the logger foreign object new line display (defaults to `false`).\n * - `setForeignObjectPadding`: Set the padding for foreign objects (defaults to `0`).\n * - `setForeignObjectIndent`: Set the indent for foreign objects (defaults to `4`).\n * - `setAlignForeignObject`: Align any foreign object to the same column (defaults to `false`).\n * - `setParameters`: Set all the parameters at once.\n * - `resetParameters`: Reset all the parameters to their default values.\n */\nconst logger = pino({ level: parameters.level }, stream) as pino.Logger & {\n /**\n * Set the logger level, available levels are:\n * - `fatal`\n * - `error`\n * - `warn`\n * - `info`\n * - `debug`\n * - `trace`\n *\n * The logging level is a **minimum** level. For instance if `logger.level` is `\"info\"` then all\n * `\"fatal\"`, `\"error\"`, `\"warn\"` and `\"info\"` logs will be enabled.\n * @param level The new logger level.\n */\n setLevel: (level: Parameters[\"level\"]) => void\n\n /**\n * Set the logger level display.\n * @param showLevel Whether to show the level or not.\n */\n setShowLevel: (showLevel: Parameters[\"showLevel\"]) => void\n\n /**\n * Set the logger timestamp display.\n * @param showTimestamp Whether to show the timestamp or not.\n */\n setShowTimestamp: (showTimestamp: Parameters[\"showTimestamp\"]) => void\n\n /**\n * Set the logger foreign object new line display (wether to start the foreign object on a new line or not).\n * @param foreignObjectStartAtNewLine Whether to start the foreign object on a new line or not.\n */\n setForeignObjectStartAtNewLine: (foreignObjectStartAtNewLine: Parameters[\"foreignObjectStartAtNewLine\"]) => void\n\n /**\n * Set the padding for foreign objects, it also accepts `\"after-timestamp\"` and\n * `\"after-level\"` to automatically calculate the padding to match the beginning of the\n * specified element.\n * @param padding The padding for foreign objects.\n */\n setForeignObjectPadding: (padding: Parameters[\"foreignObjectPadding\"]) => void\n\n /**\n * Set the indent for foreign objects.\n * @param indent The indent for foreign objects.\n */\n setForeignObjectIndent: (indent: Parameters[\"foreignObjectIndent\"]) => void\n\n /**\n * Set whether to align any foreign object to the same column.\n * @param alignForeignObject Whether to align any foreign object to the same column.\n */\n setAlignForeignObject: (alignForeignObject: Parameters[\"alignForeignObject\"]) => void\n\n /**\n * Set all the parameters at once.\n * @param parameters The new parameters.\n */\n setParameters: (parameters: Parameters) => void\n\n /**\n * Reset all the parameters to their default values.\n */\n resetParameters: () => void\n}\n\n// Inject the getters and setters\n\nlogger.setLevel = (level: Parameters[\"level\"]) => {\n parameters.level = level\n logger.level = level\n}\n\nlogger.setShowLevel = (showLevel: Parameters[\"showLevel\"]) => {\n parameters.showLevel = showLevel\n}\n\nlogger.setShowTimestamp = (showTimestamp: Parameters[\"showTimestamp\"]) => {\n parameters.showTimestamp = showTimestamp\n}\n\nlogger.setForeignObjectStartAtNewLine = (foreignObjectStartAtNewLine: Parameters[\"foreignObjectStartAtNewLine\"]) => {\n parameters.foreignObjectStartAtNewLine = foreignObjectStartAtNewLine\n}\n\nlogger.setForeignObjectPadding = (padding: Parameters[\"foreignObjectPadding\"]) => {\n parameters.foreignObjectPadding = padding\n}\n\nlogger.setForeignObjectIndent = (indent: Parameters[\"foreignObjectIndent\"]) => {\n parameters.foreignObjectIndent = indent\n}\n\nlogger.setAlignForeignObject = (alignForeignObject: Parameters[\"alignForeignObject\"] = false) => {\n parameters.alignForeignObject = alignForeignObject\n}\n\nlogger.setParameters = (newParameters: Parameters) => {\n Object.assign(parameters, newParameters)\n}\n\nlogger.resetParameters = () => {\n Object.assign(parameters, defaultParameters)\n}\n\nexport default logger\n","import slugifyLib from \"slugify\"\nimport CyCONSTANTS from \"@/main/constants\"\n\n/**\n * The slugify function from the slugify library.\n */\nconst slugify = (slugifyLib as any).default || slugifyLib\n\n/**\n * Validate a direct ID parameter (as integer for SQL DBs etc..).\n * @param id The ID to validate.\n * @returns True if the ID is valid, false otherwise.\n */\nexport function isValidIntId(id: string): boolean {\n return typeof id === \"string\" && id.length > 0 && Number.isInteger(Number(id)) && Number(id) >= 0\n}\n\n/**\n * Validates a slug.\n * @param slug The slug to validate.\n * @returns True if the slug is valid, false otherwise.\n */\nexport function isValidSlug(slug: string): boolean {\n return typeof slug === \"string\" && slug.length > 0 && CyCONSTANTS.SLUG_REGEX.test(slug)\n}\n\n/**\n * Format a number with an attached unit + an optional time unit.\n *\n * **Note:** The time unit can be set to null to only display the unit.\n * @param num The number to format.\n * @param unit The unit to use (optional, defaults to \"Op\").\n * @param timeUnit The time unit to use (optional, defaults to \"s\").\n * @param padding The padding to use (optional, defaults to 12).\n * @param addSpaceBeforeUnit Whether to add a space before the unit (optional, defaults to `true`).\n * @returns The formatted string.\n */\nexport function formatUnit(\n num: number,\n unit: string | null = \"Op\",\n timeUnit: string | null = \"s\",\n padding = 12,\n addSpaceBeforeUnit = true,\n): string {\n let strUnit: string\n\n if (typeof unit === \"string\" && typeof timeUnit === \"string\") {\n strUnit = `${unit}/${timeUnit}`\n } else if (typeof unit === \"string\") {\n strUnit = unit\n } else {\n strUnit = \"\"\n }\n\n // Add a space before the unit if needed\n const spaceOrNot = addSpaceBeforeUnit ? \" \" : \"\"\n\n // Y = yotta\n if (num >= 10 ** 24) {\n return `${(num / 10 ** 24).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}Y${strUnit}`.padStart(padding, \" \")\n }\n\n // E = exa\n if (num >= 10 ** 18) {\n return `${(num / 10 ** 18).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}E${strUnit}`.padStart(padding, \" \")\n }\n\n // P = peta\n if (num >= 10 ** 15) {\n return `${(num / 10 ** 15).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}P${strUnit}`.padStart(padding, \" \")\n }\n\n // T = tera\n if (num >= 10 ** 12) {\n return `${(num / 10 ** 12).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}T${strUnit}`.padStart(padding, \" \")\n }\n\n // G = giga\n if (num >= 10 ** 9) {\n return `${(num / 10 ** 9).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}G${strUnit}`.padStart(padding, \" \")\n }\n\n // M = mega\n if (num >= 10 ** 6) {\n return `${(num / 10 ** 6).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}M${strUnit}`.padStart(padding, \" \")\n }\n\n // k = kilo\n if (num >= 10 ** 3) {\n return `${(num / 10 ** 3).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}k${strUnit}`.padStart(padding, \" \")\n }\n\n return `${num.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}${spaceOrNot}${strUnit}`.padStart(padding, \" \")\n}\n\n/**\n * Format a high-resolution time, into a responsive string with the en-US locale format.\n * @param hrtime The hrtime in nanoseconds.\n * @param padding The padding to use (optional, defaults to 8).\n * @returns The formatted string.\n */\nexport function formatHRTime(hrtime: bigint | number, padding = 8): string {\n // Hours\n if (hrtime >= 3600000000000000n) {\n return `${(Number(hrtime) / 3600000000000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}h`.padStart(padding, \" \")\n }\n\n // Minutes\n if (hrtime >= 60000000000n) {\n return `${(Number(hrtime) / 60000000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}m`.padStart(padding, \" \")\n }\n\n // Seconds\n if (hrtime >= 1000000000n) {\n return `${(Number(hrtime) / 1000000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}s`.padStart(padding, \" \")\n }\n\n // Milliseconds\n if (hrtime >= 1000000n) {\n return `${(Number(hrtime) / 1000000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}ms`.padStart(padding, \" \")\n }\n\n // Microseconds\n if (hrtime >= 1000n) {\n return `${(Number(hrtime) / 1000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}µs`.padStart(padding, \" \")\n }\n\n // Nanoseconds\n return `${hrtime.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}ns`.padStart(padding, \" \")\n}\n\n/**\n * Format a time in milliseconds into a responsive string with the en-US locale format.\n * @param time The time in milliseconds.\n * @param padding The padding to use (optional, defaults to 10).\n * @returns The formatted string.\n */\nexport function formatTime(time: number, padding = 10): string {\n // Hours\n if (time >= 3600000) {\n return `${(time / 3600000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}h`.padStart(padding, \" \")\n }\n\n // Minutes\n if (time >= 60000) {\n return `${(time / 60000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}m`.padStart(padding, \" \")\n }\n\n // Seconds\n if (time >= 1000) {\n return `${(time / 1000).toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}s`.padStart(padding, \" \")\n }\n\n // Milliseconds\n return `${time.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}ms`.padStart(padding, \" \")\n}\n\n/**\n * Format a percentage with the en-US locale format.\n * @param percentage The percentage to format.\n * @param padding The padding to use (optional, defaults to 7).\n * @returns The formatted string.\n */\nexport function formatPercentage(percentage: number, padding = 7): string {\n return `${percentage.toLocaleString(\"en-US\", {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}%`.padStart(padding, \" \")\n}\n\n/**\n * Truncate a string to a certain length.\n * @param str The string to truncate.\n * @param len The maximum length of the string.\n * @returns The truncated string.\n */\nexport function truncateString(str: string, len: number) {\n if (str.length <= len) return str\n return `${str.slice(0, len)}...`\n}\n\n/**\n * Parse a query containing either a number or numbers separated by commas and returns an array of numbers.\n * @param query The query string to parse.\n * @returns An array of numbers extracted from the query.\n */\nexport function parseQueryNumberArray(query: string | Array<string>): number[] {\n const result: number[] = []\n const items = Array.isArray(query) ? query : query.split(\",\").map(item => item.trim())\n\n for (const item of items) {\n const num = Number.parseInt(item, 10)\n if (!Number.isNaN(num)) result.push(num)\n }\n\n return result\n}\n\n/**\n * Parse a query containing either a string or strings separated by commas and returns an array of strings.\n * @param query The query string to parse.\n * @returns An array of strings extracted from the query.\n */\nexport function parseQueryStringArray(query: string | Array<string>): string[] {\n const result: string[] = []\n const items = Array.isArray(query) ? query : query.split(\",\").map(item => item.trim())\n\n for (const item of items) {\n if (item.length > 0) result.push(item)\n }\n\n return result\n}\n\n/**\n * The options for the `slugify` function.\n */\nconst slugifyOptions = {\n lower: true,\n strict: true,\n}\n\n/**\n * Slugify a given name with support for automatic number incrementing.\n * @param name The name to slugify.\n * @param previousSlug An optional previous slug to compare against,\n * the previous slug should ends with `-<number>`, this slug will automatically\n * increment the number if the slug already exists.\n * @returns The slugified version of the name.\n */\nexport function slugifyName(name: string, previousSlug?: string): string {\n if (previousSlug) {\n // If the previous slug ends with a number, we increment it\n const match = previousSlug.match(/-(\\d+)$/)\n\n if (match) {\n const number = Number.parseInt(match[1], 10)\n const baseSlug = previousSlug.slice(0, -match[0].length)\n return slugify(`${baseSlug}-${number + 1}`, slugifyOptions)\n }\n }\n\n return slugify(name, slugifyOptions)\n}\n\n/**\n * Formats a number of bytes into a human-readable string with appropriate units.\n * @param bytes The number of bytes.\n * @param decimalPlaces The number of decimal places to include (optional, defaults to 2).\n * @returns The formatted string.\n */\nexport function formatBytes(bytes: number, decimalPlaces = 2): string {\n if (bytes === 0) return \"0 Bytes\"\n\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"]\n\n const i = Math.floor(Math.log(bytes) / Math.log(1024))\n return `${parseFloat((bytes / 1024 ** i).toFixed(decimalPlaces < 0 ? 0 : decimalPlaces))} ${sizes[i]}`\n}\n","import logger from \"@/backend/logger\"\nimport { formatHRTime, formatPercentage, formatUnit } from \"@/main/formats\"\n\n/**\n * The type of the benchmark function result.\n */\nexport type BenchmarkResult = {\n operationsPerSecond: number\n avgExecutionTime: number\n operations: number\n}\n\n/**\n * An object containing multiple benchmark results, ordered by functions.\n */\nexport type BenchmarkResults = {\n [fn: string]: BenchmarkResult\n}\n\n/**\n * A class that provides a simple way to benchmark functions.\n */\nexport default class Bench {\n /**\n * The duration of the benchmark in milliseconds.\n */\n benchmarkDuration: number\n\n /**\n * Stores the results of the benchmark.\n */\n results: BenchmarkResults = {}\n\n /**\n * Creates a new benchmarking instance.\n * @param benchmarkDuration The duration of the benchmark in milliseconds (optional, defaults to 256ms).\n */\n constructor(benchmarkDuration = 256) {\n this.benchmarkDuration = benchmarkDuration\n }\n\n /**\n * The main headless benchmarking function.\n *\n * Does not print anything to the console but returns the number of iterations per second\n * and the logs themselves for further formatting, such as console coloring depending on the results.\n * @param fn The function to run.\n * @param name The name of the function to run.\n * @returns The benchmark result (operations per second, average execution time, and total operations).\n */\n benchmark = (fn: () => unknown, name: string): void => {\n let res: unknown\n\n const initialTime = process.hrtime.bigint()\n\n let operationsPerSecond = 0\n let avgExecutionTime = 0\n let operations = 0\n let totalTime = 0n\n let t0 = 0n\n let t1 = 0n\n\n // Convert the milliseconds benchmark duration to nanoseconds (matching HRTime resolution)\n const internalBenchmarkDuration = BigInt(this.benchmarkDuration) * 1_000_000n\n\n for (let i = 0; i < Number.POSITIVE_INFINITY; i++) {\n t0 = process.hrtime.bigint()\n res = fn()\n t1 = process.hrtime.bigint()\n totalTime += t1 - t0\n\n if (t1 - initialTime >= internalBenchmarkDuration) {\n avgExecutionTime = Number(totalTime) / i\n operationsPerSecond = 1_000_000_000 / avgExecutionTime\n\n // Estimate the number of operations realized\n // Instead of measuring \"i\" because of the other operations in the loop\n operations = Number(t1 - initialTime) / avgExecutionTime\n\n // Access res to prevent the function from being optimized out\n // It slows down the benchmark but is necessary for the result to be far more accurate\n res = `${res}`\n\n // Break after one report\n break\n }\n }\n\n this.results[name] = {\n operationsPerSecond,\n avgExecutionTime: avgExecutionTime,\n operations: operations,\n }\n }\n\n /**\n * Formats and prints multiple benchmark results.\n * @param category The category of the benchmark results (optional, defaults to `RESULTS`).\n * @param clear Whether to clear the results object for the next benchmark (optional, defaults to `true`).\n */\n print = (category?: string, clear = true) => {\n const benchCategory = category || \"RESULTS\"\n\n logger.info(`\\n${benchCategory.toUpperCase()}:`)\n logger.info(\"=\".repeat(benchCategory.length + 1))\n\n // Measure the longest function name for padding\n let longestFnName = 0\n for (const fn of Object.keys(this.results)) {\n if (fn.length > longestFnName) longestFnName = fn.length\n }\n\n // Sort the functions by their operations per second\n const functions = Object.entries(this.results).sort(\n (a, b) => b[1].operationsPerSecond - a[1].operationsPerSecond,\n )\n\n for (const [fn, result] of functions) {\n // Add a percentage for each function\n // based on the fastest function's operations per second\n const fastestFn = functions[0][1].operationsPerSecond\n const percentage = (result.operationsPerSecond / fastestFn) * 100\n\n const formattedFnName = `>> ${fn} `.padEnd(longestFnName + 4, \"═\")\n const formattedAvgExecutionTime = `AVG TIME: ${formatHRTime(result.avgExecutionTime)}`\n const formattedOperationsPerSecond = `OPS: ${formatUnit(result.operationsPerSecond)}`\n const formattedPercentage = `PERCENTAGE: ${formatPercentage(percentage)}`\n\n const log = `${formattedFnName}═> ${formattedAvgExecutionTime} | ${formattedOperationsPerSecond} | ${formattedPercentage}`\n\n const indicatorPadding = 10\n if (percentage >= 90) logger.debug(log + \"(fastest)\".padStart(indicatorPadding, \" \"))\n else if (percentage >= 60) logger.info(log + \"(fast)\".padStart(indicatorPadding, \" \"))\n else if (percentage >= 30) logger.warn(log + \"(medium)\".padStart(indicatorPadding, \" \"))\n else if (percentage >= 10) logger.error(log + \"(slow)\".padStart(indicatorPadding, \" \"))\n else logger.error(log + \"(slowest)\".padStart(indicatorPadding, \" \"))\n }\n\n // Clear the results object for the next benchmark\n if (clear) this.results = {}\n }\n}\n","import type { CGASStatus, CGASStatusString } from \"@/main/types/cgas\"\n\n/**\n * Returns the formatted status of the application based on the different parameters.\n * This function should be executed within the CGAS API endpoint to return the status.\n * @param status The status of the application.\n * @param marker The marker of the application.\n * @param version The version of the application (optional).\n * @param message The message to display (optional).\n * @param markerOnly Whether to only return the marker (optional, defaults to false).\n * @returns The formatted status of the application.\n */\nexport function generateCGASStatus(\n status: CGASStatusString,\n marker: string,\n version: string | undefined,\n message?: string,\n markerOnly?: boolean,\n): CGASStatus | string {\n if (markerOnly) return marker\n\n return {\n status,\n marker,\n timestamp: new Date().toISOString(),\n version: {\n raw: version ?? \"unavailable\",\n formatted: version ? `v${version}` : \"unavailable\",\n },\n message: message ?? \"The application is running smoothly.\",\n }\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\"\n\n/**\n * The return type of the `encrypt` function.\n * - `iv`: Base64-encoded initialization vector used for encryption (no need to store it securely).\n * - `ciphertext`: Base64-encoded ciphertext resulting from the encryption process.\n * - `tag`: Authentication tag as a Buffer, used for verifying the integrity of the ciphertext.\n * - `payload`: Full payload combining iv, ciphertext, and tag, formatted as \"iv.ciphertext.tag\".\n */\nexport type CryptoAes256GcmEncryptResult = {\n iv: string\n ciphertext: string\n tag: Buffer\n payload: string\n}\n\n/**\n * Encrypts data using AES-256-GCM symmetric encryption.\n * @param key The base64-encoded key to use for encryption. Must be 32 bytes when decoded.\n * @param data The plaintext data to encrypt.\n * @returns An object containing the initialization vector (iv), ciphertext, and authentication tag.\n * @throws If any error occurs during encryption.\n */\nfunction aes256GcmEncrypt(key: string, data: string): CryptoAes256GcmEncryptResult {\n const keyBuffer = Buffer.from(key, \"base64\")\n if (keyBuffer.length !== 32) {\n throw new Error(`Invalid key length: expected 32 bytes, got ${keyBuffer.length}`)\n }\n\n const iv = randomBytes(12).toString(\"base64\")\n const cipher = createCipheriv(\"aes-256-gcm\", keyBuffer, Buffer.from(iv, \"base64\"))\n\n let ciphertext = cipher.update(data, \"utf8\", \"base64\")\n ciphertext += cipher.final(\"base64\")\n const tag = cipher.getAuthTag()\n\n const payload = `${iv}.${ciphertext}.${tag.toString(\"base64\")}`\n return { iv, ciphertext, tag, payload }\n}\n\n/**\n * Decrypts data using AES-256-GCM symmetric encryption.\n * @param key The base64-encoded key to use for decryption. Must be 32 bytes when decoded.\n * @param iv The base64-encoded initialization vector used during encryption.\n * @param ciphertext The base64-encoded ciphertext to decrypt.\n * @param tag The base64-encoded authentication tag used during encryption.\n * @returns The decrypted plaintext data or null if decryption fails.\n */\nfunction aes256GcmDecrypt(key: string, iv: string, ciphertext: string, tag: string) {\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", Buffer.from(key, \"base64\"), Buffer.from(iv, \"base64\"))\n decipher.setAuthTag(Buffer.from(tag, \"base64\"))\n\n let plaintext = decipher.update(ciphertext, \"base64\", \"utf8\")\n plaintext += decipher.final(\"utf8\")\n\n return plaintext\n } catch (_) {\n // No information is provided about the error to avoid leaking sensitive data\n return null\n }\n}\n\n/**\n * Decrypts a payload that contains the initialization vector, ciphertext, and authentication tag.\n * @param key The base64-encoded key to use for decryption. Must be 32 bytes when decoded.\n * @param payload The payload string containing iv, ciphertext, and tag separated by dots.\n * @returns The decrypted plaintext data or null if decryption fails.\n */\nfunction aes256GcmDecryptPayload(key: string, payload: string) {\n const parts = payload.split(\".\")\n if (parts.length !== 3) {\n throw new Error(\"Invalid payload format\")\n }\n\n const [iv, ciphertext, tag] = parts\n return aes256GcmDecrypt(key, iv, ciphertext, tag)\n}\n\n/**\n * Contains utility functions for encryption and decryption.\n */\nexport const crypto = {\n aes256Gcm: {\n encrypt: aes256GcmEncrypt,\n decrypt: aes256GcmDecrypt,\n decryptPayload: aes256GcmDecryptPayload,\n },\n}\n","import { randomFillSync } from \"node:crypto\"\n\n/**\n * Format an error message for the CyBuffer class.\n * @param name The name of the module.\n * @param message The error message.\n * @returns The formatted error message.\n */\nfunction formatCyBufferError(name: string, message: string): string {\n return `[CyBuffer - ${name}] ${message}`\n}\n\n/**\n * A type for a single bit (`0` or `1`).\n */\nexport type Bit = 0 | 1\n\n/**\n * A type for the endianness of a buffer.\n */\nexport type Endianness = \"LE\" | \"BE\"\n\n/**\n * A type for the encoding of a string.\n */\nexport type StringEncoding = \"utf8\" | \"hex\"\n\n/**\n * `CyBuffer` is a helper class that indirectly extends the Uint8Array class with additional methods\n * similar to the Buffer class in Node.js, while also providing multiple utility methods\n * linked to advanced cryptography and binary data manipulation.\n */\nexport default class CyBuffer {\n /**\n * The platform's endianness which all related methods will use by default,\n * in order to normalize the endianness parameter.\n */\n readonly platformEndianness: Endianness\n\n /**\n * The ArrayBuffer instance referenced by the buffer.\n */\n readonly arrayBuffer: ArrayBuffer\n\n /**\n * The Uint8Array instance that acts as a bridge between the buffer and the array buffer.\n */\n readonly array: Uint8Array\n\n /**\n * The offset in bytes of the buffer.\n */\n readonly offset: number\n\n /**\n * The length in bytes of the buffer.\n */\n readonly length: number\n\n /**\n * Creates a new `CyBuffer` instance based on a length or an input.\n * @param length The length of the buffer to create.\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param options The options to use (optional).\n * - `arrayBuffer`: The array buffer to use.\n * - `offset`: The offset in bytes to start reading from (optional, defaults to 0).\n * - `length`: The length in bytes to read (optional, defaults to the input length).\n */\n constructor(\n length: number,\n options?: {\n arrayBuffer: ArrayBuffer\n offset?: number\n length?: number\n },\n ) {\n if (length < 0) throw new RangeError(formatCyBufferError(\"constructor\", `Invalid buffer length: '${length}'.`))\n if (!Number.isInteger(length))\n throw new TypeError(formatCyBufferError(\"constructor\", `Invalid buffer length: '${length}'.`))\n\n this.platformEndianness = this.getPlatformEndianness()\n\n if (options) {\n this.arrayBuffer = options.arrayBuffer\n this.offset = options.offset ?? 0\n this.length = options.length ?? length\n this.array = new Uint8Array(this.arrayBuffer, this.offset, this.length)\n } else {\n this.arrayBuffer = new ArrayBuffer(length)\n this.offset = 0\n this.length = length\n this.array = new Uint8Array(this.arrayBuffer)\n }\n\n // Applying proxy\n // biome-ignore lint/correctness/noConstructorReturn: Used to apply the proxy\n return this._proxy\n }\n\n /**\n * ============\n * SIGNATURES\n * ============\n */\n\n /**\n * Signature for the `[]` operator.\n */\n [index: number]: number\n\n /**\n * ==================\n * INTERNAL METHODS\n * ==================\n */\n\n /**\n * Get the platform endianness.\n * @returns The platform endianness.\n */\n getPlatformEndianness = (): Endianness => {\n const tmpUint8Array = new Uint8Array(4)\n const tmpUint16View = new Uint32Array(tmpUint8Array.buffer)\n\n tmpUint16View[0] = 0xff00\n return tmpUint8Array[0] === 0xff ? \"BE\" : \"LE\"\n }\n\n /**\n * Normalizes the endianness parameter.\n *\n * By default, the extended Uint8Array is written for Little Endian, to keep it consistent,\n * if the platform is big endian the endianness parameter is reversed.\n *\n * - Little endian platform:\n * - `LE` read from left to right.\n * - `BE` read from right to left.\n * - Big endian platform:\n * - `LE` read from right to left.\n * - `BE` read from left to right.\n */\n normalizeEndianness = (endianness: Endianness): Endianness => {\n if (this.platformEndianness === \"BE\") {\n if (endianness === \"LE\") return \"BE\"\n return \"LE\"\n }\n\n return endianness\n }\n\n /**\n * Checks the offset and length for validity.\n *\n * **Note:** This method is used internally by the read/write methods.\n * @param offset The offset to check.\n * @param length The length to check.\n * @throws If the offset or length are invalid.\n * @returns The current buffer instance.\n */\n check = (offset: number, length: number): this => {\n if (Number.isNaN(offset) || Number.isNaN(length)) {\n throw new TypeError(formatCyBufferError(\"check\", `Invalid offset: '${offset}' or length: '${length}'.`))\n }\n\n if (offset < 0 || offset >= this.length) {\n throw new RangeError(\n formatCyBufferError(\"check\", `Invalid offset: '${offset}', it must be >= 0 & < ${this.length}.`),\n )\n }\n\n if (length < 1 || length > this.length) {\n throw new RangeError(\n formatCyBufferError(\"check\", `Invalid length: '${length}', it must be > 0 & <= ${this.length}.`),\n )\n }\n\n if (offset + length > this.length) {\n throw new RangeError(\n formatCyBufferError(\n \"check\",\n `Invalid offset (${offset}) + length (${length}): '${offset + length}', it must be <= ${this.length}.`,\n ),\n )\n }\n\n if (offset % 1 !== 0)\n throw new RangeError(formatCyBufferError(\"check\", `Invalid offset alignment: '${offset}'.`))\n if (length % 1 !== 0)\n throw new RangeError(formatCyBufferError(\"check\", `Invalid length alignment: '${length}'.`))\n\n return this\n }\n\n /**\n * ================\n * STATIC METHODS\n * ================\n */\n\n /**\n * Creates a new `CyBuffer` instance of the specified length, initially filled with zeros.\n * @param length The length of the buffer.\n * @param fillWith The value to initially fill the buffer with (optional).\n * @returns A new `CyBuffer` instance.\n */\n static alloc = (length: number, fillWith?: number): CyBuffer => {\n const buffer = new CyBuffer(length)\n if (fillWith !== undefined) buffer.fill(fillWith)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from an hexadecimal string (supports `0x` prefix).\n *\n * **Note:** There is no `endianness` parameter here as there is no concept of word size,\n * the order will simply follow the string.\n * @param value The hexadecimal string to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromHexString = (value: string): CyBuffer => {\n // Remove any `0x` prefix before writing\n if (value.startsWith(\"0x\")) value = value.slice(2)\n\n const byteLength = Math.ceil(value.length / 2)\n const buffer = new CyBuffer(byteLength)\n buffer.writeHexString(value, 0, byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from an UTF-8 string.\n * @param value The UTF-8 string to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUtf8String = (value: string): CyBuffer => {\n const buffer = new CyBuffer(value.length)\n buffer.writeUtf8String(value, 0, value.length)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a string using a specific encoding.\n * @param value The string to create the buffer from.\n * @param encoding The encoding to use (optional, defaults to \"utf8\").\n * @returns A new `CyBuffer` instance.\n */\n static fromString = (value: string, encoding: StringEncoding = \"utf8\"): CyBuffer => {\n const buffer = new CyBuffer(value.length)\n buffer.writeString(value, encoding, 0, value.length)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from an array of bits.\n * @param array The array of bits to create the buffer from.\n * @param msbFirst Whether to write the bits from the most significant bit (optional, defaults to `true`).\n * @returns A new `CyBuffer` instance.\n */\n static fromBits = (array: Bit[], msbFirst = true): CyBuffer => {\n const buffer = new CyBuffer(Math.ceil(array.length / 8))\n buffer.writeBits(array, 0, array.length, msbFirst)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a Uint8Array.\n * @param array The Uint8Array to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUint8Array = (array: Uint8Array): CyBuffer => {\n const buffer = new CyBuffer(array.byteLength)\n buffer.writeUint8Array(array, 0, array.byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a Uint16Array.\n * @param array The Uint16Array to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUint16Array = (array: Uint16Array): CyBuffer => {\n const buffer = new CyBuffer(array.byteLength)\n buffer.writeUint16Array(array, 0, array.byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a Uint32Array.\n * @param array The Uint32Array to create the buffer from.\n * @returns A new `CyBuffer` instance.\n */\n static fromUint32Array = (array: Uint32Array): CyBuffer => {\n const buffer = new CyBuffer(array.byteLength)\n buffer.writeUint32Array(array, 0, array.byteLength)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a big integer.\n * @param value The big integer to create the buffer from.\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns A new `CyBuffer` instance.\n */\n static fromBigInt = (value: bigint, endianness?: Endianness): CyBuffer => {\n if (value < 0n) throw new RangeError(formatCyBufferError(\"fromBigInt\", `Invalid big integer: '${value}'.`))\n\n const byteLength = Math.ceil(value.toString(16).length / 2)\n const buffer = new CyBuffer(byteLength)\n buffer.writeBigInt(value, 0, byteLength, endianness)\n return buffer\n }\n\n /**\n * Creates a new `CyBuffer` instance from a range of numbers between 0 and 255.\n * @param start The start of the range, inclusive.\n * @param end The end of the range, exclusive.\n * @returns A new `CyBuffer` instance.\n */\n static fromRange = (start: number, end: number): CyBuffer => {\n const buffer = new CyBuffer(end - start)\n buffer.writeRange(start, end)\n return buffer\n }\n\n /**\n * ===========\n * ACCESSORS\n * ===========\n */\n\n /**\n * The proxy that allows to access/assign values via the [] operator.\n * Note that both the getter and setter are safe and never throw.\n * @returns The proxy returned by the constructor.\n */\n private get _proxy(): CyBuffer {\n return new Proxy(this, {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !Number.isNaN(Number(prop))) {\n this.check(Number(prop), 1)\n\n return target.array[Number(prop)] ?? undefined\n }\n\n return target[prop as keyof this]\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\" && !Number.isNaN(Number(prop))) {\n const parsedValue = Number(value)\n\n if (Number.isNaN(parsedValue)) {\n throw new TypeError(formatCyBufferError(\"proxy\", `Invalid value: '${value}'.`))\n }\n\n if (parsedValue < 0 || parsedValue > 255) {\n throw new RangeError(formatCyBufferError(\"proxy\", `Value is out of bounds: '${value}'.`))\n }\n\n this.check(Number(prop), 1)\n\n target.array[Number(prop)] = value\n return true\n }\n\n target[prop as keyof this] = value\n return true\n },\n })\n }\n\n /**\n * The symbol iterator of the buffer, allowing to iterate over the buffer\n * using `for..of` loops and returning bytes.\n * @returns A new generator yielding the bytes of the buffer.\n */\n *[Symbol.iterator](): Generator<number> {\n let i = 0\n while (i < this.length) yield this.array[i++]\n }\n\n /**\n * Iterates over the buffer and yields the index and value of each byte as an array.\n * @returns The generator yielding the index and value of each byte.\n */\n *entries(): Generator<[number, number]> {\n for (let i = 0; i < this.length; i++) {\n yield [i, this.array[i]]\n }\n }\n\n /**\n * ===============\n * WRITE METHODS\n * ===============\n */\n\n /**\n * Writes an hexadecimal string to the buffer (supports `0x` prefix).\n *\n * **Note:** There is no `endianness` parameter here as there is no concept of word size,\n * the order will simply follow the string.\n * @param value The hexadecimal string to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the value length).\n * @returns The current buffer instance.\n */\n writeHexString = (value: string, offset = 0, length = value.length / 2): this => {\n if (length === 0) {\n throw new RangeError(\n formatCyBufferError(\"writeHexString\", `Invalid hexadecimal string length: '${length}'.`),\n )\n }\n\n if (length % 1 !== 0) {\n throw new RangeError(\n formatCyBufferError(\"writeHexString\", `Invalid hexadecimal string length: '${length}'.`),\n )\n }\n\n if (value.length % 2 !== 0) {\n throw new RangeError(\n formatCyBufferError(\"writeHexString\", `Invalid hexadecimal string length: '${value.length}'.`),\n )\n }\n\n // Remove any `0x` prefix before writing\n if (value.startsWith(\"0x\")) {\n // Detects if the length is equal to the default value,\n // if it is, edit the length by removing the prefix\n if (length === value.length / 2) length = (value.length - 2) / 2\n value = value.slice(2)\n }\n\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n const highNibble = value.charCodeAt(i * 2) | 0x20 // Convert to lowercase for A-F\n const lowNibble = value.charCodeAt(i * 2 + 1) | 0x20 // Convert to lowercase for A-F\n\n // Converts the pair of hexadecimal characters to a byte\n this.array[offset + i] =\n ((highNibble - (highNibble > 57 ? 87 : 48)) << 4) | (lowNibble - (lowNibble > 57 ? 87 : 48))\n }\n\n return this\n }\n\n /**\n * Writes an UTF-8 string to the buffer.\n * @param value The UTF-8 string to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the value length).\n * @returns The current buffer instance.\n */\n writeUtf8String = (value: string, offset = 0, length = value.length): this => {\n if (length === 0) {\n throw new RangeError(formatCyBufferError(\"writeUtf8String\", `Invalid UTF-8 string length: '${length}'.`))\n }\n\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) this.array[offset + i] = value.charCodeAt(i)\n return this\n }\n\n /**\n * Writes a string to the buffer using a specific encoding.\n *\n * **Notes:**\n * - The `hex` encoding supports `0x` prefix but there's no `endianness` parameter here,\n * it follows the order of the string.\n * @param value The string to write to the buffer.\n * @param encoding The encoding to use (optional, defaults to \"utf8\").\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the value length).\n * @returns The current buffer instance.\n */\n writeString = (value: string, encoding: StringEncoding = \"utf8\", offset = 0, length = value.length): this => {\n if (encoding === \"utf8\") {\n this.writeUtf8String(value, offset, length)\n return this\n }\n\n if (encoding === \"hex\") {\n this.writeHexString(value, offset, Math.ceil(length / 2))\n return this\n }\n\n throw new TypeError(formatCyBufferError(\"writeString\", `Invalid encoding: '${encoding}'.`))\n }\n\n /**\n * Writes a single bit to the buffer.\n * @param value The value to write (`0` or `1`).\n * @param bitOffset The offset to read from **as a number of bits** (optional, defaults to 0).\n * @param msbFirst Whether to write the bit to the most significant bit (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeBit = (value: Bit, bitOffset = 0, msbFirst = true, check = true): this => {\n if (value < 0 || value > 1)\n throw new RangeError(formatCyBufferError(\"writeBit\", `Value is out of bounds: '${value}'.`))\n\n const offset = Math.floor(bitOffset / 8)\n if (check) this.check(offset, 1)\n\n const orientedOffset = msbFirst ? 7 - (bitOffset % 8) : bitOffset % 8\n if (value === 1) this.array[offset] |= 1 << orientedOffset\n else this.array[offset] &= ~(1 << orientedOffset)\n\n return this\n }\n\n /**\n * Writes a single byte to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint8 = (value: number, offset = 0, check = true): this => {\n if (value < 0 || value > 255) {\n throw new RangeError(formatCyBufferError(\"writeUint8\", `Value is out of bounds: '${value}'.`))\n }\n\n if (check) this.check(offset, 1)\n\n value >>>= 0\n this.array[offset] = value\n\n return this\n }\n\n /**\n * **[LITTLE ENDIAN]** Writes a single 16-bit value to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16LE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffff) {\n throw new RangeError(formatCyBufferError(\"writeUint16LE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint16LE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n\n value >>>= 0\n this.array[offset] = value & 0xff\n this.array[offset + 1] = (value >> 8) & 0xff\n\n return this\n }\n\n /**\n * **[BIG ENDIAN]** Writes a single 16-bit value to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16BE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffff) {\n throw new RangeError(formatCyBufferError(\"writeUint16BE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint16BE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n\n value >>>= 0\n this.array[offset] = (value >> 8) & 0xff\n this.array[offset + 1] = value & 0xff\n\n return this\n }\n\n /**\n * Writes a single 16-bit value to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16 = (\n value: number,\n offset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n check = true,\n ): this => {\n if (this.normalizeEndianness(endianness) === \"LE\") {\n this.writeUint16LE(value, offset, verifyAlignment, check)\n return this\n }\n\n this.writeUint16BE(value, offset, verifyAlignment, check)\n return this\n }\n\n /**\n * **[LITTLE ENDIAN]** Writes a single 32-bit word to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32LE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffffffff) {\n throw new RangeError(formatCyBufferError(\"writeUint32LE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint32LE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n value >>>= 0\n this.array[offset] = value & 0xff\n this.array[offset + 1] = (value >> 8) & 0xff\n this.array[offset + 2] = (value >> 16) & 0xff\n this.array[offset + 3] = (value >> 24) & 0xff\n\n return this\n }\n\n /**\n * **[BIG ENDIAN]** Writes a single 32-bit word to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32BE = (value: number, offset = 0, verifyAlignment = true, check = true): this => {\n if (value < 0 || value > 0xffffffff) {\n throw new RangeError(formatCyBufferError(\"writeUint32BE\", `Value is out of bounds: '${value}'.`))\n }\n\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint32BE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n value >>>= 0\n this.array[offset] = (value >> 24) & 0xff\n this.array[offset + 1] = (value >> 16) & 0xff\n this.array[offset + 2] = (value >> 8) & 0xff\n this.array[offset + 3] = value & 0xff\n\n return this\n }\n\n /**\n * Writes a single 32-bit word to the buffer.\n * @param value The value to write.\n * @param offset The offset to write to (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32 = (\n value: number,\n offset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n check = true,\n ): this => {\n if (this.normalizeEndianness(endianness) === \"LE\") {\n this.writeUint32LE(value, offset, verifyAlignment, check)\n return this\n }\n\n this.writeUint32BE(value, offset, verifyAlignment, check)\n return this\n }\n\n /**\n * Writes an array of bits to the buffer.\n * @param array The array of bits to write to the buffer.\n * @param bitOffset The offset to start writing at **as a number of bits** (optional, defaults to 0).\n * @param bitLength The length to write **as a number of bits** (optional, defaults to the array length).\n * @param msbFirst Whether to write the bits from the most significant bit (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeBits = (array: Bit[], bitOffset = 0, bitLength = array.length, msbFirst = true): this => {\n if (!array || !Array.isArray(array)) {\n throw new TypeError(formatCyBufferError(\"writeBits\", `Invalid array of bits: '${array}'.`))\n }\n\n const offset = Math.floor(bitOffset / 8)\n const length = Math.ceil(bitLength / 8)\n this.check(offset, length)\n\n for (let i = 0; i < bitLength; i++) this.writeBit(array[i], bitOffset + i, msbFirst, false)\n\n return this\n }\n\n /**\n * Writes a Uint8Array to the buffer.\n * @param array The Uint8Array to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param arrayOffset The offset to start reading from in the array (optional, defaults to 0).\n * @returns The current buffer instance.\n */\n writeUint8Array = (array: Uint8Array, offset = 0, length = array.byteLength, arrayOffset = 0): this => {\n if (!array || !(array instanceof Uint8Array)) {\n throw new TypeError(formatCyBufferError(\"writeUint8Array\", `Invalid Uint8Array: '${array}'.`))\n }\n\n this.check(offset, length)\n\n for (let i = arrayOffset; i < length; i++) this.array[offset - arrayOffset + i] = array[i]\n\n return this\n }\n\n /**\n * Writes a Uint16Array to the buffer.\n * @param array The Uint16Array to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param arrayOffset The offset to start reading from in the array (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint16Array = (\n array: Uint16Array,\n offset = 0,\n length = array.byteLength,\n arrayOffset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n ): this => {\n if (!array || !(array instanceof Uint16Array)) {\n throw new TypeError(formatCyBufferError(\"writeUint16Array\", `Invalid Uint16Array: '${array}'.`))\n }\n\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint16Array\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n this.check(offset, length)\n\n if (this.normalizeEndianness(endianness) === \"LE\") {\n for (let i = arrayOffset; i < length; i += 2) {\n this.writeUint16LE(array[i / 2], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n for (let i = arrayOffset; i < length; i += 2) {\n this.writeUint16BE(array[i / 2], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n /**\n * Writes a Uint32Array to the buffer.\n * @param array The Uint16Array to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param arrayOffset The offset to start reading from in the array (optional, defaults to 0).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @returns The current buffer instance.\n */\n writeUint32Array = (\n array: Uint32Array,\n offset = 0,\n length = array.byteLength,\n arrayOffset = 0,\n endianness = this.platformEndianness,\n verifyAlignment = true,\n ): this => {\n if (!array || !(array instanceof Uint32Array)) {\n throw new TypeError(formatCyBufferError(\"writeUint32Array\", `Invalid Uint32Array: '${array}'.`))\n }\n\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"writeUint32Array\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n this.check(offset, length)\n\n if (this.normalizeEndianness(endianness) === \"LE\") {\n for (let i = arrayOffset; i < length; i += 4) {\n this.writeUint32LE(array[i / 4], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n for (let i = arrayOffset; i < length; i += 4) {\n this.writeUint32BE(array[i / 4], offset - arrayOffset + i, verifyAlignment, false)\n }\n\n return this\n }\n\n /**\n * **[LITTLE ENDIAN]** Writes a big integer of any size to the buffer.\n *\n * **No alignment is required, the length is automatically calculated.**\n * @param value The big integer to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @returns The current buffer instance.\n */\n writeBigIntLE = (value: bigint, offset = 0, length = Math.ceil(Number(value).toString(16).length / 2)): this => {\n if (value < 0n)\n throw new RangeError(formatCyBufferError(\"writeBigIntLE\", `Invalid big integer value: '${value}'.`))\n\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n this.array[offset + i] = Number(value & BigInt(0xff))\n value >>= BigInt(8)\n }\n\n return this\n }\n\n /**\n * **[BIG ENDIAN]** Writes a big integer of any size to the buffer.\n *\n * **No alignment is required, the length is automatically calculated.**\n * @param value The big integer to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @returns The current buffer instance.\n */\n writeBigIntBE = (value: bigint, offset = 0, length = Math.ceil(Number(value).toString(16).length / 2)): this => {\n if (value < 0n)\n throw new RangeError(formatCyBufferError(\"writeBigIntBE\", `Invalid big integer value: '${value}'.`))\n\n this.check(offset, length)\n\n for (let i = length - 1; i >= 0; i--) {\n this.array[offset + i] = Number(value & BigInt(0xff))\n value >>= BigInt(8)\n }\n\n return this\n }\n\n /**\n * Writes a big integer of any size to the buffer.\n *\n * **No alignment is required, the length is automatically calculated.**\n * @param value The big integer to write to the buffer.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @param length The length to write (optional, defaults to the array length).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns The current buffer instance.\n */\n writeBigInt = (\n value: bigint,\n offset = 0,\n length = Math.ceil(Number(value).toString(16).length / 2),\n endianness = this.platformEndianness,\n ): this => {\n if (this.normalizeEndianness(endianness) === \"LE\") {\n this.writeBigIntLE(value, offset, length)\n return this\n }\n\n this.writeBigIntBE(value, offset, length)\n return this\n }\n\n /**\n * Writes a range of numbers between 0 and 255 to the buffer.\n * @param start The start of the range, inclusive.\n * @param end The end of the range, exclusive.\n * @param offset The offset to start writing at (optional, defaults to 0).\n * @returns The current buffer instance.\n */\n writeRange = (start: number, end: number, offset = 0): this => {\n if (start < 0 || start > 255) {\n throw new RangeError(formatCyBufferError(\"writeRange\", `Invalid start value: '${start}'.`))\n }\n\n if (end < 0 || end > 255) {\n throw new RangeError(formatCyBufferError(\"writeRange\", `Invalid end value: '${end}'.`))\n }\n\n const length = end - start\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n this.array[offset + i] = start + i\n }\n\n return this\n }\n\n /**\n * ==============\n * READ METHODS\n * ==============\n *\n * Notes:\n * - All read methods have the capability to disable the overall check.\n * - All of the \"endianness sensitive\" methods are wrapped within a single\n * method with an optional endianness parameter.\n */\n\n /**\n * **[LITTLE ENDIAN]** Reads a part of the buffer and returns it as an hexadecimal string (always uppercase).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The hexadecimal string.\n */\n readHexStringLE = (offset = 0, length = this.length - offset, check = true): string => {\n if (check) this.check(offset, length)\n return Buffer.from(this.arrayBuffer, offset, length).toString(\"hex\").toUpperCase()\n }\n\n /**\n * **[BIG ENDIAN]** Reads a part of the buffer and returns it as an hexadecimal string (always uppercase).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The hexadecimal string.\n */\n readHexStringBE = (offset = 0, length = this.length - offset, check = true): string => {\n if (check) this.check(offset, length)\n const hexString = Buffer.from(this.arrayBuffer, offset, length).toString(\"hex\").toUpperCase()\n return hexString.match(/.{2}/g)!.reverse().join(\"\")\n }\n\n /**\n * Reads a part of the buffer and returns it as an hexadecimal string (always uppercase).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).'\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The hexadecimal string.\n */\n readHexString = (\n offset = 0,\n length = this.length - offset,\n endianness = this.platformEndianness,\n check = true,\n ): string => {\n if (check) this.check(offset, length)\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readHexStringLE(offset, length, false)\n return this.readHexStringBE(offset, length, false)\n }\n\n /**\n * Reads a part of the buffer and returns it as an UTF-8 string.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The UTF-8 string.\n */\n readUtf8String = (offset = 0, length = this.length - offset, check = true): string => {\n if (check) this.check(offset, length)\n return Buffer.from(this.arrayBuffer, offset, length).toString(\"utf8\")\n }\n\n /**\n * Read a single bit from the buffer.\n *\n * **Note:** The offset is in bits, not bytes in contrast to the other methods.\n * @param bitOffset The offset to read from **as a number of bits** (optional, defaults to 0).\n * @param msbFirst Whether to read the bit from the most significant bit (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The bit as 0 or 1.\n */\n readBit = (bitOffset = 0, msbFirst = true, check = true): Bit => {\n const offset = Math.floor(bitOffset / 8)\n if (check) this.check(offset, 1)\n\n const orderedBitOffset = msbFirst ? 7 - (bitOffset % 8) : bitOffset % 8\n return (this.array[offset] & (1 << orderedBitOffset)) !== 0 ? 1 : 0\n }\n\n /**\n * Reads a single byte from the buffer.\n *\n * Equivalent to using the index signature (square bracket notation).\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The byte as number.\n */\n readUint8 = (offset = 0, check = true): number => {\n if (check) this.check(offset, 1)\n return this.array[offset]\n }\n\n /**\n * **[LITTLE ENDIAN]** Reads a single 16-bit value from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The 16-bit value.\n */\n readUint16LE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint16LE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n\n return (this.array[offset] | (this.array[offset + 1] << 8)) >>> 0\n }\n\n /**\n * **[BIG ENDIAN]** Reads a single 16-bit value from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The 16-bit value.\n */\n readUint16BE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint16BE\", `Invalid offset alignment: '${offset}' (%2).`))\n }\n\n if (check) this.check(offset, 2)\n return ((this.array[offset] << 8) | this.array[offset + 1]) >>> 0\n }\n\n /**\n * Reads a single 16-bit value from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param endianness Whether to read the value in Little Endian (optional, defaults to `false`).\n * @param verifyAlignment Whether to verify that the offset is aligned to 2 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The 16-bit value.\n */\n readUint16 = (offset = 0, endianness = this.platformEndianness, verifyAlignment = true, check = true): number => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readUint16LE(offset, verifyAlignment, check)\n return this.readUint16BE(offset, verifyAlignment, check)\n }\n\n /**\n * **[LITTLE ENDIAN]** Reads a single 32-bit word from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n */\n readUint32LE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint32LE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n return (\n (this.array[offset] |\n (this.array[offset + 1] << 8) |\n (this.array[offset + 2] << 16) |\n (this.array[offset + 3] << 24)) >>>\n 0\n )\n }\n\n /**\n * **[BIG ENDIAN]** Reads a single 32-bit word from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n */\n readUint32BE = (offset = 0, verifyAlignment = true, check = true): number => {\n if (verifyAlignment && offset % 4 !== 0) {\n throw new RangeError(formatCyBufferError(\"readUint32BE\", `Invalid offset alignment: '${offset}' (%4).`))\n }\n\n if (check) this.check(offset, 4)\n\n return (\n ((this.array[offset] << 24) |\n (this.array[offset + 1] << 16) |\n (this.array[offset + 2] << 8) |\n this.array[offset + 3]) >>>\n 0\n )\n }\n\n /**\n * Reads a single 32-bit word from the buffer.\n * @param offset The offset to read from (optional, defaults to 0).\n * @param endianness Whether to read the value in Little Endian (optional, defaults to `false`).\n * @param verifyAlignment Whether to verify that the offset is aligned to 4 bytes (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n */\n readUint32 = (offset = 0, endianness = this.platformEndianness, verifyAlignment = true, check = true): number => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readUint32LE(offset, verifyAlignment, check)\n return this.readUint32BE(offset, verifyAlignment, check)\n }\n\n /**\n * Reads a part of the buffer and return it as a bit array.\n *\n * **Note:** The offset is in bits, not bytes in contrast to the other methods.\n * @param bitOffset The offset to read from **as a number of bits** (optional, defaults to 0).\n * @param bitLength The length to read **as a number of bits** (optional, defaults to the buffer length - offset).\n * @param msbFirst Whether to read the bits from the most significant bit (optional, defaults to `true`).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The bit array.\n */\n readBits = (offset = 0, length = this.length * 8 - offset * 8, msbFirst = true, check = true): Bit[] => {\n const bits: Bit[] = []\n\n for (let i = 0; i < length; i++) bits.push(this.readBit(offset + i, msbFirst, check))\n\n return bits\n }\n\n /**\n * Reads a part of the buffer and return it as a Uint8Array.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param check Whether to enable the overall check (optional, defaults to `true`).\n * @returns The Uint8Array.\n */\n readUint8Array = (offset = 0, length = this.length - offset, check = true): Uint8Array => {\n if (check) this.check(offset, length)\n return new Uint8Array(this.arrayBuffer, offset ?? this.offset, length ?? this.length)\n }\n\n /**\n * Reads a part of the buffer and return it as a Uint16Array.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The Uint16Array.\n */\n readUint16Array = (offset = 0, length = this.length - offset, check = true): Uint16Array => {\n if (check) this.check(offset, length)\n return new Uint16Array(this.arrayBuffer, offset ?? this.offset, length ? length / 2 : this.length / 2)\n }\n\n /**\n * Reads a part of the buffer and return it as a Uint32Array.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The Uint32Array.\n */\n readUint32Array = (offset = 0, length = this.length - offset, check = true): Uint32Array => {\n if (check) this.check(offset, length)\n return new Uint32Array(this.arrayBuffer, offset ?? this.offset, length ? length / 4 : this.length / 4)\n }\n\n /**\n * **[LITTLE ENDIAN]** Reads a certain amount of bytes from the buffer and converts it into a big integer.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The big integer.\n */\n readBigIntLE = (offset = 0, length = this.length - offset, check = true): bigint => {\n if (check) this.check(offset, length)\n\n let result = 0n\n for (let i = length - 1; i >= 0; i--) {\n result = (result << 8n) | BigInt(this.array[offset + i])\n }\n\n return result\n }\n\n /**\n * **[BIG ENDIAN]** Reads a certain amount of bytes from the buffer and converts it into a big integer.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @returns The big integer.\n */\n readBigIntBE = (offset = 0, length = this.length - offset, check = true): bigint => {\n if (check) this.check(offset, length)\n\n let result = 0n\n for (let i = 0; i < length; i++) {\n result = (result << 8n) | BigInt(this.array[offset + i])\n }\n\n return result\n }\n\n /**\n * Reads a certain amount of bytes from the buffer and converts it into a big integer.\n * @param offset The offset to start reading from (optional, defaults to 0).\n * @param length The length to read (optional, defaults to the buffer length - offset).\n * @param endianness Whether to read the value in Little Endian (optional, defaults to `false`).\n * @returns The big integer.\n */\n readBigInt = (\n offset = 0,\n length = this.length - offset,\n endianness = this.platformEndianness,\n check = true,\n ): bigint => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readBigIntLE(offset, length, check)\n return this.readBigIntBE(offset, length, check)\n }\n\n /**\n * ====================\n * CONVERSION METHODS\n * ====================\n */\n\n /**\n * Converts the buffer into an hexadecimal string (always uppercase).\n * @param prefix Whether to prefix the hexadecimal string with `0x` (optional, defaults to `false`).\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns The hexadecimal string.\n */\n toHexString = (prefix = false, endianness = this.platformEndianness): string => {\n let hexString = Buffer.from(this.arrayBuffer).toString(\"hex\").toUpperCase()\n\n if (this.normalizeEndianness(endianness) === \"BE\") {\n hexString = hexString.match(/.{2}/g)?.reverse().join(\"\") ?? \"\"\n }\n\n if (prefix) return `0x${hexString}`\n return hexString\n }\n\n /**\n * Converts the buffer into an UTF-8 string.\n * @returns The UTF-8 string.\n */\n toUtf8String = (): string => Buffer.from(this.arrayBuffer).toString(\"utf8\")\n\n /**\n * Converts the buffer into a string representation (hex string is always uppercase).\n * @param encoding The encoding to use (optional, defaults to \"hex\").\n * @param hexPrefix Whether to prefix the hexadecimal string with `0x` (optional, defaults to `false`).\n * @returns The string representation of the buffer.\n */\n toString = (encoding: \"utf8\" | \"hex\" = \"hex\", hexPrefix = false): string => {\n if (encoding === \"utf8\") return this.toUtf8String()\n return this.toHexString(hexPrefix)\n }\n\n /**\n * Converts the buffer into a bit array.\n * @param msbFirst Whether to read the bits from the most significant bit (optional, defaults to `true`).\n * @returns The bit array.\n */\n toBits = (msbFirst = true): Bit[] => {\n const length = this.length * 8\n const bits: Bit[] = new Array(length)\n for (let i = 0; i < length; i++) bits[i] = this.readBit(i, msbFirst)\n return bits\n }\n\n /**\n * Converts the buffer into a Uint8Array.\n * @returns The Uint8Array.\n */\n toUint8Array = (): Uint8Array => new Uint8Array(this.arrayBuffer, this.offset, this.length)\n\n /**\n * Converts the buffer into a Uint16Array.\n * @returns The Uint16Array.\n */\n toUint16Array = (): Uint16Array => new Uint16Array(this.arrayBuffer, this.offset, this.length / 2)\n\n /**\n * Converts the buffer into a Uint32Array.\n * @returns The Uint32Array.\n */\n toUint32Array = (): Uint32Array => new Uint32Array(this.arrayBuffer, this.offset, this.length / 4)\n\n /**\n * Converts the buffer into a big integer.\n * @param endianness The endianness to use (optional, defaults to the platform's endianness).\n * @returns The big integer.\n */\n toBigInt = (endianness = this.platformEndianness): bigint => {\n if (this.normalizeEndianness(endianness) === \"LE\") return this.readBigIntLE()\n return this.readBigIntBE()\n }\n\n /**\n * ===============\n * CHECK METHODS\n * ===============\n */\n\n /**\n * Checks if the current buffer is equal to the specified buffer.\n * @param buffer The buffer to compare to.\n * @returns Whether the buffers are equal.\n */\n equals = (buffer: CyBuffer): boolean => {\n if (this.length !== buffer.length) {\n return false\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.array[i] !== buffer[i]) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Check if the buffer is empty.\n * @returns Whether the buffer is empty.\n */\n isEmpty = (): boolean => {\n for (let i = 0; i < this.length; i++) {\n if (this.array[i] !== 0) return false\n }\n\n return true\n }\n\n /**\n * Check if the buffer is full.\n * @returns Whether the buffer is full.\n */\n isFull = (): boolean => {\n for (let i = 0; i < this.length; i++) {\n if (this.array[i] !== 255) return false\n }\n\n return true\n }\n\n /**\n * ====================\n * RANDOMNESS METHODS\n * ====================\n */\n\n /**\n * Randomly fills the buffer with bytes.\n *\n * **WARNING:** This method is not safe for cryptographic contexts, use the `safeRandomFill` method\n * when security is a concern.\n * @param offset The offset to start filling at (optional, defaults to 0).\n * @param length The length to fill (optional, defaults to the buffer length - offset).\n */\n randomFill = (offset = 0, length = this.length - offset) => {\n this.check(offset, length)\n\n for (let i = 0; i < length; i++) {\n this.array[offset + i] = Math.floor(Math.random() * 256)\n }\n }\n\n /**\n * Randomly fills the buffer with bytes.\n *\n * **WARNING:** This method is safe for cryptographic contexts, but is far slower than the `randomFill` method,\n * use this method when security is a concern. Uses the Node.js `crypto.randomFillSync` method.\n * @param offset The offset to start filling at (optional, defaults to 0).\n * @param length The length to fill (optional, defaults to the buffer length - offset).\n */\n safeRandomFill = (offset = 0, length = this.length) => randomFillSync(this.array, offset, length)\n\n /**\n * =================\n * UTILITY METHODS\n * =================\n */\n\n /**\n * Copies the buffer into a new buffer.\n * @param offset The offset to start copying at (optional, defaults to 0).\n * @param length The length to copy (optional, defaults to the buffer length).\n * @returns A new buffer containing the copied data.\n */\n copy = (offset = 0, length = this.length): CyBuffer => {\n this.check(offset, length)\n const buffer = new CyBuffer(length)\n for (let i = 0; i < length; i++) buffer[i] = this.array[i + offset]\n return buffer\n }\n\n /**\n * Returns a new buffer that references the same memory as the original buffer,\n * A lot more efficient than copying it (~ 4 times faster than the `copy` method).\n * @param offset The start offset (optional, defaults to 0).\n * @param end The end offset (optional, defaults to the buffer length).\n * @returns The subarray pointing to the same memory.\n */\n subarray = (offset = 0, length = this.length): CyBuffer => {\n this.check(offset, length)\n\n return new CyBuffer(length, {\n arrayBuffer: this.arrayBuffer,\n offset: offset,\n length: length,\n })\n }\n\n /**\n * Swaps the order of the buffer.\n * @param offset The offset to start swapping at (optional, defaults to 0).\n * @param length The length to swap (optional, defaults to the buffer length).\n * @param wordLength The length per word (optional, defaults to 4).\n * @returns The current buffer instance.\n */\n swap = (offset = 0, length = this.length, wordLength = 4): this => {\n if (wordLength < 2) throw new RangeError(formatCyBufferError(\"swap\", `Invalid word length: '${wordLength}'.`))\n\n if (wordLength % 2 !== 0) {\n throw new RangeError(formatCyBufferError(\"swap\", `Invalid word length alignment: '${wordLength}'.`))\n }\n\n this.check(offset, length)\n\n const calculatedLength = offset + length\n for (let i = 0; i < calculatedLength; i += wordLength) {\n const offsetIndex = i + offset\n\n for (let j = 0; j < wordLength / 2; j++) {\n const temp = this.array[offsetIndex + j]\n this.array[offsetIndex + j] = this.array[offsetIndex + wordLength - j - 1]\n this.array[offsetIndex + wordLength - j - 1] = temp\n }\n }\n\n return this\n }\n\n /**\n * Reverses a part of the buffer.\n * @param offset The offset to start reversing at (optional, defaults to 0).\n * @param length The length to reverse (optional, defaults to the buffer length).\n * @returns The current buffer instance.\n */\n partialReverse = (offset = 0, length = this.length): this => {\n this.check(offset, length)\n\n const dividedLength = Math.floor(length / 2)\n const calculatedLength = offset + length\n\n for (let i = 0; i < dividedLength; i++) {\n const offsetIndex = i + offset\n const endOffsetIndex = calculatedLength - i - 1\n const temp = this.array[offsetIndex]\n this.array[offsetIndex] = this.array[endOffsetIndex]\n this.array[endOffsetIndex] = temp\n }\n\n return this\n }\n\n /**\n * Reverses the entire buffer.\n * @returns The current buffer instance.\n */\n reverse = (): this => {\n this.array.reverse()\n return this\n }\n\n /**\n * Rotates the buffer to the left.\n * @returns The current buffer instance.\n */\n rotateLeft = (): this => {\n const first = this.array[0]\n\n for (let i = 0; i < this.length - 1; i++) this.array[i] = this.array[i + 1]\n this.array[this.length - 1] = first\n\n return this\n }\n\n /**\n * Rotates the buffer to the right.\n * @returns The current buffer instance.\n */\n rotateRight = (): this => {\n const last = this.array[this.length - 1]\n\n for (let i = this.length - 1; i > 0; i--) this.array[i] = this.array[i - 1]\n this.array[0] = last\n\n return this\n }\n\n /**\n * Shifts the buffer to the left, filling the empty space with zeros.\n * @param offset The offset to start shifting at (optional, defaults to 0).\n * @param length The length to shift (optional, defaults to the buffer length).\n * @param shift The number of bytes to shift (optional, defaults to 1).\n * @returns The current buffer instance.\n */\n shiftLeft = (offset = 0, length = this.length, shift = 1): this => {\n this.check(offset, length)\n\n for (let i = 0; i < this.length - 1; i++) this.array[i] = this.array[i + shift]\n for (let i = 0; i < shift; i++) this.array[this.length - i - 1] = 0\n\n return this\n }\n\n /**\n * Shifts the buffer to the right, filling the empty spaces with zeros.\n * @param offset The offset to start shifting at (optional, defaults to 0).\n * @param length The length to shift (optional, defaults to the buffer length).\n * @param shift The number of bytes to shift (optional, defaults to 1).\n * @returns The current buffer instance.\n */\n shiftRight = (offset = 0, length = this.length, shift = 1): this => {\n this.check(offset, length)\n\n for (let i = this.length - 1; i > 0; i--) this.array[i] = this.array[i - shift]\n for (let i = 0; i < shift; i++) this.array[i] = 0\n\n return this\n }\n\n /**\n * Fills the buffer with a specified value.\n * @param value The value to fill the buffer with.\n * @param offset The offset to start filling at (optional, defaults to 0).\n * @param length The length to fill (optional, defaults to the buffer length).\n * @returns The current buffer instance.\n */\n fill = (value: number, offset = 0, length = this.length): this => {\n if (value < 0 || value > 255) throw new RangeError(formatCyBufferError(\"fill\", `Invalid value: '${value}'.`))\n\n this.check(offset, length)\n this.array.fill(value, offset, offset + length)\n return this\n }\n\n /**\n * Clears the buffer by filling it with zeros.\n * @param offset The offset to start clearing at (optional, defaults to 0).\n * @param length The length to clear (optional, defaults to the buffer length).\n * @returns The current buffer instance.\n */\n clear = (offset = 0, length = this.length): this => {\n this.check(offset, length)\n this.array.fill(0, offset, offset + length)\n return this\n }\n}\n","import { execSync } from \"node:child_process\"\nimport { hostname } from \"node:os\"\n\n/**\n * Get the name of the host on which the application is running.\n * @returns The name of the host.\n */\nexport function getHostname() {\n switch (process.platform) {\n case \"win32\":\n return process.env.COMPUTERNAME\n case \"darwin\":\n return execSync(\"scutil --get ComputerName\").toString().trim()\n case \"linux\": {\n const prettyName = execSync(\"hostnamectl --pretty\").toString().trim()\n return prettyName === \"\" ? hostname() : prettyName\n }\n default:\n return hostname()\n }\n}\n","import { stringify } from \"@/main/json\"\nimport type { ErrorObj, FailedRequest } from \"@/main/types/requests\"\n\n/**\n * Formats an `ErrorObj` into a standard error sent back by an API endpoint.\n */\nexport function formatErrorResponse(error: ErrorObj, customMessage?: string, additionalData?: unknown) {\n let err: ErrorObj\n if (additionalData) err = { ...error, data: additionalData }\n else err = error\n\n return {\n success: false,\n message: customMessage || error.message,\n error: err,\n }\n}\n\n/**\n * Formats an `ErrorObj` and stringifies it for it to be supported by the `Error` class.\n * @param error The `ErrorObj` object to format.\n * @param message Replaces the standard error message with a custom one (optional).\n * @param additionalData Additional data to include in the error (optional).\n * @returns The formatted error string.\n */\nexport function stringifyError(error: ErrorObj, message?: string, additionalData?: unknown): string {\n if (message) error.message = message\n\n let err: ErrorObj\n if (additionalData) err = { ...error, data: additionalData }\n else err = error\n\n // Allow special keys in the JSON stringification\n const allowSpecialKeys = (_: string, value: unknown) => {\n if (typeof value === \"function\") return value.toString()\n if (typeof value === \"bigint\") return value.toString()\n\n return value\n }\n\n return JSON.stringify(err, allowSpecialKeys, 4)\n}\n\n/**\n * Parse the error of a CRUD call and return a standardized error.\n * @param error The error to parse.\n * @returns The standardized error object.\n */\nexport function parseCRUDError(error: unknown): FailedRequest {\n let errorString = \"\"\n\n try {\n try {\n errorString = (error as any).toString()\n } catch (_) {\n errorString = stringify(error)\n }\n } catch (_) {\n errorString = \"Unknown error\"\n }\n\n return {\n success: false,\n message: \"An error occurred while performing a CRUD operation.\",\n error: {\n status: 500,\n name: \"CRUD_ERROR\",\n message: \"CRUD operation failed.\",\n data: {\n rawError: error,\n error: errorString,\n },\n },\n }\n}\n\n/**\n * Formats a message and an error object into a JSON string that follows the `FailedRequest` standard,\n * the goal is to not end up with special characters such as newlines in the message, so it can be parsed\n * back into an object without issues.\n * @param message The message to format.\n * @param error The error object to format.\n * @returns The formatted JSON string.\n */\nexport function formatMessageAsStringifiedError(message: string, error?: unknown): string {\n let errorObj: ErrorObj = {\n status: 500,\n name: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred.\",\n data: null,\n }\n\n if (error) {\n try {\n // Testing with JSON.stringify to see if it's a valid JSON object\n stringify(error, 4)\n\n errorObj = error as ErrorObj\n } catch {\n // Convert the error to a basic non-escaped string\n errorObj = {\n ...errorObj,\n data: {\n rawError: `${error}`,\n },\n }\n }\n }\n\n const res = stringify({\n success: false,\n message,\n error: errorObj,\n })\n\n // Ensure that no \"Error: \" or line break ends up in the message\n return res.replaceAll(\"Error: \", \"\").replaceAll(\"\\n\", \" \")\n}\n\n/**\n * Contains all the standard available errors for the application, it serves as a base\n * to extend with your custom errors.\n *\n * The recommended way is to create an `AppErrors` object that extends this one, preferably\n * at a place similar to `lib/utils/errors.ts`:\n * ```typescript\n * import { BaseErrors } from \"...\"\n *\n * export const AppErrors = {\n * ...BaseErrors,\n * //=====//\n *\t // 401 //\n *\t //=====//\n * BLAH_BLAH: {\n * status: 401,\n * name: \"BlahBlah\",\n * message: \"Blah blah blah.\",\n * data: null,\n * },\n * }\n * ```\n */\nexport const BaseErrors = {\n //=====//\n // 400 //\n //=====//\n BAD_REQUEST: {\n status: 400,\n name: \"BadRequest\",\n message: \"Bad request.\",\n data: null,\n },\n //=====//\n // 401 //\n //=====//\n UNAUTHORIZED: {\n status: 401,\n name: \"Unauthorized\",\n message: \"Unauthorized.\",\n data: null,\n },\n //=====//\n // 402 //\n //=====//\n PAYMENT_REQUIRED: {\n status: 402,\n name: \"PaymentRequired\",\n message: \"Payment required.\",\n data: null,\n },\n //=====//\n // 403 //\n //=====//\n FORBIDDEN: {\n status: 403,\n name: \"Forbidden\",\n message: \"Forbidden.\",\n data: null,\n },\n //=====//\n // 404 //\n //=====//\n NOT_FOUND: {\n status: 404,\n name: \"NotFound\",\n message: \"Not found.\",\n data: null,\n },\n //=====//\n // 405 //\n //=====//\n METHOD_NOT_ALLOWED: {\n status: 405,\n name: \"MethodNotAllowed\",\n message: \"Method not allowed.\",\n data: null,\n },\n //=====//\n // 408 //\n //=====//\n REQUEST_TIMEOUT: {\n status: 408,\n name: \"RequestTimeout\",\n message: \"Request timed out.\",\n data: null,\n },\n //=====//\n // 409 //\n //=====//\n CONFLICT: {\n status: 409,\n name: \"Conflict\",\n message: \"Conflict.\",\n data: null,\n },\n //=====//\n // 500 //\n //=====//\n INTERNAL_SERVER_ERROR: {\n status: 500,\n name: \"InternalServerError\",\n message: \"Internal server error.\",\n data: null,\n },\n BACKEND_FUNCTION_RUNNING_ON_CLIENT: {\n status: 500,\n name: \"BackendFunctionRunningOnClient\",\n message: \"A function reserved for the backend is running on the client.\",\n data: null,\n },\n //=====//\n // 501 //\n //=====//\n NOT_IMPLEMENTED: {\n status: 501,\n name: \"NotImplemented\",\n message: \"Not implemented.\",\n data: null,\n },\n //=====//\n // 509 //\n //=====//\n BANDWIDTH_LIMIT_EXCEEDED: {\n status: 509,\n name: \"BandwidthLimitExceeded\",\n message: \"Bandwidth limit exceeded.\",\n data: null,\n },\n} as const satisfies Record<string, ErrorObj>\n","import type { NextApiRequest, NextApiResponse } from \"next\"\nimport { BaseErrors } from \"@/main/errors\"\nimport type { ErrorObj, FailedRequest } from \"@/main/types/requests\"\n\n/**\n * The type for the overall wrapper options.\n */\n// biome-ignore lint/complexity/noBannedTypes: Unused for now\ntype WrapperOptions = {}\n\n/**\n * The type for a Next API wrapped method input.\n */\nexport type NextApiMethodInput = {\n req: NextApiRequest\n res: NextApiResponse\n wrapper: NextApiWrapper\n}\n\n/**\n * The type for a Next API wrapped method.\n */\ntype NextApiMethod = ({ req, res, wrapper }: NextApiMethodInput) => Promise<void> | void\n\n/**\n * The type for a Next API wrapped method, extended with specific options.\n */\ntype NextApiMethodWithOptions = {\n method: NextApiMethod\n}\n\n/**\n * An object containing all methods for the API route.\n */\ntype NextApiMethods = {\n read?: NextApiMethod | NextApiMethodWithOptions\n write?: NextApiMethod | NextApiMethodWithOptions\n update?: NextApiMethod | NextApiMethodWithOptions\n replace?: NextApiMethod | NextApiMethodWithOptions\n remove?: NextApiMethod | NextApiMethodWithOptions\n}\n\n/**\n * A class that wraps the Next.js API routes.\n */\nexport default class NextApiWrapper {\n private _req!: NextApiRequest\n private _res!: NextApiResponse\n\n // Methods\n private _read: NextApiMethod | NextApiMethodWithOptions | undefined\n private _write: NextApiMethod | NextApiMethodWithOptions | undefined\n private _update: NextApiMethod | NextApiMethodWithOptions | undefined\n private _replace: NextApiMethod | NextApiMethodWithOptions | undefined\n private _remove: NextApiMethod | NextApiMethodWithOptions | undefined\n\n // Options\n private _options!: WrapperOptions\n\n /**\n * The constructor for the `NextApiWrapper` class.\n * @param req The `NextApiRequest` object.\n * @param res The `NextApiResponse` object.\n * @param methods The methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n * @param options The options for the wrapper:\n * - (Currently none)\n */\n constructor(req: NextApiRequest, res: NextApiResponse, methods?: NextApiMethods, options?: WrapperOptions) {\n this.setRequestResponse(req, res)\n this.setMethods(methods || {})\n this.setOptions(options || {})\n }\n\n /**\n * Set request and response objects.\n * @param req The new `NextApiRequest` object.\n * @param res The new `NextApiResponse` object.\n */\n setRequestResponse(req: NextApiRequest, res: NextApiResponse) {\n this._req = req\n this._res = res\n }\n\n /**\n * Set methods for the API route.\n * @param methods The new methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n */\n setMethods(methods: NextApiMethods) {\n this._read = methods?.read\n this._write = methods?.write\n this._update = methods?.update\n this._replace = methods?.replace\n this._remove = methods?.remove\n }\n\n /**\n * Set options for the API route.\n * @param options The new options for the wrapper:\n * - (Currently none)\n */\n setOptions(options: Partial<WrapperOptions>) {\n this._options = { ...this._options, ...options }\n }\n\n /**\n * A private method to check data validity.\n * @param data The data to be checked.\n * @returns Whether the data is valid.\n */\n private _checkDataValidity(data: unknown) {\n if (data === undefined || data === null) return false\n return true\n }\n\n /**\n * Returns a properly formatted success response.\n * @param status Status code to be sent in the response.\n * @param data Data to be sent in the response (optional, defaults to `null`).\n */\n successResponse(status: number, data?: unknown) {\n return this._res.status(status).send({\n success: true,\n data: this._checkDataValidity(data) ? data : null,\n })\n }\n\n /**\n * Returns a properly formatted error response, based on error constants.\n * @param error Error code constant to be sent in the response.\n * @param data Additional data to be sent in the response (optional).\n * @param message Error message to be sent in the response (optional, defaults to the internal error message).\n */\n errorResponse(error: ErrorObj, data?: unknown, message?: string) {\n const response: FailedRequest = {\n success: false,\n message: message || error.message,\n error: this._checkDataValidity(data) ? { ...error, data } : error,\n }\n\n return this._res.status(error.status).send(response)\n }\n\n /**\n * Check if a method is a direct method or a method with options and execute it.\n * @param method The method to be checked.\n * @param methodInput The method input object.\n * @returns Whether the method was executed successfully.\n */\n private async _executeMethod(method: NextApiMethod | NextApiMethodWithOptions, methodInput: NextApiMethodInput) {\n if (typeof method === \"function\") {\n await method(methodInput)\n return true\n }\n\n await method.method(methodInput)\n return true\n }\n\n /**\n * Run and route the request to the appropriate method.\n * @returns The response from the method.\n */\n async run() {\n const methodInput: NextApiMethodInput = {\n req: this._req,\n res: this._res,\n wrapper: this,\n }\n\n try {\n switch (this._req.method) {\n case \"GET\":\n if (this._read) return await this._executeMethod(this._read, methodInput)\n break\n case \"POST\":\n if (this._write) return await this._executeMethod(this._write, methodInput)\n break\n case \"PATCH\":\n if (this._update) return await this._executeMethod(this._update, methodInput)\n break\n case \"PUT\":\n if (this._replace) return await this._executeMethod(this._replace, methodInput)\n break\n case \"DELETE\":\n if (this._remove) return await this._executeMethod(this._remove, methodInput)\n break\n default:\n return this.errorResponse(BaseErrors.METHOD_NOT_ALLOWED)\n }\n } catch (error) {\n return this.errorResponse(BaseErrors.INTERNAL_SERVER_ERROR, error)\n }\n }\n}\n","import type { NextApiRequest, NextApiResponse } from \"next\"\nimport type { Session } from \"next-auth\"\nimport { BaseErrors } from \"@/main/errors\"\nimport type { ErrorObj, FailedRequest } from \"@/main/types/requests\"\n\n/**\n * A session with a user extended with optional roles.\n */\nexport type ExtendedSession = Session & {\n user: Session[\"user\"] & {\n roles: string[] | undefined\n }\n}\n\n/**\n * The type for the authentication options.\n */\nexport type AuthOptions = {\n requireAuth?: boolean\n hasRole?: string\n hasSomeRoles?: string[]\n hasAllRoles?: string[]\n}\n\n/**\n * The type for the overall wrapper options.\n */\ntype WrapperOptions = {\n authFunction?: (req: NextApiRequest, res: NextApiResponse) => Promise<ExtendedSession | null>\n roles?: string[]\n} & AuthOptions\n\n/**\n * The type for a Next API wrapped method input.\n */\nexport type NextAuthApiMethodInput = {\n req: NextApiRequest\n res: NextApiResponse\n session: ExtendedSession | null\n wrapper: NextAuthApiWrapper\n}\n\n/**\n * The type for a Next API wrapped method.\n */\ntype NextApiMethod = ({ req, res, session, wrapper }: NextAuthApiMethodInput) => Promise<void> | void\n\n/**\n * The type for a Next API wrapped method, extended with specific auth options.\n */\ntype NextAuthApiMethodWithAuthOptions = {\n method: NextApiMethod\n authOptions?: AuthOptions\n}\n\n/**\n * An object containing all methods for the API route.\n */\ntype NextApiMethods = {\n read?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n write?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n update?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n replace?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n remove?: NextApiMethod | NextAuthApiMethodWithAuthOptions\n}\n\n/**\n * A class that wraps the Next.js API routes.\n */\nexport default class NextAuthApiWrapper {\n private _req!: NextApiRequest\n private _res!: NextApiResponse\n\n // Methods\n private _read: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _write: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _update: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _replace: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n private _remove: NextApiMethod | NextAuthApiMethodWithAuthOptions | undefined\n\n // Options\n private _options!: WrapperOptions\n\n /**\n * The constructor for the `NextAuthApiWrapper` class.\n * @param req The `NextApiRequest` object.\n * @param res The `NextApiResponse` object.\n * @param methods The methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n * @param options The options for the wrapper:\n * - `authFunction`: The function to be used for authentication.\n * - `roles`: The roles to be used for the wrapper.\n * - `requireAuth`: Whether to require authentication (defaults to `false`).\n * - `hasRole`: The user needs to have the role.\n * - `hasSomeRoles`: The user needs to have at least one of the roles.\n * - `hasAllRoles`: The user needs to have all of the roles.\n */\n constructor(req: NextApiRequest, res: NextApiResponse, methods?: NextApiMethods, options?: WrapperOptions) {\n this.setRequestResponse(req, res)\n this.setMethods(methods || {})\n this.setOptions(options || {})\n }\n\n /**\n * Set request and response objects.\n * @param req The new `NextApiRequest` object.\n * @param res The new `NextApiResponse` object.\n */\n setRequestResponse(req: NextApiRequest, res: NextApiResponse) {\n this._req = req\n this._res = res\n }\n\n /**\n * Set methods for the API route.\n * @param methods The new methods to be used for the API route:\n * - `read`: The *GET* method.\n * - `write`: The *POST* method.\n * - `update`: The *PATCH* method.\n * - `replace`: The *PUT* method.\n * - `remove`: The *DELETE* method.\n */\n setMethods(methods: NextApiMethods) {\n this._read = methods?.read\n this._write = methods?.write\n this._update = methods?.update\n this._replace = methods?.replace\n this._remove = methods?.remove\n }\n\n /**\n * Set options for the API route.\n * @param options The new options for the wrapper:\n * - `authFunction`: The function to be used for authentication.\n * - `roles`: The roles to be used for the wrapper.\n * - `requireAuth`: Whether to require authentication (defaults to `false`).\n * - `hasRole`: The user needs to have the role.\n * - `hasSomeRoles`: The user needs to have at least one of the roles.\n * - `hasAllRoles`: The user needs to have all of the roles.\n */\n setOptions(options: Partial<WrapperOptions>) {\n this._options = { ...this._options, ...options }\n }\n\n /**\n * A private method to check data validity.\n * @param data The data to be checked.\n * @returns Whether the data is valid.\n */\n private _checkDataValidity(data: unknown) {\n if (data === undefined || data === null) return false\n return true\n }\n\n /**\n * Returns a properly formatted success response.\n * @param status Status code to be sent in the response.\n * @param data Data to be sent in the response (optional, defaults to `null`).\n */\n successResponse(status: number, data?: unknown) {\n return this._res.status(status).send({\n success: true,\n data: this._checkDataValidity(data) ? data : null,\n })\n }\n\n /**\n * Returns a properly formatted error response, based on error constants.\n * @param error Error code constant to be sent in the response.\n * @param data Additional data to be sent in the response (optional).\n * @param message Error message to be sent in the response (optional, defaults to the internal error message).\n */\n errorResponse(error: ErrorObj, data?: unknown, message?: string) {\n const response: FailedRequest = {\n success: false,\n message: message || error.message,\n error: this._checkDataValidity(data) ? { ...error, data } : error,\n }\n\n return this._res.status(error.status).send(response)\n }\n\n /**\n * Verify if the user has a specific role.\n * @param user The user object.\n * @param role The role to be checked.\n * @returns Whether the user has the role.\n */\n hasRole(user: ExtendedSession[\"user\"], role: string) {\n return user.roles?.includes(role)\n }\n\n /**\n * Verify if the user has at least one of the roles.\n * @param user The user object.\n * @param roles The roles to be checked.\n * @returns Whether the user has at least one of the roles.\n */\n hasSomeRoles(user: ExtendedSession[\"user\"], roles: string[]) {\n return roles.some(role => user.roles?.includes(role))\n }\n\n /**\n * Verify if the user has all of the roles.\n * @param user The user object.\n * @param roles The roles to be checked.\n * @returns Whether the user has all of the roles.\n */\n hasAllRoles(user: ExtendedSession[\"user\"], roles: string[]) {\n return roles.every(role => user.roles?.includes(role))\n }\n\n /**\n * Check the authentication and roles of the user based on the auth options.\n * @param session The session object.\n * @param authOptions The authentication options.\n * @returns Whether the user has the required authentication and roles.\n */\n checkAuthOptions(session: ExtendedSession | null, authOptions: AuthOptions) {\n if (authOptions.requireAuth) {\n if (!session) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n if (authOptions.hasRole) {\n if (!session || !this.hasRole(session.user, authOptions.hasRole)) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n if (authOptions.hasSomeRoles) {\n if (!session || !this.hasSomeRoles(session.user, authOptions.hasSomeRoles)) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n if (authOptions.hasAllRoles) {\n if (!session || !this.hasAllRoles(session.user, authOptions.hasAllRoles)) {\n this.errorResponse(BaseErrors.UNAUTHORIZED)\n return false\n }\n }\n\n return true\n }\n\n /**\n * Check if a method is a direct method or a method with auth options and execute it.\n * @param method The method to be checked.\n * @param methodInput The method input object.\n * @returns Whether the method was executed successfully.\n */\n private async _executeMethod(\n method: NextApiMethod | NextAuthApiMethodWithAuthOptions,\n methodInput: NextAuthApiMethodInput,\n ) {\n if (typeof method === \"function\") {\n await method(methodInput)\n return true\n }\n\n if (method.authOptions) {\n const authCheckRes = this.checkAuthOptions(methodInput.session, method.authOptions)\n if (!authCheckRes) return false\n }\n\n await method.method(methodInput)\n return true\n }\n\n /**\n * Run and route the request to the appropriate method.\n * @returns The response from the method.\n */\n async run() {\n const session = this._options.authFunction ? await this._options.authFunction(this._req, this._res) : null\n const authCheckRes = this.checkAuthOptions(session, this._options)\n if (!authCheckRes) return\n\n const methodInput: NextAuthApiMethodInput = {\n req: this._req,\n res: this._res,\n session,\n wrapper: this,\n }\n\n try {\n switch (this._req.method) {\n case \"GET\":\n if (this._read) return await this._executeMethod(this._read, methodInput)\n break\n case \"POST\":\n if (this._write) return await this._executeMethod(this._write, methodInput)\n break\n case \"PATCH\":\n if (this._update) return await this._executeMethod(this._update, methodInput)\n break\n case \"PUT\":\n if (this._replace) return await this._executeMethod(this._replace, methodInput)\n break\n case \"DELETE\":\n if (this._remove) return await this._executeMethod(this._remove, methodInput)\n break\n default:\n return this.errorResponse(BaseErrors.METHOD_NOT_ALLOWED)\n }\n } catch (error) {\n return this.errorResponse(BaseErrors.INTERNAL_SERVER_ERROR, error)\n }\n }\n}\n"]}