@cybearl/cypack 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,7 +17,7 @@ $ npm install @cybearl/cypack
17
17
  // With yarn
18
18
  $ yarn add @cybearl/cypack
19
19
  ```
20
- And that's it! You can now use the utilities in your project.
20
+ And that's it! You can now use our utilities in your project.
21
21
 
22
22
  Categories and utilities
23
23
  ------------------------
@@ -66,6 +66,7 @@ Contains utilities to get the Next.js server and other Next.js-related informati
66
66
  await wrapper.run()
67
67
  }
68
68
  ```
69
+ - `nextAuthApiWrapper`: Similar to `NextApiWrapper`, but with built-in NextAuth support (specifically for page router).
69
70
 
70
71
  Frontend utilities
71
72
  ------------------
@@ -112,6 +113,8 @@ Contains a set of utilities to format numbers, time, and other values.
112
113
  - `formatTime`: Format a time in milliseconds into a responsive string with the en-US locale format.
113
114
  - `formatPercentage`: Formats a number as a percentage.
114
115
  - `truncateString`: Truncate a string to a specified length.
116
+ - `parseQueryNumberArray`: Parse a query containing either a number or numbers separated by commas and returns an array of numbers.
117
+ - `parseQueryStringArray`: Parse a query containing either a string or strings separated by commas and returns an array of strings.
115
118
 
116
119
  #### JSON utilities
117
120
  Contains utilities to parse and stringify JSON objects.
@@ -121,6 +124,8 @@ Contains utilities to parse and stringify JSON objects.
121
124
  #### Math utilities
122
125
  Contains utilities to perform mathematical operations.
123
126
  - `mapRange`: Maps a number from one range to another.
127
+ - `safeAverage`: Safely creates an average value based on a total and count coming from a Lucid ORM / SQL query result.
128
+ - `safePercentage`: Safely creates a percentage based on a numerator and denominator coming from a Lucid ORM / SQL query result.
124
129
 
125
130
  #### Middleware utilities
126
131
  Contains utilities to create middleware functions (for Next.js, etc.).
package/backend.d.ts CHANGED
@@ -71,14 +71,14 @@ type CGASStatusString = "enabled" | "disabled" | "in-maintenance" | "in-developm
71
71
  * - `in-development`: The application is in development mode and not available to the public.
72
72
  */
73
73
  type CGASStatus = {
74
- status: CGASStatusString
75
- marker: string
76
- timestamp: string
77
- version: {
78
- raw: string
79
- formatted: `v${string}` | "unavailable"
80
- }
81
- message: string
74
+ status: CGASStatusString
75
+ marker: string
76
+ timestamp: string
77
+ version: {
78
+ raw: string
79
+ formatted: `v${string}` | "unavailable"
80
+ }
81
+ message: string
82
82
  }
83
83
 
84
84
  /**
@@ -959,10 +959,123 @@ declare const logger: pino.Logger & {
959
959
  * The type definition for an error object.
960
960
  */
961
961
  type ErrorObj = {
962
- status: number
963
- name: string
964
- message: string
965
- data: unknown
962
+ status: number
963
+ name: string
964
+ message: string
965
+ data: unknown
966
+ }
967
+
968
+ /**
969
+ * The type for the overall wrapper options.
970
+ */
971
+ type WrapperOptions$1 = {};
972
+ /**
973
+ * The type for a Next API wrapped method input.
974
+ */
975
+ type NextApiMethodInput = {
976
+ req: NextApiRequest;
977
+ res: NextApiResponse;
978
+ wrapper: NextApiWrapper;
979
+ };
980
+ /**
981
+ * The type for a Next API wrapped method.
982
+ */
983
+ type NextApiMethod$1 = ({ req, res, wrapper }: NextApiMethodInput) => Promise<void> | void;
984
+ /**
985
+ * The type for a Next API wrapped method, extended with specific options.
986
+ */
987
+ type NextApiMethodWithOptions = {
988
+ method: NextApiMethod$1;
989
+ };
990
+ /**
991
+ * An object containing all methods for the API route.
992
+ */
993
+ type NextApiMethods$1 = {
994
+ read?: NextApiMethod$1 | NextApiMethodWithOptions;
995
+ write?: NextApiMethod$1 | NextApiMethodWithOptions;
996
+ update?: NextApiMethod$1 | NextApiMethodWithOptions;
997
+ replace?: NextApiMethod$1 | NextApiMethodWithOptions;
998
+ remove?: NextApiMethod$1 | NextApiMethodWithOptions;
999
+ };
1000
+ /**
1001
+ * A class that wraps the Next.js API routes.
1002
+ */
1003
+ declare class NextApiWrapper {
1004
+ private _req;
1005
+ private _res;
1006
+ private _read;
1007
+ private _write;
1008
+ private _update;
1009
+ private _replace;
1010
+ private _remove;
1011
+ private _options;
1012
+ /**
1013
+ * The constructor for the `NextApiWrapper` class.
1014
+ * @param req The `NextApiRequest` object.
1015
+ * @param res The `NextApiResponse` object.
1016
+ * @param methods The methods to be used for the API route:
1017
+ * - `read`: The *GET* method.
1018
+ * - `write`: The *POST* method.
1019
+ * - `update`: The *PATCH* method.
1020
+ * - `replace`: The *PUT* method.
1021
+ * - `remove`: The *DELETE* method.
1022
+ * @param options The options for the wrapper:
1023
+ * - (Currently none)
1024
+ */
1025
+ constructor(req: NextApiRequest, res: NextApiResponse, methods?: NextApiMethods$1, options?: WrapperOptions$1);
1026
+ /**
1027
+ * Set request and response objects.
1028
+ * @param req The new `NextApiRequest` object.
1029
+ * @param res The new `NextApiResponse` object.
1030
+ */
1031
+ setRequestResponse(req: NextApiRequest, res: NextApiResponse): void;
1032
+ /**
1033
+ * Set methods for the API route.
1034
+ * @param methods The new methods to be used for the API route:
1035
+ * - `read`: The *GET* method.
1036
+ * - `write`: The *POST* method.
1037
+ * - `update`: The *PATCH* method.
1038
+ * - `replace`: The *PUT* method.
1039
+ * - `remove`: The *DELETE* method.
1040
+ */
1041
+ setMethods(methods: NextApiMethods$1): void;
1042
+ /**
1043
+ * Set options for the API route.
1044
+ * @param options The new options for the wrapper:
1045
+ * - (Currently none)
1046
+ */
1047
+ setOptions(options: Partial<WrapperOptions$1>): void;
1048
+ /**
1049
+ * A private method to check data validity.
1050
+ * @param data The data to be checked.
1051
+ * @returns Whether the data is valid.
1052
+ */
1053
+ private _checkDataValidity;
1054
+ /**
1055
+ * Returns a properly formatted success response.
1056
+ * @param status Status code to be sent in the response.
1057
+ * @param data Data to be sent in the response (optional, defaults to `null`).
1058
+ */
1059
+ successResponse(status: number, data?: unknown): void;
1060
+ /**
1061
+ * Returns a properly formatted error response, based on error constants.
1062
+ * @param error Error code constant to be sent in the response.
1063
+ * @param data Additional data to be sent in the response (optional).
1064
+ * @param message Error message to be sent in the response (optional, defaults to the internal error message).
1065
+ */
1066
+ errorResponse(error: ErrorObj, data?: unknown, message?: string): void;
1067
+ /**
1068
+ * Check if a method is a direct method or a method with options and execute it.
1069
+ * @param method The method to be checked.
1070
+ * @param methodInput The method input object.
1071
+ * @returns Whether the method was executed successfully.
1072
+ */
1073
+ private _executeMethod;
1074
+ /**
1075
+ * Run and route the request to the appropriate method.
1076
+ * @returns The response from the method.
1077
+ */
1078
+ run(): Promise<boolean | void>;
966
1079
  }
967
1080
 
968
1081
  /**
@@ -992,20 +1105,20 @@ type WrapperOptions = {
992
1105
  /**
993
1106
  * The type for a Next API wrapped method input.
994
1107
  */
