@cybearl/cypack 1.10.7 → 1.11.2

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
@@ -5,167 +5,217 @@
5
5
  <p align="center">A set of general utilities for Cybearl projects.</p>
6
6
  </p>
7
7
 
8
- This package includes multiple centralized utilities for the Cybearl application and API service. It is designed to be a single package that can be used in both the client and server side of the application. It is also designed to be well-optimized and well-documented for easy use.
8
+ This package provides a centralized set of utilities for Cybearl projects. It is designed to work in both client and server environments and is split into three entry points to keep each environment's footprint minimal.
9
9
 
10
10
  Integration into your project
11
11
  -----------------------------
12
12
  #### 0. Install the package
13
- ```typescript
14
- // With npm
15
- $ npm install @cybearl/cypack
13
+ ```bash
14
+ # With npm
15
+ npm install @cybearl/cypack
16
16
 
17
- // With yarn
18
- $ yarn add @cybearl/cypack
17
+ # With yarn
18
+ yarn add @cybearl/cypack
19
19
  ```
20
- And that's it! You can now use our utilities in your project.
21
20
 
22
21
  Categories and utilities
23
22
  ------------------------
24
- Note that the package is divided into three modules:
25
- - `backend` (`@cybearl/cypack/backend`): Contains utilities that are meant to be used in the backend.
26
- - `frontend` (`@cybearl/cypack/frontend`): Contains utilities that are meant to be used in the frontend.
27
- - `main` (`@cybearl/cypack`): Contains utilities that can be used in both the client and server side of the application.
23
+ The package is divided into three modules:
24
+ - `@cybearl/cypack`: Universal utilities usable in both browser and Node.js.
25
+ - `@cybearl/cypack/backend`: Node.js-only utilities (server, API routes, etc.).
26
+ - `@cybearl/cypack/frontend`: Browser-side utilities (React, Next.js client components, etc.).
28
27
 
29
28
  Backend utilities
30
29
  -----------------
31
30
  #### Benchmark utilities
32
31
  - `Bench`: A class that provides a simple way to benchmark functions.
33
32
 
34
- #### Crypto:
35
- Note that these are stored inside a `crypto` object that is exported from the package.
33
+ #### Crypto
34
+ Note that these are stored inside a `crypto` object exported from the package.
36
35
  - `aes256Gcm` (AES-256-GCM symmetric encryption):
37
36
  - `encrypt`: Encrypts data using AES-256-GCM symmetric encryption.
38
37
  - `decrypt`: Decrypts data using AES-256-GCM symmetric encryption.
39
- - `decryptPayload`: Decrypts a payload that contains the initialization vector, ciphertext, and authentication tag.
38
+ - `decryptPayload`: Decrypts a payload containing the initialization vector, ciphertext, and authentication tag.
40
39
 
41
- #### CyBuffer class
42
- - `CyBuffer`: A class that extends the Uint8Array class with additional methods to read and write data.
40
+ #### CyBuffer
41
+ - `CyBuffer`: Extends `Uint8Array` with additional methods to read and write typed data.
43
42
 
44
43
  #### Cybearl General API System
45
- - `generateCGASStatus`: Generates a Cybearl General API System (CGAS) status object.
46
-
47
- #### Host-related utilities
48
- Contains utilities to get the hostname and other host-related information.
49
- - `getHostname`: Get the name of the host on which the application is running.
50
-
51
- #### Logger utilities
52
- Contains a simple multi-level logger that logs to the console based on `Winston`.
53
- - `logger`: A simple multi-level logger that logs to the console based on `Winston`.
44
+ - `generateCGASStatus`: Generates a CGAS status object.
45
+
46
+ #### Headers utilities
47
+ Contains utilities to convert between Node.js and Web API header formats.
48
+ - `convertNodeHeadersToWebHeaders`: Converts Node.js `IncomingHttpHeaders` to the Web API `Headers` format.
49
+
50
+ #### Host utilities
51
+ - `getHostname`: Returns the name of the host on which the application is running.
52
+
53
+ #### Logger
54
+ A configurable, pino-based structured logger for Node.js server environments.
55
+ - `serverLogger`: The default logger instance. Supports levels `fatal`, `error`, `warn`, `info`, `debug`, `trace` and exposes chainable setters:
56
+ - `setLevel`: Set the minimum log level.
57
+ - `setShowLevel`: Toggle level display.
58
+ - `setShowTimestamp`: Toggle timestamp display.
59
+ - `setForeignObjectStartAtNewLine`: Start any attached foreign object on a new line.
60
+ - `setForeignObjectPadding`: Set padding for foreign object alignment (also accepts `"after-timestamp"` and `"after-level"`).
61
+ - `setForeignObjectIndent`: Set indentation for foreign objects.
62
+ - `setAlignForeignObject`: Align all foreign objects to the same column.
63
+ - `setParameters` / `resetParameters`: Set or reset all parameters at once.
54
64
 
55
65
  #### Next.js utilities
56
- Contains utilities to get the Next.js server and other Next.js-related information.
57
- - `NextApiWrapper`: A class that wraps the Next.js API route handler (specifically for page router):
66
+ - `NextApiWrapper`: Wraps a Next.js page-router API handler with structured method dispatch:
58
67
  ```typescript
