import * as Events from 'events'; import * as Express from 'express'; import * as Http from 'http'; import * as Stream from 'stream'; import * as Https from 'https'; declare module "kras" { export interface ConfigurationOptions { name?: string; host?: string; port?: number; logs?: LogLevel; dir?: string; cert?: string; key?: string; skipApi?: boolean; initial?: Partial; required?: Partial; } export interface ConfigurationFile { [key: string]: any; } export function makePathsAbsolute(baseDir: string, config: ConfigurationFile): void; export function readConfiguration(path: string): ConfigurationFile; export function mergeConfiguration(options?: ConfigurationOptions, ...configs: Array): KrasConfiguration; export const defaultConfig: KrasConfiguration; export function buildConfiguration(config?: Partial): KrasConfiguration; export const serverDir: string; export const distDir: string; export const rootDir: string; export const currentDir: string; export const krasrc: ".krasrc"; export const author: string; export const name: string; export const version: string; export const injectorDebug: boolean; export const injectorConfig: any; export const injectorMain: string; export function withInjectors(server: KrasServer, config: KrasConfiguration): Promise; export class MockServer extends MockServerCore implements KrasServer { readonly injectors: Array; readonly middlewares: Array; readonly logs: Array; readonly logLevel: LogLevel; constructor(private config: KrasConfiguration); setup(): Promise; stop(): Promise; private log(type: LogEntryType, data: any): void; } export function readKrasConfig(options?: ConfigurationOptions, ...files: Array): KrasConfiguration; export function buildKras(config?: Partial): MockServer; export function buildKrasWithCli(config: KrasConfiguration): MockServer; export function runKras(config?: Partial): Promise; export type KrasRuntimeConfiguration = Partial & KrasHandlerConfiguration; export function withKras(config?: KrasRuntimeConfiguration): (callback: KrasRunner) => Promise; export function runWithKras(cb: KrasRunner, config?: KrasRuntimeConfiguration): Promise; export function connectToCli(server: MockServer, canManage?: boolean): void; export function runFromCli(options: ConfigurationOptions, rcfile: string): Promise; export type LogLevel = "debug" | "info" | "error"; export interface KrasConfiguration extends WebServerConfiguration { name: string; client: string; directory: string; sources?: Array; api: string | false; auth: undefined | KrasAuth; middlewares: Array; injectorDirs?: Array; injectors: KrasConfigurationInjectors; } export interface KrasServer extends BaseKrasServer { readonly injectors: Array; readonly middlewares: Array; readonly recorder: KrasRecorder; readonly logs: Array; readonly logLevel: LogLevel; } export interface KrasInjector { active: boolean; config: KrasInjectorConfig; readonly name: string; readonly handle: KrasRequestHandler; getOptions(): KrasInjectorOptions; setOptions(options: Dict): void; dispose?(): void; setup?(): void | Promise; } export type ScriptFiles = Array; export interface Watcher { directories: Array; close(): void; } export interface KrasInjectorConfig { /** * Determins if the injector is active. */ active: boolean; /** * Optionally sets the targets to ignore. * Otherwise, no targets are ignored. */ ignore?: Array; /** * Optionally sets explicitly the targets to handle. * Otherwise, all targets are handled. */ handle?: Array; /** * Optionally sets the base dir of the injector, i.e., * the directory where the injector could be found. */ baseDir?: string; [config: string]: any; } export interface ScriptInjectorConfig { directory?: string | Array; extended?: ScriptContextData; } export interface ScriptContextData { [prop: string]: any; } export type KrasInjectorOptions = Dict; export interface DynamicScriptInjectorConfig { extended: string; directories: Array; files: Array<{ name: string; active: boolean; }>; } export interface KrasRequest extends BasicKrasRequest { /** * Indicates if the request has been encrypted. */ encrypted: boolean; /** * The remote address triggering the request. */ remoteAddress: string; /** * The port used for the request. */ port: string; } export interface KrasAnswer { headers: Headers; status: { code: number; text?: string; }; url: string; redirectUrl?: string; content: string | Buffer; injector?: KrasInjectorInfo; } export interface WebSocketSessions { [id: string]: WebSocketDisposer; } export interface ProxyInjectorConfig { agentOptions?: any; proxy?: any; xfwd?: boolean; defaultHeaders?: Array; discardHeaders?: Array; permitHeaders?: Array; injectHeaders?: Record; followRedirect?: boolean; } export interface DynamicProxyInjectorConfig { [target: string]: string; } export interface ProxyRequestInfo { remoteAddress: string; port: string; encrypted: boolean; headers: Record>; } export type HarFiles = Array>; export interface HarInjectorConfig { directory?: string | Array; delay?: boolean; } export interface DynamicHarInjectorConfig { delay: boolean; directories: Array; files: Array<{ name: string; entries: Array<{ active: boolean; }>; }>; } export interface HttpArchive { active: boolean; request: HarRequest; response: HarResponse; time: number; } export type Headers = Dict>; export interface HarResponse { status: number; statusText: string; redirectURL: string; headers: HarHeaders; content: { encoding?: BufferEncoding; mimeType: string; text?: string; }; } export class JsonStore { constructor(public file: string); insert(item: T): void; delete(predicate?: (item: T) => boolean): void; select(predicate?: (item: T) => boolean): Array; switchTo(file: string): void; } export interface StoreRequestEntry { request: KrasRequest; response: { status: number; }; } export interface StoreInjectorConfig { directory?: string; filename?: string; } export interface DynamicStoreInjectorConfig { file?: string; } export type JsonFiles = Array>; export interface JsonInjectorConfig { directory?: string | Array; randomize?: boolean; generator?: boolean; generatorLocaleName?: string; } export interface DynamicJsonInjectorConfig { randomize: boolean; directories: Array; files: Array<{ name: string; entries: Array<{ active: boolean; }>; }>; } export const Buffer: BufferConstructor; export interface FileInfo { path: string; active: boolean; error?: string; } export interface DescribeEntry { (item: T, file: string, index: number): string; } export function editDirectoryOption(directories: Array): KrasInjectorOption; export function editFileOption(files: Array): KrasInjectorOption; export function editEntryOption(files: Array>, desc: DescribeEntry): KrasInjectorOption; export type HarHeaders = Array<{ name: string; value: string; }>; export interface HarRequest { url: string; method: string; target?: string; postData?: { text?: string; }; headers: HarHeaders; queryString: HarHeaders; } export interface NodeResponse { headers: Dict>; statusCode: number; statusMessage: string; url?: string; request: { href: string; }; } export function fromNode(ans: NodeResponse, body: Buffer, injector?: KrasInjectorInfo): KrasAnswer; export function fromHar(url: string, response: HarResponse, injector?: KrasInjectorInfo): KrasAnswer; export function fromJson(url: string, statusCode: number, statusText: string, headers: Headers, content: string | Buffer, injector?: KrasInjectorInfo): KrasAnswer; export function fromMissing(url: string): KrasAnswer; export function compareRequests(a: BasicKrasRequest, b: BasicKrasRequest): boolean; export function getClient(cwd: string, path: string): Promise; export function withFiles(server: KrasServer, config: KrasConfiguration): Promise; export function configureHandler(server: KrasServer, config?: KrasHandlerConfiguration): void; export interface FullKrasServer extends KrasServer { start(): Promise; stop(): Promise; } export function runWith(server: FullKrasServer, callback: KrasRunner): Promise; export function integrateXfwd(headers: Record>, protocol: string, req: ProxyRequestInfo): void; export function isEncrypted(req: any): boolean; export function getPort(req: Express.Request): string; export function isFile(file: string): boolean; export function mk(directory: string): boolean; export function ls(directory: string): Array; export function toAbsolute(directory: string): (file: string) => string; export function asJson(file: string, defaultValue: T): T; export function asScript(file: string): Promise; export function toFile(file: string, obj: T): string; export function isInDirectory(fn: string, dir: string): boolean; export function watch(directory: string | Array, extensions: Array, callback: (type: string, file: string) => void, watched?: Array): Watcher; export function open(file: string): JsonStore; export function withMiddlewares(server: KrasServer, config: KrasConfiguration): Promise; export const defaultProxyHeaders: Array; export interface ProxyRequestOptions { url: string; method: string; headers: RawAxiosRequestHeaders; body: Buffer; agentOptions?: any; proxy?: any; injector?: KrasInjectorInfo; redirect?: boolean; } export function proxyRequest(req: ProxyRequestOptions): Promise; export interface ProxyWebSocketOptions { id: string; ws: KrasWebSocket; url: string; headers: Headers; core: Events.EventEmitter; } export interface WebSocketDisposer { (): void; } export function proxyWebSocket(client: ProxyWebSocketOptions): WebSocketDisposer; export function mapReverse(items: Array, select: (item: T, index: number, rindex: number) => U): Array; export function filterReverse(items: Array, check: (item: T, index: number, rindex: number) => boolean): Array; export function deepMerge(obj: any, value: any): any; export function getLast(value: string | Array): string; export function getFirst(value: string | Array): string; export class MockServerCore extends WebServer { readonly recorder: Recorder; constructor(config?: WebServerConfiguration); } export interface KrasMiddleware { source: string; direction: "in" | "out"; options: Array; active: boolean; handler: KrasServerHandler; } export interface LogEntry { type: LogEntryType; time: Date; data: any; } export type LogEntryType = "error"; export interface KrasHandlerConfiguration { handlers?: { [url: string]: KrasServerHandler; }; } export interface KrasRunner { (s: KrasConfigurator): Promise | void; } export interface Dict { [key: string]: T; } export interface SslConfiguration { key: string; cert: string; } export interface StoredFileEntry { id?: number; active: boolean; file: string; method?: string; url?: string; error?: string; } export interface AppConfiguration { logLevel: LogLevel; } export interface WebServerConfigurationMap { [target: string]: string | boolean; } export interface WebServerConfiguration extends AppConfiguration { map: WebServerConfigurationMap; ssl: SslConfiguration; ws: boolean | Dict; uploadLimit: number; port: number; host: string; } export interface KrasAuthSimpleAccount { username: string; password: string; } export interface KrasAuth { provider: "simple"; accounts: Array; } export interface KrasConfigurationInjectors { [name: string]: KrasInjectorConfig; } export interface KrasInjectorInfo { name?: string; host?: { target: string; address: string; }; file?: { name: string; entry?: number; }; } export type KrasResult = KrasAnswer | void; export type KrasResponse = Promise | KrasResult; export interface KrasRequestHandler { (req: KrasRequest): KrasResponse; } export interface KrasMiddlewareDefinition { source: string; direction?: "in" | "out"; baseDir?: string; options?: Array; } export interface KrasInjectorStringOption { type: "text"; value: string; } export interface KrasInjectorCheckboxOption { type: "checkbox"; value: boolean; } export interface KrasInjectorFileOption { type: "file"; value: Array<{ id: string; name: string; basename: string; active: boolean; error?: string; }>; } export interface KrasInjectorDirectoryOption { type: "directory"; value: Array; } export interface KrasInjectorEntryOption { type: "entry"; value: Array<{ id: string; name: string; basename: string; entries: Array<{ active: boolean; description: string; error?: string; }>; }>; } export interface KrasInjectorJsonOption { type: "json"; value: string; } export type KrasInjectorValueOption = KrasInjectorStringOption | KrasInjectorCheckboxOption | KrasInjectorFileOption | KrasInjectorDirectoryOption | KrasInjectorEntryOption | KrasInjectorJsonOption; export type KrasInjectorOption = { title: string; description: string; } & KrasInjectorValueOption; export interface RecordedRequest { id: string; start: Date; end: Date; request: KrasRequest; response: KrasAnswer; } export interface RecordedError { id: string; start: Date; end: Date; request: KrasRequest; } export interface WebSocketMessage { content: string; from: string; to: string; remote: boolean; } export interface RecordedMessage extends WebSocketMessage { id: string; time: Date; } export interface KrasRecorder extends Events.EventEmitter { readonly requests: Array; readonly errors: Array; readonly messages: Array; } export interface KrasRequestQuery { [key: string]: string | Array; } export interface BasicKrasRequest { /** * The URL used for the request. */ url: string; /** * The target path of the request. */ target: string; /** * The query parameters of the request. */ query: KrasRequestQuery; /** * The method to trigger the request. */ method: string; /** * The headers used for the request. */ headers: Http.IncomingHttpHeaders; /** * The content of the request. */ content: string | FormData; /** * The raw content of the request. */ rawContent: Buffer; /** * The form data, in case a form was given. */ formData?: FormData; } export interface KrasServerMethods { get(handler: KrasServerHandler): KrasServerMethods; put(handler: KrasServerHandler): KrasServerMethods; post(handler: KrasServerHandler): KrasServerMethods; delete(handler: KrasServerHandler): KrasServerMethods; any(handler: KrasServerHandler): KrasServerMethods; feed(handler: KrasServerConnector): KrasServerMethods; } export interface BaseKrasServer extends Events.EventEmitter { add(hook: KrasServerHook): void; remove(hook: KrasServerHook): void; at(...segments: Array): KrasServerMethods; broadcast(msg: T): void; ws: boolean; } export interface KrasServerHook { handle(req: Express.Request, res: Express.Response): void; rate(req: Express.Request): number; } export interface KrasServerHandler { (req: Express.Request, res: Express.Response, next?: Express.NextFunction): void; } export type KrasWebSocket = Events.EventEmitter & { protocol: string; send(msg: Data, onError?: (err: Error) => void): void; close(): void; }; export interface KrasServerConnector { (ws: KrasWebSocket, req: Express.Request): void; } export interface KrasWebSocketEvent { id: string; ws: KrasWebSocket; target: string; url: string; req: Express.Request; handled?: boolean; } export interface KrasConfigurator { at(url: string): KrasServerMethods; } export interface UserCredentials { username: string; password: string; } export interface ScriptResponseBuilderData { statusCode?: number; statusText?: string; headers?: Headers; content?: string; } export interface ScriptResponseBuilder { (data: ScriptResponseBuilderData): KrasAnswer; } export interface ScriptFileEntry { path: string; active: boolean; error?: string; handler?: ScriptExports; } export interface HarFileEntry { path: string; active: boolean; request: { method: string; url: string; target: string; content: string; rawContent: any; formData?: FormData; headers: Headers; query: Headers; }; response: HarResponse; time: number; } export type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "utf-16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"; export interface JsonFileItem { path: string; active: boolean; request: KrasRequest; response: KrasAnswer | Array; } /** * Raw data is stored in instances of the Buffer class. * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' */ export interface BufferConstructor { /** * Allocates a new buffer containing the given {str}. * Allocates a new buffer of {size} octets. * Allocates a new buffer containing the given {array} of octets. * Produces a Buffer backed by the same allocated memory as * the given {ArrayBuffer}/{SharedArrayBuffer}. * Copies the passed {buffer} data onto a new {Buffer} instance. * @param str String to store in buffer. * @param encoding encoding to use, optional. Default is 'utf8' * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. * @param size count of octets to allocate. * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). * @param array The octets to store. * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. * @param arrayBuffer The ArrayBuffer with which to share memory. * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. * @param array The octets to store. * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. * @param buffer The buffer to copy. * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. */ new (str: string, encoding?: BufferEncoding): Buffer; /** * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. * Array entries outside that range will be truncated to fit into it. * * ```js * import { Buffer } from 'node:buffer'; * * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); * ``` * * If `array` is an `Array`\-like object (that is, one with a `length` property of * type `number`), it is treated as if it is an array, unless it is a `Buffer` or * a `Uint8Array`. This means all other `TypedArray` variants get treated as an `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. * * A `TypeError` will be thrown if `array` is not an `Array` or another type * appropriate for `Buffer.from()` variants. * * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. * @since v5.10.0 */ from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; /** * Creates a new Buffer using the passed {data} * @param data data to create a new Buffer */ from(data: Uint8Array | readonly number[]): Buffer; from(data: WithImplicitCoercion): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. */ from(str: WithImplicitCoercion | { [Symbol.toPrimitive](hint: "string"): string; }, encoding?: BufferEncoding): Buffer; /** * Creates a new Buffer using the passed {data} * @param values to create a new Buffer */ of(...items: Array): Buffer; /** * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. * * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. * * If `totalLength` is not provided, it is calculated from the `Buffer` instances * in `list` by adding their lengths. * * If `totalLength` is provided, it is coerced to an unsigned integer. If the * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is * truncated to `totalLength`. * * ```js * import { Buffer } from 'node:buffer'; * * // Create a single `Buffer` from a list of three `Buffer` instances. * * const buf1 = Buffer.alloc(10); * const buf2 = Buffer.alloc(14); * const buf3 = Buffer.alloc(18); * const totalLength = buf1.length + buf2.length + buf3.length; * * console.log(totalLength); * // Prints: 42 * * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); * * console.log(bufA); * // Prints: * console.log(bufA.length); * // Prints: 42 * ``` * * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. * @since v0.7.11 * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. */ concat(list: readonly Uint8Array[], totalLength?: number): Buffer; /** * Copies the underlying memory of `view` into a new `Buffer`. * * ```js * const u16 = new Uint16Array([0, 0xffff]); * const buf = Buffer.copyBytesFrom(u16, 1, 1); * u16[1] = 0; * console.log(buf.length); // 2 * console.log(buf[0]); // 255 * console.log(buf[1]); // 255 * ``` * @since v19.8.0 * @param view The {TypedArray} to copy. * @param offset The starting offset within `view`. * @param length The number of elements from `view` to copy. */ copyBytesFrom(view: NodeJS_TypedArray, offset?: number, length?: number): Buffer; /** * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. * * ```js * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5); * * console.log(buf); * // Prints: * ``` * * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. * * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. * * ```js * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(5, 'a'); * * console.log(buf); * // Prints: * ``` * * If both `fill` and `encoding` are specified, the allocated `Buffer` will be * initialized by calling `buf.fill(fill, encoding)`. * * ```js * import { Buffer } from 'node:buffer'; * * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); * * console.log(buf); * // Prints: * ``` * * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance * contents will never contain sensitive data from previous allocations, including * data that might not have been allocated for `Buffer`s. * * A `TypeError` will be thrown if `size` is not a number. * @since v5.10.0 * @param size The desired length of the new `Buffer`. * @param fill A value to pre-fill the new `Buffer` with. * @param encoding If `fill` is a string, this is its encoding. */ alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; /** * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. * * The underlying memory for `Buffer` instances created in this way is _not_ * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. * * ```js * import { Buffer } from 'node:buffer'; * * const buf = Buffer.allocUnsafe(10); * * console.log(buf); * // Prints (contents may vary): * * buf.fill(0); * * console.log(buf); * // Prints: * ``` * * A `TypeError` will be thrown if `size` is not a number. * * The `Buffer` module pre-allocates an internal `Buffer` instance of * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). * * Use of this pre-allocated internal memory pool is a key difference between * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less * than or equal to half `Buffer.poolSize`. The * difference is subtle but can be important when an application requires the * additional performance that `Buffer.allocUnsafe()` provides. * @since v5.10.0 * @param size The desired length of the new `Buffer`. */ allocUnsafe(size: number): Buffer; /** * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if * `size` is 0. * * The underlying memory for `Buffer` instances created in this way is _not_ * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize * such `Buffer` instances with zeroes. * * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This * allows applications to avoid the garbage collection overhead of creating many * individually allocated `Buffer` instances. This approach improves both * performance and memory usage by eliminating the need to track and clean up as * many individual `ArrayBuffer` objects. * * However, in the case where a developer may need to retain a small chunk of * memory from a pool for an indeterminate amount of time, it may be appropriate * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and * then copying out the relevant bits. * * ```js * import { Buffer } from 'node:buffer'; * * // Need to keep around a few small chunks of memory. * const store = []; * * socket.on('readable', () => { * let data; * while (null !== (data = readable.read())) { * // Allocate for retained data. * const sb = Buffer.allocUnsafeSlow(10); * * // Copy the data into the new allocation. * data.copy(sb, 0, 0, 10); * * store.push(sb); * } * }); * ``` * * A `TypeError` will be thrown if `size` is not a number. * @since v5.12.0 * @param size The desired length of the new `Buffer`. */ allocUnsafeSlow(size: number): Buffer; /** * Returns `true` if `obj` is a `Buffer`, `false` otherwise. * * ```js * import { Buffer } from 'node:buffer'; * * Buffer.isBuffer(Buffer.alloc(10)); // true * Buffer.isBuffer(Buffer.from('foo')); // true * Buffer.isBuffer('a string'); // false * Buffer.isBuffer([]); // false * Buffer.isBuffer(new Uint8Array(1024)); // false * ``` * @since v0.1.101 */ isBuffer(obj: any): obj is Buffer; /** * Returns `true` if `encoding` is the name of a supported character encoding, * or `false` otherwise. * * ```js * import { Buffer } from 'node:buffer'; * * console.log(Buffer.isEncoding('utf8')); * // Prints: true * * console.log(Buffer.isEncoding('hex')); * // Prints: true * * console.log(Buffer.isEncoding('utf/8')); * // Prints: false * * console.log(Buffer.isEncoding('')); * // Prints: false * ``` * @since v0.9.1 * @param encoding A character encoding name to check. */ isEncoding(encoding: string): encoding is BufferEncoding; /** * Returns the byte length of a string when encoded using `encoding`. * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account * for the encoding that is used to convert the string into bytes. * * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the * return value might be greater than the length of a `Buffer` created from the * string. * * ```js * import { Buffer } from 'node:buffer'; * * const str = '\u00bd + \u00bc = \u00be'; * * console.log(`${str}: ${str.length} characters, ` + * `${Buffer.byteLength(str, 'utf8')} bytes`); * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes * ``` * * When `string` is a * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. * @since v0.1.90 * @param string A value to calculate the length of. * @param encoding If `string` is a string, this is its encoding. * @return The number of bytes contained within `string`. */ byteLength(string: string | Buffer | NodeJS_ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; /** * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. * * ```js * import { Buffer } from 'node:buffer'; * * const buf1 = Buffer.from('1234'); * const buf2 = Buffer.from('0123'); * const arr = [buf1, buf2]; * * console.log(arr.sort(Buffer.compare)); * // Prints: [ , ] * // (This result is equal to: [buf2, buf1].) * ``` * @since v0.11.13 * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. */ compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; /** * This is the size (in bytes) of pre-allocated internal `Buffer` instances used * for pooling. This value may be modified. * @since v0.11.3 */ poolSize: number; } export type RawAxiosRequestHeaders = Partial; export class WebServer extends Events.EventEmitter implements BaseKrasServer { private readonly app: Express.Application & { ws?(target: string, connect: KrasServerConnector): void; }; private readonly hooks: Array; private readonly routes: Array; private readonly port: number; private readonly host: string; private readonly protocol: string; private readonly targets: Array; private readonly server: Server; private readonly wsOptions: Dict; private sockets: WebSocketConnection; constructor(config?: Partial); get ws(): boolean; set ws(value: boolean); add(hook: KrasServerHook): this; remove(hook: KrasServerHook): this; at(...segments: Array): KrasServerMethods; setup(): Promise; start(): Promise; stop(): Promise; broadcast(msg: T): void; } export class Recorder extends Events.EventEmitter implements KrasRecorder { private readonly maximum: number; private enabled: boolean; readonly requests: Array; readonly errors: Array; readonly messages: Array; constructor(maximum: number); disable(): void; hit(start: Date, end: Date, request: KrasRequest, response: KrasAnswer): void; message(time: Date, data: WebSocketMessage): void; miss(start: Date, end: Date, request: KrasRequest): void; } export class FormData extends Stream.Readable { constructor(options?: Options); append(key: string, value: any, options?: AppendOptions | string): void; getHeaders(userHeaders?: Headers___1): Headers___1; submit(params: string | SubmitOptions, callback?: (error: Error | null, response: Http.IncomingMessage) => void): Http.ClientRequest; getBuffer(): Buffer; setBoundary(boundary: string): void; getBoundary(): string; getLength(callback: (err: Error | null, length: number) => void): void; getLengthSync(): number; hasKnownLength(): boolean; } /** * Data represents the message payload received over the WebSocket. */ export type Data = string | Buffer | ArrayBuffer | Array; export interface ScriptExports { (ctx: ScriptContextData, req: KrasRequest, builder: ScriptResponseBuilder): KrasAnswer | Promise | undefined; setup?(ctx: ScriptContextData): void; teardown?(ctx: ScriptContextData): void; connected?(ctx: ScriptContextData, e: KrasWebSocketEvent): void | boolean; disconnected?(ctx: ScriptContextData, e: KrasWebSocketEvent): void; } export type WithImplicitCoercion = T | { valueOf(): T; }; export type NodeJS_TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array; export type NodeJS_ArrayBufferView = NodeJS_TypedArray | DataView; export interface RawAxiosHeaders { [key: string]: AxiosHeaderValue; } export type CommonRequestHeadersList = "Accept" | "Content-Length" | "User-Agent" | "Content-Encoding" | "Authorization"; export type AxiosHeaderValue = AxiosHeaders | string | Array | number | boolean | null; export type ContentType = AxiosHeaderValue | "text/html" | "text/plain" | "multipart/form-data" | "application/json" | "application/x-www-form-urlencoded" | "application/octet-stream"; export type Server = Http.Server | Https.Server; export interface WebSocketConnection { getWss(target?: Array): { clients: Set<{ send(data: string): void; }>; close(): void; }; } export interface Options extends ReadableOptions { writable?: boolean; readable?: boolean; dataSize?: number; maxDataSize?: number; pauseStreams?: boolean; } export interface AppendOptions { header?: string | Headers___1; knownLength?: number; filename?: string; filepath?: string; contentType?: string; } export interface Headers___1 { [key: string]: any; } export interface SubmitOptions extends Http.RequestOptions { protocol?: "https:" | "http:"; } export class AxiosHeaders { constructor(headers?: RawAxiosHeaders | AxiosHeaders | string); [key: string]: any; set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders; get(headerName: string, parser: RegExp): RegExpExecArray | null; get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue; has(header: string, matcher?: AxiosHeaderMatcher): boolean; delete(header: string | Array, matcher?: AxiosHeaderMatcher): boolean; clear(matcher?: AxiosHeaderMatcher): boolean; normalize(format: boolean): AxiosHeaders; concat(...targets: Array): AxiosHeaders; toJSON(asStrings?: boolean): RawAxiosHeaders; static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; static accessor(header: string | Array): AxiosHeaders; static concat(...targets: Array): AxiosHeaders; setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentType(parser?: RegExp): RegExpExecArray | null; getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentType(matcher?: AxiosHeaderMatcher): boolean; setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentLength(parser?: RegExp): RegExpExecArray | null; getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentLength(matcher?: AxiosHeaderMatcher): boolean; setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getAccept(parser?: RegExp): RegExpExecArray | null; getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasAccept(matcher?: AxiosHeaderMatcher): boolean; setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getUserAgent(parser?: RegExp): RegExpExecArray | null; getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentEncoding(parser?: RegExp): RegExpExecArray | null; getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getAuthorization(parser?: RegExp): RegExpExecArray | null; getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; "[Symbol.iterator]"(): IterableIterator<[string, AxiosHeaderValue]>; } export interface ReadableOptions { highWaterMark?: number; encoding?: string; objectMode?: boolean; read?(this: Stream.Readable, size: number): void; destroy?(this: Stream.Readable, error: Error | null, callback: (error: Error | null) => void): void; autoDestroy?: boolean; } export type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean); export type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any; }