995
- type NextApiMethodInput = {
1108
+ type NextAuthApiMethodInput = {
996
1109
  req: NextApiRequest;
997
1110
  res: NextApiResponse;
998
1111
  session: ExtendedSession | null;
999
- wrapper: NextApiWrapper;
1112
+ wrapper: NextAuthApiWrapper;
1000
1113
  };
1001
1114
  /**
1002
1115
  * The type for a Next API wrapped method.
1003
1116
  */
1004
- type NextApiMethod = ({ req, res, session, wrapper }: NextApiMethodInput) => Promise<void> | void;
1117
+ type NextApiMethod = ({ req, res, session, wrapper }: NextAuthApiMethodInput) => Promise<void> | void;
1005
1118
  /**
1006
1119
  * The type for a Next API wrapped method, extended with specific auth options.
1007
1120
  */
1008
- type NextApiMethodWithAuthOptions = {
1121
+ type NextAuthApiMethodWithAuthOptions = {
1009
1122
  method: NextApiMethod;
1010
1123
  authOptions?: AuthOptions;
1011
1124
  };
@@ -1013,16 +1126,16 @@ type NextApiMethodWithAuthOptions = {
1013
1126
  * An object containing all methods for the API route.
1014
1127
  */
1015
1128
  type NextApiMethods = {
1016
- read?: NextApiMethod | NextApiMethodWithAuthOptions;
1017
- write?: NextApiMethod | NextApiMethodWithAuthOptions;
1018
- update?: NextApiMethod | NextApiMethodWithAuthOptions;
1019
- replace?: NextApiMethod | NextApiMethodWithAuthOptions;
1020
- remove?: NextApiMethod | NextApiMethodWithAuthOptions;
1129
+ read?: NextApiMethod | NextAuthApiMethodWithAuthOptions;
1130
+ write?: NextApiMethod | NextAuthApiMethodWithAuthOptions;
1131
+ update?: NextApiMethod | NextAuthApiMethodWithAuthOptions;
1132
+ replace?: NextApiMethod | NextAuthApiMethodWithAuthOptions;
1133
+ remove?: NextApiMethod | NextAuthApiMethodWithAuthOptions;
1021
1134
  };
1022
1135
  /**
1023
1136
  * A class that wraps the Next.js API routes.
1024
1137
  */
1025
- declare class NextApiWrapper {
1138
+ declare class NextAuthApiWrapper {
1026
1139
  private _req;
1027
1140
  private _res;
1028
1141
  private _read;
@@ -1032,7 +1145,7 @@ declare class NextApiWrapper {
1032
1145
  private _remove;
1033
1146
  private _options;
1034
1147
  /**
1035
- * The constructor for the NextApiWrapper class.
1148
+ * The constructor for the `NextAuthApiWrapper` class.
1036
1149
  * @param req The `NextApiRequest` object.
1037
1150
  * @param res The `NextApiResponse` object.
1038
1151
  * @param methods The methods to be used for the API route:
@@ -1069,12 +1182,14 @@ declare class NextApiWrapper {
1069
1182
  /**
1070
1183
  * Set options for the API route.
1071
1184
  * @param options The new options for the wrapper:
1185
+ * - `authFunction`: The function to be used for authentication.
1186
+ * - `roles`: The roles to be used for the wrapper.
1072
1187
  * - `requireAuth`: Whether to require authentication (defaults to `false`).
1073
1188
  * - `hasRole`: The user needs to have the role.
1074
1189
  * - `hasSomeRoles`: The user needs to have at least one of the roles.
1075
1190
  * - `hasAllRoles`: The user needs to have all of the roles.
1076
1191
  */
1077
- setOptions(options: Partial<AuthOptions>): void;
1192
+ setOptions(options: Partial<WrapperOptions>): void;
1078
1193
  /**
1079
1194
  * A private method to check data validity.
1080
1195
  * @param data The data to be checked.
@@ -1136,4 +1251,4 @@ declare class NextApiWrapper {
1136
1251
  run(): Promise<boolean | void>;
1137
1252
  }
1138
1253
 
1139
- export { Bench, type BenchmarkResult, type BenchmarkResults, type Bit, type CryptoAes256GcmEncryptResult, CyBuffer, type Endianness, type NextApiMethodInput, NextApiWrapper, type StringEncoding, crypto, generateCGASStatus, getHostname, logger };
1254
+ export { Bench, type BenchmarkResult, type BenchmarkResults, type Bit, type CryptoAes256GcmEncryptResult, CyBuffer, type Endianness, type NextApiMethodInput, NextApiWrapper, type NextAuthApiMethodInput, NextAuthApiWrapper, type StringEncoding, crypto, generateCGASStatus, getHostname, logger };
package/backend.js CHANGED
@@ -1,6 +1,6 @@
1
- import M,{masks}from'dateformat';import D from'pino';import F from'pino-pretty';import {randomBytes,createCipheriv,createDecipheriv,randomFillSync}from'crypto';import {execSync}from'child_process';import {hostname}from'os';function U(n,t=4){return JSON.stringify(n,(r,e)=>typeof e=="function"||typeof e=="bigint"?e.toString():e,t)}var B={level:process.env.LOG_LEVEL||"trace",showLevel:true,showTimestamp:true,foreignObjectStartAtNewLine:false,foreignObjectPadding:0,foreignObjectIndent:4},u={...B};function P(n,t){let r={level:n.level,time:n.time,pid:n.pid,hostname:n.hostname,msg:n.msg},e=Object.entries(n).reduce((d,[p,R])=>(Object.keys(r).includes(p)||(d[p]=R),d),{}),i="N/A",s,a;switch(n.level){case 10:case "trace":i="TRACE",a=t.black;break;case 20:case "debug":i="DEBUG",a=t.blue;break;case 30:case "info":i="INFO",a=t.green;break;case 40:case "warn":i="WARN",a=t.yellow;break;case 50:case "error":i="ERROR",a=t.redBright;break;case 60:case "fatal":i="FATAL",s=t.bold,a=t.redBright;break;default:i="N/A",a=t.white;break}let o="";u.showTimestamp&&(o=`[${M(new Date(n.time),masks.isoDateTime)}] `);let c="";u.showLevel&&(c=`[${i}] `.padEnd(8," "));let m="";Object.keys(e).length>0&&(u.foreignObjectPadding==="after-timestamp"?u.foreignObjectPadding=o.length:u.foreignObjectPadding==="after-level"&&(u.foreignObjectPadding=o.length+c.length),m=`${u.foreignObjectStartAtNewLine?`
2
- `:" "}${U(e,u.foreignObjectIndent)}`.split(`
3
- `).map((d,p)=>p===0?d:d.padStart(d.length+u.foreignObjectPadding," ")).join(`
4
- `));let l=a(`${o}${c}${n.msg}${m}`);return s&&(l=s(l)),console.log(l),""}var C=F({crlf:false,colorize:true,sync:true,include:"",messageFormat:(n,t,r,{colors:e})=>P(n,e)}),E=D({level:u.level},C);E.setLevel=n=>{u.level=n,E.level=n;};E.setShowLevel=n=>{u.showLevel=n;};E.setShowTimestamp=n=>{u.showTimestamp=n;};E.setForeignObjectStartAtNewLine=n=>{u.foreignObjectStartAtNewLine=n;};E.setForeignObjectPadding=n=>{u.foreignObjectPadding=n;};E.setForeignObjectIndent=n=>{u.foreignObjectIndent=n;};E.setParameters=n=>{Object.assign(u,n);};E.resetParameters=()=>{Object.assign(u,B);};var w=E;function I(n,t="Op",r="s",e=12,i=true){let s;typeof t=="string"&&typeof r=="string"?s=`${t}/${r}`:typeof t=="string"?s=t:s="";let a=i?" ":"";return n>=10**24?`${(n/10**24).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}Y${s}`.padStart(e," "):n>=10**18?`${(n/10**18).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}E${s}`.padStart(e," "):n>=10**15?`${(n/10**15).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}P${s}`.padStart(e," "):n>=10**12?`${(n/10**12).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}T${s}`.padStart(e," "):n>=10**9?`${(n/10**9).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}G${s}`.padStart(e," "):n>=10**6?`${(n/10**6).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}M${s}`.padStart(e," "):n>=10**3?`${(n/10**3).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}k${s}`.padStart(e," "):`${n.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}${s}`.padStart(e," ")}function L(n,t=8){return n>=3600000000000000n?`${(Number(n)/36e14).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}h`.padStart(t," "):n>=60000000000n?`${(Number(n)/6e10).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}m`.padStart(t," "):n>=1000000000n?`${(Number(n)/1e9).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}s`.padStart(t," "):n>=1000000n?`${(Number(n)/1e6).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}ms`.padStart(t," "):n>=1000n?`${(Number(n)/1e3).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}\xB5s`.padStart(t," "):`${n.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}ns`.padStart(t," ")}function _(n,t=7){return `${n.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}%`.padStart(t," ")}var A=class{benchmarkDuration;results={};constructor(t=256){this.benchmarkDuration=t;}benchmark=(t,r)=>{let i=process.hrtime.bigint(),s=0,a=0,o=0,c=0n,m=0n,l=0n,d=BigInt(this.benchmarkDuration)*1000000n;for(let p=0;p<Number.POSITIVE_INFINITY;p++)if(m=process.hrtime.bigint(),t(),l=process.hrtime.bigint(),c+=l-m,l-i>=d){a=Number(c)/p,s=1e9/a,o=Number(l-i)/a;break}this.results[r]={operationsPerSecond:s,avgExecutionTime:a,operations:o};};print=(t,r=true)=>{let e=t||"RESULTS";w.info(`
5
- ${e.toUpperCase()}:`),w.info("=".repeat(e.length+1));let i=0;for(let a of Object.keys(this.results))a.length>i&&(i=a.length);let s=Object.entries(this.results).sort((a,o)=>o[1].operationsPerSecond-a[1].operationsPerSecond);for(let[a,o]of s){let c=s[0][1].operationsPerSecond,m=o.operationsPerSecond/c*100,l=`>> ${a} `.padEnd(i+4,"\u2550"),d=`AVG TIME: ${L(o.avgExecutionTime)}`,p=`OPS: ${I(o.operationsPerSecond)}`,R=`PERCENTAGE: ${_(m)}`,b=`${l}\u2550> ${d} | ${p} | ${R}`,S=10;m>=90?w.debug(b+"(fastest)".padStart(S," ")):m>=60?w.info(b+"(fast)".padStart(S," ")):m>=30?w.warn(b+"(medium)".padStart(S," ")):m>=10?w.error(b+"(slow)".padStart(S," ")):w.error(b+"(slowest)".padStart(S," "));}r&&(this.results={});}};function j(n,t,r,e,i){return i?t:{status:n,marker:t,timestamp:new Date().toISOString(),version:{raw:r??"unavailable",formatted:r?`v${r}`:"unavailable"},message:e??"The application is running smoothly."}}function q(n,t){let r=Buffer.from(n,"base64");if(r.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${r.length}`);let e=randomBytes(12).toString("base64"),i=createCipheriv("aes-256-gcm",r,Buffer.from(e,"base64")),s=i.update(t,"utf8","base64");s+=i.final("base64");let a=i.getAuthTag(),o=`${e}.${s}.${a.toString("base64")}`;return {iv:e,ciphertext:s,tag:a,payload:o}}function $(n,t,r,e){try{let i=createDecipheriv("aes-256-gcm",Buffer.from(n,"base64"),Buffer.from(t,"base64"));i.setAuthTag(Buffer.from(e,"base64"));let s=i.update(r,"base64","utf8");return s+=i.final("utf8"),s}catch{return null}}function W(n,t){let r=t.split(".");if(r.length!==3)throw new Error("Invalid payload format");let[e,i,s]=r;return $(n,e,i,s)}var V={aes256Gcm:{encrypt:q,decrypt:$,decryptPayload:W}};function h(n,t){return `[CyBuffer - ${n}] ${t}`}var x=class n{platformEndianness;arrayBuffer;array;offset;length;constructor(t,r){if(t<0)throw new RangeError(h("constructor",`Invalid buffer length: '${t}'.`));if(!Number.isInteger(t))throw new TypeError(h("constructor",`Invalid buffer length: '${t}'.`));return this.platformEndianness=this.getPlatformEndianness(),r?(this.arrayBuffer=r.arrayBuffer,this.offset=r.offset??0,this.length=r.length??t,this.array=new Uint8Array(this.arrayBuffer,this.offset,this.length)):(this.arrayBuffer=new ArrayBuffer(t),this.offset=0,this.length=t,this.array=new Uint8Array(this.arrayBuffer)),this._proxy}getPlatformEndianness=()=>{let t=new Uint8Array(4),r=new Uint32Array(t.buffer);return r[0]=65280,t[0]===255?"BE":"LE"};normalizeEndianness=t=>this.platformEndianness==="BE"?t==="LE"?"BE":"LE":t;check=(t,r)=>{if(Number.isNaN(t)||Number.isNaN(r))throw new TypeError(h("check",`Invalid offset: '${t}' or length: '${r}'.`));if(t<0||t>=this.length)throw new RangeError(h("check",`Invalid offset: '${t}', it must be >= 0 & < ${this.length}.`));if(r<1||r>this.length)throw new RangeError(h("check",`Invalid length: '${r}', it must be > 0 & <= ${this.length}.`));if(t+r>this.length)throw new RangeError(h("check",`Invalid offset (${t}) + length (${r}): '${t+r}', it must be <= ${this.length}.`));if(t%1!==0)throw new RangeError(h("check",`Invalid offset alignment: '${t}'.`));if(r%1!==0)throw new RangeError(h("check",`Invalid length alignment: '${r}'.`));return this};static alloc=(t,r)=>{let e=new n(t);return r!==void 0&&e.fill(r),e};static fromHexString=t=>{t.startsWith("0x")&&(t=t.slice(2));let r=Math.ceil(t.length/2),e=new n(r);return e.writeHexString(t,0,r),e};static fromUtf8String=t=>{let r=new n(t.length);return r.writeUtf8String(t,0,t.length),r};static fromString=(t,r="utf8")=>{let e=new n(t.length);return e.writeString(t,r,0,t.length),e};static fromBits=(t,r=true)=>{let e=new n(Math.ceil(t.length/8));return e.writeBits(t,0,t.length,r),e};static fromUint8Array=t=>{let r=new n(t.byteLength);return r.writeUint8Array(t,0,t.byteLength),r};static fromUint16Array=t=>{let r=new n(t.byteLength);return r.writeUint16Array(t,0,t.byteLength),r};static fromUint32Array=t=>{let r=new n(t.byteLength);return r.writeUint32Array(t,0,t.byteLength),r};static fromBigInt=(t,r)=>{if(t<0n)throw new RangeError(h("fromBigInt",`Invalid big integer: '${t}'.`));let e=Math.ceil(t.toString(16).length/2),i=new n(e);return i.writeBigInt(t,0,e,r),i};static fromRange=(t,r)=>{let e=new n(r-t);return e.writeRange(t,r),e};get _proxy(){return new Proxy(this,{get:(t,r)=>typeof r=="string"&&!Number.isNaN(Number(r))?(this.check(Number(r),1),t.array[Number(r)]??void 0):t[r],set:(t,r,e)=>{if(typeof r=="string"&&!Number.isNaN(Number(r))){let i=Number(e);if(Number.isNaN(i))throw new TypeError(h("proxy",`Invalid value: '${e}'.`));if(i<0||i>255)throw new RangeError(h("proxy",`Value is out of bounds: '${e}'.`));return this.check(Number(r),1),t.array[Number(r)]=e,true}return t[r]=e,true}})}*[Symbol.iterator](){let t=0;for(;t<this.length;)yield this.array[t++];}*entries(){for(let t=0;t<this.length;t++)yield [t,this.array[t]];}writeHexString=(t,r=0,e=t.length/2)=>{if(e===0)throw new RangeError(h("writeHexString",`Invalid hexadecimal string length: '${e}'.`));if(e%1!==0)throw new RangeError(h("writeHexString",`Invalid hexadecimal string length: '${e}'.`));if(t.length%2!==0)throw new RangeError(h("writeHexString",`Invalid hexadecimal string length: '${t.length}'.`));t.startsWith("0x")&&(e===t.length/2&&(e=(t.length-2)/2),t=t.slice(2)),this.check(r,e);for(let i=0;i<e;i++){let s=t.charCodeAt(i*2)|32,a=t.charCodeAt(i*2+1)|32;this.array[r+i]=s-(s>57?87:48)<<4|a-(a>57?87:48);}return this};writeUtf8String=(t,r=0,e=t.length)=>{if(e===0)throw new RangeError(h("writeUtf8String",`Invalid UTF-8 string length: '${e}'.`));this.check(r,e);for(let i=0;i<e;i++)this.array[r+i]=t.charCodeAt(i);return this};writeString=(t,r="utf8",e=0,i=t.length)=>{if(r==="utf8")return this.writeUtf8String(t,e,i),this;if(r==="hex")return this.writeHexString(t,e,Math.ceil(i/2)),this;throw new TypeError(h("writeString",`Invalid encoding: '${r}'.`))};writeBit=(t,r=0,e=true,i=true)=>{if(t<0||t>1)throw new RangeError(h("writeBit",`Value is out of bounds: '${t}'.`));let s=Math.floor(r/8);i&&this.check(s,1);let a=e?7-r%8:r%8;return t===1?this.array[s]|=1<<a:this.array[s]&=~(1<<a),this};writeUint8=(t,r=0,e=true)=>{if(t<0||t>255)throw new RangeError(h("writeUint8",`Value is out of bounds: '${t}'.`));return e&&this.check(r,1),t>>>=0,this.array[r]=t,this};writeUint16LE=(t,r=0,e=true,i=true)=>{if(t<0||t>65535)throw new RangeError(h("writeUint16LE",`Value is out of bounds: '${t}'.`));if(e&&r%2!==0)throw new RangeError(h("writeUint16LE",`Invalid offset alignment: '${r}' (%2).`));return i&&this.check(r,2),t>>>=0,this.array[r]=t&255,this.array[r+1]=t>>8&255,this};writeUint16BE=(t,r=0,e=true,i=true)=>{if(t<0||t>65535)throw new RangeError(h("writeUint16BE",`Value is out of bounds: '${t}'.`));if(e&&r%2!==0)throw new RangeError(h("writeUint16BE",`Invalid offset alignment: '${r}' (%2).`));return i&&this.check(r,2),t>>>=0,this.array[r]=t>>8&255,this.array[r+1]=t&255,this};writeUint16=(t,r=0,e=this.platformEndianness,i=true,s=true)=>this.normalizeEndianness(e)==="LE"?(this.writeUint16LE(t,r,i,s),this):(this.writeUint16BE(t,r,i,s),this);writeUint32LE=(t,r=0,e=true,i=true)=>{if(t<0||t>4294967295)throw new RangeError(h("writeUint32LE",`Value is out of bounds: '${t}'.`));if(e&&r%4!==0)throw new RangeError(h("writeUint32LE",`Invalid offset alignment: '${r}' (%4).`));return i&&this.check(r,4),t>>>=0,this.array[r]=t&255,this.array[r+1]=t>>8&255,this.array[r+2]=t>>16&255,this.array[r+3]=t>>24&255,this};writeUint32BE=(t,r=0,e=true,i=true)=>{if(t<0||t>4294967295)throw new RangeError(h("writeUint32BE",`Value is out of bounds: '${t}'.`));if(e&&r%4!==0)throw new RangeError(h("writeUint32BE",`Invalid offset alignment: '${r}' (%4).`));return i&&this.check(r,4),t>>>=0,this.array[r]=t>>24&255,this.array[r+1]=t>>16&255,this.array[r+2]=t>>8&255,this.array[r+3]=t&255,this};writeUint32=(t,r=0,e=this.platformEndianness,i=true,s=true)=>this.normalizeEndianness(e)==="LE"?(this.writeUint32LE(t,r,i,s),this):(this.writeUint32BE(t,r,i,s),this);writeBits=(t,r=0,e=t.length,i=true)=>{if(!t||!Array.isArray(t))throw new TypeError(h("writeBits",`Invalid array of bits: '${t}'.`));let s=Math.floor(r/8),a=Math.ceil(e/8);this.check(s,a);for(let o=0;o<e;o++)this.writeBit(t[o],r+o,i,false);return this};writeUint8Array=(t,r=0,e=t.byteLength,i=0)=>{if(!t||!(t instanceof Uint8Array))throw new TypeError(h("writeUint8Array",`Invalid Uint8Array: '${t}'.`));this.check(r,e);for(let s=i;s<e;s++)this.array[r-i+s]=t[s];return this};writeUint16Array=(t,r=0,e=t.byteLength,i=0,s=this.platformEndianness,a=true)=>{if(!t||!(t instanceof Uint16Array))throw new TypeError(h("writeUint16Array",`Invalid Uint16Array: '${t}'.`));if(a&&r%2!==0)throw new RangeError(h("writeUint16Array",`Invalid offset alignment: '${r}' (%2).`));if(this.check(r,e),this.normalizeEndianness(s)==="LE"){for(let o=i;o<e;o+=2)this.writeUint16LE(t[o/2],r-i+o,a,false);return this}for(let o=i;o<e;o+=2)this.writeUint16BE(t[o/2],r-i+o,a,false);return this};writeUint32Array=(t,r=0,e=t.byteLength,i=0,s=this.platformEndianness,a=true)=>{if(!t||!(t instanceof Uint32Array))throw new TypeError(h("writeUint32Array",`Invalid Uint32Array: '${t}'.`));if(a&&r%4!==0)throw new RangeError(h("writeUint32Array",`Invalid offset alignment: '${r}' (%4).`));if(this.check(r,e),this.normalizeEndianness(s)==="LE"){for(let o=i;o<e;o+=4)this.writeUint32LE(t[o/4],r-i+o,a,false);return this}for(let o=i;o<e;o+=4)this.writeUint32BE(t[o/4],r-i+o,a,false);return this};writeBigIntLE=(t,r=0,e=Math.ceil(Number(t).toString(16).length/2))=>{if(t<0n)throw new RangeError(h("writeBigIntLE",`Invalid big integer value: '${t}'.`));this.check(r,e);for(let i=0;i<e;i++)this.array[r+i]=Number(t&BigInt(255)),t>>=BigInt(8);return this};writeBigIntBE=(t,r=0,e=Math.ceil(Number(t).toString(16).length/2))=>{if(t<0n)throw new RangeError(h("writeBigIntBE",`Invalid big integer value: '${t}'.`));this.check(r,e);for(let i=e-1;i>=0;i--)this.array[r+i]=Number(t&BigInt(255)),t>>=BigInt(8);return this};writeBigInt=(t,r=0,e=Math.ceil(Number(t).toString(16).length/2),i=this.platformEndianness)=>this.normalizeEndianness(i)==="LE"?(this.writeBigIntLE(t,r,e),this):(this.writeBigIntBE(t,r,e),this);writeRange=(t,r,e=0)=>{if(t<0||t>255)throw new RangeError(h("writeRange",`Invalid start value: '${t}'.`));if(r<0||r>255)throw new RangeError(h("writeRange",`Invalid end value: '${r}'.`));let i=r-t;this.check(e,i);for(let s=0;s<i;s++)this.array[e+s]=t+s;return this};readHexStringLE=(t=0,r=this.length-t,e=true)=>(e&&this.check(t,r),Buffer.from(this.arrayBuffer,t,r).toString("hex").toUpperCase());readHexStringBE=(t=0,r=this.length-t,e=true)=>(e&&this.check(t,r),Buffer.from(this.arrayBuffer,t,r).toString("hex").toUpperCase().match(/.{2}/g).reverse().join(""));readHexString=(t=0,r=this.length-t,e=this.platformEndianness,i=true)=>(i&&this.check(t,r),this.normalizeEndianness(e)==="LE"?this.readHexStringLE(t,r,false):this.readHexStringBE(t,r,false));readUtf8String=(t=0,r=this.length-t,e=true)=>(e&&this.check(t,r),Buffer.from(this.arrayBuffer,t,r).toString("utf8"));readBit=(t=0,r=true,e=true)=>{let i=Math.floor(t/8);e&&this.check(i,1);let s=r?7-t%8:t%8;return (this.array[i]&1<<s)!==0?1:0};readUint8=(t=0,r=true)=>(r&&this.check(t,1),this.array[t]);readUint16LE=(t=0,r=true,e=true)=>{if(r&&t%2!==0)throw new RangeError(h("readUint16LE",`Invalid offset alignment: '${t}' (%2).`));return e&&this.check(t,2),(this.array[t]|this.array[t+1]<<8)>>>0};readUint16BE=(t=0,r=true,e=true)=>{if(r&&t%2!==0)throw new RangeError(h("readUint16BE",`Invalid offset alignment: '${t}' (%2).`));return e&&this.check(t,2),(this.array[t]<<8|this.array[t+1])>>>0};readUint16=(t=0,r=this.platformEndianness,e=true,i=true)=>this.normalizeEndianness(r)==="LE"?this.readUint16LE(t,e,i):this.readUint16BE(t,e,i);readUint32LE=(t=0,r=true,e=true)=>{if(r&&t%4!==0)throw new RangeError(h("readUint32LE",`Invalid offset alignment: '${t}' (%4).`));return e&&this.check(t,4),(this.array[t]|this.array[t+1]<<8|this.array[t+2]<<16|this.array[t+3]<<24)>>>0};readUint32BE=(t=0,r=true,e=true)=>{if(r&&t%4!==0)throw new RangeError(h("readUint32BE",`Invalid offset alignment: '${t}' (%4).`));return e&&this.check(t,4),(this.array[t]<<24|this.array[t+1]<<16|this.array[t+2]<<8|this.array[t+3])>>>0};readUint32=(t=0,r=this.platformEndianness,e=true,i=true)=>this.normalizeEndianness(r)==="LE"?this.readUint32LE(t,e,i):this.readUint32BE(t,e,i);readBits=(t=0,r=this.length*8-t*8,e=true,i=true)=>{let s=[];for(let a=0;a<r;a++)s.push(this.readBit(t+a,e,i));return s};readUint8Array=(t=0,r=this.length-t,e=true)=>(e&&this.check(t,r),new Uint8Array(this.arrayBuffer,t??this.offset,r??this.length));readUint16Array=(t=0,r=this.length-t,e=true)=>(e&&this.check(t,r),new Uint16Array(this.arrayBuffer,t??this.offset,r?r/2:this.length/2));readUint32Array=(t=0,r=this.length-t,e=true)=>(e&&this.check(t,r),new Uint32Array(this.arrayBuffer,t??this.offset,r?r/4:this.length/4));readBigIntLE=(t=0,r=this.length-t,e=true)=>{e&&this.check(t,r);let i=0n;for(let s=r-1;s>=0;s--)i=i<<8n|BigInt(this.array[t+s]);return i};readBigIntBE=(t=0,r=this.length-t,e=true)=>{e&&this.check(t,r);let i=0n;for(let s=0;s<r;s++)i=i<<8n|BigInt(this.array[t+s]);return i};readBigInt=(t=0,r=this.length-t,e=this.platformEndianness,i=true)=>this.normalizeEndianness(e)==="LE"?this.readBigIntLE(t,r,i):this.readBigIntBE(t,r,i);toHexString=(t=false,r=this.platformEndianness)=>{let e=Buffer.from(this.arrayBuffer).toString("hex").toUpperCase();return this.normalizeEndianness(r)==="BE"&&(e=e.match(/.{2}/g)?.reverse().join("")??""),t?`0x${e}`:e};toUtf8String=()=>Buffer.from(this.arrayBuffer).toString("utf8");toString=(t="hex",r=false)=>t==="utf8"?this.toUtf8String():this.toHexString(r);toBits=(t=true)=>{let r=this.length*8,e=new Array(r);for(let i=0;i<r;i++)e[i]=this.readBit(i,t);return e};toUint8Array=()=>new Uint8Array(this.arrayBuffer,this.offset,this.length);toUint16Array=()=>new Uint16Array(this.arrayBuffer,this.offset,this.length/2);toUint32Array=()=>new Uint32Array(this.arrayBuffer,this.offset,this.length/4);toBigInt=(t=this.platformEndianness)=>this.normalizeEndianness(t)==="LE"?this.readBigIntLE():this.readBigIntBE();equals=t=>{if(this.length!==t.length)return false;for(let r=0;r<this.length;r++)if(this.array[r]!==t[r])return false;return true};isEmpty=()=>{for(let t=0;t<this.length;t++)if(this.array[t]!==0)return false;return true};isFull=()=>{for(let t=0;t<this.length;t++)if(this.array[t]!==255)return false;return true};randomFill=(t=0,r=this.length-t)=>{this.check(t,r);for(let e=0;e<r;e++)this.array[t+e]=Math.floor(Math.random()*256);};safeRandomFill=(t=0,r=this.length)=>randomFillSync(this.array,t,r);copy=(t=0,r=this.length)=>{this.check(t,r);let e=new n(r);for(let i=0;i<r;i++)e[i]=this.array[i+t];return e};subarray=(t=0,r=this.length)=>(this.check(t,r),new n(r,{arrayBuffer:this.arrayBuffer,offset:t,length:r}));swap=(t=0,r=this.length,e=4)=>{if(e<2)throw new RangeError(h("swap",`Invalid word length: '${e}'.`));if(e%2!==0)throw new RangeError(h("swap",`Invalid word length alignment: '${e}'.`));this.check(t,r);let i=t+r;for(let s=0;s<i;s+=e){let a=s+t;for(let o=0;o<e/2;o++){let c=this.array[a+o];this.array[a+o]=this.array[a+e-o-1],this.array[a+e-o-1]=c;}}return this};partialReverse=(t=0,r=this.length)=>{this.check(t,r);let e=Math.floor(r/2),i=t+r;for(let s=0;s<e;s++){let a=s+t,o=i-s-1,c=this.array[a];this.array[a]=this.array[o],this.array[o]=c;}return this};reverse=()=>(this.array.reverse(),this);rotateLeft=()=>{let t=this.array[0];for(let r=0;r<this.length-1;r++)this.array[r]=this.array[r+1];return this.array[this.length-1]=t,this};rotateRight=()=>{let t=this.array[this.length-1];for(let r=this.length-1;r>0;r--)this.array[r]=this.array[r-1];return this.array[0]=t,this};shiftLeft=(t=0,r=this.length,e=1)=>{this.check(t,r);for(let i=0;i<this.length-1;i++)this.array[i]=this.array[i+e];for(let i=0;i<e;i++)this.array[this.length-i-1]=0;return this};shiftRight=(t=0,r=this.length,e=1)=>{this.check(t,r);for(let i=this.length-1;i>0;i--)this.array[i]=this.array[i-e];for(let i=0;i<e;i++)this.array[i]=0;return this};fill=(t,r=0,e=this.length)=>{if(t<0||t>255)throw new RangeError(h("fill",`Invalid value: '${t}'.`));return this.check(r,e),this.array.fill(t,r,r+e),this};clear=(t=0,r=this.length)=>(this.check(t,r),this.array.fill(0,t,t+r),this)};function X(){switch(process.platform){case "win32":return process.env.COMPUTERNAME;case "darwin":return execSync("scutil --get ComputerName").toString().trim();case "linux":{let n=execSync("hostnamectl --pretty").toString().trim();return n===""?hostname():n}default:return hostname()}}var y={BAD_REQUEST:{status:400,name:"BadRequest",message:"Bad request.",data:null},UNAUTHORIZED:{status:401,name:"Unauthorized",message:"Unauthorized.",data:null},PAYMENT_REQUIRED:{status:402,name:"PaymentRequired",message:"Payment required.",data:null},FORBIDDEN:{status:403,name:"Forbidden",message:"Forbidden.",data:null},NOT_FOUND:{status:404,name:"NotFound",message:"Not found.",data:null},METHOD_NOT_ALLOWED:{status:405,name:"MethodNotAllowed",message:"Method not allowed.",data:null},REQUEST_TIMEOUT:{status:408,name:"RequestTimeout",message:"Request timed out.",data:null},CONFLICT:{status:409,name:"Conflict",message:"Conflict.",data:null},INTERNAL_SERVER_ERROR:{status:500,name:"InternalServerError",message:"Internal server error.",data:null},BACKEND_FUNCTION_RUNNING_ON_CLIENT:{status:500,name:"BackendFunctionRunningOnClient",message:"A function reserved for the backend is running on the client.",data:null},NOT_IMPLEMENTED:{status:501,name:"NotImplemented",message:"Not implemented.",data:null},BANDWIDTH_LIMIT_EXCEEDED:{status:509,name:"BandwidthLimitExceeded",message:"Bandwidth limit exceeded.",data:null}};var N=class{_req;_res;_read;_write;_update;_replace;_remove;_options;constructor(t,r,e,i){this.setRequestResponse(t,r),this.setMethods(e||{}),this.setOptions(i||{});}setRequestResponse(t,r){this._req=t,this._res=r;}setMethods(t){this._read=t?.read,this._write=t?.write,this._update=t?.update,this._replace=t?.replace,this._remove=t?.remove;}setOptions(t){this._options={...this._options,...t};}_checkDataValidity(t){return t!=null}successResponse(t,r){return this._res.status(t).send({success:true,data:this._checkDataValidity(r)?r:null})}errorResponse(t,r,e){let i={success:false,message:e||t.message,error:this._checkDataValidity(r)?{...t,data:r}:t};return this._res.status(t.status).send(i)}hasRole(t,r){return t.roles?.includes(r)}hasSomeRoles(t,r){return r.some(e=>t.roles?.includes(e))}hasAllRoles(t,r){return r.every(e=>t.roles?.includes(e))}checkAuthOptions(t,r){return r.requireAuth&&!t?(this.errorResponse(y.UNAUTHORIZED),false):r.hasRole&&(!t||!this.hasRole(t.user,r.hasRole))?(this.errorResponse(y.UNAUTHORIZED),false):r.hasSomeRoles&&(!t||!this.hasSomeRoles(t.user,r.hasSomeRoles))?(this.errorResponse(y.UNAUTHORIZED),false):r.hasAllRoles&&(!t||!this.hasAllRoles(t.user,r.hasAllRoles))?(this.errorResponse(y.UNAUTHORIZED),false):true}async _executeMethod(t,r){return typeof t=="function"?(await t(r),true):t.authOptions&&!this.checkAuthOptions(r.session,t.authOptions)?false:(await t.method(r),true)}async run(){let t=this._options.authFunction?await this._options.authFunction(this._req,this._res):null;if(!this.checkAuthOptions(t,this._options))return;let e={req:this._req,res:this._res,session:t,wrapper:this};try{switch(this._req.method){case "GET":if(this._read)return await this._executeMethod(this._read,e);break;case "POST":if(this._write)return await this._executeMethod(this._write,e);break;case "PATCH":if(this._update)return await this._executeMethod(this._update,e);break;case "PUT":if(this._replace)return await this._executeMethod(this._replace,e);break;case "DELETE":if(this._remove)return await this._executeMethod(this._remove,e);break;default:return this.errorResponse(y.METHOD_NOT_ALLOWED)}}catch(i){return this.errorResponse(y.INTERNAL_SERVER_ERROR,i)}}};export{A as Bench,x as CyBuffer,N as NextApiWrapper,V as crypto,j as generateCGASStatus,X as getHostname,w as logger};//# sourceMappingURL=backend.js.map
1
+ import T,{masks}from'dateformat';import F from'pino';import P from'pino-pretty';import {randomBytes,createCipheriv,createDecipheriv,randomFillSync}from'crypto';import {execSync}from'child_process';import {hostname}from'os';function U(n,t=4){return JSON.stringify(n,(e,r)=>typeof r=="function"||typeof r=="bigint"?r.toString():r,t)}var B={level:process.env.LOG_LEVEL||"trace",showLevel:true,showTimestamp:true,foreignObjectStartAtNewLine:false,foreignObjectPadding:0,foreignObjectIndent:4},u={...B};function C(n,t){let e={level:n.level,time:n.time,pid:n.pid,hostname:n.hostname,msg:n.msg},r=Object.entries(n).reduce((g,[d,_])=>(Object.keys(e).includes(d)||(g[d]=_),g),{}),i="N/A",s,a;switch(n.level){case 10:case "trace":i="TRACE",a=t.black;break;case 20:case "debug":i="DEBUG",a=t.blue;break;case 30:case "info":i="INFO",a=t.green;break;case 40:case "warn":i="WARN",a=t.yellow;break;case 50:case "error":i="ERROR",a=t.redBright;break;case 60:case "fatal":i="FATAL",s=t.bold,a=t.redBright;break;default:i="N/A",a=t.white;break}let o="";u.showTimestamp&&(o=`[${T(new Date(n.time),masks.isoDateTime)}] `);let c="";u.showLevel&&(c=`[${i}] `.padEnd(8," "));let f="";Object.keys(r).length>0&&(u.foreignObjectPadding==="after-timestamp"?u.foreignObjectPadding=o.length:u.foreignObjectPadding==="after-level"&&(u.foreignObjectPadding=o.length+c.length),f=`${u.foreignObjectStartAtNewLine?`
2
+ `:" "}${U(r,u.foreignObjectIndent)}`.split(`
3
+ `).map((g,d)=>d===0?g:g.padStart(g.length+u.foreignObjectPadding," ")).join(`
4
+ `));let l=a(`${o}${c}${n.msg}${f}`);return s&&(l=s(l)),console.log(l),""}var v=P({crlf:false,colorize:true,sync:true,include:"",messageFormat:(n,t,e,{colors:r})=>C(n,r)}),E=F({level:u.level},v);E.setLevel=n=>{u.level=n,E.level=n;};E.setShowLevel=n=>{u.showLevel=n;};E.setShowTimestamp=n=>{u.showTimestamp=n;};E.setForeignObjectStartAtNewLine=n=>{u.foreignObjectStartAtNewLine=n;};E.setForeignObjectPadding=n=>{u.foreignObjectPadding=n;};E.setForeignObjectIndent=n=>{u.foreignObjectIndent=n;};E.setParameters=n=>{Object.assign(u,n);};E.resetParameters=()=>{Object.assign(u,B);};var y=E;function I(n,t="Op",e="s",r=12,i=true){let s;typeof t=="string"&&typeof e=="string"?s=`${t}/${e}`:typeof t=="string"?s=t:s="";let a=i?" ":"";return n>=10**24?`${(n/10**24).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}Y${s}`.padStart(r," "):n>=10**18?`${(n/10**18).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}E${s}`.padStart(r," "):n>=10**15?`${(n/10**15).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}P${s}`.padStart(r," "):n>=10**12?`${(n/10**12).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}T${s}`.padStart(r," "):n>=10**9?`${(n/10**9).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}G${s}`.padStart(r," "):n>=10**6?`${(n/10**6).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}M${s}`.padStart(r," "):n>=10**3?`${(n/10**3).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}k${s}`.padStart(r," "):`${n.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}${a}${s}`.padStart(r," ")}function M(n,t=8){return n>=3600000000000000n?`${(Number(n)/36e14).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}h`.padStart(t," "):n>=60000000000n?`${(Number(n)/6e10).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}m`.padStart(t," "):n>=1000000000n?`${(Number(n)/1e9).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}s`.padStart(t," "):n>=1000000n?`${(Number(n)/1e6).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}ms`.padStart(t," "):n>=1000n?`${(Number(n)/1e3).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}\xB5s`.padStart(t," "):`${n.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}ns`.padStart(t," ")}function L(n,t=7){return `${n.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}%`.padStart(t," ")}var b=class{benchmarkDuration;results={};constructor(t=256){this.benchmarkDuration=t;}benchmark=(t,e)=>{let i=process.hrtime.bigint(),s=0,a=0,o=0,c=0n,f=0n,l=0n,g=BigInt(this.benchmarkDuration)*1000000n;for(let d=0;d<Number.POSITIVE_INFINITY;d++)if(f=process.hrtime.bigint(),t(),l=process.hrtime.bigint(),c+=l-f,l-i>=g){a=Number(c)/d,s=1e9/a,o=Number(l-i)/a;break}this.results[e]={operationsPerSecond:s,avgExecutionTime:a,operations:o};};print=(t,e=true)=>{let r=t||"RESULTS";y.info(`
5
+ ${r.toUpperCase()}:`),y.info("=".repeat(r.length+1));let i=0;for(let a of Object.keys(this.results))a.length>i&&(i=a.length);let s=Object.entries(this.results).sort((a,o)=>o[1].operationsPerSecond-a[1].operationsPerSecond);for(let[a,o]of s){let c=s[0][1].operationsPerSecond,f=o.operationsPerSecond/c*100,l=`>> ${a} `.padEnd(i+4,"\u2550"),g=`AVG TIME: ${M(o.avgExecutionTime)}`,d=`OPS: ${I(o.operationsPerSecond)}`,_=`PERCENTAGE: ${L(f)}`,A=`${l}\u2550> ${g} | ${d} | ${_}`,x=10;f>=90?y.debug(A+"(fastest)".padStart(x," ")):f>=60?y.info(A+"(fast)".padStart(x," ")):f>=30?y.warn(A+"(medium)".padStart(x," ")):f>=10?y.error(A+"(slow)".padStart(x," ")):y.error(A+"(slowest)".padStart(x," "));}e&&(this.results={});}};function j(n,t,e,r,i){return i?t:{status:n,marker:t,timestamp:new Date().toISOString(),version:{raw:e??"unavailable",formatted:e?`v${e}`:"unavailable"},message:r??"The application is running smoothly."}}function W(n,t){let e=Buffer.from(n,"base64");if(e.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${e.length}`);let r=randomBytes(12).toString("base64"),i=createCipheriv("aes-256-gcm",e,Buffer.from(r,"base64")),s=i.update(t,"utf8","base64");s+=i.final("base64");let a=i.getAuthTag(),o=`${r}.${s}.${a.toString("base64")}`;return {iv:r,ciphertext:s,tag:a,payload:o}}function O(n,t,e,r){try{let i=createDecipheriv("aes-256-gcm",Buffer.from(n,"base64"),Buffer.from(t,"base64"));i.setAuthTag(Buffer.from(r,"base64"));let s=i.update(e,"base64","utf8");return s+=i.final("utf8"),s}catch{return null}}function V(n,t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid payload format");let[r,i,s]=e;return O(n,r,i,s)}var z={aes256Gcm:{encrypt:W,decrypt:O,decryptPayload:V}};function h(n,t){return `[CyBuffer - ${n}] ${t}`}var N=class n{platformEndianness;arrayBuffer;array;offset;length;constructor(t,e){if(t<0)throw new RangeError(h("constructor",`Invalid buffer length: '${t}'.`));if(!Number.isInteger(t))throw new TypeError(h("constructor",`Invalid buffer length: '${t}'.`));return this.platformEndianness=this.getPlatformEndianness(),e?(this.arrayBuffer=e.arrayBuffer,this.offset=e.offset??0,this.length=e.length??t,this.array=new Uint8Array(this.arrayBuffer,this.offset,this.length)):(this.arrayBuffer=new ArrayBuffer(t),this.offset=0,this.length=t,this.array=new Uint8Array(this.arrayBuffer)),this._proxy}getPlatformEndianness=()=>{let t=new Uint8Array(4),e=new Uint32Array(t.buffer);return e[0]=65280,t[0]===255?"BE":"LE"};normalizeEndianness=t=>this.platformEndianness==="BE"?t==="LE"?"BE":"LE":t;check=(t,e)=>{if(Number.isNaN(t)||Number.isNaN(e))throw new TypeError(h("check",`Invalid offset: '${t}' or length: '${e}'.`));if(t<0||t>=this.length)throw new RangeError(h("check",`Invalid offset: '${t}', it must be >= 0 & < ${this.length}.`));if(e<1||e>this.length)throw new RangeError(h("check",`Invalid length: '${e}', it must be > 0 & <= ${this.length}.`));if(t+e>this.length)throw new RangeError(h("check",`Invalid offset (${t}) + length (${e}): '${t+e}', it must be <= ${this.length}.`));if(t%1!==0)throw new RangeError(h("check",`Invalid offset alignment: '${t}'.`));if(e%1!==0)throw new RangeError(h("check",`Invalid length alignment: '${e}'.`));return this};static alloc=(t,e)=>{let r=new n(t);return e!==void 0&&r.fill(e),r};static fromHexString=t=>{t.startsWith("0x")&&(t=t.slice(2));let e=Math.ceil(t.length/2),r=new n(e);return r.writeHexString(t,0,e),r};static fromUtf8String=t=>{let e=new n(t.length);return e.writeUtf8String(t,0,t.length),e};static fromString=(t,e="utf8")=>{let r=new n(t.length);return r.writeString(t,e,0,t.length),r};static fromBits=(t,e=true)=>{let r=new n(Math.ceil(t.length/8));return r.writeBits(t,0,t.length,e),r};static fromUint8Array=t=>{let e=new n(t.byteLength);return e.writeUint8Array(t,0,t.byteLength),e};static fromUint16Array=t=>{let e=new n(t.byteLength);return e.writeUint16Array(t,0,t.byteLength),e};static fromUint32Array=t=>{let e=new n(t.byteLength);return e.writeUint32Array(t,0,t.byteLength),e};static fromBigInt=(t,e)=>{if(t<0n)throw new RangeError(h("fromBigInt",`Invalid big integer: '${t}'.`));let r=Math.ceil(t.toString(16).length/2),i=new n(r);return i.writeBigInt(t,0,r,e),i};static fromRange=(t,e)=>{let r=new n(e-t);return r.writeRange(t,e),r};get _proxy(){return new Proxy(this,{get:(t,e)=>typeof e=="string"&&!Number.isNaN(Number(e))?(this.check(Number(e),1),t.array[Number(e)]??void 0):t[e],set:(t,e,r)=>{if(typeof e=="string"&&!Number.isNaN(Number(e))){let i=Number(r);if(Number.isNaN(i))throw new TypeError(h("proxy",`Invalid value: '${r}'.`));if(i<0||i>255)throw new RangeError(h("proxy",`Value is out of bounds: '${r}'.`));return this.check(Number(e),1),t.array[Number(e)]=r,true}return t[e]=r,true}})}*[Symbol.iterator](){let t=0;for(;t<this.length;)yield this.array[t++];}*entries(){for(let t=0;t<this.length;t++)yield [t,this.array[t]];}writeHexString=(t,e=0,r=t.length/2)=>{if(r===0)throw new RangeError(h("writeHexString",`Invalid hexadecimal string length: '${r}'.`));if(r%1!==0)throw new RangeError(h("writeHexString",`Invalid hexadecimal string length: '${r}'.`));if(t.length%2!==0)throw new RangeError(h("writeHexString",`Invalid hexadecimal string length: '${t.length}'.`));t.startsWith("0x")&&(r===t.length/2&&(r=(t.length-2)/2),t=t.slice(2)),this.check(e,r);for(let i=0;i<r;i++){let s=t.charCodeAt(i*2)|32,a=t.charCodeAt(i*2+1)|32;this.array[e+i]=s-(s>57?87:48)<<4|a-(a>57?87:48);}return this};writeUtf8String=(t,e=0,r=t.length)=>{if(r===0)throw new RangeError(h("writeUtf8String",`Invalid UTF-8 string length: '${r}'.`));this.check(e,r);for(let i=0;i<r;i++)this.array[e+i]=t.charCodeAt(i);return this};writeString=(t,e="utf8",r=0,i=t.length)=>{if(e==="utf8")return this.writeUtf8String(t,r,i),this;if(e==="hex")return this.writeHexString(t,r,Math.ceil(i/2)),this;throw new TypeError(h("writeString",`Invalid encoding: '${e}'.`))};writeBit=(t,e=0,r=true,i=true)=>{if(t<0||t>1)throw new RangeError(h("writeBit",`Value is out of bounds: '${t}'.`));let s=Math.floor(e/8);i&&this.check(s,1);let a=r?7-e%8:e%8;return t===1?this.array[s]|=1<<a:this.array[s]&=~(1<<a),this};writeUint8=(t,e=0,r=true)=>{if(t<0||t>255)throw new RangeError(h("writeUint8",`Value is out of bounds: '${t}'.`));return r&&this.check(e,1),t>>>=0,this.array[e]=t,this};writeUint16LE=(t,e=0,r=true,i=true)=>{if(t<0||t>65535)throw new RangeError(h("writeUint16LE",`Value is out of bounds: '${t}'.`));if(r&&e%2!==0)throw new RangeError(h("writeUint16LE",`Invalid offset alignment: '${e}' (%2).`));return i&&this.check(e,2),t>>>=0,this.array[e]=t&255,this.array[e+1]=t>>8&255,this};writeUint16BE=(t,e=0,r=true,i=true)=>{if(t<0||t>65535)throw new RangeError(h("writeUint16BE",`Value is out of bounds: '${t}'.`));if(r&&e%2!==0)throw new RangeError(h("writeUint16BE",`Invalid offset alignment: '${e}' (%2).`));return i&&this.check(e,2),t>>>=0,this.array[e]=t>>8&255,this.array[e+1]=t&255,this};writeUint16=(t,e=0,r=this.platformEndianness,i=true,s=true)=>this.normalizeEndianness(r)==="LE"?(this.writeUint16LE(t,e,i,s),this):(this.writeUint16BE(t,e,i,s),this);writeUint32LE=(t,e=0,r=true,i=true)=>{if(t<0||t>4294967295)throw new RangeError(h("writeUint32LE",`Value is out of bounds: '${t}'.`));if(r&&e%4!==0)throw new RangeError(h("writeUint32LE",`Invalid offset alignment: '${e}' (%4).`));return i&&this.check(e,4),t>>>=0,this.array[e]=t&255,this.array[e+1]=t>>8&255,this.array[e+2]=t>>16&255,this.array[e+3]=t>>24&255,this};writeUint32BE=(t,e=0,r=true,i=true)=>{if(t<0||t>4294967295)throw new RangeError(h("writeUint32BE",`Value is out of bounds: '${t}'.`));if(r&&e%4!==0)throw new RangeError(h("writeUint32BE",`Invalid offset alignment: '${e}' (%4).`));return i&&this.check(e,4),t>>>=0,this.array[e]=t>>24&255,this.array[e+1]=t>>16&255,this.array[e+2]=t>>8&255,this.array[e+3]=t&255,this};writeUint32=(t,e=0,r=this.platformEndianness,i=true,s=true)=>this.normalizeEndianness(r)==="LE"?(this.writeUint32LE(t,e,i,s),this):(this.writeUint32BE(t,e,i,s),this);writeBits=(t,e=0,r=t.length,i=true)=>{if(!t||!Array.isArray(t))throw new TypeError(h("writeBits",`Invalid array of bits: '${t}'.`));let s=Math.floor(e/8),a=Math.ceil(r/8);this.check(s,a);for(let o=0;o<r;o++)this.writeBit(t[o],e+o,i,false);return this};writeUint8Array=(t,e=0,r=t.byteLength,i=0)=>{if(!t||!(t instanceof Uint8Array))throw new TypeError(h("writeUint8Array",`Invalid Uint8Array: '${t}'.`));this.check(e,r);for(let s=i;s<r;s++)this.array[e-i+s]=t[s];return this};writeUint16Array=(t,e=0,r=t.byteLength,i=0,s=this.platformEndianness,a=true)=>{if(!t||!(t instanceof Uint16Array))throw new TypeError(h("writeUint16Array",`Invalid Uint16Array: '${t}'.`));if(a&&e%2!==0)throw new RangeError(h("writeUint16Array",`Invalid offset alignment: '${e}' (%2).`));if(this.check(e,r),this.normalizeEndianness(s)==="LE"){for(let o=i;o<r;o+=2)this.writeUint16LE(t[o/2],e-i+o,a,false);return this}for(let o=i;o<r;o+=2)this.writeUint16BE(t[o/2],e-i+o,a,false);return this};writeUint32Array=(t,e=0,r=t.byteLength,i=0,s=this.platformEndianness,a=true)=>{if(!t||!(t instanceof Uint32Array))throw new TypeError(h("writeUint32Array",`Invalid Uint32Array: '${t}'.`));if(a&&e%4!==0)throw new RangeError(h("writeUint32Array",`Invalid offset alignment: '${e}' (%4).`));if(this.check(e,r),this.normalizeEndianness(s)==="LE"){for(let o=i;o<r;o+=4)this.writeUint32LE(t[o/4],e-i+o,a,false);return this}for(let o=i;o<r;o+=4)this.writeUint32BE(t[o/4],e-i+o,a,false);return this};writeBigIntLE=(t,e=0,r=Math.ceil(Number(t).toString(16).length/2))=>{if(t<0n)throw new RangeError(h("writeBigIntLE",`Invalid big integer value: '${t}'.`));this.check(e,r);for(let i=0;i<r;i++)this.array[e+i]=Number(t&BigInt(255)),t>>=BigInt(8);return this};writeBigIntBE=(t,e=0,r=Math.ceil(Number(t).toString(16).length/2))=>{if(t<0n)throw new RangeError(h("writeBigIntBE",`Invalid big integer value: '${t}'.`));this.check(e,r);for(let i=r-1;i>=0;i--)this.array[e+i]=Number(t&BigInt(255)),t>>=BigInt(8);return this};writeBigInt=(t,e=0,r=Math.ceil(Number(t).toString(16).length/2),i=this.platformEndianness)=>this.normalizeEndianness(i)==="LE"?(this.writeBigIntLE(t,e,r),this):(this.writeBigIntBE(t,e,r),this);writeRange=(t,e,r=0)=>{if(t<0||t>255)throw new RangeError(h("writeRange",`Invalid start value: '${t}'.`));if(e<0||e>255)throw new RangeError(h("writeRange",`Invalid end value: '${e}'.`));let i=e-t;this.check(r,i);for(let s=0;s<i;s++)this.array[r+s]=t+s;return this};readHexStringLE=(t=0,e=this.length-t,r=true)=>(r&&this.check(t,e),Buffer.from(this.arrayBuffer,t,e).toString("hex").toUpperCase());readHexStringBE=(t=0,e=this.length-t,r=true)=>(r&&this.check(t,e),Buffer.from(this.arrayBuffer,t,e).toString("hex").toUpperCase().match(/.{2}/g).reverse().join(""));readHexString=(t=0,e=this.length-t,r=this.platformEndianness,i=true)=>(i&&this.check(t,e),this.normalizeEndianness(r)==="LE"?this.readHexStringLE(t,e,false):this.readHexStringBE(t,e,false));readUtf8String=(t=0,e=this.length-t,r=true)=>(r&&this.check(t,e),Buffer.from(this.arrayBuffer,t,e).toString("utf8"));readBit=(t=0,e=true,r=true)=>{let i=Math.floor(t/8);r&&this.check(i,1);let s=e?7-t%8:t%8;return (this.array[i]&1<<s)!==0?1:0};readUint8=(t=0,e=true)=>(e&&this.check(t,1),this.array[t]);readUint16LE=(t=0,e=true,r=true)=>{if(e&&t%2!==0)throw new RangeError(h("readUint16LE",`Invalid offset alignment: '${t}' (%2).`));return r&&this.check(t,2),(this.array[t]|this.array[t+1]<<8)>>>0};readUint16BE=(t=0,e=true,r=true)=>{if(e&&t%2!==0)throw new RangeError(h("readUint16BE",`Invalid offset alignment: '${t}' (%2).`));return r&&this.check(t,2),(this.array[t]<<8|this.array[t+1])>>>0};readUint16=(t=0,e=this.platformEndianness,r=true,i=true)=>this.normalizeEndianness(e)==="LE"?this.readUint16LE(t,r,i):this.readUint16BE(t,r,i);readUint32LE=(t=0,e=true,r=true)=>{if(e&&t%4!==0)throw new RangeError(h("readUint32LE",`Invalid offset alignment: '${t}' (%4).`));return r&&this.check(t,4),(this.array[t]|this.array[t+1]<<8|this.array[t+2]<<16|this.array[t+3]<<24)>>>0};readUint32BE=(t=0,e=true,r=true)=>{if(e&&t%4!==0)throw new RangeError(h("readUint32BE",`Invalid offset alignment: '${t}' (%4).`));return r&&this.check(t,4),(this.array[t]<<24|this.array[t+1]<<16|this.array[t+2]<<8|this.array[t+3])>>>0};readUint32=(t=0,e=this.platformEndianness,r=true,i=true)=>this.normalizeEndianness(e)==="LE"?this.readUint32LE(t,r,i):this.readUint32BE(t,r,i);readBits=(t=0,e=this.length*8-t*8,r=true,i=true)=>{let s=[];for(let a=0;a<e;a++)s.push(this.readBit(t+a,r,i));return s};readUint8Array=(t=0,e=this.length-t,r=true)=>(r&&this.check(t,e),new Uint8Array(this.arrayBuffer,t??this.offset,e??this.length));readUint16Array=(t=0,e=this.length-t,r=true)=>(r&&this.check(t,e),new Uint16Array(this.arrayBuffer,t??this.offset,e?e/2:this.length/2));readUint32Array=(t=0,e=this.length-t,r=true)=>(r&&this.check(t,e),new Uint32Array(this.arrayBuffer,t??this.offset,e?e/4:this.length/4));readBigIntLE=(t=0,e=this.length-t,r=true)=>{r&&this.check(t,e);let i=0n;for(let s=e-1;s>=0;s--)i=i<<8n|BigInt(this.array[t+s]);return i};readBigIntBE=(t=0,e=this.length-t,r=true)=>{r&&this.check(t,e);let i=0n;for(let s=0;s<e;s++)i=i<<8n|BigInt(this.array[t+s]);return i};readBigInt=(t=0,e=this.length-t,r=this.platformEndianness,i=true)=>this.normalizeEndianness(r)==="LE"?this.readBigIntLE(t,e,i):this.readBigIntBE(t,e,i);toHexString=(t=false,e=this.platformEndianness)=>{let r=Buffer.from(this.arrayBuffer).toString("hex").toUpperCase();return this.normalizeEndianness(e)==="BE"&&(r=r.match(/.{2}/g)?.reverse().join("")??""),t?`0x${r}`:r};toUtf8String=()=>Buffer.from(this.arrayBuffer).toString("utf8");toString=(t="hex",e=false)=>t==="utf8"?this.toUtf8String():this.toHexString(e);toBits=(t=true)=>{let e=this.length*8,r=new Array(e);for(let i=0;i<e;i++)r[i]=this.readBit(i,t);return r};toUint8Array=()=>new Uint8Array(this.arrayBuffer,this.offset,this.length);toUint16Array=()=>new Uint16Array(this.arrayBuffer,this.offset,this.length/2);toUint32Array=()=>new Uint32Array(this.arrayBuffer,this.offset,this.length/4);toBigInt=(t=this.platformEndianness)=>this.normalizeEndianness(t)==="LE"?this.readBigIntLE():this.readBigIntBE();equals=t=>{if(this.length!==t.length)return false;for(let e=0;e<this.length;e++)if(this.array[e]!==t[e])return false;return true};isEmpty=()=>{for(let t=0;t<this.length;t++)if(this.array[t]!==0)return false;return true};isFull=()=>{for(let t=0;t<this.length;t++)if(this.array[t]!==255)return false;return true};randomFill=(t=0,e=this.length-t)=>{this.check(t,e);for(let r=0;r<e;r++)this.array[t+r]=Math.floor(Math.random()*256);};safeRandomFill=(t=0,e=this.length)=>randomFillSync(this.array,t,e);copy=(t=0,e=this.length)=>{this.check(t,e);let r=new n(e);for(let i=0;i<e;i++)r[i]=this.array[i+t];return r};subarray=(t=0,e=this.length)=>(this.check(t,e),new n(e,{arrayBuffer:this.arrayBuffer,offset:t,length:e}));swap=(t=0,e=this.length,r=4)=>{if(r<2)throw new RangeError(h("swap",`Invalid word length: '${r}'.`));if(r%2!==0)throw new RangeError(h("swap",`Invalid word length alignment: '${r}'.`));this.check(t,e);let i=t+e;for(let s=0;s<i;s+=r){let a=s+t;for(let o=0;o<r/2;o++){let c=this.array[a+o];this.array[a+o]=this.array[a+r-o-1],this.array[a+r-o-1]=c;}}return this};partialReverse=(t=0,e=this.length)=>{this.check(t,e);let r=Math.floor(e/2),i=t+e;for(let s=0;s<r;s++){let a=s+t,o=i-s-1,c=this.array[a];this.array[a]=this.array[o],this.array[o]=c;}return this};reverse=()=>(this.array.reverse(),this);rotateLeft=()=>{let t=this.array[0];for(let e=0;e<this.length-1;e++)this.array[e]=this.array[e+1];return this.array[this.length-1]=t,this};rotateRight=()=>{let t=this.array[this.length-1];for(let e=this.length-1;e>0;e--)this.array[e]=this.array[e-1];return this.array[0]=t,this};shiftLeft=(t=0,e=this.length,r=1)=>{this.check(t,e);for(let i=0;i<this.length-1;i++)this.array[i]=this.array[i+r];for(let i=0;i<r;i++)this.array[this.length-i-1]=0;return this};shiftRight=(t=0,e=this.length,r=1)=>{this.check(t,e);for(let i=this.length-1;i>0;i--)this.array[i]=this.array[i-r];for(let i=0;i<r;i++)this.array[i]=0;return this};fill=(t,e=0,r=this.length)=>{if(t<0||t>255)throw new RangeError(h("fill",`Invalid value: '${t}'.`));return this.check(e,r),this.array.fill(t,e,e+r),this};clear=(t=0,e=this.length)=>(this.check(t,e),this.array.fill(0,t,t+e),this)};function Z(){switch(process.platform){case "win32":return process.env.COMPUTERNAME;case "darwin":return execSync("scutil --get ComputerName").toString().trim();case "linux":{let n=execSync("hostnamectl --pretty").toString().trim();return n===""?hostname():n}default:return hostname()}}var w={BAD_REQUEST:{status:400,name:"BadRequest",message:"Bad request.",data:null},UNAUTHORIZED:{status:401,name:"Unauthorized",message:"Unauthorized.",data:null},PAYMENT_REQUIRED:{status:402,name:"PaymentRequired",message:"Payment required.",data:null},FORBIDDEN:{status:403,name:"Forbidden",message:"Forbidden.",data:null},NOT_FOUND:{status:404,name:"NotFound",message:"Not found.",data:null},METHOD_NOT_ALLOWED:{status:405,name:"MethodNotAllowed",message:"Method not allowed.",data:null},REQUEST_TIMEOUT:{status:408,name:"RequestTimeout",message:"Request timed out.",data:null},CONFLICT:{status:409,name:"Conflict",message:"Conflict.",data:null},INTERNAL_SERVER_ERROR:{status:500,name:"InternalServerError",message:"Internal server error.",data:null},BACKEND_FUNCTION_RUNNING_ON_CLIENT:{status:500,name:"BackendFunctionRunningOnClient",message:"A function reserved for the backend is running on the client.",data:null},NOT_IMPLEMENTED:{status:501,name:"NotImplemented",message:"Not implemented.",data:null},BANDWIDTH_LIMIT_EXCEEDED:{status:509,name:"BandwidthLimitExceeded",message:"Bandwidth limit exceeded.",data:null}};var S=class{_req;_res;_read;_write;_update;_replace;_remove;_options;constructor(t,e,r,i){this.setRequestResponse(t,e),this.setMethods(r||{}),this.setOptions(i||{});}setRequestResponse(t,e){this._req=t,this._res=e;}setMethods(t){this._read=t?.read,this._write=t?.write,this._update=t?.update,this._replace=t?.replace,this._remove=t?.remove;}setOptions(t){this._options={...this._options,...t};}_checkDataValidity(t){return t!=null}successResponse(t,e){return this._res.status(t).send({success:true,data:this._checkDataValidity(e)?e:null})}errorResponse(t,e,r){let i={success:false,message:r||t.message,error:this._checkDataValidity(e)?{...t,data:e}:t};return this._res.status(t.status).send(i)}async _executeMethod(t,e){return typeof t=="function"?(await t(e),true):(await t.method(e),true)}async run(){let t={req:this._req,res:this._res,wrapper:this};try{switch(this._req.method){case "GET":if(this._read)return await this._executeMethod(this._read,t);break;case "POST":if(this._write)return await this._executeMethod(this._write,t);break;case "PATCH":if(this._update)return await this._executeMethod(this._update,t);break;case "PUT":if(this._replace)return await this._executeMethod(this._replace,t);break;case "DELETE":if(this._remove)return await this._executeMethod(this._remove,t);break;default:return this.errorResponse(w.METHOD_NOT_ALLOWED)}}catch(e){return this.errorResponse(w.INTERNAL_SERVER_ERROR,e)}}};var R=class{_req;_res;_read;_write;_update;_replace;_remove;_options;constructor(t,e,r,i){this.setRequestResponse(t,e),this.setMethods(r||{}),this.setOptions(i||{});}setRequestResponse(t,e){this._req=t,this._res=e;}setMethods(t){this._read=t?.read,this._write=t?.write,this._update=t?.update,this._replace=t?.replace,this._remove=t?.remove;}setOptions(t){this._options={...this._options,...t};}_checkDataValidity(t){return t!=null}successResponse(t,e){return this._res.status(t).send({success:true,data:this._checkDataValidity(e)?e:null})}errorResponse(t,e,r){let i={success:false,message:r||t.message,error:this._checkDataValidity(e)?{...t,data:e}:t};return this._res.status(t.status).send(i)}hasRole(t,e){return t.roles?.includes(e)}hasSomeRoles(t,e){return e.some(r=>t.roles?.includes(r))}hasAllRoles(t,e){return e.every(r=>t.roles?.includes(r))}checkAuthOptions(t,e){return e.requireAuth&&!t?(this.errorResponse(w.UNAUTHORIZED),false):e.hasRole&&(!t||!this.hasRole(t.user,e.hasRole))?(this.errorResponse(w.UNAUTHORIZED),false):e.hasSomeRoles&&(!t||!this.hasSomeRoles(t.user,e.hasSomeRoles))?(this.errorResponse(w.UNAUTHORIZED),false):e.hasAllRoles&&(!t||!this.hasAllRoles(t.user,e.hasAllRoles))?(this.errorResponse(w.UNAUTHORIZED),false):true}async _executeMethod(t,e){return typeof t=="function"?(await t(e),true):t.authOptions&&!this.checkAuthOptions(e.session,t.authOptions)?false:(await t.method(e),true)}async run(){let t=this._options.authFunction?await this._options.authFunction(this._req,this._res):null;if(!this.checkAuthOptions(t,this._options))return;let r={req:this._req,res:this._res,session:t,wrapper:this};try{switch(this._req.method){case "GET":if(this._read)return await this._executeMethod(this._read,r);break;case "POST":if(this._write)return await this._executeMethod(this._write,r);break;case "PATCH":if(this._update)return await this._executeMethod(this._update,r);break;case "PUT":if(this._replace)return await this._executeMethod(this._replace,r);break;case "DELETE":if(this._remove)return await this._executeMethod(this._remove,r);break;default:return this.errorResponse(w.METHOD_NOT_ALLOWED)}}catch(i){return this.errorResponse(w.INTERNAL_SERVER_ERROR,i)}}};export{b as Bench,N as CyBuffer,S as NextApiWrapper,R as NextAuthApiWrapper,z as crypto,j as generateCGASStatus,Z as getHostname,y as logger};//# sourceMappingURL=backend.js.map
6
6
  //# sourceMappingURL=backend.js.map