59
68
  function read({ req, wrapper }: NextApiMethodInput) {
60
- if (!req.query.blabla) return wrapper.errorResponse(AppErrors.UNAUTHORIZED)
61
- return wrapper.successResponse(200, status)
69
+ if (!req.query.id) return wrapper.errorResponse(AppErrors.UNAUTHORIZED)
70
+ return wrapper.successResponse(200, data)
62
71
  }
63
72
 
64
73
  export default async function handler(req: NextApiRequest, res: NextApiResponse) {
65
- const wrapper = new NextApiWrapper(req, res, { read })
66
- await wrapper.run()
74
+ const wrapper = new NextApiWrapper(req, res, { read })
75
+ await wrapper.run()
67
76
  }
68
77
  ```
69
- - `nextAuthApiWrapper`: Similar to `NextApiWrapper`, but with built-in NextAuth support (specifically for page router).
78
+ - `NextAuthApiWrapper`: Same as `NextApiWrapper` but with built-in NextAuth support.
70
79
 
71
80
  Frontend utilities
72
81
  ------------------
73
82
  #### Cybearl General API System
74
- - `getCGASStatus`: Returns the current status of the application, or the application marker only if specified,
75
- in the Cybearl General API System (CGAS) format.
76
- - `fallbackCGASStatus`: The fallback CGAS status, used when the CGAS API is not available.
83
+ - `getCGASStatus`: Returns the current CGAS status of the application.
84
+ - `fallbackCGASStatus`: The fallback CGAS status used when the CGAS API is unavailable.
85
+
86
+ #### Styling utilities
87
+ Contains utilities for Tailwind CSS class merging and CSS value conversion.
88
+ - `cn`: Merges Tailwind CSS class names without style conflicts (wraps `clsx` + `tailwind-merge`).
89
+ - `convertCssDelayToMs`: Converts a CSS delay string (e.g., `"1s"`, `"500ms"`) or a plain number to milliseconds.
77
90
 
78
- #### URLs utilities
79
- Contains utilities to manipulate URLs.
80
- - `addParamsToUrl`: Allows to add query parameters to a URL.
81
- - `currentUrlOrigin`: Get the current URL origin or null if it's not available.
91
+ #### URL utilities
92
+ - `addParamsToUrl`: Adds query parameters to a URL, skipping null/undefined values.
93
+ - `currentUrlOrigin`: The current URL origin, or `null` if unavailable (e.g., during SSR).
82
94
 
83
95
  Main utilities
84
96
  --------------
85
- #### Checks utilities
86
- - `arrayEqual`: Compares two arrays for equality.
87
- - `isClient`: Check if the code is running on the client.
88
- - `isServer`: Check if the code is running on the server.
97
+ #### Check utilities
98
+ - `isClient`: Returns `true` when running in a browser environment.
99
+ - `isServer`: Returns `true` when running in a Node.js environment.
100
+ - `arrayEqual`: Compares two arrays for shallow equality.
89
101
 
90
102
  #### Constants
91
- - `CyCONSTANTS`: Multiple constants used throughout the application:
92
- - Security: `HASH_SALT_ROUNDS`.
93
- - User-related fields such as `(MIN / MAX)_PASSWORD_LENGTH` etc..
94
- - Image and video sizes specifically for image optimization.
103
+ - `CyCONSTANTS`: Shared constants used across Cybearl projects:
104
+ - Security: `HASH_SALT_ROUNDS`.
105
+ - User fields: `(MIN|MAX)_USERNAME_LENGTH`, `(MIN|MAX)_PASSWORD_LENGTH`, `MAX_NAME_LENGTH`, etc.
106
+ - Validation: `USERNAME_REGEX`, `SLUG_REGEX`.
107
+ - Image sizes: `IMG_SIZES_(HIGH|MEDIUM|BASE|LOW)_QUALITY`.
95
108
 
96
109
  #### Countries
97
- - `Country`: An object containing all countries with their respective details (name, code, continent, etc.), based on the ISO 3166-1 standard (alpha-2).
98
- - `formatCountryName`: Formats a country name from camel case to a spaced name.
99
- - `COUNTRIES_SELECT_FIELD`: An array of countries formatted for use in select fields.
100
- - `getCountryNameFromCode`: Get the country name from its ISO 3166-1 alpha-2 code.
110
+ - `Country`: All countries with their details (name, code, continent, etc.), based on ISO 3166-1 alpha-2.
111
+ - `formatCountryName`: Formats a country name from camelCase to a spaced string.
112
+ - `COUNTRIES_SELECT_FIELD`: Countries pre-formatted for use in select fields.
113
+ - `getCountryNameFromCode`: Returns the country name for a given ISO 3166-1 alpha-2 code.
114
+
115
+ #### Environment utilities
116
+ Contains utilities to validate environment variables at startup, with protection against private variables leaking into the client bundle.
117
+ - `checkEnvironmentVariables`: Checks that all required variables are present for the current environment (server or client) and throws if any are missing or if private variables are exposed to the client. Logs errors instead of throwing in production.
118
+ ```typescript
119
+ checkEnvironmentVariables(
120
+ {
121
+ public: ["NODE_ENV", "NEXT_PUBLIC_APP_URL"],
122
+ private: ["DATABASE_URL", "SECRET_KEY"],
123
+ },
124
+ {
125
+ NODE_ENV: process.env.NODE_ENV,
126
+ NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
127
+ DATABASE_URL: process.env.DATABASE_URL,
128
+ SECRET_KEY: process.env.SECRET_KEY,
129
+ },
130
+ )
131
+ ```
132
+ Note: the second argument must inline `process.env.X` calls directly, dynamic key access (`process.env[name]`) is eliminated by most bundlers at build time.
101
133
 
102
134
  #### Error utilities
103
- Contains a set of base error that follows the Cybearl error format, and other error-related utilities.
104
135
  - `formatErrorResponse`: Formats an error response object.
105
136
  - `stringifyError`: Stringifies an error object.
106
- - `parseCRUDError`: Parse the error of a CRUD call and return a standardized error.
107
- - `formatMessageAsStringifiedError`: Formats a message and an error object into a JSON string that follows the `FailedRequest` standard.
108
- - `BaseError`: The base error class that all Cybearl errors inherit from, don't forget to do:
137
+ - `parseCRUDError`: Parses the error from a CRUD call and returns a standardized error.
138
+ - `formatMessageAsStringifiedError`: Formats a message and error into a JSON string following the `FailedRequest` standard.
139
+ - `BaseErrors`: A set of standard HTTP error definitions. Extend it for your app:
109
140
  ```typescript
110
141
  export const AppErrors = {
111
142
  ...BaseErrors,
112
- // Add your custom errors here
143
+ // Add custom errors here
113
144
  } as const satisfies Record<string, ErrorObj>
114
145
  ```
115
- To be sure that you respect the error format.
116
146
 
117
147
  #### Formatting utilities
118
- Contains a set of utilities to format numbers, time, and other values.
119
- - `isValidIntId`: Validate a direct ID parameter (as integer for SQL DBs etc..).
120
- - `isValidSlug`: Validates a slug.
121
- - `formatUnit`: Format a number with an attached unit + an optional time unit.
122
- - `formatHRTime`: Format a high-resolution time, into a responsive string with the en-US locale format.
123
- - `formatTime`: Format a time in milliseconds into a responsive string with the en-US locale format.
124
- - `formatPercentage`: Formats a number as a percentage.
125
- - `truncateString`: Truncate a string to a specified length.
126
- - `parseQueryNumberArray`: Parse a query containing either a number or numbers separated by commas and returns an array of numbers.
127
- - `parseQueryStringArray`: Parse a query containing either a string or strings separated by commas and returns an array of strings.
128
- - `slugifyName`: Slugify a given name with support for automatic number incrementing.
129
- - `formatBytes`: Formats a number of bytes into a human-readable string with appropriate units.
148
+ - `isValidIntId`: Validates an integer ID parameter (for SQL databases, etc.).
149
+ - `isValidSlug`: Validates a slug string.
150
+ - `formatUnit`: Formats a number with a unit and optional time unit, using SI prefixes (k, M, G … Y).
151
+ - `formatHRTime`: Formats a high-resolution time (nanoseconds as `bigint`) into a human-readable string.
152
+ - `formatTime`: Formats a duration in milliseconds into a human-readable string.
153
+ - `formatPercentage`: Formats a number as a percentage string.
154
+ - `formatBytes`: Formats a byte count into a human-readable string (KB, MB, GB, etc.).
155
+ - `formatRelativeTime`: Formats a `Date` as a relative time string (e.g., `"just now"`, `"5m ago"`, `"3h ago"`).
156
+ - `formatDate`: Formats a `Date` as a locale-aware datetime string (e.g., `"04/25/2026, 03:45:00 PM"`).
157
+ - `bigintToScientific`: Formats a `bigint` as a `[coefficient, exponent]` scientific notation tuple using only integer arithmetic, supports arbitrarily large values.
158
+ - `bigintToMetricFormatted`: Formats a `bigint` as a metric-prefixed string (e.g., `1500n` → `"1.5k"`). Supports up to exa (E).
159
+ - `truncateString`: Truncates a string to a specified length, appending `"..."`.
160
+ - `parseQueryNumberArray`: Parses a comma-separated query string into an array of numbers.
161
+ - `parseQueryStringArray`: Parses a comma-separated query string into an array of strings.
162
+ - `slugifyName`: Slugifies a name, with support for automatic number incrementing on collision.
130
163
 
131
164
  #### JSON utilities
132
- Contains utilities to parse and stringify JSON objects.
133
- - `formatJson`: Format a JSON object with indentation.
134
- - `stringify`: Stringify a JSON object with support for BigInt and functions.
165
+ - `formatJson`: Re-formats a JSON string with 4-space indentation.
166
+ - `stringify`: Stringifies a value with support for `BigInt` and functions.
167
+
168
+ #### Logger
169
+ A zero-dependency isomorphic Next.js-compatible logger that works in both browser and Node.js. ANSI indicators are automatically suppressed in browser environments.
170
+ - `nextLogger`: The default logger instance.
171
+ - `createNextLogger(prefix?, prefixLength?)`: Creates a new logger instance with an optional default prefix and column width for prefix alignment.
172
+ - `.success` / `.info` / `.warn` / `.error` / `.debug`: Log at the respective level.
173
+ - `.withPrefix(prefix)`: Returns a new logger with the given prefix fixed as its default.
174
+ - `generateNextLoggerPrefix(uuid, prefix?)`: Derives a short prefix from a UUID (e.g., `"worker-a1b"`), useful for per-job logger scoping.
175
+ - `NEXT_LOG_INDICATORS`: The ANSI indicator strings used by the logger (`success`, `warning`, `error`, `info`, `debug`).
135
176
 
136
177
  #### Math utilities
137
- Contains utilities to perform mathematical operations.
138
178
  - `mapRange`: Maps a number from one range to another.
139
- - `safeAverage`: Safely creates an average value based on a total and count coming from a Lucid ORM / SQL query result.
140
- - `safePercentage`: Safely creates a percentage based on a numerator and denominator coming from a Lucid ORM / SQL query result.
179
+ - `safeAverage`: Safely computes an average from a total and count (guards against division by zero).
180
+ - `safePercentage`: Safely computes a percentage from a numerator and denominator.
141
181
 
142
182
  #### Middleware utilities
143
- Contains utilities to create middleware functions (for Next.js, etc.).
144
- - `fullyPermissiveCspHeader`: A Content Security Policy (CSP) header that allows everything, used for development.
183
+ - `fullyPermissiveCspHeader`: A Content Security Policy header that allows everything, intended for development use.
145
184
 
146
185
  #### String utilities
147
- Contains utilities to manipulate strings.
148
- - `convertErrorToString`: Safely converts any error into a string for parsing/searching.
149
- - `decodeObjectURIComponents`: Decodes all components of an object as URI components (e.g., for decoding Next.js `req.query`).
186
+ - `convertErrorToString`: Safely converts any error value to a string.
187
+ - `decodeObjectURIComponents`: Decodes all string values of an object as URI components (e.g., for Next.js `req.query`).
150
188
 
151
189
  #### Styling utilities
152
- Contains utilities to manipulate CSS styles.
153
- - `shadeColor`: Shades a color by a percentage.
190
+ - `shadeColor`: Shades a hex color by a given percentage.
191
+ - `invertHexColor`: Returns the inverse of a hex color (e.g., `"#aabbcc"` → `"#554433"`).
192
+ - `applyHexColorOpacity`: Applies an opacity factor (0–1) to a hex color, returning an 8-character hex string.
154
193
 
155
194
  Related types
156
195
  -------------
157
- - `Bit`: A single bit value used by CyBuffer.
158
- - `BenchmarkResult`: The type of the benchmark function result.
159
- - `BenchmarkResults`: An object containing multiple benchmark results, ordered by functions.
160
- - `CGASStatusString`: The type for the CGAS status string (`enabled`, `disabled`, `in-maintenance`, `in-development`).
161
- - `CGASStatus`: The Cybearl General API System (CGAS) status response.
162
- - `Endianness`: The endianness (`LE` or `BE`).
163
- - `ErrorObj`: The type definition for an error object.
164
- - `StringEncoding`: The available string encoding instruction for the `CyBuffer` string methods.
165
- - `SuccessfulRequest`: The type for a successful request, containing the data of type T.
166
- - `FailedRequest`: The type for a failed request, containing the error message and the error object.
167
- - `RequestResult`: Returns a failed request in case the `success` field is set to `false`,
168
- otherwise returns a successful request with a data object of type T.
196
+ **Backend**
197
+ - `Bit`: A single bit value used by `CyBuffer`.
198
+ - `BenchmarkResult`: The result of a single benchmark run.
199
+ - `BenchmarkResults`: A map of benchmark results keyed by function name.
200
+ - `CryptoAes256GcmEncryptResult`: The result of an AES-256-GCM encryption call.
201
+ - `Endianness`: `"LE"` or `"BE"`.
202
+ - `NextApiMethodInput`: Input type for `NextApiWrapper` method handlers.
203
+ - `NextAuthApiMethodInput`: Input type for `NextAuthApiWrapper` method handlers.
204
+ - `StringEncoding`: Available string encoding options for `CyBuffer` string methods.
205
+
206
+ **Frontend**
207
+ - `CSSDelay`: A CSS delay value, either a number (milliseconds) or a string (`"1s"`, `"500ms"`).
208
+
209
+ **Main**
210
+ - `CGASStatus`: The CGAS status response object.
211
+ - `CGASStatusString`: The CGAS status string (`"enabled"`, `"disabled"`, `"in-maintenance"`, `"in-development"`).
212
+ - `ErrorObj`: The shape of a Cybearl error object.
213
+ - `FailedRequest`: A failed request response containing an error object.
214
+ - `NextLoggerInstance`: The type of a logger returned by `createNextLogger` or `withPrefix`.
215
+ - `NextLoggerOptions`: Options accepted by each log method (`prefix`, `data`).
216
+ - `RequiredEnvVars`: The `{ public, private }` config shape for `checkEnvironmentVariables`.
217
+ - `RequestResult<T>`: A discriminated union of `SuccessfulRequest<T>` and `FailedRequest`.
218
+ - `SuccessfulRequest<T>`: A successful request response containing typed data.
169
219
 
170
220
  Dev notes
171
221
  ---------
package/backend.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { IncomingHttpHeaders } from 'node:http';
1
2
  import pino from 'pino';
2
3
  import { NextApiRequest, NextApiResponse } from 'next';
3
4
  import { Session } from 'next-auth';
@@ -863,6 +864,13 @@ declare class CyBuffer {
863
864
  clear: (offset?: number, length?: number) => this;
864
865
  }
865
866
 
867
+ /**
868
+ * Converts Node.js IncomingHttpHeaders to the Web API Headers format.
869
+ * @param headers The incoming HTTP headers from Node.js.
870
+ * @returns The headers as a Web API Headers object.
871
+ */
872
+ declare function convertNodeHeadersToWebHeaders(headers: IncomingHttpHeaders): Headers;
873
+
866
874
  /**
867
875
  * Get the name of the host on which the application is running.
868
876
  * @returns The name of the host.
@@ -882,7 +890,7 @@ type Parameters = {
882
890
  alignForeignObject?: boolean;
883
891
  };
884
892
  /**
885
- * A custom logger instance compatible with both front and back-end, allowing to log messages
893
+ * A custom serverLogger instance compatible with both front and back-end, allowing to log messages
886
894
  * with different levels and colors.
887
895
  *
888
896
  * The available levels are:
@@ -894,19 +902,19 @@ type Parameters = {
894
902
  * - `trace`
895
903
  *
896
904
  * The available parameters are:
897
- * - `setLevel`: Set the logger level (defaults to `"trace"`).
898
- * - `setShowLevel`: Set the logger level display (defaults to `true`).
899
- * - `setShowTimestamp`: Set the logger timestamp display (defaults to `true`).
900
- * - `setForeignObjectStartAtNewLine`: Set the logger foreign object new line display (defaults to `false`).
905
+ * - `setLevel`: Set the serverLogger level (defaults to `"trace"`).
906
+ * - `setShowLevel`: Set the serverLogger level display (defaults to `true`).
907
+ * - `setShowTimestamp`: Set the serverLogger timestamp display (defaults to `true`).
908
+ * - `setForeignObjectStartAtNewLine`: Set the serverLogger foreign object new line display (defaults to `false`).
901
909
  * - `setForeignObjectPadding`: Set the padding for foreign objects (defaults to `0`).
902
910
  * - `setForeignObjectIndent`: Set the indent for foreign objects (defaults to `4`).
903
911
  * - `setAlignForeignObject`: Align any foreign object to the same column (defaults to `false`).
904
912
  * - `setParameters`: Set all the parameters at once.
905
913
  * - `resetParameters`: Reset all the parameters to their default values.
906
914
  */
907
- declare const logger: pino.Logger & {
915
+ declare const serverLogger: pino.Logger & {
908
916
  /**
909
- * Set the logger level, available levels are:
917
+ * Set the serverLogger level, available levels are:
910
918
  * - `fatal`
911
919
  * - `error`
912
920
  * - `warn`
@@ -914,23 +922,23 @@ declare const logger: pino.Logger & {
914
922
  * - `debug`
915
923
  * - `trace`
916
924
  *
917
- * The logging level is a **minimum** level. For instance if `logger.level` is `"info"` then all
925
+ * The logging level is a **minimum** level. For instance if `serverLogger.level` is `"info"` then all
918
926
  * `"fatal"`, `"error"`, `"warn"` and `"info"` logs will be enabled.
919
- * @param level The new logger level.
927
+ * @param level The new serverLogger level.
920
928
  */
921
929
  setLevel: (level: Parameters["level"]) => void;
922
930
  /**
923
- * Set the logger level display.
931
+ * Set the serverLogger level display.
924
932
  * @param showLevel Whether to show the level or not.
925
933
  */
926
934
  setShowLevel: (showLevel: Parameters["showLevel"]) => void;
927
935
  /**
928
- * Set the logger timestamp display.
936
+ * Set the serverLogger timestamp display.
929
937
  * @param showTimestamp Whether to show the timestamp or not.
930
938
  */
931
939
  setShowTimestamp: (showTimestamp: Parameters["showTimestamp"]) => void;
932
940
  /**
933
- * Set the logger foreign object new line display (wether to start the foreign object on a new line or not).
941
+ * Set the serverLogger foreign object new line display (wether to start the foreign object on a new line or not).
934
942
  * @param foreignObjectStartAtNewLine Whether to start the foreign object on a new line or not.
935
943
  */
936
944
  setForeignObjectStartAtNewLine: (foreignObjectStartAtNewLine: Parameters["foreignObjectStartAtNewLine"]) => void;
@@ -1258,4 +1266,4 @@ declare class NextAuthApiWrapper {
1258
1266
  run(): Promise<boolean | void>;
1259
1267
  }
1260
1268
 
1261
- 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 };
1269
+ export { Bench, type BenchmarkResult, type BenchmarkResults, type Bit, type CryptoAes256GcmEncryptResult, CyBuffer, type Endianness, type NextApiMethodInput, NextApiWrapper, type NextAuthApiMethodInput, NextAuthApiWrapper, type StringEncoding, convertNodeHeadersToWebHeaders, crypto, generateCGASStatus, getHostname, serverLogger };
package/backend.js CHANGED
@@ -1,6 +1,6 @@
1
- import D,{masks}from'dateformat';import P from'pino';import C from'pino-pretty';import M from'slugify';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,alignForeignObject:false},u={...B};function v(n,t){let e={level:n.level,time:n.time,pid:n.pid,hostname:n.hostname,msg:n.msg},r=Object.entries(n).reduce((d,[E,_])=>(Object.keys(e).includes(E)||(d[E]=_),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=`[${D(new Date(n.time),masks.isoDateTime)}] `);let c="";u.showLevel&&(c=u.alignForeignObject?`[${i}] `.padEnd(8," "):`[${i}] `);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((d,E)=>E===0?d:d.padStart(d.length+u.foreignObjectPadding," ")).join(`
4
- `));let g=a(`${o}${c}${n.msg}${f}`);return s&&(g=s(g)),console.log(g),""}var j=C({crlf:false,colorize:true,sync:true,include:"",messageFormat:(n,t,e,{colors:r})=>v(n,r)}),l=P({level:u.level},j);l.setLevel=n=>{u.level=n,l.level=n;};l.setShowLevel=n=>{u.showLevel=n;};l.setShowTimestamp=n=>{u.showTimestamp=n;};l.setForeignObjectStartAtNewLine=n=>{u.foreignObjectStartAtNewLine=n;};l.setForeignObjectPadding=n=>{u.foreignObjectPadding=n;};l.setForeignObjectIndent=n=>{u.foreignObjectIndent=n;};l.setAlignForeignObject=(n=false)=>{u.alignForeignObject=n;};l.setParameters=n=>{Object.assign(u,n);};l.resetParameters=()=>{Object.assign(u,B);};var y=l;M.default||M;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 O(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,g=0n,d=BigInt(this.benchmarkDuration)*1000000n;for(let E=0;E<Number.POSITIVE_INFINITY;E++)if(f=process.hrtime.bigint(),t(),g=process.hrtime.bigint(),c+=g-f,g-i>=d){a=Number(c)/E,s=1e9/a,o=Number(g-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,g=`>> ${a} `.padEnd(i+4,"\u2550"),d=`AVG TIME: ${O(o.avgExecutionTime)}`,E=`OPS: ${I(o.operationsPerSecond)}`,_=`PERCENTAGE: ${L(f)}`,A=`${g}\u2550> ${d} | ${E} | ${_}`,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 G(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 V(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 $(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 z(n,t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid payload format");let[r,i,s]=e;return $(n,r,i,s)}var X={aes256Gcm:{encrypt:V,decrypt:$,decryptPayload:z}};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 Q(){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,X as crypto,G as generateCGASStatus,Q as getHostname,y as logger};//# sourceMappingURL=backend.js.map
1
+ import F,{masks}from'dateformat';import v from'pino';import C from'pino-pretty';import M from'slugify';import {randomBytes,createCipheriv,createDecipheriv,randomFillSync}from'crypto';import {execSync}from'child_process';import {hostname}from'os';function B(n,t=4){return JSON.stringify(n,(e,r)=>typeof r=="function"||typeof r=="bigint"?r.toString():r,t)}var U={level:process.env.LOG_LEVEL||"trace",showLevel:true,showTimestamp:true,foreignObjectStartAtNewLine:false,foreignObjectPadding:0,foreignObjectIndent:4,alignForeignObject:false},u={...U};function j(n,t){let e={level:n.level,time:n.time,pid:n.pid,hostname:n.hostname,msg:n.msg},r=Object.entries(n).reduce((l,[y,_])=>(Object.keys(e).includes(y)||(l[y]=_),l),{}),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=`[${F(new Date(n.time),masks.isoDateTime)}] `);let c="";u.showLevel&&(c=u.alignForeignObject?`[${i}] `.padEnd(8," "):`[${i}] `);let m="";Object.keys(r).length>0&&(u.foreignObjectPadding==="after-timestamp"?u.foreignObjectPadding=o.length:u.foreignObjectPadding==="after-level"&&(u.foreignObjectPadding=o.length+c.length),m=`${u.foreignObjectStartAtNewLine?`
2
+ `:" "}${B(r,u.foreignObjectIndent)}`.split(`
3
+ `).map((l,y)=>y===0?l:l.padStart(l.length+u.foreignObjectPadding," ")).join(`
4
+ `));let g=a(`${o}${c}${n.msg}${m}`);return s&&(g=s(g)),console.log(g),""}var H=C({crlf:false,colorize:true,sync:true,include:"",messageFormat:(n,t,e,{colors:r})=>j(n,r)}),d=v({level:u.level},H);d.setLevel=n=>{u.level=n,d.level=n;};d.setShowLevel=n=>{u.showLevel=n;};d.setShowTimestamp=n=>{u.showTimestamp=n;};d.setForeignObjectStartAtNewLine=n=>{u.foreignObjectStartAtNewLine=n;};d.setForeignObjectPadding=n=>{u.foreignObjectPadding=n;};d.setForeignObjectIndent=n=>{u.foreignObjectIndent=n;};d.setAlignForeignObject=(n=false)=>{u.alignForeignObject=n;};d.setParameters=n=>{Object.assign(u,n);};d.resetParameters=()=>{Object.assign(u,U);};var E=d;M.default||M;function L(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 I(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 O(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,m=0n,g=0n,l=BigInt(this.benchmarkDuration)*1000000n;for(let y=0;y<Number.POSITIVE_INFINITY;y++)if(m=process.hrtime.bigint(),t(),g=process.hrtime.bigint(),c+=g-m,g-i>=l){a=Number(c)/y,s=1e9/a,o=Number(g-i)/a;break}this.results[e]={operationsPerSecond:s,avgExecutionTime:a,operations:o};};print=(t,e=true)=>{let r=t||"RESULTS";E.info(`
5
+ ${r.toUpperCase()}:`),E.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,m=o.operationsPerSecond/c*100,g=`>> ${a} `.padEnd(i+4,"\u2550"),l=`AVG TIME: ${I(o.avgExecutionTime)}`,y=`OPS: ${L(o.operationsPerSecond)}`,_=`PERCENTAGE: ${O(m)}`,A=`${g}\u2550> ${l} | ${y} | ${_}`,x=10;m>=90?E.debug(A+"(fastest)".padStart(x," ")):m>=60?E.info(A+"(fast)".padStart(x," ")):m>=30?E.warn(A+"(medium)".padStart(x," ")):m>=10?E.error(A+"(slow)".padStart(x," ")):E.error(A+"(slowest)".padStart(x," "));}e&&(this.results={});}};function G(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 z(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 $(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 X(n,t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid payload format");let[r,i,s]=e;return $(n,r,i,s)}var Z={aes256Gcm:{encrypt:z,decrypt:$,decryptPayload:X}};function h(n,t){return `[CyBuffer - ${n}] ${t}`}var T=(()=>{let n=new Uint8Array(4);return new Uint32Array(n.buffer)[0]=65280,n[0]===255?"BE":"LE"})(),S=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=T,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=()=>T;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 TextEncoder().encode(t),r=new n(e.byteLength);return r.array.set(e),r};static fromString=(t,e="utf8")=>{if(e==="utf8"){let r=new TextEncoder().encode(t),i=new n(r.byteLength);return i.array.set(r),i}if(e==="hex"){let r=Math.ceil(t.length/2),i=new n(r);return i.writeHexString(t,0,r),i}throw new TypeError(h("fromString",`Invalid encoding: '${e}'.`))};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)=>{if(typeof e=="string"){let r=Number(e);if(!Number.isNaN(r))return this.check(r,1),t.array[r]}return t[e]},set:(t,e,r)=>{if(typeof e=="string"){let i=Number(e);if(!Number.isNaN(i)){let s=Number(r);if(Number.isNaN(s))throw new TypeError(h("proxy",`Invalid value: '${r}'.`));if(s<0||s>255)throw new RangeError(h("proxy",`Value is out of bounds: '${r}'.`));return this.check(i,1),t.array[i]=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=new TextEncoder().encode(t).byteLength)=>{if(r===0)throw new RangeError(h("writeUtf8String",`Invalid UTF-8 string length: '${r}'.`));let i=new TextEncoder().encode(t);return this.check(e,r),this.array.set(i.subarray(0,r),e),this};writeString=(t,e="utf8",r=0,i)=>{if(e==="utf8"){let s=new TextEncoder().encode(t),a=i??s.byteLength;return this.check(r,a),this.array.set(s.subarray(0,a),r),this}if(e==="hex")return this.writeHexString(t,r,Math.ceil((i??t.length)/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}'.`));return this.check(e,r),this.array.set(t.subarray(i,r),e),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(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(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(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?0:1};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)=>{if(e===0)return [];let s=Math.floor(t/8),a=Math.ceil((t+e)/8)-s;i&&this.check(s,a);let o=[];for(let c=0;c<e;c++)o.push(this.readBit(t+c,r,false));return o};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,this.offset,this.length).toString("hex").toUpperCase();return this.normalizeEndianness(e)==="BE"&&(r=r.match(/.{2}/g)?.reverse().join("")??""),t?`0x${r}`:r};toUtf8String=()=>Buffer.from(this.arrayBuffer,this.offset,this.length).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);return r.array.set(this.array.subarray(t,t+e)),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);for(let i=t;i<t+e;i+=r)for(let s=0;s<r/2;s++){let a=this.array[i+s];this.array[i+s]=this.array[i+r-s-1],this.array[i+r-s-1]=a;}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=t;i<t+e-r;i++)this.array[i]=this.array[i+r];for(let i=0;i<r;i++)this.array[t+e-i-1]=0;return this};shiftRight=(t=0,e=this.length,r=1)=>{this.check(t,e);for(let i=t+e-1;i>=t+r;i--)this.array[i]=this.array[i-r];for(let i=0;i<r;i++)this.array[t+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 Y(n){let t=new Headers;for(let[e,r]of Object.entries(n))if(Array.isArray(r))for(let i of r)t.append(e,i);else r!==void 0&&t.append(e,r);return t}function K(){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 N=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,S as CyBuffer,N as NextApiWrapper,R as NextAuthApiWrapper,Y as convertNodeHeadersToWebHeaders,Z as crypto,G as generateCGASStatus,K as getHostname,E as serverLogger};//# sourceMappingURL=backend.js.map
6
6
  //# sourceMappingURL=backend.js.map